Timestamped webhook signature package

You build a Go package that signs timestamps with raw webhook bodies and verifies HMAC-SHA256 headers against an injected time and tolerance. It accepts any matching v1 signature and authenticates before checking freshness.

Ticket

Build a Go package named webhooksig with Sign and Verify. Sign returns a timestamped HMAC-SHA256 header. Verify checks that header against the raw request body, a supplied time, and a freshness tolerance.

Webhook receivers need to reject forged callbacks and limit how long a captured request remains reusable. Signing the timestamp and body together prevents an attacker from changing an old timestamp to make a request appear fresh. This is the final optional module after Project documentation. No later Week 8 step depends on it, and timestamp validation does not replace event-ID deduplication for repeated deliveries inside the freshness window.

The provided tests call these exported declarations:

go
package webhooksig

import "time"

var (
    ErrBadHeader    error
    ErrStale        error
    ErrBadSignature error
)

func Sign(secret []byte, now time.Time, body []byte) string

func Verify(secret []byte, header string, body []byte, now time.Time, tolerance time.Duration) error

Acceptance criteria

  • Sign returns a header in the exact format t=<unix seconds>,v1=<lowercase hex>. Its HMAC-SHA256 input is the base-10 Unix timestamp, a period, and the raw body bytes, forming <unix seconds>.<body>.
  • A correctly signed request verifies successfully when its timestamp is 2 seconds before the supplied now and the tolerance is 5 minutes.
  • Verifying a signature against a modified body, including {"id":"evt_2"}, returns ErrBadSignature.
  • Verifying a signature with a different secret, including another-secret-0123456789, returns ErrBadSignature.
  • A correctly signed request whose timestamp is 5 minutes and 1 second before now, with a 5-minute tolerance, returns ErrStale.
  • A correctly signed request whose timestamp is 6 minutes after now, with a 5-minute tolerance, returns ErrStale.
  • A correctly signed request is accepted when its timestamp is exactly 5 minutes before now or exactly 5 minutes after now, with a 5-minute tolerance.
  • Changing a signed header's timestamp to a fresh timestamp without recomputing its signature returns ErrBadSignature.
  • A stale request with an invalid signature returns ErrBadSignature, not ErrStale. For example, t=1700000000,v1= followed by 64 zeroes must return ErrBadSignature when checked with now set to at.Add(time.Hour) and a 5-minute tolerance.
  • A header containing multiple v1 values verifies successfully when at least one candidate matches the expected signature.
  • Verify returns ErrBadHeader for an empty header, a missing timestamp, a missing signature, a non-numeric timestamp such as t=soon, a non-hexadecimal signature such as v1=zz, or a pair without an equals sign such as t1700000000.

Constraints

  • Use the now and tolerance arguments supplied to Verify when checking freshness.
  • Treat the tolerance boundary as inclusive for timestamps in both the past and the future.
  • Authenticate the signature before checking timestamp freshness.
  • Accept a request when any supplied v1 candidate matches.
  • Do not modify the provided tests.

Design direction

Keep header parsing, signature verification, and freshness validation as separate responsibilities inside the package. Any internal layout that meets the contract passes.

Construct the signed message from the timestamp and the original body bytes. Avoid decoding and re-encoding the body, because a change in JSON whitespace or field ordering changes the signed bytes. The standard library's HMAC and SHA-256 packages provide the primitives you need. Use hmac.Equal for signature comparisons.

Consider the order in which you report errors. A malformed header is different from a well-formed header with an incorrect signature. A stale request should only be reported after authentication succeeds. Keeping these cases distinct lets callers use errors.Is to handle each failure.

How to check your work

Run the optional package tests from the repository root:

bash
cd backend
make test W=8O1

Read the first failing assertion as the broken contract. Compare the actual header or returned error with the expected format or sentinel before investigating later failures.

Finished Exercise 8.13?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Implement the webhooksig package and its exported declarations.
  2. Sign the timestamp and raw body with HMAC-SHA256.
  3. Parse headers and support multiple v1 signatures.
  4. Return distinct errors for malformed, invalid, and stale requests.
  5. Verify inclusive past and future tolerance boundaries.
  6. Run make test W=8O1 successfully.

Commands

terminal
cd backend && make test W=8O1

Tests

  • TestW8O1_SignBuildsATimestampedHeaderOverTimestampDotBody in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_AFreshSignatureVerifies in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_ATamperedBodyIsABadSignature in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_AnotherSecretIsABadSignature in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_ReplayingAnOldRequestIsStale in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_ATimestampFromTheFutureBeyondTheToleranceIsStale in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_TheToleranceBoundaryIsInclusive in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_SwappingInAFreshTimestampBreaksTheSignature in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_AStaleRequestWithABadSignatureReportsTheBadSignature in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_AnyOfSeveralV1SignaturesMayMatchForKeyRotation in backend/internal/webhooksig/webhooksig_test.go
  • TestW8O1_MalformedHeadersAreBadHeaders in backend/internal/webhooksig/webhooksig_test.go