AMP Cache Update Script

2 min read

AMP Cache Update Script

2 min read

I recently read up on the AMP Project and installed the plugin to enable AMP-compatible pages for my blog. A couple weeks later I realized the code snippets in some of my blog posts were formatted incorrectly. I fixed the problem but the problem still appeared on the AMP cached version of the page. A quick search showed that there is an officially supported method of flushing the cache for any document. 

The instructions are fairly technical involving creating a digital signature and calling a specially crafted URL. There are several undocumented gotchas. For example an invalid SSL certificate is associated with the cache.cdn.ampproject.org domain so Chrome correctly refuses to make the request. I struggled to craft a valid request so much that I started to suspect whoever came up with this cache invalidation scheme was playing a cruel joke on me. The requirement to include a timestamp in the digital signature and as a request parameter makes sense from a security standpoint since it prevents replay attacks. However, the signature is only valid for +/- 1 minute from a given timestamp. This leaves you with a small window in which you have to run all of the commands required to sign and construct the request.

I created a Python script to automate the process. 

Prerequisites

  1. Create your private and public key
  2. Publish the public key to your website at /.well-known/amphtml/apikey.pub
  3. Install the requests and OpenSSL libraries for Python 3

Running the Script

To run the script:

chmod +x update_amp_cache.py
./update_amp_cache.py

The script asks for two inputs, 1) the URL of the document to be flushed and 2) The filesystem path to your private key.

You should enter the URL of the source document, not Google’s cache URL. For example, instead of https://www.google.com/amp/s/www.takaitra.com/mcp4151-digital-potentiometer-raspberry-pi/amp/ enter https://www.takaitra.com/mcp4151-digital-potentiometer-raspberry-pi/amp/. 

Future Work

  • Input validation
  • Verify that public key is installed at /.well-known/amphtml/apikey.pub
  • Make CacheUpdate class thread-safe

No Comments

Leave a Reply

I accept the Privacy Policy

×