Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-5-haiku-20241022· AnthropicHugging Face LMArena Human Preference 140K

I am a Principal Solutions Architect working for AWS. A customer would like to use…

  1. User

    I am a Principal Solutions Architect working for AWS. A customer would like to use Amazon CloudFront Functions to sign tokens using RS256 algorithm. I shared the code snippet below with them, which works very well. They get back to me with the message below, they use Java to generate the JWT and public/private key. Help me address each of the questions they've asked.

    Customer message

    Following are the question wrt to your code to accommodate validation of the token generated from the attached code:

    • What goes in the ‘data’, the token to be validated?
    • Does ‘signature’ remains constant? If not, how do we generate it?
    • In import key function - ‘kty’, ‘e’, ‘alg’, ‘ext’, ‘key_ops’ all remains constant or are these variable and what value values go into it if its not constant?
    • The ‘alg’ value used in your code is PS256, while the token generated using RS256, does this aligns or do we need to change out token generation algo?
    • What goes in the attribute ‘n’, public key? If public key, which part of public key or the whole key? - - Do we copy the plain key and put it in ‘n’ or does it requires and processing?

    Code I sent

    async function handler(event) {
        var request = event.request;
        var headers = request.headers;
    
        // 1. Validate presence of specific headers
        if (!headers['x-custom-header']) {
            return {
                statusCode: 400,
                body: "Missing required header: x-custom-header"
            };
        }
        
        // 2. Validate attributes in the header (example: x-custom-header must be 'allowed-value')
        if (headers['x-custom-header'].value !== 'allowed-value') {
            return {
                statusCode: 400,
                body: "Invalid value for x-custom-header"
            };
        }
        
        // 3. Add specific header values per request basis
        headers['x-added-header'] = { value: 'custom-value' };
    
        // 4. Manage cache key before accessing cache (example: add a custom query string parameter)
        if (!request.querystring) {
            request.querystring = '';
        }
        request.querystring += '&customCacheKey=true';
    
        // 5. RSA Signature
        const data = new TextEncoder().encode("Hello, world!");
        
        const signature = Uint8Array.from([54, 151, 202, 3, 254, 82, 161, 166, 224, 219, 170, 54, 201, 15, 210, 202, 144, 175, 51, 51, 74, 102, 63, 140, 42, 107, 178, 142, 254, 236, 35, 255, 132, 80, 65, 209, 215, 47, 7, 18, 14, 56, 253, 15, 113, 136, 203, 136, 111, 25, 77, 8, 160, 5, 91, 60, 2, 99, 60, 189, 62, 82, 45, 221, 45, 175, 42, 144, 56, 166, 228, 40, 191, 164, 22, 14, 211, 70, 216, 61, 56, 43, 65, 82, 51, 255, 78, 223, 61, 173, 202, 60, 243, 112, 253, 149, 166, 161, 202, 40, 10, 228, 35, 32, 140, 15, 145, 76, 252, 128, 133, 88, 251, 24, 210, 176, 218, 148, 217, 197, 210, 83, 159, 29, 163, 151, 160, 149, 177, 182, 67, 4, 166, 128, 40, 80, 87, 233, 17, 251, 34, 126, 41, 153, 154, 37, 106, 53, 207, 160, 181, 183, 5, 183, 110, 65, 204, 205, 186, 67, 167, 95, 80, 8, 168, 253, 9, 199, 238, 163, 253, 242, 45, 54, 174, 57, 24, 150, 192, 78, 213, 144, 173, 114, 77, 121, 215, 77, 103, 176, 58, 49, 12, 201, 199, 29, 144, 105, 55, 107, 111, 161, 235, 42, 45, 87, 84, 209, 7, 162, 142, 147, 137, 130, 176, 126, 66, 142, 234, 153, 182, 216, 253, 96, 119, 190, 129, 174, 234, 79, 218, 208, 142, 94, 160, 226, 159, 143, 231, 219, 227, 41, 246, 41, 87, 65, 80, 186, 241, 121, 125, 223, 91, 131, 119, 218]);
        
        const subtle = require('webcrypto').subtle;
      
        const key = await importKey();
        
        const isValid = await subtle.verify(
            {
                name: "RSA-PSS",
                saltLength: 32 // Typically 32 bytes (256 bits) for RSA-PSS with SHA-256
            },
            key,
            signature,
            data
        );
        
        if(isValid){
            console.log("Verification succeeded");
        }else{
            console.log("Verification failed");
        }
        
        return {
            statusCode: 200,
            statusDescription: 'OK',
            headers: {
                'content-type': { value: 'text/plain' }
            },
            body: isValid ? 'Verification succeeded' : 'Verification failed'
        };
    }
    
    async function importKey() {
        return await require('webcrypto').subtle.importKey(
            'jwk',
            {
                kty: "RSA",
                e: "AQAB",
                n: "pjsjPB1tsI1RrnJL3L50UyHwwDQJbFHnIfhAFCP-3xTY0oeb9Q6uJU-MXcDTCDnAoRdwZi6oGsjE76NnVxskaSgJdW6QipOKyMOlJxBVhxQTMyNZvLq-LygiHUQ-QFKGtovgQyzdiZKcouFEgyOnht3whbl9d4J8K-H8C0nj-owiuWyy1UpZvxpN1APlEU4tMbchF2BRRpm0TE9JTRdX81YPKSi9NxSwiEfUpubZNiWv0zwProAoH92L_I0byCwYGdg8igEkryRVn2U3fult8FVQrOQzPRFof7jE5wrqrqQf7uQ6IUPsGEcpEyt0ygXavhFT_VxipEmvOGLkTcD9ew",
                alg: "PS256", // Changed from RS512 to PS256 for RSA-PSS with SHA-256
                ext: true,
                key_ops: ["verify"]
            },
            {
                name: "RSA-PSS",
                hash: "SHA-256"  // Changed to SHA-256 to match PS256
            },
            true,
            ["verify"]
        );
    }
    

    Please look through the above questions, we need these to be answered to have full command over the code and make it work for out token validation.

  2. Claude Assistant

    I'll help you address each of the customer's questions regarding the CloudFront Functions JWT validation code:

    1. What goes in the 'data', the token to be validated?

      • In the current code, data is a hardcoded string "Hello, world!" encoded as a Uint8Array. For JWT validation, you would typically want to pass the entire JWT token (or more specifically, the part being signed) as the data.
      • For a JWT, this would typically be the base64-encoded header and payload concatenated with a period (.). So data would be something like:
        const data = new TextEncoder().encode(
          `${base64EncodedHeader}.${base64EncodedPayload}`
        );
        
    2. Does 'signature' remain constant? If not, how do we generate it?

      • The signature should NOT be constant. It's specific to each token and is generated during token creation.
      • In the Java JWT generation, the signature will be created using the private key and the algorithm (RS256 in this case).
      • You would need to extract the actual signature from the JWT and convert it to a Uint8Array for verification.
    3. Import key function parameters:

      • kty: Remains "RSA" for RSA keys (constant)
      • e: Usually "AQAB" for most RSA public keys (typically constant)
      • alg: Should match the algorithm used (RS256 in this case)
      • ext: Usually true for keys that can be exported
      • key_ops: Typically ["verify"] for public keys used in verification
    4. Algorithm Alignment:

      • The code uses PS256 (RSA-PSS), but the customer is using RS256 (RSASSA-PKCS1-v1_5)
      • You'll need to modify the code to use RSASSA-PKCS1-v1_5 instead of RSA-PSS:
      async function importKey() {
        return await require('webcrypto').subtle.importKey(
          'jwk',
          {
            kty: "RSA",
            e: "AQAB",
            n: "...", // public key modulus
            alg: "RS256", // Changed from PS256 to RS256
            ext: true,
            key_ops: ["verify"]
          },
          {
            name: "RSASSA-PKCS1-v1_5",
            hash: "SHA-256"
          },
          true,
          ["verify"]
        );
      }
      
      // And in the verify method:
      const isValid = await subtle.verify(
        {
          name: "RSASSA-PKCS1-v1_5",
          hash: "SHA-256"
        },
        key,
        signature,
        data
      );
      
    5. Attribute 'n' (public key modulus):

      • n contains the base64url-encoded modulus of the public key
      • This is typically the numeric part of the public key, not the entire key
      • In the JWK (JSON Web Key) format, n is the base64url-encoded modulus
      • You should use the exact n value from the JWK generated by the Java JWT library
      • No additional processing is needed - just copy the n value directly from the JWK

    Here's a more complete example of how you might modify the code for JWT verification:

    async function handler(event) {
        const jwt = event.request.headers['authorization'].value.split(' ')[1]; // Assuming Bearer token
        const [encodedHeader, encodedPayload, encodedSignature] = jwt.split('.');
        
        // Decode the signature
        const signature = base64UrlToUint8Array(encodedSignature);
        
        // Prepare data to verify (header and payload)
        const data = new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`);
        
        const subtle = require('webcrypto').subtle;
        const key = await importKey(); // Your key import function
        
        try {
            const isValid = await subtle.verify(
                {
                    name: "RSASSA-PKCS1-v1_5",
                    hash: "SHA-256"
                },
                key,
                signature,
                data
            );
            
            return {
                statusCode: isValid ? 200 : 401,
                body: isValid ? 'Token is valid' : 'Token is invalid'
            };
        } catch (error) {
            return {
                statusCode: 500,
                body: 'Verification error'
            };
        }
    }
    
    // Utility function to convert base64url to Uint8Array
    function base64UrlToUint8Array(base64Url) {
        // Convert base64url to standard base64
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        // Pad with = if needed
        const padded = base64 + '=='.slice(0, (4 - base64.length % 4) % 4);
        // Decode to Uint8Array
        return new Uint8Array(atob(padded).split('').map(char => char.charCodeAt(0)));
    }
    

    Key changes:

    • Switched from PS256 to RS256
    • Changed verification method to RSASSA-PKCS1-v1_5
    • Added base64url decoding for signature
    • Prepared data from JWT header and payload

    Note: This is a basic example and doesn't include full JWT validation (like checking expiration, issuer, etc.). You'd want to add those checks in a production environment.