Skip to content

Security-sensitive boundaries

Difficulty: Advanced

Key concepts

  • trust boundary
  • input validation
  • allow-list
  • buffer overflow
  • integer overflow
  • least privilege
  • secrets handling
  • fail closed
  • fuzzing
  • What a Trust boundary is, how to find the ones in a design, and why the code at a boundary deserves different rules from the code behind it.
  • How to parse untrusted binary input in C++ so that no input, however hostile, can make the parser read outside its buffer, allocate without limit, or be fooled by integer wrap-around.
  • Why an allow-list beats a block-list, and why a parser should accept nothing it does not fully understand.
  • How to design interfaces for least privilege: each part gets only the powers it needs, so a logic bug in it can do only so much; and why that is not a sandbox.
  • How to handle secrets in a type that resists the common leaks, and what such a type cannot promise.
  • What failing closed means, and how to test all of this, including with a fuzzer.

The problem: data from people you have never met

Section titled “The problem: data from people you have never met”

A power company has thousands of electricity meters in the field. Every fifteen minutes each meter measures how much energy was used, and a few times a day it sends its readings to the company’s gateway over the internet. The gateway checks each upload and passes the readings on to storage, where billing uses them.

The meters are not the only ones who can reach the gateway. Anyone on the internet can send it bytes. Some senders are honest meters with a bug; some are curious; some want to crash the gateway, read other customers’ data, or make their own meter report less energy than it used. The gateway’s code is the first, and sometimes the only, thing standing between those bytes and the billing system.

That changes the question the code must answer. Behind the gateway, the question is “is this correct?”. At the gateway, it is “what is the worst thing this input could make my code do?”

A trust boundary is a place where data or control passes from a part of the system you trust less to one you trust more. Typical ones:

  • A network connection, as here. Anything can arrive.
  • A file that a user, another program, or an attacker could have written: an upload, a configuration file in a shared directory, a document someone sent you.
  • A plugin, or any code loaded at run time, as Plugin architecture discusses.
  • A process with fewer privileges asking one with more to do something on its behalf.
  • Environment variables and command-line arguments of a program that runs with more rights than the person starting it.

Finding them is a design activity: draw where data comes from and where it goes, and mark each place where the next part trusts the data more than its source deserves. The boundary is where checks are required; everywhere behind it, code may rely on what was checked.

Untrusted bytes cross one boundary, into the gateway. Only parsed, authenticated packets go further, and the gateway reaches the trusted side only through narrow interfaces.
Text description of the diagram

Three zones. On the untrusted side, the internet, are honest meters and broken or hostile senders; both send bytes to parse_packet. The trust boundary is the gateway, which holds parse_packet, which checks bounds, limits, and an allow-list, and passes its result to Gateway::receive, which authenticates and fails closed. On the trusted side are the CredentialStore, the reading store, and the audit log. Gateway::receive reaches each through one narrow interface: TokenVerifier, which can only verify, to the CredentialStore; ReadingSink, which can only append, to the reading store; and AuditLog, which can only record, to the audit log.

Diagram source (Mermaid)
flowchart LR
subgraph Untrusted["untrusted: the internet"]
  M["honest meters"]
  A["broken or hostile senders"]
end
subgraph Gateway["trust boundary: the gateway"]
  P["parse_packet<br/>bounds, limits, allow-list"]
  G["Gateway::receive<br/>authenticate, fail closed"]
  P --> G
end
subgraph Trusted["trusted: behind the gateway"]
  CS["CredentialStore"]
  ST["reading store"]
  AU["audit log"]
end
M -->|"bytes"| P
A -->|"bytes"| P
G -->|"TokenVerifier: verify only"| CS
G -->|"ReadingSink: append only"| ST
G -->|"AuditLog: record only"| AU
# Requirement Design consequence
R1 No input can make the gateway read or write outside its buffers Every read goes through a bounds-checked reader; no length from the input is trusted
R2 No input can make the gateway use unbounded memory or time A size limit checked first; every count limited before it is used
R3 Only packets that are entirely valid are accepted Allow-lists, exact lengths, no trailing bytes; anything unexpected is rejected
R4 Only known meters with the right token can store readings Authentication before anything is stored; one reply for “unknown” and “wrong”
R5 Secrets are not leaked through logs, copies, or timing A Secret type that does not print, copy, or compare early
R6 A logic bug in the gateway can do as little harm as possible The gateway gets narrow interfaces: verify, append, record
R7 Any failure, planned or not, rejects the packet One noexcept entry point; unexpected exceptions become “try later”, nothing stored

Meters send a small binary packet. Numbers are big-endian:

Bytes Field Rules
2 magic the characters MR
1 version 1
1, then n device ID length, ID 1 to 32 characters from a-z, 0-9, -
1, then n token length, token 16 to 64 bytes
2 reading count 1 to 100
8 each readings offset in seconds (unsigned 32-bit), then value in thousandths of a kWh (signed 32-bit)

Offsets start at 0, increase strictly, and stay within one day. Nothing may follow the last reading. A real meter would authenticate with a key and a vetted cryptographic protocol, as the callout below explains; this page uses a token to keep the focus on the boundary.

The quickest parser copies fields where the format says they are. This one was compiled and run in a scratch program with both compilers, with and without the sanitizers; both compilers built it at -Wall -Wextra -Wpedantic without a single warning.

It parses an honest packet correctly. It even has a length check. What the scratch runs showed:

  • The wrapping count. A packet that claims 8193 readings and carries one passes the check: out.count * 8 is computed as an int, 65544, and storing it in a 16-bit needed keeps only the low 16 bits, which are 8, exactly the size of the one reading that is there. The loop then reads 8193 readings. Without sanitizers, both builds crashed with a segmentation fault (exit 139); with AddressSanitizer, both reported a heap-buffer-overflow, a read past the end of the input. A crash is the lucky outcome: the same loop also writes past the end of values.
  • The long device ID. A 200-character ID makes memcpy write 200 bytes into a 33-byte array. The program printed a normal result and exited 0, with and without AddressSanitizer: the overflow stayed inside the RawPacket object, overwriting count and values, which AddressSanitizer does not check. Only UndefinedBehaviorSanitizer reported anything, and only for the terminator write; Clang’s build reported “index 200 out of bounds for type ‘char[33]’”, and GCC’s said the same with its own spacing. Memory corruption that produces a plausible answer is the most dangerous kind.
  • A bug nobody listed. A fuzzer, run on this function in a scratch build (see the testing section), found a third bug almost at once, within its first 50,000 inputs: in a packet that ends early, data[pos] reads the token’s length past the end of the input. AddressSanitizer reported a heap-buffer-overflow on the “skip the token” line.

No compiler warning helps here: even with -Wconversion added, which warns about many narrowing conversions, neither compiler flagged the line that stores out.count * 8 in 16 bits. The function has one check where it needs one before every read. That is the pattern of most parsing bugs: the code was written for the packets its author imagined, and the attacker sends a different one.

Step 2: a reader that cannot go out of bounds

Section titled “Step 2: a reader that cannot go out of bounds”

The fix is not more care in each line; it is a design in which the unsafe line is hard to write. All reads go through one small class:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

