|
| 1 | +// Copyright 2016-2025, Pulumi Corporation. All rights reserved. |
| 2 | + |
| 3 | +import * as aws from "@pulumi/aws"; |
| 4 | +import * as apigateway from "@pulumi/aws-apigateway"; |
| 5 | +import * as pulumi from "@pulumi/pulumi"; |
| 6 | + |
| 7 | +import * as crypto from "crypto"; |
| 8 | +import * as jwt from "jsonwebtoken"; |
| 9 | +import * as jwksClient from "jwks-rsa"; |
| 10 | + |
| 11 | +interface APIGatewayProxyEvent { |
| 12 | + headers: { [key: string]: string | undefined }; |
| 13 | + requestContext: { |
| 14 | + domainName: string; |
| 15 | + path: string; |
| 16 | + }; |
| 17 | + body: string | null; |
| 18 | +} |
| 19 | + |
| 20 | +interface APIGatewayProxyResult { |
| 21 | + statusCode: number; |
| 22 | + headers?: { [key: string]: string }; |
| 23 | + body: string; |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Reusable helper for validating ESC external provider requests. |
| 28 | + * Copy-paste this into your own adapters to get secure JWT validation. |
| 29 | + */ |
| 30 | +class ESCRequestValidator { |
| 31 | + private client: jwksClient.JwksClient; |
| 32 | + |
| 33 | + constructor(jwksUrl: string = "https://api.pulumi.com/oidc/.well-known/jwks") { |
| 34 | + this.client = jwksClient({ |
| 35 | + jwksUri: jwksUrl, |
| 36 | + cache: true, |
| 37 | + cacheMaxAge: 600000, // 10 minutes |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Validates an ESC external provider request. |
| 43 | + * Returns the validated JWT claims and request body on success. |
| 44 | + * Throws an error with a user-friendly message on validation failure. |
| 45 | + */ |
| 46 | + async validateRequest(event: APIGatewayProxyEvent): Promise<{ |
| 47 | + claims: jwt.JwtPayload; |
| 48 | + requestBody: any; |
| 49 | + }> { |
| 50 | + // Extract Authorization header |
| 51 | + const authHeader = event.headers.Authorization || event.headers.authorization; |
| 52 | + if (!authHeader || !authHeader.startsWith("Bearer ")) { |
| 53 | + throw new Error("Missing or invalid Authorization header"); |
| 54 | + } |
| 55 | + |
| 56 | + const token = authHeader.substring(7); |
| 57 | + const requestBody = event.body || "{}"; |
| 58 | + |
| 59 | + // Verify JWT signature and claims |
| 60 | + const decoded = await this.verifyJWT(token); |
| 61 | + |
| 62 | + // Verify audience matches adapter URL |
| 63 | + const requestUrl = `https://${event.headers.Host || event.requestContext.domainName}${event.requestContext.path}`; |
| 64 | + if (decoded.aud !== requestUrl) { |
| 65 | + throw new Error(`Audience mismatch: expected ${requestUrl}, got ${decoded.aud}`); |
| 66 | + } |
| 67 | + |
| 68 | + // Verify body hash |
| 69 | + const bodyHash = decoded.body_hash as string; |
| 70 | + if (!bodyHash) { |
| 71 | + throw new Error("Missing body_hash claim in JWT"); |
| 72 | + } |
| 73 | + |
| 74 | + if (!this.verifyBodyHash(requestBody, bodyHash)) { |
| 75 | + throw new Error("Body hash verification failed"); |
| 76 | + } |
| 77 | + |
| 78 | + return { |
| 79 | + claims: decoded, |
| 80 | + requestBody: JSON.parse(requestBody), |
| 81 | + }; |
| 82 | + } |
| 83 | + |
| 84 | + private async verifyJWT(token: string): Promise<jwt.JwtPayload> { |
| 85 | + return new Promise((resolve, reject) => { |
| 86 | + jwt.verify( |
| 87 | + token, |
| 88 | + (header, callback) => { |
| 89 | + this.client.getSigningKey(header.kid, (err, key) => { |
| 90 | + if (err) { |
| 91 | + callback(err); |
| 92 | + return; |
| 93 | + } |
| 94 | + callback(null, key?.getPublicKey()); |
| 95 | + }); |
| 96 | + }, |
| 97 | + { |
| 98 | + algorithms: ["RS256"], |
| 99 | + complete: false, |
| 100 | + }, |
| 101 | + (err, decoded) => { |
| 102 | + if (err) { reject(err); } |
| 103 | + else { resolve(decoded as jwt.JwtPayload); } |
| 104 | + }, |
| 105 | + ); |
| 106 | + }); |
| 107 | + } |
| 108 | + |
| 109 | + private verifyBodyHash(body: string, expectedHash: string): boolean { |
| 110 | + const hash = crypto.createHash("sha256").update(body).digest("base64"); |
| 111 | + const actualHash = `sha256-${hash}`; |
| 112 | + return actualHash === expectedHash; |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +const adapterFunction = new aws.lambda.CallbackFunction("escExternalAdapter", { |
| 117 | + callback: async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => { |
| 118 | + try { |
| 119 | + // Initialize the validator (Lambda will cache across invocations) |
| 120 | + const validator = new ESCRequestValidator(); |
| 121 | + |
| 122 | + // Validate the request using the reusable helper |
| 123 | + const { claims, requestBody } = await validator.validateRequest(event); |
| 124 | + |
| 125 | + // Log JWT claims for debugging. You can use these claims for authorization decisions. |
| 126 | + console.log("JWT validation successful"); |
| 127 | + console.log("Organization:", claims.org); |
| 128 | + console.log("Environment:", claims.current_env); |
| 129 | + console.log("Trigger User:", claims.trigger_user); |
| 130 | + console.log("Issued At:", new Date((claims.iat || 0) * 1000).toISOString()); |
| 131 | + |
| 132 | + // TODO: Replace this with your secret fetching logic |
| 133 | + // For example: |
| 134 | + // const secret = await fetchFromYourSecretStore(requestBody.secretName); |
| 135 | + // return { statusCode: 200, body: JSON.stringify(secret) }; |
| 136 | + |
| 137 | + return { |
| 138 | + statusCode: 200, |
| 139 | + headers: { |
| 140 | + "Content-Type": "application/json", |
| 141 | + }, |
| 142 | + body: JSON.stringify({ |
| 143 | + message: "External secrets adapter responding successfully!", |
| 144 | + requestEcho: requestBody, |
| 145 | + timestamp: new Date().toISOString(), |
| 146 | + }), |
| 147 | + }; |
| 148 | + } catch (error: any) { |
| 149 | + console.error("Error processing request:", error); |
| 150 | + |
| 151 | + // Return appropriate status code based on error type |
| 152 | + const statusCode = error.message.includes("Authorization") ? 401 |
| 153 | + : error.message.includes("hash") || error.message.includes("Audience") ? 400 |
| 154 | + : 500; |
| 155 | + |
| 156 | + return { |
| 157 | + statusCode, |
| 158 | + body: JSON.stringify({ |
| 159 | + error: error.message || "Internal server error", |
| 160 | + }), |
| 161 | + }; |
| 162 | + } |
| 163 | + }, |
| 164 | + policies: [aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole], |
| 165 | +}); |
| 166 | + |
| 167 | +const api = new apigateway.RestAPI("escExternalAdapterApi", { |
| 168 | + routes: [{ |
| 169 | + path: "/", |
| 170 | + method: "POST", |
| 171 | + eventHandler: adapterFunction, |
| 172 | + }], |
| 173 | + // Don't treat JSON as binary data |
| 174 | + binaryMediaTypes: [], |
| 175 | +}); |
| 176 | + |
| 177 | +export const adapterUrl = api.url; |
| 178 | +export const functionName = adapterFunction.name; |
| 179 | +export const functionArn = adapterFunction.arn; |
0 commit comments