HMAC signing for cursors
You can authenticate a cursor before decoding its keyset position, allowing W2O1 to reject modified pagination requests without changing the restaurant-list contract.
Learning outcomes
- Explain why an unsigned base64url cursor lets a client change the restaurant ID used for keyset pagination.
- Distinguish a plain hash, encryption and HMAC, including the integrity guarantees HMAC provides.
- Generate and verify HMAC-SHA256 tags in Go using
crypto/hmacand compare them in constant time. - Explain the
v1.<payload>.<tag>format, why verification precedes parsing, and how secret configuration affects cursor behaviour. - Identify why signing does not prevent replay and why rotating the signing secret invalidates existing cursors.
The restaurant list uses Keyset pagination to continue from the last restaurant ID on the previous page. Its next_cursor is an Opaque cursor that the client sends back unchanged. But an unsigned cursor can be decoded, edited and encoded again, allowing a client to request a different pagination position.
For the optional exercise GET /v1/restaurants: signed cursors, you add an integrity check without changing the existing pagination behaviour. When CURSOR_SECRET is configured, the API signs each cursor and verifies it before trusting its contents.
Why encoding is not protection
The existing cursor uses base64url to make its payload safe to transport in a URL. Encoding changes how bytes are represented. It does not prevent a client from changing them.
Suppose a decoded cursor contains the restaurant ID 42. A client can change that ID to 900000 and encode the modified value.
Original position: 42
Modified position: 900000If the API accepts the modified cursor, the client can jump to a position that the API did not issue. The problem is not the pagination query. The problem is that the API has no way to distinguish its own cursor from an edited one.
Message authentication
A message authentication code (MAC) lets a receiver verify that a message was created by someone who knows a shared secret and has not been modified. HMAC combines a secret key with a cryptographic hash function. HMAC-SHA256 uses SHA-256 as that hash function.
The server calculates a tag from the secret and the cursor data. When the client sends the cursor back, the server calculates the expected tag again and checks whether it matches the supplied tag.
A plain hash cannot provide the same guarantee. If the server uses SHA-256 directly, a client can modify the cursor and calculate a new hash because the hashing operation does not require a secret.
Encryption solves a different problem. It protects confidentiality by making the original message unreadable without a decryption key. The restaurant ID in a cursor does not need to be secret. The API needs to detect edits, not hide the pagination position.
HMAC provides integrity and authenticity, not confidentiality.
Generating an HMAC in Go
Go's standard library provides crypto/hmac for keyed authentication and crypto/sha256 for the hash function. Both the signing and verification sides must use the same secret and exactly the same message bytes.
import (
"crypto/hmac"
"crypto/sha256"
)
func tagFor(secret []byte, message string) []byte {
mac := hmac.New(sha256.New, secret)
_, _ = mac.Write([]byte(message))
return mac.Sum(nil)
}
func verifyTag(secret []byte, message string, provided []byte) bool {
expected := tagFor(secret, message)
return hmac.Equal(provided, expected)
}mac.Sum(nil) returns the authentication tag. Verification computes the expected tag from the original message and checks it against the tag received from the client.
A change to even one byte of the authenticated message produces a different tag. Without the secret, a client cannot practically create a valid tag for an edited cursor.
Constant-time tag comparison
Do not compare authentication tags with ordinary equality. A normal comparison can stop as soon as it finds the first differing byte. Its execution time can therefore depend on how many initial bytes match.
An attacker who repeatedly submits guessed tags and measures response timing may gain information about the expected tag. Constant-time comparison avoids making the comparison time depend on the position of the first differing byte.
Go's hmac.Equal is designed for comparing authentication tags. Use it instead of == or bytes.Equal.
The comparison has one result: the supplied tag matches, or it does not. Do not reveal which part of a tag failed verification.
Signed cursor format
A signed cursor adds an authentication tag to the existing cursor payload. The token has three parts:
v1.<payload>.<tag>The payload retains the existing cursor representation, encoded with base64url without padding. The tag is the base64url encoding of the HMAC-SHA256 result.
The server authenticates the version and payload together:
v1.<payload>Including the version prevents someone from changing the token's version while keeping the same valid tag. It also gives you room to introduce a later format with different validation or payload rules.
A signed cursor must be deterministic. Given the same pagination position and the same signing secret, the API must produce the same cursor. Do not include a timestamp or random nonce in the authenticated message. Either would make two walks of the same query produce different cursors at the same position.
Verification before parsing
Treat the cursor as untrusted until its tag has been verified. Check the token structure and authenticate the encoded payload before decoding the pagination position.
The verification process follows this order:
- Split the token into exactly three parts: version, payload and tag.
- Reject an unsupported version or a missing part.
- Decode the supplied tag using base64url.
- Calculate the expected HMAC over the version and encoded payload.
- Compare the tags with
hmac.Equal. - Decode and parse the pagination position only after successful verification.
For example, changing the version or one character of the payload invalidates the tag. A truncated token or a token with extra content must also be rejected.
Parsing first is the wrong order. It lets unauthenticated input reach the pagination logic before the API has established that the token is valid.
Secret configuration
The API reads the signing secret from the CURSOR_SECRET environment variable. The secret must contain at least 32 bytes when configured. If it is set to a shorter value, the API must refuse to start.
When CURSOR_SECRET is not set, the API keeps the existing unsigned cursor behaviour. This preserves the restaurant list's existing contract when signing is not configured.
Do not embed the secret in source code or print it in application logs. The signer should retain its own copy of the secret so that later changes to the original byte slice cannot change the signing key.
Consistent error handling
Every invalid signed cursor should produce the same external API error. This includes malformed token layouts, unsupported versions, invalid base64url, modified payloads, incorrect tags and cursors signed with a different secret.
The cursor package can represent these failures with one sentinel error, such as ErrInvalid. The caller can identify it with errors.Is without relying on the internal error message.
Use error wrapping when you need to add context inside the application. Wrapping preserves the original error identity, allowing the handler to recognize the sentinel error.
The handler maps that error to the same HTTP status code and API error code for every invalid cursor:
HTTP/1.1 400 Bad Request
Content-Type: application/json{
"error": "invalid_cursor",
"message": "cursor is invalid or was not issued by this API"
}The message can explain the failure to a person, but the response should not reveal whether the version, payload or authentication tag failed validation.
Limits of signing
Signing prevents a client from creating a new valid cursor or modifying an existing one. It does not prevent replay. A client can submit an older cursor that the server genuinely issued. Preventing replay requires additional state or an expiration policy.
Secret rotation has a separate consequence: a cursor authenticated with an old secret will no longer verify with the new one. For ordinary restaurant pagination, the client can restart from the first page.
Cursor signing in the restaurant API
The existing restaurant service already creates and decodes cursors for the GET /v1/restaurants endpoint. The optional exercise adds signing around that existing behaviour. The client still follows next_cursor without interpreting its contents.
With CURSOR_SECRET configured, the same pagination position must always produce the same signed cursor. The API must verify the signature before parsing the position and return 400 invalid_cursor for modified, truncated or extended cursors. Without the environment variable, unsigned cursor behaviour remains available.
Check your understanding
A client decodes a restaurant cursor, changes its ID and encodes it again with base64url. The API accepts the modified cursor. What is missing?
References
Everything above is explained on this page; these are where it comes from (Go 1.27).