byte_reader.hpp
// Reads untrusted bytes from the front of a buffer. Every read checks
// how much is left first, so no read can go past the end, whatever the
// input says. The bytes must outlive the reader and any span it returns.
//
// The idea: the reader keeps a view of the whole buffer (bytes_) and a
// position (pos_), the index of the next unread byte. Each read hands back
// the bytes at the position and moves the position on. Nothing here throws
// (every function is noexcept): a read that cannot be done returns an empty
// std::optional instead, and the caller decides what that means.
class ByteReader {
public:
// Keeps a view of the caller's bytes; copies none of them. A span is a
// pointer and a length kept together, so the reader always knows where
// the buffer ends. `explicit` stops a span turning into a reader silently.
explicit ByteReader(std::span<const std::byte> bytes) noexcept : bytes_(bytes) {}
// How many bytes are still unread. The invariant pos_ <= bytes_.size()
// means this subtraction can never go below zero and wrap.
[[nodiscard]] std::size_t remaining() const noexcept { return bytes_.size() - pos_; }
// The next n bytes, or nullopt, and nothing consumed, if fewer remain.
// The only function that moves pos_, so this one check guards every read.
// The span it returns points into the caller's buffer: it is a view, not
// a copy, and is only valid while that buffer is alive.
[[nodiscard]] std::optional<std::span<const std::byte>> take(std::size_t n) noexcept {
// Not "pos_ + n > bytes_.size()": with an n from the input, that
// sum can wrap around to a small number and pass.
if (n > remaining()) return std::nullopt; // refuse before touching anything
// subspan(pos_, n): a view of n bytes starting at index pos_. Safe,
// because the check above proved pos_ + n <= bytes_.size().
const std::span<const std::byte> out = bytes_.subspan(pos_, n);
pos_ += n; // consume them; pos_ is still at most bytes_.size()
return out;
}
// One byte as a number from 0 to 255, or nullopt at the end of input.
// Every read below follows the same three steps: take the bytes, give
// up if take refused, then turn the bytes into a number.
[[nodiscard]] std::optional<std::uint8_t> u8() noexcept {
const auto b = take(1); // b is an optional span of one byte
if (!b) return std::nullopt; // an empty optional converts to false
// *b opens the optional to get the span; [0] is its only byte.
// std::to_integer is the explicit way to turn a std::byte into a number.
return std::to_integer<std::uint8_t>((*b)[0]);
}
// Multi-byte numbers are big-endian on the wire, whatever this
// machine uses, and are put together with shifts, not memcpy.
// Big-endian means the most significant byte comes first: the bytes
// 0x01 0x2C give (0x01 << 8) | 0x2C = 0x012C = 300. `<< 8` moves the first
// byte up into the high half, and `|` drops the second into the low half.
[[nodiscard]] std::optional<std::uint16_t> u16() noexcept {
const auto b = take(2);
if (!b) return std::nullopt;
// The shifts are done in 32 bits (byte_at returns uint32_t), and the
// result is at most 0xFFFF, so static_cast to 16 bits loses nothing.
return static_cast<std::uint16_t>((byte_at(*b, 0) << 8) | byte_at(*b, 1));
}
// The same with four bytes: the first lands in the top 8 of the 32 bits.
[[nodiscard]] std::optional<std::uint32_t> u32() noexcept {
const auto b = take(4);
if (!b) return std::nullopt;
return (byte_at(*b, 0) << 24) | (byte_at(*b, 1) << 16) | (byte_at(*b, 2) << 8) |
byte_at(*b, 3);
}
private:
// Byte i of b as an unsigned 32-bit number, ready to be shifted. Being
// unsigned and 32 bits wide, it has room for a shift of up to 24 and keeps
// every result a plain unsigned number, with no sign to worry about.
// Callers only pass an i that take() has already proved is in range.
static std::uint32_t byte_at(std::span<const std::byte> b, std::size_t i) noexcept {
return std::to_integer<std::uint32_t>(b[i]);
}
std::span<const std::byte> bytes_; // the whole input; never changed after construction
std::size_t pos_ = 0; // invariant: pos_ <= bytes_.size()
};
  • A view, not a pointer and a size. std::span<const std::byte> keeps the buffer and its length together. std::byte is not a number, so the bytes cannot be used in arithmetic by accident; the reader converts them explicitly with std::to_integer.
  • One check, in one place. take(n) is the only function that moves the position, and it refuses any n larger than what is left. Everything else is built on it, so the check cannot be forgotten.
  • The check cannot overflow. n > remaining() compares two sizes that are both valid. The tempting pos_ + n > bytes_.size() adds a number from the input to a position, and for a large enough n the sum wraps around to something small and passes. With a position of at most 1024 and a one-byte length that cannot happen, but the safe form costs nothing and stays safe when a later version reads a 64-bit length.
  • Failure is explicit. Every read returns std::optional, and a failed read consumes nothing. That makes failure hard to ignore, not impossible: [[nodiscard]] only warns when a result is thrown away, and * on an empty optional is still undefined behaviour. The parser uses *in.u32() for the readings without checking each one, and that is safe only because the exact-length check just before guarantees the bytes are there; its comment says so, because a later edit that moved the check would make those reads unsafe.
  • Byte order is explicit. Numbers are built with shifts from bytes, in the order the format defines, not copied with memcpy into an integer, which would depend on the machine’s byte order and on alignment.

Step 3: a parser that accepts only what it understands

Section titled “Step 3: a parser that accepts only what it understands”

The result types and limits:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

packet.hpp
// Every limit an attacker could otherwise choose for us. Plain values with
// defaults, so Limits{} is the normal configuration and a test can change
// one field. The parser reads them; it never trusts a size from the packet
// without comparing it with one of these first.
struct Limits {
std::size_t max_packet_bytes = 1024; // checked before anything is read
std::size_t max_readings = 100; // bounds the vector the parser builds
std::uint32_t max_span_seconds = 86'400; // one packet covers at most a day
};
// One meter reading, after parsing. The value is a whole number of
// thousandths (1500 means 1.5 kWh), so no floating-point rounding is involved.
struct Reading {
std::uint32_t offset_seconds = 0; // from the first reading
std::int32_t value_milli = 0; // thousandths of a kilowatt-hour
};
// A packet that has passed every check. The parser is the only code that
// makes one from bytes, so code that holds a Packet can rely on its rules.
// It owns its data: a string, a Secret, and a vector, all by value.
struct Packet {
std::string device_id; // checked: only [a-z0-9-], so safe to log
Secret token; // never logged, never compared with ==
std::vector<Reading> readings;
};
// Why a packet was refused: one value for each check in parse_packet.
// The gateway logs it for operators but does not tell the sender.
enum class ParseError {
too_large,
truncated,
bad_magic,
unsupported_version,
bad_device_id,
bad_token_length,
bad_reading_count,
bad_offsets,
trailing_bytes,
};
// Either a Packet or the reason there is none, never both and never
// neither. std::variant holds exactly one of the types listed; the caller
// asks which one it holds (std::get_if or std::holds_alternative).
using ParseResult = std::variant<Packet, ParseError>;
// Never reads outside bytes, never allocates more than the limits allow,
// and accepts nothing it does not fully understand.
// In: the raw bytes from the network, and the limits to apply. Out: a
// Packet, or the first ParseError found. Bad input is an expected outcome
// here, so it is returned, not thrown; only a failed allocation could throw.
[[nodiscard]] ParseResult parse_packet(std::span<const std::byte> bytes, const Limits& limits);
[[nodiscard]] std::string_view error_name(ParseError error) noexcept;

The parser:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

