Part 3 of 12 · 2 min read
The signature says who signed, and the nonce says how many times
A signature alone does not stop the same valid approval being presented twice; something has to be spent the first time it is used.
Think of a train ticket that is both stamped by the conductor (proving it is real) and punched the first time it is used (proving it cannot be used again). The stamp and the punch solve two different problems.
HMAC is a keyed hash proving a message was produced by someone holding the signing key, a nonce is a random value that makes each token unique. Single use means the executor remembers which nonces it has already accepted and refuses to accept the same one twice.
A worked example. A token is issued, then presented to the executor and accepted (ex.run(tok, ...) returns (True, "ok")). The exact same token, presented a second time, is rejected with "replayed" -- nothing about the token itself changed between the two calls; what changed is that its nonce is now in the executor's used set. Separately, a token whose last few characters are corrupted (a forged or tampered signature) is rejected with "bad signature" before the executor even looks at the nonce, because hmac.compare_digest catches the mismatch first.
The key lines. From code/mini-approvals/approvals.py:
# from code/mini-approvals/approvals.py
if p["nonce"] in self.used: return self._deny("replayed")
if p["approver"] == p["requester"]: return self._deny("self-approval")
if p["ver"] is not None and p["ver"] != state_version: return self._deny("state changed since approval")
approvers.add(p["approver"]); nonces.append(p["nonce"])
if len(approvers) < need:
return self._deny("not enough distinct approvers")
self.used.update(nonces)
Read it as: self.used.update(nonces) runs only after every other check has already passed. A token is never marked spent until the action it authorizes is actually about to run. That is why a failed attempt (wrong amount, say) on an otherwise-valid token does not burn it. The legitimate retry right after still works.
HMAC, nonce, single use
HMAC is a keyed hash proving a message was produced by someone holding the key. A nonce is a random value that makes each token unique. Single use means the executor remembers used nonces and refuses a second use.
Example: replaying the identical token a moment after its first successful use is rejected purely because its nonce is now in self.used -- the signature is still perfectly valid, which is the point: single use is enforced by the executor's memory, not by anything cryptographic in the token itself.