table azure_config {
  "azure_account_key": "YOUR-ACCOUNT-KEY-HERE",
  "azure_account_name": "YOUR-ACCOUNT-NAME-HERE",
  "azure_blob_container" : "BLOB-CONTAINER-NAME-HERE"
}

sub create_azure_authorization_header {
  declare local var.azure_account_name STRING;
  declare local var.azure_account_key STRING;
  declare local var.azure_blob_container STRING;
  declare local var.decoded_access_key STRING;
  declare local var.canonical_headers STRING;
  declare local var.canonical_resource STRING;
  declare local var.string_to_sign STRING;
  declare local var.hmac_base64 STRING;
  
  if (!bereq.http.Authorization) {
  
    # Fetch Azure config
    set var.azure_account_name = table.lookup(azure_config,"azure_account_name", "");
    set var.azure_account_key = table.lookup(azure_config,"azure_account_key", "");
    set var.azure_blob_container = table.lookup(azure_config,"azure_blob_container", "missing-container");

    # API version to use when creating the digest.
    # Header must be passed to Azure, so write directly to header
    set bereq.http.x-ms-version = table.lookup(azure_config,"azure_api_version","2017-11-09");

    # Set the Time to now, token is valid for 45 minutes.
    # Header must be passed to Azure
    set bereq.http.x-ms-date = now;

    # Base64 decode the storage access key to a binary string
    set var.decoded_access_key = digest.base64_decode(var.azure_account_key);
  
    # Canonical headers must be sorted and concatenated with
    # newlines.  If there are query params there is a separate
    # spec for that, not supported here yet
    set var.canonical_headers = "x-ms-date:" + bereq.http.x-ms-date + "%0A" + "x-ms-version:" + bereq.http.x-ms-version + "%0A";

    # Canonical Resource is /ACCOUNT/CONTAINER/FILE
    set var.canonical_resource = "/" + var.azure_account_name + "/" + var.azure_blob_container + bereq.url;

    # Construct everything properly before signing
    # We are adding 4 newlines here, however the spec says we
    # can override any of these 4 headers with values if we want.
    # For now we are just blanking them out
    # We use ShareKeyLite instead of ShareKey becasue we can not get IMS/INM value
    # to revalidate from varnish to backend.
    set var.string_to_sign = "GET" + std.strrep(LF, 4) + var.canonical_headers + var.canonical_resource;

    # HMAC-sign with SHA256 and Base64-encode the result
    set var.hmac_base64 = digest.hmac_sha256_base64(var.decoded_access_key, var.string_to_sign);

    # Construct the Authorization Header which is "SharedKeyLite AccountName:SIGNATURE"
    set bereq.http.Authorization = "SharedKeyLite " + var.azure_account_name + ":" + var.hmac_base64;
    set bereq.url = "/" + var.azure_blob_container + bereq.url; 
  }
}