packet.cpp
// Reads the fields in the order the format lists them. Each field is read
// the same way: read it (an empty optional means the input ended, so
// `truncated`), then check its value against the rules, and return the
// matching ParseError at the first problem. Returning a ParseError or a
// Packet works because ParseResult, a std::variant, converts from either.
ParseResult parse_packet(std::span<const std::byte> bytes, const Limits& limits) {
// Size first: the cheapest check bounds the cost of all the others.
if (bytes.size() > limits.max_packet_bytes) return ParseError::too_large;
ByteReader in(bytes); // from here on, every read goes through the reader
// The magic number: two fixed bytes that say "this is a meter packet".
const auto magic = in.take(2);
if (!magic) return ParseError::truncated;
// std::byte{'M'} makes a byte from the character, so the two sides of
// != have the same type; a std::byte cannot be compared with a char.
if ((*magic)[0] != std::byte{'M'} || (*magic)[1] != std::byte{'R'}) return ParseError::bad_magic;
const auto version = in.u8();
if (!version) return ParseError::truncated;
if (*version != 1) return ParseError::unsupported_version;
// An allow-list: say what is valid, and reject everything else.
// A length field, then that many bytes. The length is checked against
// our own rule (1 to 32) before it is used, and take() still refuses it
// if the input has fewer bytes than it claims.
const auto id_length = in.u8();
if (!id_length) return ParseError::truncated;
if (*id_length < 1 || *id_length > 32) return ParseError::bad_device_id;
const auto id = in.take(*id_length);
if (!id) return ParseError::truncated;
// std::all_of is true only if allowed_in_id (defined above: a-z, 0-9,
// or '-') says yes for every byte. id-> reaches the span in the optional.
if (!std::all_of(id->begin(), id->end(), allowed_in_id)) return ParseError::bad_device_id;
const auto token_length = in.u8();
if (!token_length) return ParseError::truncated;
if (*token_length < 16 || *token_length > 64) return ParseError::bad_token_length;
const auto token = in.take(*token_length);
if (!token) return ParseError::truncated;
// token is still only a view into the input; it is copied into a Secret
// at the very end, once the whole packet is known to be good.
// Check the count against the limit before using it in arithmetic
// or to size anything; after that, count * 8 cannot overflow.
const auto count = in.u16();
if (!count) return ParseError::truncated;
if (*count < 1 || *count > limits.max_readings) return ParseError::bad_reading_count;
// std::size_t{*count} widens the 16-bit count before multiplying, so
// the product is computed in std::size_t; with count <= max_readings it
// is small. reading_bytes is 8: a u32 offset and a u32 value.
const std::size_t expected = std::size_t{*count} * reading_bytes;
if (in.remaining() < expected) return ParseError::truncated;
if (in.remaining() > expected) return ParseError::trailing_bytes;
// From here, exactly count * 8 bytes are left: every read below succeeds.
std::vector<Reading> readings;
readings.reserve(*count); // one allocation, of at most max_readings entries
for (std::size_t i = 0; i < *count; ++i) {
// * opens each optional without checking it. That is safe only
// because of the exact-length check above; move that check and
// these become reads of an empty optional, undefined behaviour.
const std::uint32_t offset = *in.u32(); // the length check above covers these
// A two's-complement conversion: well defined since C++20.
// For example 0xFFFFFFD8 on the wire becomes -40.
const auto value = static_cast<std::int32_t>(*in.u32());
// ?: picks the rule: the first reading must be at offset 0, and each
// later one must be strictly after the one before (back() is the
// last reading kept so far). Strictly, so a repeat is refused too.
const bool in_order = readings.empty() ? offset == 0 : offset > readings.back().offset_seconds;
if (!in_order || offset > limits.max_span_seconds) return ParseError::bad_offsets;
readings.push_back({offset, value}); // builds a Reading from the two values
}
// Every check passed: only now are the bytes copied into owned values.
// reinterpret_cast views the std::byte data as chars for std::string;
// the allow-list has already made sure every one is a-z, 0-9, or '-'.
// Secret(*token) copies the token bytes into the Secret, and
// std::move(readings) hands the vector over without copying it.
const auto* id_chars = reinterpret_cast<const char*>(id->data());
return Packet{std::string(id_chars, id->size()), Secret(*token), std::move(readings)};
}
How this code works: parse_packet

parse_packet walks through the packet once, from the first byte to the last, and the reader’s position only moves forward. Here is the honest packet the demo sends first (PacketSpec{} in wire.hpp), 59 bytes, with the position at which each field starts:

Bytes Field Value in the honest packet
0 to 1 magic M R
2 version 1
3 ID length 7
4 to 10 device ID meter-7
11 token length 21
12 to 32 token correct-horse-battery
33 to 34 reading count 00 03, which is 3
35 to 58 readings (0, 1500), (900, 1620), (1800, -40): 8 bytes each
  1. Size. 59 is not more than 1024, so parsing starts. A 2000-byte input stops here with too_large, before a single byte is read.
  2. Magic and version. take(2) returns a view of bytes 0 and 1, and the position moves to 2. u8() reads the version and moves it to 3.
  3. Device ID. u8() gives 7, which is between 1 and 32, so take(7) returns bytes 4 to 10, and std::all_of checks each of the seven characters against the allow-list. The position is now 11.
  4. Token. The length 21 is between 16 and 64; take(21) returns bytes 12 to 32. The position is now 33.
  5. Count and exact length. u16() reads 00 03: (0 << 8) | 3, so 3. That is between 1 and 100. expected is 3 times 8, 24, and remaining() is 59 minus 35, also 24: neither fewer nor more.
  6. Readings. The loop runs 3 times and reads two u32 values each time. The offsets 0, 900, 1800 start at 0 and increase, so every in_order is true. The last value arrives as FF FF FF D8, which the static_cast turns into -40.
  7. The result. Only now are the ID and the token copied out of the input, into a std::string and a Secret, and the readings vector is moved into the Packet.

Two hostile packets from the demo, followed the same way:

  • Cut off after 20 bytes. Steps 2 and 3 succeed and the token length 21 is read at byte 11, so the position is 12. Only 8 bytes are left, so take(21) refuses, nothing is consumed, and the result is truncated. The reader never looks past the 20 bytes it was given.
  • The wrapping count, 43 bytes. Everything up to the count is honest. u16() reads 8193, which is more than 100, so the result is bad_reading_count. The multiplication count * 8 that broke the flawed parser is never reached.

The order of the checks is a design:

  • Size first (R2). Before anything else, the packet must be at most max_packet_bytes. Every later check is then bounded too, so no input can make parsing expensive.
  • Limit, then use. The count is compared with max_readings before it is multiplied or used to reserve memory. After that check, count * 8 is at most 800, computed in std::size_t, so it cannot wrap; the flawed version did the multiplication before it knew the count was reasonable, and in a 16-bit type.
  • Exact length. The remaining bytes must be exactly the readings: fewer is truncated, more is trailing_bytes. Accepting extra bytes “to be lenient” means two programs can read the same packet differently, which is how attackers slip data past one check and into another system.
  • Allow-lists, not block-lists (R3). The device ID may contain only a-z, 0-9, and -. A block-list, “no newlines, no quotes”, is always one character short: it forgets the tab, the null byte, or the Unicode character that some later system treats as special. An allow-list also removes whole classes of problems for every later part that logs the ID or uses it as a file name or a database key. It does not replace their own defences: a database query still passes the ID as a parameter, never by joining strings, and this list even allows an ID that starts with -, which a command-line tool would read as an option.
  • Signed values from unsigned bytes. The value field is read as an unsigned 32-bit number and converted to std::int32_t. Since C++20 that conversion is defined to wrap the way two’s complement does, so 0xFFFFFFFF becomes -1 on every compiler; before C++20 it was implementation-defined.
  • Semantic checks too. Offsets must start at zero, increase, and stay within a day. They are cheap, they need nothing but the packet, and they stop a meter from sending the same reading twice in one packet. Duplicates across packets, such as a retry after try_later, need deduplication or replay protection, which this gateway does not have.
  • A Packet only at the end. The function returns ParseError at the first problem. Code that receives a Packet knows every rule above holds, which is the “parse, don’t validate” idea from API contracts and validation placement.

