polycratia

A signed offer should not depend on your JSON encoder

· 9 min read

A server that prices a request, signs the offer, and later checks the offer a client hands back has to decide which bytes the signature covers. Say "the JSON I sent" and you have signed key order, whitespace, numeric formatting, omitempty decisions and whatever the next release of the encoding library decides to emit. None of that is part of the offer. The signed bytes need a definition separate from the wire format, and the shape you pick for them decides whether you can ever add a field again.

I hit this first on legally binding e-signature work, where the signed artifact and the transported artifact are visibly different things and nobody argues about it. In HTTP APIs the distinction quietly gets skipped, because the JSON is sitting right there and signing it looks free. It is not free: it is a signature over a dependency's changelog.

The code below is from paygate402, an x402 payment gate I wrote for Go HTTP handlers. An unpaid request comes back as 402 with the terms the server accepts and a signed quote behind each one, and the client repeats the request with the quote it is answering in X-PAYMENT-QUOTE. The gate then has to establish that this is an offer it made, at the amount it made it, before it puts anything to a facilitator.

What a JSON signature actually commits to#

A quote on the wire is JSON:

go
type Quote struct {
    Amount    string    `json:"amount"`
    Asset     string    `json:"asset"`
    Network   string    `json:"network,omitempty"`
    Resource  string    `json:"resource,omitempty"`
    PayTo     string    `json:"payTo,omitempty"`
    Expiry    time.Time `json:"expiry"`
    Nonce     string    `json:"nonce"`
    Signature string    `json:"signature,omitempty"`
}

If the signature covered the marshalled bytes, three unrelated things would turn load-bearing. Struct field order, since that is the order encoding/json emits in. The omitempty tags, since adding or removing one changes the document. The time format, since time.Time marshals as RFC 3339 with whatever precision happens to sit in the value.

Worse, verification would need the exact bytes that arrived, held on to. Anything that decodes to a struct and re-encodes (a client library, a proxy, a test helper) destroys the signature without touching one field value. In this package a quote goes out inside a 402 body, comes back inside a header, and is decoded into a Quote along the way. There is a test whose whole job is to assert the signature survives that trip, and it can only pass because the signed bytes are not the JSON.

Lengths, not separators#

So the signed form gets built explicitly:

go
func (q Quote) Canonical() []byte {
    out := appendPart(nil, quoteDomain)
    for _, field := range q.canonicalFields() {
        if field.value == "" {
            continue
        }
        out = appendPart(out, field.name)
        out = appendPart(out, field.value)
    }
    return out
}

func appendPart(out []byte, part string) []byte {
    out = binary.AppendUvarint(out, uint64(len(part)))
    return append(out, part...)
}

Every part is a length followed by its bytes. That is the whole encoding, and it rules out the failure that hand-rolled signing strings keep hitting: a value that imitates the structure. Join fields with | and an asset identifier containing a | moves a boundary. Concatenate with no marker at all and the amount 1 with the asset 0x00…ff gives you the same bytes as the amount 10x00…ff with no asset at all. Put a length in front and there is no separator to forge, because there is no separator.

Schematically, with lengths written in decimal:

text
19 "paygate402/quote/v1"
 6 "amount"    5 "10000"
 5 "asset"    42 "0x…"
 6 "expiry"  10 "1800000060"
 7 "network"  4 "base"
 5 "nonce"   32 "ffffffffffffffffffffffffffffffff"

The signature itself is not in there: the mac method clears Signature before running HMAC-SHA256 over Canonical, so the field that carries the result is never an input to it.

The field's name is what makes a skip safe#

The field list is fixed and ordered by name:

go
func (q Quote) canonicalFields() []quoteField {
    expiry := ""
    if !q.Expiry.IsZero() {
        expiry = strconv.FormatInt(q.Expiry.UTC().Unix(), 10)
    }
    return []quoteField{
        {"amount", q.Amount},
        {"asset", q.Asset},
        {"expiry", expiry},
        {"network", q.Network},
        {"nonce", q.Nonce},
        {"payTo", q.PayTo},
        {"resource", q.Resource},
    }
}

Two decisions do the real work here, and they only work together.

