Introducing Edgio Applications v7Find out what's new.
Edgio
Edgio

Basic Request Signing

Request signing is a technique used to verify the authenticity and integrity of a request. It involves adding a signature to the request, which is generated using a secret key and specific request parameters. This signature can then be verified by the recipient to ensure that the request has not been tampered with and originated from a trusted source.
Request signing can be used in various scenarios, such as API authentication, secure communication between services, and preventing replay attacks. By including a signature with each request, both the sender and receiver can have confidence in the integrity and authenticity of the data being exchanged.

Router Configuration

In the Edgio router, you can use the edge_function feature to specify the path to the edge function that will handle the request signing and verification. Because this edge function is designed to handle both signing and verification, we’ll match any request beginning with /sign/ or /verify/, and capture the remaining path for use in the edge function.
JavaScriptroutes.js
1import {Router, edgioRoutes} from '@edgio/core';
2
3export default new Router()
4 .use(edgioRoutes)
5
6 .match(/\/(sign|verify)\/(.*)/, {
7 edge_function: './edge-functions/main.js',
8 });

Edge Function

The edge function will be responsible for generating a signed URL for the given request, or verifying the signature of a request and forwarding it to the origin. The edge function will be invoked for any request that matches the route above, so we’ll need to check the request path to determine whether we are signing or verifying the request.
In either case, we’ll need to generate a signature using a cryptographic hash function. In this example, we’ll use the HMAC-SHA1 algorithm, which is a widely used cryptographic hash function. The signature will be generated using a secret key, which should be defined as an environment variable in the Edgio Console. The secret key should never be shared publicly, and should be kept private to ensure that the signature cannot be forged.
The Edge Function runtime does not currently support a native crypto library, so a third-party library to generate the signature is needed. In this example, we’ll use the crypto-js library.
JavaScriptedge-functions/main.js
1import {URL} from 'whatwg-url';
2import HmacSHA1 from 'crypto-js/hmac-sha1';
3import Base64 from 'crypto-js/enc-base64';
4
5export async function handleHttpRequest(request, context) {
6 // ** IMPORTANT **
7 // Secret key should be defined as an environment variable in the Edgio console
8 const secretKey = '$0m3th!ngS3cr3t'; // context.environmentVars.REQ_SIGNING_SECRET_KEY;
9
10 if (request.url.includes('/sign/')) {
11 return generateSignedUrl(request, secretKey);
12 }
13
14 return verifyAndFetch(request, secretKey);
15}
16
17/**
18 * Generates a signed URL for the given URL and secret key
19 * @param {URL} url
20 * @param {string} key
21 */
22async function generateSignedUrl(request, key) {
23 const url = new URL(request.url);
24
25 // Replace /sign/ with /verify/ in the URL since we are generating a signed URL for verification
26 url.pathname = url.pathname.replace('/sign/', '/verify/');
27
28 const expirationMs = 1000 * 60 * 5; // 5 minutes
29 const expiry = Date.now() + expirationMs;
30 const dataToAuthenticate = url.pathname + expiry;
31
32 const hash = HmacSHA1(dataToAuthenticate, key);
33 const base64Mac = Base64.stringify(hash);
34
35 url.searchParams.set('mac', base64Mac);
36 url.searchParams.set('expiry', expiry.toString());
37
38 // respond with the signed URL that can be used to verify the request
39 return new Response(url.toString());
40}
41
42/**
43 * Verifies the MAC and expiry of the given URL. If the URL is valid, the request is forwarded to the origin.
44 */
45async function verifyAndFetch(request, key) {
46 const invalidResponse = (reason) =>
47 new Response(`Invalid request - ${reason}`, {status: 403});
48 const url = new URL(request.url);
49
50 if (!url.searchParams.has('mac') || !url.searchParams.has('expiry')) {
51 return invalidResponse('Missing MAC or expiry');
52 }
53
54 const expiry = Number(url.searchParams.get('expiry'));
55 const dataToAuthenticate = url.pathname + expiry;
56
57 const receivedMacBase64 = url.searchParams.get('mac');
58 const receivedMac = Base64.parse(receivedMacBase64);
59
60 const hash = HmacSHA1(dataToAuthenticate, key);
61 const hashInBase64 = Base64.stringify(hash);
62
63 // Ensure that the MAC is valid
64 if (hashInBase64 !== receivedMacBase64) {
65 return invalidResponse('Invalid MAC');
66 }
67
68 // Ensure that the URL has not expired
69 if (Date.now() > expiry) {
70 return invalidResponse('URL has expired');
71 }
72
73 // Forward the remaining request path after **/verify/* to the origin
74 url.pathname = url.pathname.split('/verify/')[1];
75
76 return fetch(url.toString(), {
77 edgio: {origin: 'web'},
78 });
79}