A token is a secret, and secrets leak in boring ways: printed in a log line, copied into a crash report, left in freed memory, or revealed by how long a comparison takes. A type can close some of those doors:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

secret.hpp
// A credential's bytes. The type exists to make the safe thing the easy
// one: it cannot be copied by accident, it prints as <secret>, it
// compares without stopping at the first difference, and it overwrites
// its bytes when it is destroyed.
// It owns its own copy of the bytes, in a vector, so it does not depend on
// the buffer the token arrived in staying alive.
class Secret {
public:
// Copies the bytes the span points at into this object's own vector
// (the vector constructor that takes a begin and an end iterator).
// `explicit`: a span of bytes never becomes a Secret without the
// reader seeing the word Secret. May throw std::bad_alloc.
explicit Secret(std::span<const std::byte> bytes) : bytes_(bytes.begin(), bytes.end()) {}
// `= delete` removes copying: writing a copy is a compile error, so the
// bytes cannot end up in a second place by accident.
Secret(const Secret&) = delete;
Secret& operator=(const Secret&) = delete;
// Moving is allowed. `= default` moves the vector, which hands over its
// buffer: the new Secret owns the same bytes, and the old one is empty.
Secret(Secret&& other) noexcept = default; // takes the bytes; copies nothing
// Move assignment: this Secret already holds bytes, and they are about
// to be released, so wipe them first, then take the other's buffer.
Secret& operator=(Secret&& other) noexcept {
wipe();
bytes_ = std::move(other.bytes_);
return *this;
}
// The destructor runs whenever a Secret goes away (end of scope, or
// the Packet holding it is destroyed), so the wipe cannot be forgotten.
~Secret() { wipe(); }
[[nodiscard]] std::size_t size() const noexcept { return bytes_.size(); }
// Takes as long for a near miss as for a total miss, for secrets of
// one length; the length itself is not hidden.
[[nodiscard]] bool equals(std::span<const std::byte> other) const noexcept;
// Compares with another Secret by passing its bytes to the function above
// (a vector converts to a span without copying).
[[nodiscard]] bool equals(const Secret& other) const noexcept { return equals(other.bytes_); }
// `out << secret` prints the fixed text <secret>, never the bytes. The
// parameter has no name because the function never looks at it.
// `friend` makes it a free function written inside the class; the
// compiler finds it whenever a Secret is printed with <<.
friend std::ostream& operator<<(std::ostream& out, const Secret&) { return out << "<secret>"; }
private:
void wipe() noexcept; // overwrites every byte with zero (secret.cpp)
std::vector<std::byte> bytes_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

secret.cpp
// True if other holds exactly the same bytes, in the same order. Throws
// nothing. Different lengths are refused at once (the length is not hidden).
bool Secret::equals(std::span<const std::byte> other) const noexcept {
if (other.size() != bytes_.size()) return false;
// Look at every byte, and decide only at the end. An early return at
// the first difference would let an attacker who can time many
// attempts learn the secret one byte at a time.
// `a ^ b` (exclusive or) has a 1 bit wherever the two bytes differ, so
// it is zero only for equal bytes. `|=` collects those bits: once any
// pair differs, difference stays non-zero to the end. For example,
// 'y' ^ 'z' is 0x79 ^ 0x7A = 0x03, so one wrong byte is enough.
std::byte difference{0};
for (std::size_t i = 0; i < bytes_.size(); ++i) difference |= bytes_[i] ^ other[i];
return difference == std::byte{0}; // zero means no byte differed
}
// Sets every byte to zero. The vector keeps its size; only the values
// change. Called by the destructor and by move assignment.
void Secret::wipe() noexcept {
// Writes through a volatile pointer, which the compiler may not
// remove as it may remove writes to memory that is about to be freed.
volatile std::byte* p = bytes_.data();
for (std::size_t i = 0; i < bytes_.size(); ++i) p[i] = std::byte{0};
}
  • It prints as <secret>. Code that writes a Packet’s token to a log by mistake writes nothing useful. A type with no operator<< would make that a compile error instead, which is stricter; this one chooses not to break generic code that prints whatever it is given.
  • It cannot be copied. Every copy is one more place the bytes live, and one more to wipe. A move transfers the bytes without copying them, and moves are noexcept.
  • It compares in time that does not depend on where the bytes differ. An early-exit comparison, such as == on strings, stops at the first different byte. An attacker who can time many attempts can then guess the secret one byte at a time, because a right first byte takes slightly longer to reject. equals looks at every byte and decides at the end. The length is still revealed, which is usual; tokens of one fixed length avoid even that.
  • It wipes its bytes when it is destroyed. A plain loop that writes zeros to memory about to be freed may be removed by the optimiser, because no one reads the zeros. Writing through a volatile pointer is the usual portable way to keep the writes.

Step 5: least privilege, and failing closed

Section titled “Step 5: least privilege, and failing closed”

The gateway needs to do three things on the trusted side: check a token, store readings, and tell the operators what happened. It gets exactly those three powers, each as its own interface:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

gateway.hpp
// Each port grants the gateway one narrow power, and nothing more.
// A port is an abstract class: `virtual ... = 0` declares a function with
// no body here, which a concrete class (an adapter) must provide. The
// gateway calls through the port and never knows which adapter it has.
// The virtual destructor makes destroying an adapter through a port safe.
// Can check a device's credential. Cannot list devices, read a stored
// token, or add a device. verify is const (checking changes nothing) and
// noexcept (it reports a failure as false, never by throwing).
class TokenVerifier {
public:
virtual ~TokenVerifier() = default;
[[nodiscard]] virtual bool verify(std::string_view device_id,
const Secret& presented) const noexcept = 0;
};
// The one exception the gateway expects from storage. Its own type, so
// the gateway can catch it apart from every other error.
class StorageUnavailable : public std::runtime_error {
public:
using std::runtime_error::runtime_error; // reuse runtime_error's constructors
};
// Can add readings for a device. Cannot read, change, or delete any.
// Stores all of the readings or none: if append throws, nothing was
// stored. Throws StorageUnavailable if the store cannot be reached.
// The readings arrive as a span: a view of the caller's vector, not a copy.
class ReadingSink {
public:
virtual ~ReadingSink() = default;
virtual void append(std::string_view device_id, std::span<const Reading> readings) = 0;
};
// Records security-relevant events for the operators. Must not throw.
class AuditLog {
public:
virtual ~AuditLog() = default;
virtual void record(std::string_view event, std::string_view detail) noexcept = 0;
};

This is least privilege applied to interfaces (R6). The credential store can also add devices, and the reading store could read, change, and delete readings, but the gateway cannot reach any of that: it holds a const TokenVerifier& and a ReadingSink&, not the store objects. A logic bug in the gateway’s code can then only check tokens, append readings, and write audit lines. Notice that append takes any device ID: nothing in these types ties it to a successful verify, so a gateway with the checks in the wrong order could still store readings for a device it never authenticated. A stronger design has verify return a small AuthenticatedDevice value that only a verifier can create, and has append require one; it was not built here.

These types limit what code that is correct but mistaken can do. They are not a sandbox: an attacker who corrupts memory inside the process can reach anything the process can, whatever the types say, which is why process isolation, in the table below, is a separate layer. The same thinking applies at every scale: a process that runs as a user with no rights, a database account that can only insert, a file opened read-only.

The gateway itself:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

gateway.hpp
// What a device is told. Deliberately vague: "unauthorized" does not
// say whether the device ID or the token was wrong, and "malformed"
// does not say which check failed. The audit log has the details.
enum class ReplyCode { accepted, malformed, unauthorized, try_later };
// The whole answer to a device. The default code is try_later, so a Reply
// that is not filled in properly still refuses rather than accepts.
struct Reply {
ReplyCode code = ReplyCode::try_later;
std::size_t readings = 0; // how many were stored, if accepted
};
[[nodiscard]] std::string_view reply_name(ReplyCode code) noexcept;
// The trust boundary itself. It holds references to the three ports, so
// it owns none of them: whoever builds the gateway owns the adapters.
class Gateway {
public:
// The ports must outlive the gateway.
Gateway(const TokenVerifier& verifier, ReadingSink& sink, AuditLog& audit,
Limits limits) noexcept
: verifier_(verifier), sink_(sink), audit_(audit), limits_(limits) {}
// Never throws, and never accepts by mistake: any failure it did not
// expect becomes try_later, with nothing stored.
[[nodiscard]] Reply receive(std::span<const std::byte> bytes) noexcept;
private:
// References, not copies: each names an object that lives elsewhere.
// verifier_ is a reference to const, so the gateway can only call verify.
const TokenVerifier& verifier_;
ReadingSink& sink_;
AuditLog& audit_;
Limits limits_; // a copy: small, and fixed for the gateway's life
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

gateway.cpp
// Handles one upload: parse, then authenticate, then store, stopping at the
// first step that fails. The whole body sits in a try block, and the catch
// blocks turn any exception into a try_later reply, so nothing can escape
// this noexcept function (an exception escaping noexcept would end the
// program with std::terminate).
Reply Gateway::receive(std::span<const std::byte> bytes) noexcept {
try {
ParseResult parsed = parse_packet(bytes, limits_);
// std::get_if<ParseError>(&parsed) gives a pointer to the error if
// the variant holds one, or nullptr if it holds a Packet. Declaring
// it inside the if makes the test "did parsing fail?".
if (const ParseError* error = std::get_if<ParseError>(&parsed)) {
audit_.record("rejected", error_name(*error)); // details for operators
return {ReplyCode::malformed}; // builds a Reply; readings stays 0
}
// Here the variant must hold a Packet, so std::get cannot throw. A
// const reference looks at the Packet inside `parsed`, without a copy.
const Packet& packet = std::get<Packet>(parsed);
if (!verifier_.verify(packet.device_id, packet.token)) {
audit_.record("unauthorized", packet.device_id); // the ID, never the token
return {ReplyCode::unauthorized};
}
// Only now does anything the device sent reach the system.
// The vector converts to the span append takes, and the string to a
// string_view, with no copying. append may throw StorageUnavailable,
// or any other exception; the catch blocks below handle both.
sink_.append(packet.device_id, packet.readings);
return {ReplyCode::accepted, packet.readings.size()};
} catch (const StorageUnavailable&) { // the failure the design expects
audit_.record("storage_unavailable", "");
return {ReplyCode::try_later};
} catch (...) { // `...` catches every other exception, whatever its type
// Fail closed: an error nobody planned for is not a reason to
// let a packet through, or to tell the device what went wrong.
audit_.record("internal_error", "");
return {ReplyCode::try_later};
}
}
How this code works: Gateway::receive

Every call ends in exactly one of five ways. Which one depends on how far the packet gets:

  1. The parser refuses it. std::get_if finds a ParseError, the audit log gets its name (for example truncated), and the device is told malformed. Nothing else is called.
  2. The token does not match. The packet parsed, so std::get takes the Packet out of the variant, but verify returns false. The audit log gets the device ID, and the device is told unauthorized. The same happens for a device the store does not know.
  3. Everything passes. append stores the readings, and the reply is accepted with the number of readings, 3 for the honest meter.
  4. The store is down. append throws StorageUnavailable. The rest of the try block is skipped, the first catch runs, and the reply is try_later.
  5. Anything else throws. For example, parse_packet runs out of memory and throws std::bad_alloc. The catch (...) runs, and the reply is again try_later.

In every path except 3, append either was never called or threw, and the ReadingSink contract says a sink that throws has stored nothing. The packet reference is only used inside the try block, while parsed, the variant it points into, is still alive.

  • Parse, then authenticate, then act. Nothing the device sent reaches storage until the packet is fully parsed and its token verified. Parsing first is safe only because parsing is bounded and has no side effects; with a message authentication code, the code would be checked over the raw bytes before the content is trusted.
  • Fail closed (R7). receive is noexcept, and every path that does not end in accepted stores nothing, because the ReadingSink contract says a sink stores all of the readings or none; MemorySink builds its batch first, so that nothing it does after storing the first reading can throw. An exception nobody planned for, such as a failed allocation, becomes try_later: never an accidental acceptance, and never a crash caused by an exception that escapes. It does not help with bugs that do not throw, such as a read out of bounds, which is what Steps 2 and 3 are for. The opposite, failing open, is the classic security bug: “if the permission check throws, carry on”.
  • Say little to the caller. An unknown device and a wrong token get the same reply, so the gateway cannot be used to find out which device IDs exist. The specific reason goes to the audit log, for people who are allowed to see it.
  • Never log the secret. The audit records the device ID, which the allow-list made safe, and never the token.

The adapters behind the ports, including the credential store:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

adapters.hpp
// Holds every device's token. The gateway sees it only as a
// TokenVerifier; adding devices is for the code that creates the store.
// `final`: no class may derive from this one. `override` on verify asks the
// compiler to check that it really replaces TokenVerifier::verify.
class CredentialStore final : public TokenVerifier {
public:
// Registers a device, or replaces its token if the ID is already known
// (insert_or_assign). Both parameters are taken by value and moved into
// the map; a Secret cannot be copied, so the caller must pass a
// temporary or std::move one in.
void add(std::string device_id, Secret token) {
tokens_.insert_or_assign(std::move(device_id), std::move(token));
}
// True only if the device is known and the presented token has the same
// bytes. find gives an iterator to the matching entry, or end() if none.
[[nodiscard]] bool verify(std::string_view device_id,
const Secret& presented) const noexcept override {
const auto found = tokens_.find(device_id);
// An unknown device and a wrong token give the same answer, so a
// caller cannot use the gateway to discover which IDs exist.
// && stops early: equals runs only when the device was found.
// found->second is the Secret stored for that device.
return found != tokens_.end() && found->second.equals(presented);
}
private:
// Device ID to token. std::less<> (a "transparent" comparison) lets
// find take the string_view directly, without building a std::string.
std::map<std::string, Secret, std::less<>> tokens_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

adapters.hpp
// Writes one line per event. The detail may come from a device, so it
// is escaped; an empty detail is written as "-".
// audit_value returns raw unchanged if every character is visible ASCII
// other than a quote or backslash. Otherwise it writes each other byte
// (a space, a newline, a non-ASCII byte, a quote, a backslash) as \xHH, two
// hex digits, and puts the whole value in quotes: the three characters
// a, newline, b come out as "a\x0ab". A newline from a device therefore
// cannot start a fake log line.
[[nodiscard]] std::string audit_value(std::string_view raw);
// An AuditLog that writes lines such as `audit event=rejected
// detail=truncated` to a stream it does not own (std::cout in the demo).
class StreamAudit final : public AuditLog {
public:
explicit StreamAudit(std::ostream& out) noexcept : out_(out) {}
// noexcept, as the port demands: if writing fails, the event is lost
// rather than an exception escaping (see adapters.cpp).
void record(std::string_view event, std::string_view detail) noexcept override;
private:
std::ostream& out_; // the stream must outlive this object
};

CredentialStore::verify looks up the device and compares the token with Secret::equals. An unknown device returns sooner than a wrong token, so the two may still be told apart by timing, even though the replies are the same; comparing against a dummy secret for unknown devices narrows that gap, although the lookup’s own time can still vary. The store also keeps the tokens themselves, so anyone who reads it learns every token. Real systems store a hash of each token, or a keyed hash with a key only the server holds, and compare hashes; a leaked store then reveals no tokens, and every value compared has the same length. The audit adapter writes any byte that is not a visible ASCII character, and any quote or backslash, as \xHH, and quotes a value that needed escaping. The parser’s allow-list already keeps device IDs clean, so this is defence in depth: if a later change logs a value the parser did not check, it still cannot forge a line, as Observability explains for logs in general.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The composition root holds the full objects; the gateway gets only
// the narrow interface of each.
// The three adapters are local variables of main, declared before the
// gateway, so they outlive it: locals are destroyed in reverse order.
meters::CredentialStore credentials;
// bytes_of turns the text into bytes; the temporary Secret is moved in.
credentials.add("meter-7", meters::Secret(meters::bytes_of("correct-horse-battery")));
meters::MemorySink store;
meters::StreamAudit audit(std::cout);
// credentials binds to `const TokenVerifier&`, store to `ReadingSink&`,
// and audit to `AuditLog&`: the gateway sees only those interfaces.
meters::Gateway gateway(credentials, store, audit, meters::Limits{});

The demo sends eight packets: an honest one, one cut off after 20 bytes, the wrapping count from Step 1, a wrong token, an unknown device, a device ID with a newline that tries to add a fake audit line, 2000 bytes of zeros, and an honest packet while the store is down. The wrapping one is built like this:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Claims 8193 readings but carries one. 8193 * 8 is 65544, which
// wraps to 8 in 16-bit arithmetic: exactly the size of one reading.
// PacketSpec (wire.hpp) describes a packet field by field, starting
// from an honest one; encode turns it into bytes. Setting count writes
// 8193 into the count field instead of the real number of readings.
PacketSpec wrap;
wrap.count = 8193;
wrap.readings = {{0, 1}}; // one Reading: offset 0, value 1
list.push_back({"count chosen to wrap", meters::encode(wrap)});
Expected output
-- honest meter (59 bytes)
reply: accepted, 3 readings
-- cut off after 20 bytes (20 bytes)
audit event=rejected detail=truncated
reply: malformed
-- count chosen to wrap (43 bytes)
audit event=rejected detail=bad_reading_count
reply: malformed
-- wrong token (56 bytes)
audit event=unauthorized detail=meter-7
reply: unauthorized
-- unknown device (60 bytes)
audit event=unauthorized detail=meter-99
reply: unauthorized
-- newline in the device ID (81 bytes)
audit event=rejected detail=bad_device_id
reply: malformed
-- 2000 bytes of zeros (2000 bytes)
audit event=rejected detail=too_large
reply: malformed
-- honest meter, store down (59 bytes)
audit event=storage_unavailable detail=-
reply: try_later
-- stored readings: 3
  • Each hostile packet is rejected at the first check it fails, and the sender learns only malformed or unauthorized.
  • The wrapping count, which crashed the flawed parser, is rejected as bad_reading_count before any arithmetic.
  • The newline never reaches the audit log: the allow-list rejects the ID first.
  • With the store down, the honest meter is told try_later, and nothing is stored. Only the first packet’s three readings are kept.

A boundary’s tests are mostly about input that should be rejected, and about proving that rejection is safe. All of these run in the sanitizer build too, where any read outside a buffer fails the test.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_parser.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if
// the condition is false; LLD_CHECK_EQ(actual, expected) does the same for
// actual == expected and prints both values when they differ. They come from
// the site's small test header, lld_test.hpp. Two helpers defined above
// these tests: encode(spec) builds the bytes of a PacketSpec (an honest
// packet unless a field is changed), and parse_spec(spec) parses those bytes
// with the default Limits and returns the ParseError's name, or "parsed".
// Sets up: the honest 59-byte packet. Proves: each of its 59 shorter
// prefixes, from 0 to 58 bytes, is refused with some ParseError.
LLD_TEST(every_cut_off_packet_is_rejected) {
const std::vector<std::byte> whole = encode(PacketSpec{});
for (std::size_t length = 0; length < whole.size(); ++length) {
// A new vector of the first `length` bytes, copied from an iterator
// range. The static_cast is there because iterator arithmetic takes
// a signed number and length is an unsigned std::size_t.
const std::vector<std::byte> cut(whole.begin(), whole.begin() + static_cast<long>(length));
// holds_alternative asks the variant "do you hold a ParseError?".
LLD_CHECK(std::holds_alternative<ParseError>(parse_packet(cut, Limits{})));
}
}
// Sets up: the attack from Step 1, a count of 8193 with one reading.
// Proves: the count limit refuses it before it is ever multiplied.
LLD_TEST(a_count_that_would_wrap_is_rejected_before_any_arithmetic) {
PacketSpec wrap;
wrap.count = 8193; // 8193 * 8 wraps to 8 in 16 bits
wrap.readings = {{0, 1}};
LLD_CHECK_EQ(parse_spec(wrap), "bad_reading_count");
}
// Proves both edges of the count rule: 0 readings is refused, exactly 100
// (the limit) is accepted, and 101 is refused.
LLD_TEST(the_reading_count_must_be_between_one_and_the_limit) {
PacketSpec spec;
spec.readings.clear(); // count 0
LLD_CHECK_EQ(parse_spec(spec), "bad_reading_count");
// Offsets 0, 60, ..., 5940: one a minute, increasing, within a day.
for (std::uint32_t i = 0; i < 100; ++i) spec.readings.push_back({i * 60, 0});
LLD_CHECK_EQ(parse_spec(spec), "parsed");
spec.readings.push_back({100 * 60, 0}); // the 101st reading
LLD_CHECK_EQ(parse_spec(spec), "bad_reading_count");
}
// Each bad ID breaks one rule: empty, an uppercase letter, a space, a
// newline, a non-ASCII letter (the two bytes C3 A9 are the UTF-8 for é),
// and 33 characters, one too many. Then 32 characters, the most allowed,
// must still parse: the test checks the edge from both sides.
LLD_TEST(the_device_id_is_checked_against_an_allow_list) {
const std::vector<std::string> bad_ids{"", "Meter-7", "meter 7", "meter-7\n",
"m\xc3\xa9ter", std::string(33, 'a')};
for (const std::string& id : bad_ids) {
PacketSpec spec;
spec.device_id = id;
LLD_CHECK_EQ(parse_spec(spec), "bad_device_id");
}
PacketSpec longest;
longest.device_id = std::string(32, 'a');
LLD_CHECK_EQ(parse_spec(longest), "parsed");
}

every_cut_off_packet_is_rejected parses every prefix of an honest packet, from zero bytes to one short of the whole, so every “the input ends here” path runs at least once. The ID test lists IDs a block-list would let through: uppercase, a space, a newline, and a UTF-8 é, as well as an empty ID and one that is a character too long.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_parser.cpp
// Changes every byte of an honest packet to a few chosen values, one at
// a time, and parses each result. Whatever the parser decides, it must
// decide safely: the sanitizer builds fail on any read outside the
// input, and an accepted packet must still respect the limits.
LLD_TEST(single_byte_changes_never_break_the_parser) {
const std::vector<std::byte> honest = encode(PacketSpec{});
int accepted = 0;
for (std::size_t at = 0; at < honest.size(); ++at) {
// 59 positions times 5 values: 295 packets, each one byte off.
for (const unsigned value : {0x00u, 0x01u, 0x7fu, 0x80u, 0xffu}) {
std::vector<std::byte> changed = honest; // a fresh copy each time
changed[at] = static_cast<std::byte>(value);
const ParseResult result = parse_packet(changed, Limits{});
// Most changes are refused, which needs no check here. For the
// ones that parse, the limits must still hold.
if (const auto* packet = std::get_if<Packet>(&result)) {
++accepted;
LLD_CHECK(packet->readings.size() <= Limits{}.max_readings);
LLD_CHECK(!packet->device_id.empty() && packet->device_id.size() <= 32);
}
}
}
// Changes to the token bytes and the reading values are still valid
// packets; the checks above ran on each of them.
LLD_CHECK(accepted > 0);
}

The mutation test changes each byte of an honest packet to five values chosen to hit the edges: zero, one, the largest positive and smallest negative 8-bit values, and all ones. It checks no particular result, only that whatever happens is safe. It is a small, deterministic cousin of fuzzing.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_secret.cpp
// static_assert(condition) is checked by the compiler, not when the tests
// run: if the condition is false, this file does not compile. The type
// traits from <type_traits> answer questions about Secret at compile time:
// can it be copy-constructed, copy-assigned, and moved without throwing?
static_assert(!std::is_copy_constructible_v<Secret>, "a secret is never copied by accident");
static_assert(!std::is_copy_assignable_v<Secret>);
static_assert(std::is_nothrow_move_constructible_v<Secret>);
// LLD_TEST(name) defines one test, and LLD_CHECK(condition) records a
// failure if the condition is false; both come from lld_test.hpp.
// bytes_of (wire.hpp) turns text into a vector of bytes.
// Proves: equals is true for the same bytes, and false for one different
// byte, for one byte fewer, and for nothing at all.
LLD_TEST(a_secret_matches_only_the_same_bytes) {
const Secret secret(bytes_of("correct-horse-battery"));
LLD_CHECK(secret.equals(bytes_of("correct-horse-battery")));
LLD_CHECK(!secret.equals(bytes_of("correct-horse-batterz"))); // last byte differs
LLD_CHECK(!secret.equals(bytes_of("correct-horse-batter"))); // one byte shorter
LLD_CHECK(!secret.equals(bytes_of("")));
}
// Prints a Secret into a string stream, then reads the text back.
// LLD_CHECK_EQ(actual, expected) fails, printing both, unless they are equal.
LLD_TEST(a_secret_never_prints_its_bytes) {
const Secret secret(bytes_of("correct-horse-battery"));
std::ostringstream out;
out << "token=" << secret;
LLD_CHECK_EQ(out.str(), "token=<secret>");
}

The static_asserts make “cannot be copied” part of the build: if someone adds a copy constructor or a copy assignment, the test file stops compiling.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_gateway.cpp
// LLD_TEST(name) defines one test; LLD_CHECK(condition) and
// LLD_CHECK_EQ(actual, expected) record a failure if the condition is false
// or the values differ (both come from lld_test.hpp).
// Each test starts with `Fixture f;`, defined above these tests: a fresh
// gateway wired to a CredentialStore that knows meter-7, a MemorySink, and
// an audit log written to a string (f.audit_text), so a test can read
// exactly what was logged. The verifier is wrapped in a CountingVerifier,
// which counts its calls in f.verifier.calls and then asks the real store.
// The honest path: three readings stored, and nothing in the audit log.
LLD_TEST(an_honest_packet_is_stored) {
Fixture f;
const meters::Reply reply = f.gateway.receive(encode(PacketSpec{}));
LLD_CHECK_EQ(reply.code, ReplyCode::accepted);
LLD_CHECK_EQ(reply.readings, std::size_t{3});
LLD_CHECK_EQ(f.store.stored.size(), std::size_t{3});
LLD_CHECK_EQ(f.audit_text.str(), "");
}
// Both get `unauthorized`; only the audit log, for operators, records
// which device ID was involved. Neither stores anything.
LLD_TEST(a_wrong_token_and_an_unknown_device_look_the_same_to_the_caller) {
Fixture f;
PacketSpec wrong_token;
wrong_token.token = "guessed-password-1";
PacketSpec unknown;
unknown.device_id = "meter-99";
LLD_CHECK_EQ(f.gateway.receive(encode(wrong_token)).code, ReplyCode::unauthorized);
LLD_CHECK_EQ(f.gateway.receive(encode(unknown)).code, ReplyCode::unauthorized);
LLD_CHECK(f.store.stored.empty());
LLD_CHECK_EQ(f.audit_text.str(),
"audit event=unauthorized detail=meter-7\n"
"audit event=unauthorized detail=meter-99\n");
}
// Version 9 is refused by the parser, so the verifier is never called
// (calls stays 0): nothing is authenticated before it is understood.
LLD_TEST(a_malformed_packet_never_reaches_the_verifier_or_the_store) {
Fixture f;
PacketSpec bad;
bad.version = 9;
LLD_CHECK_EQ(f.gateway.receive(encode(bad)).code, ReplyCode::malformed);
LLD_CHECK_EQ(f.verifier.calls, 0);
LLD_CHECK(f.store.stored.empty());
LLD_CHECK_EQ(f.audit_text.str(), "audit event=rejected detail=unsupported_version\n");
}
// Two kinds of storage failure, both answered with try_later. First the
// expected one: the store is switched off, so append throws
// StorageUnavailable. Then an unexpected one: ThrowingSink, defined above,
// throws std::bad_alloc from append, which only the catch (...) handles.
LLD_TEST(any_failure_while_storing_fails_closed) {
Fixture f;
f.store.available = false;
LLD_CHECK_EQ(f.gateway.receive(encode(PacketSpec{})).code, ReplyCode::try_later);
LLD_CHECK(f.store.stored.empty());
// A second gateway, sharing the fixture's credentials and audit log.
ThrowingSink broken;
Gateway gateway(f.credentials, broken, f.audit, meters::Limits{});
LLD_CHECK_EQ(gateway.receive(encode(PacketSpec{})).code, ReplyCode::try_later);
LLD_CHECK_EQ(f.audit_text.str(),
"audit event=storage_unavailable detail=-\n"
"audit event=internal_error detail=-\n");
}
// Sends a wrong token, then the same token in a malformed packet, and
// searches the whole audit text for part of it. receive is [[nodiscard]],
// so static_cast<void>(...) marks its reply as ignored on purpose.
LLD_TEST(the_token_never_appears_in_the_audit_log) {
Fixture f;
PacketSpec spec;
spec.token = "guessed-password-1";
static_cast<void>(f.gateway.receive(encode(spec)));
spec.version = 7;
static_cast<void>(f.gateway.receive(encode(spec)));
// find returns std::string::npos when the text is not there at all.
LLD_CHECK(f.audit_text.str().find("guessed") == std::string::npos);
}

These check the gateway’s promises from the outside: malformed packets never reach the verifier, “unknown” and “wrong” look the same, a sink that fails before storing anything leaves nothing stored and the reply is try_later, and the token never reaches the audit log.

Fuzzing. A fuzzer generates inputs by the million, keeps the ones that reach new code, and mutates them further. For this page, a fuzzing entry point for parse_packet was written in a scratch file, compiled with Clang 14 and its libFuzzer, and run on this machine. It is not part of the example, because it needs Clang and a separate build:

// Scratch fuzzing entry point for parse_packet; not part of the example.
#include "packet.hpp"
#include <cstddef>
#include <cstdint>
#include <span>
// libFuzzer calls this function once for every input it generates, with
// a pointer to the bytes and their count. extern "C" gives it the plain
// name the fuzzer looks for.
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) {
// Views the fuzzer's bytes as std::byte, the type parse_packet takes.
const std::span bytes(reinterpret_cast<const std::byte*>(data), size);
static_cast<void>(meters::parse_packet(bytes, meters::Limits{}));
return 0; // the sanitizers report any problem
}

It was built with clang++ -std=c++20 -g -O1 -fsanitize=fuzzer,address,undefined together with packet.cpp and secret.cpp, and run with -max_len=1100, a little over the size limit. In 60 seconds it ran about 17.5 million inputs and found no problem. The same setup, run on the flawed parser from Step 1, found the out-of-bounds token-length read almost at once. A clean fuzzing run is evidence, not proof; parsers exposed to the internet are usually fuzzed continuously, not once.

The gateway is one layer. These belong to others, and were not built or tested here:

Layer What it adds
Transport security TLS, so packets cannot be read or changed on the way
Rate limiting Stops one sender from using all of the gateway’s time, even with valid packets, and limits how fast anyone can guess tokens
Process isolation The gateway runs as a user with no rights, or in a sandbox, so a bug that escapes the code still cannot reach much
Compiler hardening Stack protectors, position-independent executables, and similar compiler and linker options, which make exploiting a memory bug harder
Monitoring A rise in unauthorized or malformed events is often the first sign of an attack (Observability)

class meters::ByteReader

a view of untrusted bytes; never reads past the end

Member functions