Each field writes its own name. That is what makes the empty-field skip unambiguous. If the form were positional (seven values in order, empties written as zero-length parts) then skipping would be unreadable, because the bytes would no longer say which positions were present, and two different quotes could land on one byte string. The name travels with the value, so the signed bytes describe themselves, and leaving a field out reads as a statement instead of a gap.

That skip is the forward-compatibility story. A quote that does not set payTo produces canonical bytes with no payTo part. Add an eighth field in a later version and every quote that does not use it produces byte-identical output to the version before it. Signatures already issued keep verifying. For a priced offer that is not hypothetical: quotes have short lifetimes but not zero ones, so at any deploy there are outstanding offers in flight, and the alternative to this property is some clients getting ErrQuoteSignature on a quote the previous process legitimately signed.

The same rule gives clients nothing. Drop a field that was set and the bytes change and the signature fails. Stripping network to escape a term is one of the tampering cases the tests cover, alongside a cheaper amount, a later expiry and a different payee.

One detail follows from the encoding rather than from taste. The expiry is signed as whole Unix seconds, so sub-second precision is not part of the offer. The truncation therefore has to happen when the quote is issued, not when it is checked: Issue cuts the expiry with Truncate(time.Second) so the instant a client reads is the instant that was signed, and Expired compares now.Unix() with q.Expiry.Unix() at that same precision. Precision you do not sign has to come off before anybody sees it. Take it off afterwards and the client was shown a value the signature never covered.

One key, two documents#

The form opens with a domain tag that carries its own version:

go
const quoteDomain = "paygate402/quote/v1"
const receiptDomain = "paygate402/receipt/v1"

The gate signs two things. A quote is the offer behind a 402. A receipt is the record of a payment that settled, returned on the paid response for the payer to keep. They use the same appendPart and the same HMAC construction, and they share five field names: amount, asset, network, payTo, resource. Under one key and with no tag, "is this byte string a quote or a receipt?" becomes a question the verifier answers by inspection, and cross-type confusion is exactly the class of bug that signing was supposed to close. With the tag it is not a question at all. A receipt's bytes cannot be read as a quote's, because the first part differs.

The version in the tag is the other half. The skip rule absorbs added fields. It cannot absorb a rename, a reorder, or a change in how a value is rendered. Those take a new tag, so a changed layout gets new bytes instead of quietly reinterpreting bytes that were already signed.

What this costs#

Worth being plain about the bill, because it gets paid later and by someone else.

The field list is frozen. Names sit in the signed bytes, so renaming payTo breaks every signature ever issued. The order sits in the signed bytes too, so a new field goes in its alphabetical place rather than at the end where a Go programmer would naturally put it. Both constraints live in a comment above a slice literal, which is the weakest enforcement mechanism in the language.

Empty and absent are the same thing. A field can never be given a meaning for the empty string distinct from being unset, so required-ness has to live somewhere else. In this package it lives in Validate, which returns ErrQuoteIncomplete naming every missing field among amount, asset, nonce and expiry, and also refuses an amount that is not an unsigned integer, since 0.01 is not an amount in an asset's own units. Sign runs it first, so an unsignable quote gets refused rather than signed into something that verifies and means nothing.

And compatibility only runs one way. An old verifier handed a quote that uses a new field cannot reproduce the bytes and will reject it. That is the correct direction to fail in, but it is a real deploy ordering constraint: verifiers before signers.

What I would do differently#

I would not change the encoding. I would change how it is defended.

The invariant holding all of this up (this exact field list, in this exact order, with these exact names) is currently protected by a comment. A refactor that sorts the slice differently, or a rename driven by an editor, produces code that passes every behavioural test, because the tests sign and verify with the same build. What catches it is a golden vector: a fixed quote and its expected canonical bytes, asserted byte for byte. That test fails on exactly the change that would break production and on nothing else.

The second thing is documentation. A tag that says v1 is a promise to an implementation that is not mine. Right now the canonical form is described in doc comments, which is probably enough for a reader of the package and not enough for anyone writing the other side. A claimed version should have a written spec behind it, or it should not claim one.

Signing was the easy part here. Deciding what the bytes are, and still being able to answer that question after two years of changes, is where the work went...

react

$ new-project --brief

or email hey@polycratia.com