Skip to content

is_mac_valid

The is_mac_valid() function checks if a provided message with a MAC (Message Authentication Code) is valid. This is useful for validating signed URLs or requests.

Syntax

is_mac_valid(secret, message_mac, ttl, timestamp, separator_len)

Parameters

  • secret: The secret key used for MAC generation (bytes, literal).
  • message_mac: The message with the MAC to validate (bytes, field/expression).
  • ttl: Time-to-live in seconds (integer, literal).
  • timestamp: UNIX timestamp (integer, typically http.request.timestamp.sec).
  • separator_len: Length of the separator between the message and the MAC (integer, optional, defaults to 0).

Return Value

Returns a boolean value: true if the MAC is valid and the timestamp is within the TTL, false otherwise.

MAC Message Format

The expected format of the message_mac is [message][separator][timestamp]-[mac].

For example, in a signed URL: /data/?mac=169344654-P%2FfCbpJGVlevtLtYDMY%2FO0%2FNU8Wjg82PTZmuyxrimuA%3D

  • Message: /data/
  • Separator: ?mac= (length is 5)
  • Timestamp: 169344654
  • MAC: P%2FfCbpJGVlevtLtYDMY%2FO0%2FNU8Wjg82PTZmuyxrimuA%3D

The MAC value itself is an HMAC with SHA256, base64 encoded, and may also be URL-encoded. The function handles decoding automatically.

Example

# Validating a signed URL where the MAC is in the query string
is_mac_valid(
  "my_secret_key",
  http.request.uri,
  3600,
  http.request.timestamp.sec,
  5
)
In this example, separator_len is 5, which is the length of ?mac=.

Use Cases

  • Validating signed URLs to grant temporary access to resources.
  • Authenticating API requests without exposing a persistent token in the URL.
  • Ensuring message integrity and preventing tampering in custom communication protocols.