  • explicit ByteReader(std::span<const std::byte> bytes) noexcept;
  • std::size_t remaining() const noexcept;
  • std::optional<std::span<const std::byte>> take(std::size_t n) noexcept; nullopt if fewer remain
  • std::optional<std::uint8_t> u8() noexcept;
  • std::optional<std::uint16_t> u16() noexcept; big-endian
  • std::optional<std::uint32_t> u32() noexcept;

class meters::Secret

move-only; prints as <secret>; wiped on destruction

Member functions

  • explicit Secret(std::span<const std::byte> bytes);
  • bool equals(std::span<const std::byte> other) const noexcept; no early exit

class meters::Gateway

the trust boundary

Data members

  • const TokenVerifier& verifier_; verify only
  • ReadingSink& sink_; append only
  • AuditLog& audit_; record only
  • Limits limits_;

Member functions

  • Gateway(const TokenVerifier& verifier, ReadingSink& sink, AuditLog& audit, Limits limits) noexcept;
  • Reply receive(std::span<const std::byte> bytes) noexcept; fails closed
The boundary: a bounded reader, a secret, narrow ports, and a gateway that fails closed
Situation How careful
Input from a network, from users, or from files others wrote All of this page: bounded reading, limits first, allow-lists, fail closed, fuzzing
Data from another component of the same program Contracts and invariants, as in API contracts; not hostile-input defences
A file your own program wrote, in a directory only it can write Check versions and sizes, since files get corrupted; full hostile-input rigour is optional
A quick internal tool on trusted data Ordinary correctness; but code is copied, so the parser may meet the internet later

The last row is a real risk: a parser written for trusted files is reused for uploads, and its assumptions travel with it. If a parser might ever see outside data, it is cheaper to write it for that from the start.

