Search code examples
pythonamp-htmlpython-cryptography

How do I sign an AMP update-cache request with Python's cryptography package?


How do I sign a URL for AMP's update-cache API using Python's cryptography package?


Solution

  • This is the core signature logic that will determine the path and query parameters for your update-cache request. Here, domain is the actual domain for your site, not the special AMP subdomain one.

    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding
    from cryptography.hazmat.primitives import serialization
    
    def sign_amp_update_cache_url(private_key: bytes, domain: str, url: str) -> str:
        private_key = serialization.load_pem_private_key(private_key, password=None)  # or whatever your key's password is
        message = f"/update-cache/c/s/{domain}{url}?amp_action=flush&amp_ts={int(time.time())}"
        binary_signature = private_key.sign(
            message.encode("UTF-8"),
            padding.PKCS1v15(),
            hashes.SHA256()
        )
        encoded_signature = base64.b64encode(binary_signature, altchars=b"-_").replace(b"=", b"").decode("UTF-8")
        signed_url = f"{message}&amp_url_signature={encoded_signature}"
        return signed_url
    

    To finish preparing the request, you must compute the AMP cache subdomain for your domain, get the updateCacheApiDomainSuffix from caches.json, and concatenate the AMP cache subdomain, updateCacheApiDomainSuffix, and signed AMP update cache URL from the function above. Here are Google's docs on the process with examples of what the cache URL should look like.