A corrupted attempt tally must fail the request, not reset the limit
A brute-force limit is a counter, and a counter is only as strong as the code that reads it back. If a malformed tally decodes as zero failures, or if an error handler deletes the key to get the endpoint working again, then anyone who can write junk into the store has found an attempt reset. We built the lockout in otpguard the other way round. Stored state the library did not write counts as a fault, and a fault is a different thing from a wrong code. The request fails, nothing is granted, and the key stays where it is.
The tally is state, and state is an interface#
A one-time-code flow in otpguard keeps nothing in the process. Everything a verification needs is a handful of keys per identifier, and the one that matters here is fails:<id>, holding an encoded AttemptRecord. We chose that deliberately, since it lets any number of workers share one flow and lets a lock survive a restart, and it also means the control's state lives in a store the library does not own exclusively. The Redis adapter says so in its own docstring:
class RedisStorage:
"""Adapter over a synchronous redis-py client.
Keys are prefixed so the library can share a database with the rest of the
application. Values come back as text whether or not the client decodes
responses itself.
"""Sharing a database is the normal way to deploy this. The consequence is that the bytes behind fails:<id> are reachable by anything else holding a connection, including another service with an overlapping prefix, a maintenance script, a restored snapshot taken from an older schema, or a debugging session that set a key by hand. None of that requires an attacker. But if any of it can make the tally read as "no failures yet", then you have an authentication bypass with extra steps, because the only thing standing between a six-digit code and a brute-force run is that number.
Whether malformed state can appear is already settled. What matters is what the library does on the one request where it appears.
Two helpful behaviours that are both resets#
The first tempting behaviour is tolerant decoding. A record that fails to parse is treated as absent, missing fields fall back to zero, a string where an integer was expected is coerced. The endpoint keeps working, nobody gets paged, and the lockout silently stops existing for that identifier. Tolerance here is indistinguishable from an attacker-supplied reset, since it is the same effect reached by a different route.
The second is recovery in the handler. It usually arrives during an incident, and it looks reasonable:
try:
ok = flow.verify(identifier, candidate)
except LockedOut as exc:
return too_many_requests(retry_after=exc.retry_after_seconds)
except ValueError:
store.delete(f"fails:{identifier}") # never do this
ok = flow.verify(identifier, candidate)That handler turns "one junk value can be written" into "the tally can be cleared on demand". It also turns a real corruption bug into something that never shows up in the logs twice. Both behaviours fail in the attacker's favour, and that is the one direction a refusal control must not fail in.
Strict decoding, and exactly one narrow tolerance#
AttemptRecord.decode refuses anything it did not write. The failure is a single ValueError with the text malformed attempt record, raised for a payload that is not JSON, a payload that is not a dict, and a locked_until that is neither absent nor a string that datetime.fromisoformat accepts:
@classmethod
def decode(cls, encoded: str) -> AttemptRecord:
try:
payload = json.loads(encoded)
except (TypeError, json.JSONDecodeError) as exc:
raise ValueError("malformed attempt record") from exc
if not isinstance(payload, dict):
raise ValueError("malformed attempt record")
raw = payload.get("locked_until")
if raw is None:
locked_until = None
elif isinstance(raw, str):
try:
locked_until = datetime.fromisoformat(raw)
except ValueError as exc:
raise ValueError("malformed attempt record") from exc
else:
raise ValueError("malformed attempt record")
return cls(
failures=_count(payload, "failures"),
locked_until=locked_until,
locks=_count(payload, "locks"),
)The counts go through _count, which reads failures and locks with a default of 0 and refuses any value that is not an int. It names bool explicitly, because True would otherwise pass as 1:
>>> AttemptRecord.decode('{"failures": 2}')
AttemptRecord(failures=2, locked_until=None, locks=0)
>>> AttemptRecord.decode('{"failures": true}')
ValueError: malformed attempt recordThat bool check is the part reviewers ask about. It exists because the tolerant version of this code is the bug: a tally of True compares as one failure, and a type-confused counter is a counter an attacker can steer. The frozen dataclass then closes the remaining gaps in __post_init__. Negative counts are rejected, and a locked_until without an offset is rejected through _require_aware, so a naive datetime cannot become a lock whose expiry depends on the server's local zone.
The single tolerance is the default of 0 in _count. A record written before locks existed decodes cleanly, with zero locks served. That is a value whose absence has a correct meaning, which is a different situation from a value whose content cannot be read. Encoding is symmetric about it: encode omits locks when it is zero, so the tolerance accepts exactly what the library itself produces, and nothing wider.
The same instinct runs through the code layer. HashedCode.decode demands exactly three parts around the $ separator and turns a base64 failure into ValueError("malformed hashed code"). There is one soft case, and the boundary is worth stating precisely. A well-formed value whose algorithm is not ALGORITHM makes verify_code return False. That value was written in the library's own format and simply cannot be matched, so what you have is a pending code that will not verify, a wrong code. A value that is not in the format at all was not written by the library, and that is a fault. Storage draws the line as well. MemoryStorage.incr passes an existing value through _as_counter and raises value at 'gate:alice' is not a counter when it finds a non-number, so a non-number does not become a fresh start.
Where the refusal lands inside verify#
Strict decoding only helps if it runs before anything else has a chance to act on the broken record. In OtpFlow.verify, the first step after reading the fails key is lockout.check(record, moment), and check decodes. A junk tally therefore raises before the code key is read, before register_failure runs, and before any set or delete touches the store.
store = MemoryStorage()
store.set("fails:alice", "not json")
flow.verify("alice", "482913") # ValueError: malformed attempt recordThe ordering is the whole design, and three things follow from it. The submission is never charged as a wrong code, so the corrupted record is not quietly overwritten by a well-formed one carrying a tally of one. The verification never reaches the digest, so no code can be spent while the limit is unreadable. And the junk is still in the store afterwards, byte for byte, for whoever has to work out how it got there.
Nothing in the flow catches ValueError. The README maps the fault to a 500 that grants nothing, and that is the correct shape for an application handler as well: no 400 inviting a retry, no fallback path, no cleanup. A 500 is an honest statement that the service cannot currently tell whether this identifier is allowed to submit a code, and the safe answer to that question is no.
What it costs to run#
It costs you an identifier that stays unusable until someone repairs the store. Every verification for that identifier fails as long as the junk is there, and because the value was not written by the library it carries whatever lifetime its writer gave it, possibly none, in which case it will not age out on its own. Repair is a deliberate human act: look at the value, work out the writer, then remove the key. We treat that deletion the way we treat any other manual clearing of a security counter, with the operator and the reason recorded, because from the user's side it is identical to the attack the strictness was built to refuse.
The operational requirement that comes with this choice is alerting. malformed attempt record must page someone. Left to sit in a 500 count, a per-identifier denial stays invisible until a support ticket arrives. In exchange, the failure mode is bounded and runs in one direction only: a corrupted tally costs availability for one identifier and does not cost a limit. For a control whose entire purpose is to refuse, that is the only trade we are willing to make.