  • Trusting a length from the input. Every length, count, and offset in a packet is a number an attacker chose. Check it against what is really there, and against a limit, before using it.
  • Checking after the arithmetic. count * size in a small type wraps before the check sees it. Limit first, then compute in a type that cannot overflow.
  • Block-lists. They always miss something. Say what is allowed.
  • Being lenient. Accepting trailing bytes, unknown versions, or “close enough” values gives attackers room, and makes two parsers disagree.
  • Telling the caller why. “Unknown device” versus “wrong token” lets anyone list your devices.
  • Logging secrets, or comparing them with ==.
  • Failing open. A check that is skipped when it throws is no check.
  • Giving the boundary code the whole database. Give it the one operation it needs.
  • Writing your own cryptography. Use a maintained library.
  • Testing only honest input. The interesting cases at a boundary are the hostile ones; generate them.
  • “Version 2 of the packet adds a firmware field.” Add a separate parsing path for version 2, with its own exact rules; keep rejecting unknown versions. Never let a version 1 packet be “parsed as version 2 with defaults”.
  • “Meters may send up to 10,000 readings.” Raise the limit, and check that every computation that uses the count still cannot overflow; 10,000 × 8 still fits easily in std::size_t. Raise max_packet_bytes with it, and think about time per packet.
  • “Operators want to see the rejected bytes.” Log a size and a short hexadecimal prefix, escaped, in the audit log only; never a whole packet, which may contain a valid token.
  • “Let meters update their own token.” That is a new power, and it deserves its own narrow interface, its own authentication rules, and its own audit event; do not widen TokenVerifier.

Exercise: Find the boundary flaws

A colleague wrote a handler for a “rename my meter” request. The request is text: a device ID, a token, and a new display name, sent over the network. Find every problem, say which requirement it breaks, and say how you would fix it. The code is a sketch and was not compiled.

Rename(request):
parts = split(request.text, ",") // id,token,name
device = database.find(parts[0])
if device == null:
reply "no such device " + parts[0]
return
if device.token != parts[1]:
log("bad token " + parts[1] + " for " + parts[0])
reply "wrong token"
return
if parts[2] contains "<" or ">" or "'":
reply "bad name"
return
char buffer[64]
copy(buffer, parts[2]) // display names are short
try:
database.execute("UPDATE meters SET name='" + buffer + "' WHERE id='" + parts[0] + "'")
except:
log("update failed, accepting anyway")
reply "ok"
Show the explained answer
  1. parts[1] and parts[2] may not exist. A request with no commas makes the code read past the end of parts. Check the number of parts first, and require exactly three: a comma in the name would make a fourth part that the code silently ignores, the kind of leniency R3 forbids (R1, R3).
  2. “no such device” versus “wrong token” tells anyone which IDs exist, and echoing parts[0] back may reflect hostile text into whatever displays the reply. Use one reply for both, with no echo (R4).
  3. != on tokens is an early-exit comparison; use a constant-time comparison, through a Secret-like type (R5).
  4. The token is logged on failure, and the log would then hold near-misses of real tokens, or real tokens typed into the wrong field. Log the device ID, checked, and never the token (R5).
  5. The name check is a block-list. It misses ", ;, \, newlines, control characters, and everything else no one thought of. Define what a display name may contain, such as letters, digits, spaces, and -, with a maximum length, and reject the rest (R3).
  6. copy into char buffer[64] has no length check: a long name overflows the stack buffer, the same bug as the device ID in Step 1. Check the length first, or do not copy at all; use a std::string (R1).
  7. The SQL is built by joining strings, so a name or ID containing a quote can change the statement: SQL injection. Even a perfect allow-list is the wrong defence here; use the database library’s parameterised statements, which pass values separately from the SQL text (R3).
  8. The handler has the whole database. It needs one operation, “rename this device”, which deserves a narrow interface; the generic execute gives any bug in this code every power the database account has (R6).
  9. “update failed, accepting anyway” fails open: the caller is told ok when nothing changed. Reply “try later” and do not pretend (R7).
  10. No size limit on the request at all, before splitting it into parts, so one huge request costs as much memory and time as the sender wants (R2).
  11. The token is sent with the request, presumably in clear text if the connection is not encrypted; the transport needs TLS, and better authentication than a token in a text field (see “Real authentication” above).
  • A trust boundary is where data passes from a less trusted source to more trusted code. Find them by following the data; they are where checks are required.
  • At a boundary, ask what the worst input could make the code do. Every length and count in the input was chosen by someone else.
  • Read untrusted bytes through one bounds-checked reader, check sizes and counts against limits before any arithmetic, use allow-lists, and accept nothing you do not fully understand.
  • Keep secrets in a type that does not print, copy, or compare early, and know what it cannot protect against. Use maintained libraries for real cryptography.
  • Give boundary code only the powers it needs, through narrow interfaces, and make it fail closed.
  • Test with hostile input: every truncation, systematic mutations, the sanitizers, and a fuzzer.