See what your app really sends: Postgres, MySQL, MariaDB and Redis on the wire
An app log tells you what the app thinks it asked. One command puts mitmproxy between your app and each database in your via.yaml, and open source decoders show the question and the answer for Postgres, MySQL, MariaDB and Redis. With the code to build it yourself, the demo, the tests, a CI step and a lesson.
TL;DR: List your databases as services in
via.yamland runvia net apply --inspect. The Viaalink CLI puts mitmproxy between your app and that database, on the same machine. Open source decoders turn the bytes into the query, its parameters, the answer and the error, for Postgres, MySQL, MariaDB and Redis. A plainvia net applytakes it out again. The film (3:16) is at the top of this post. Further down: how the decoders work, with their code, how to run the demo and the tests yourself, how to read the wire of a failing CI job, and the film as a lesson.
The question a log cannot answer
Your shop on staging shows an empty page, and the app log is empty too. There are two possible causes. The database had nothing, or the app asked the wrong question.
The app log cannot tell them apart. It records what the app thinks it sent. The database knows what it was really asked, and what it answered. That conversation only exists on the connection between the two, at the moment it happens.
This post shows how to read that conversation live, for four databases, without adding one log line to the app.
What it is built from
Three parts, each usable without the next:
- The decoders. Three mitmproxy addons that read the Postgres, MySQL/MariaDB and Redis protocols. They are open source (MIT), in the caddy-api-client repository. All three ship in the npm package @viaalink/caddy-api-client since version 0.14.0.
- The Viaalink CLI. It reads
via.yaml, starts mitmproxy with those decoders, and routes each database connection through it. - Your own Relay. It brings the inspector’s page to your browser over HTTPS, behind a login, when the server is somewhere else.
We go through them in that order.
Step 1: the decoders on their own
The decoders are plain mitmproxy addons, one Python file each. The npm package brings all three; load them into mitmweb:
npm install @viaalink/caddy-api-client@0.14.0 # or: bun add @viaalink/caddy-api-client@0.14.0
addons=node_modules/@viaalink/caddy-api-client/mitmproxy-addons
mitmweb --mode reverse:tcp://127.0.0.1:5432@15432 \
--mode reverse:tcp://127.0.0.1:3306@13306 \
--mode reverse:tcp://127.0.0.1:6379@16379 \
-s $addons/pgwire.py -s $addons/mysqlwire.py -s $addons/rediswire.pyEach --mode line opens a port that forwards to one database. Point your app at port 15432 instead of 5432 and its Postgres traffic shows up in mitmweb, decoded.
No npm on that machine? Download the three files from GitHub instead:
base=https://github.com/viaalink/asd-caddy-api-client/raw/main/mitmproxy-addons
curl -fsSLO $base/pgwire.py -O $base/mysqlwire.py -O $base/rediswire.py
addons=. # then run the same mitmweb command| Addon | Reads | What you see |
|---|---|---|
pgwire | PostgreSQL | SQL, bind parameters, columns, rows, errors |
mysqlwire | MySQL and MariaDB | which server answered and its version, SQL, prepared statements, errors |
rediswire | Redis (RESP2 and RESP3) | commands with their arguments, replies summarised |
A decoder picks its flows by what the protocol looks like, never by port number. One mitmweb can load all three. How that works is further down.
This works, but the plumbing is yours. You pick the ports, change the app’s connection settings, restart it, and put everything back afterwards. On a server you also have to get the mitmweb page to your own browser safely.
Step 2: the same thing from one file
The Viaalink CLI does that plumbing from via.yaml. Each database is a service, and tunnelProtocol: tcp says it speaks raw TCP. Inspect is off unless you ask for it.
version: 1
project:
name: shop
domain: localhost
network:
services:
web:
dial: "127.0.0.1:4300"
public: true
# inspect: true on a service keeps its inspector on
postgres:
dial: "127.0.0.1:5432"
tunnelProtocol: tcp
mysql:
dial: "127.0.0.1:3306"
tunnelProtocol: tcp
mariadb:
dial: "127.0.0.1:3316"
tunnelProtocol: tcp
redis:
dial: "127.0.0.1:6379"
tunnelProtocol: tcpOnly web has public: true. The databases do not, so they are never published. Their traffic stays on the machine.
Ask for the inspector on the command line, for the four databases:
via net apply --inspect --ids postgres,mysql,mariadb,redis--inspect turns the inspector on for this run, and --ids names the services it is for. The file stays as it is. If you want a service inspected every time, put inspect: true on it in the file instead.
The CLI starts mitmproxy with the three decoders and gives each database a local address. For every database it prints one line that ends in queries inspected. via net urls lists the addresses, for example:
postgres
Local TCP tcp://127.0.0.1:38933 (this machine)Your app connects to that Local TCP address instead of the database’s own port. This is the one change on the app’s side, and you make it once: with inspect off, the same address leads straight to the database.
If the server is not the machine you sit at, the inspector’s page comes to you through your Relay: encrypted, and behind a login.
What the wire showed
The demo shop in the film has three bugs. None of them is in the app log.
Postgres: a category that matches nothing. Pick the category Electronics, and the page is empty. This is the query as Postgres received it:
→ PARSE select name, category, description, price from products where category = $1 order by price limit 20
→ BIND $1='electronics'
← COLUMNS name, category, description, price
← DONE SELECT 0The shop asked for electronics in lower case and got zero rows. A search for “keyboard” returns a row whose category is Electronics, with a capital E. The button sends the wrong value.
MySQL: an error the app swallowed. Sort the orders by shipping date, and the shop says “something went wrong”. The server was more precise:
→ PREPARE select id, customer, total, status, placed_at from orders where status <> ? order by shipped_at desc limit 20
← ERROR 1054 (42S22) Unknown column 'shipped_at' in 'order clause'The sort option shipped. The column never reached this server.
MariaDB: which server is this? Customers load fine, but the first line of the connection is worth reading:
← SERVER MariaDB 11.4.13 (version string '11.4.13-MariaDB-ubu2404', connection 11, auth mysql_native_password)
→ CONNECT user=shop database=shop auth=mysql_native_password (credentials not shown)MariaDB speaks the MySQL protocol, so the same decoder reads it and tells you which of the two answered.
Redis: two keys, one letter apart. Add a keyboard to the cart, open the cart, and it is empty. Redis is not SQL, so you read its commands instead. The shop reads the list cart:anna. This is what it wrote a moment before:
→ RPUSH 'cart:Anna' 'Mechanical Keyboard'
← INTEGER 1It writes to cart:Anna and reads from cart:anna.
Logins never show
Look at the CONNECT line above: (credentials not shown). Each decoder leaves login data out of what it shows, and blanks it in the stored flow once it has been forwarded. That covers Postgres password messages, the MySQL and MariaDB auth exchange, and Redis AUTH.
How a decoder knows its protocol
mitmproxy hands every addon every TCP message. An addon that guessed by port would break the moment you run a database somewhere else, so each one looks at the first bytes instead. That is less simple than it sounds: in Redis the client speaks first, in MySQL the server does.
Redis, client first. A client opens with a RESP array (* and a digit) or an inline command made of letters. Anything that looks like GET / HTTP/1.1 is HTTP, so the addon leaves it alone. From rediswire.py:
def looks_like_redis(first_client_bytes: bytes) -> bool | None:
data = first_client_bytes
if not data:
return None
if data[:1] == b"\x16":
return True # TLS: reported as such
if data[:1] == b"*":
if len(data) < 2:
return None
return data[1:2].isdigit() or data[1:2] == b"-"
line, crlf, _ = data.partition(b"\r\n")
word = line.split(b" ", 1)[0]
if not crlf:
# An inline command still coming in: undecided while it can still be one.
if len(data) > 4096 or (b" " in line and not word.isalpha()):
return False
return None if word.isalpha() or not word else False
if not word.isalpha() or len(word) > 20:
return False
# Inline commands, but not other text protocols on a TCP port.
return b" HTTP/" not in lineMySQL and MariaDB, server first. The server’s greeting is a packet with sequence number 0, protocol version 10 and a printable version string. From mysqlwire.py:
def looks_like_mysql(first_server_bytes: bytes) -> bool | None:
data = first_server_bytes
if len(data) >= 4 and data[3] != 0:
return False # not sequence 0
if len(data) >= 5 and data[4] not in (10, 0xFF):
return False # not protocol 10, not an error
...
end = data.find(b"\x00", 5)
version = data[5:end] if end > 5 else b""
return bool(version) and version[:1].isdigit() and all(32 <= c < 127 for c in version)The version string also tells the two servers apart. MariaDB prefixes 5.5.5- for old clients and names itself, so server_kind() turns 5.5.5-11.4.13-MariaDB-ubu2404 into MariaDB 11.4.13.
Three rules make this safe when several addons run in one mitmweb:
- Not sure yet, so wait. With too few bytes, both functions return
None. The addon keeps the messages and decodes them all once it knows. - First come, first served. The addon that recognises a flow writes its name in
flow.metadata["wire_protocol"], and the others skip that flow. - A decoder bug never breaks the connection. Decoding runs in a
try; a failure becomes the line(could not decode: …), and the bytes go through as they were.
Keeping passwords off the screen
A decoder shows AUTH (credentials not shown), but mitmweb also keeps the raw bytes of each message, so those must be blanked too. There is a catch: mitmproxy forwards a message after the tcp_message hook returns. Change the message inside the hook and the database receives the blanked bytes, and the login fails.
So the addon notes which messages carried a password and blanks them on the next message, once they are out. From rediswire.py:
@staticmethod
def _hide_secrets(flow: tcp.TCPFlow, keep_last: bool) -> None:
"""
Blank messages that carried a password once they have been forwarded,
so mitmweb's Raw and Auto views never show it. A message is sent when
its tcp_message hook returns; only the stored copy is changed here.
"""
pending = flow.metadata.get(f"{NAME}_hide", [])
last = len(flow.messages) - 1
for index in [i for i in pending if not (keep_last and i == last)]:
message = flow.messages[index]
message.content = f"({NAME}: message with credentials hidden, {len(message.content)} bytes)".encode()
pending.remove(index)A password can arrive split over several TCP messages. The connection keeps one buffer per direction, and Direction.take() returns which messages the bytes it consumed came from, so every message that held a piece of the password is blanked.
Behind Caddy: swap the route, no restart
The CLI does this for you. If you run Caddy yourself, the same library does it from code. Caddy reaches each database through a caddy-l4 listener. caddy-l4 has no matcher for MySQL or Redis, and a MySQL server speaks first, so there is nothing to match on: those routes have no match. From the demo’s backend:
const TCP_DATABASES = [
{ id: "mysql", listen: ":3306", backend: { host: "mysql", port: 3306 } },
{ id: "mariadb", listen: ":3307", backend: { host: "mariadb", port: 3306 } },
{ id: "redis", listen: ":6379", backend: { host: "redis", port: 6379 } },
] as const
for (const d of TCP_DATABASES) {
mitmManager.register({
protocol: "tcp",
id: d.id,
serverId: d.id,
backend: d.backend,
proxy: d.id,
})
}
// Later, from a button or a test:
await mitmManager.enable("mysql", { proxy: "mysql" }) // the route now goes through mitmproxy
await mitmManager.disable("mysql") // straight to the database againenable and disable change the route through Caddy’s admin API, without restarting Caddy. A TCP connection is routed when it opens, so the next new connection takes the new route. The demo keeps its connection pools short-lived for that reason.
Run the demo yourself
Everything in the film runs on your own machine. You need Docker, just, Bun and the Viaalink CLI.
git clone https://github.com/viaalink/asd-caddy-api-client caddy-api-client
cd caddy-api-client
just demo start # the shop, four databases, Caddy and a mitmweb per database
just demo url # the dashboard address
just demo stopmitmweb asks for a password: demo, unless you set DEMO_MITMWEB_PASSWORD in .env.
The dashboard has a tab per database. Click MITM on a tab to swap that route through mitmweb, then use the shop on the left. Each checkout gets its own ports, so two clones run side by side. What runs is in demo/docker-compose.yml. The mitmweb for MySQL, for example, comes down to this:
mitmproxy-mysql:
image: mitmproxy/mitmproxy:12.2.1
command: >
mitmweb
--mode reverse:tcp://mysql:3306@3306
--web-host 0.0.0.0
--web-port 8081
-s /addons/mysqlwire.py
volumes:
- ../mitmproxy-addons:/addons:roRun the tests
just test-addons # the decoders on their own: plain python3, no Docker
just test-layer4 # Caddy, Postgres, MySQL 8, MariaDB 11, Redis 7 and mitmweb in Docker
just test-layer4-down # remove that stack againjust test-addons feeds recorded conversations through each addon. A test reads like the transcript you see in mitmweb, from test_rediswire.py:
→ AUTH (credentials not shown)
→ HGETALL 'product:7'
← ARRAY 4 items: ['name', 'Wireless Mouse', 'price', '29.99']
← ERROR WRONGTYPE Operation against a key holding the wrong kind of valueWriting a decoder of your own? Use the two helpers in helpers.py. play() sends messages through your addon the way mitmproxy does. bytewise() splits every message into single bytes, the worst split TCP can give you. A decoder that passes with bytewise() handles any real network:
def bytewise(chunks: list[tuple[bool, bytes]]) -> list[tuple[bool, bytes]]:
"""Every byte its own TCP message: the worst split there is."""
return [(c, data[i : i + 1]) for c, data in chunks for i in range(len(data))]
flow = play([rediswire.RedisWire()], bytewise(SESSION))When it fails in CI
A database test that only fails in CI is where reading the wire helps most, and the CI runner is exactly where you cannot look. With Viaalink CI/CD you can. Run the tests, and when they fail, put the job’s mitmweb on an address of its own through your Relay, behind a login, together with a terminal on the runner:
- name: Database tests
id: tests
run: just test-layer4
continue-on-error: true
- name: Read the wire on failure
if: steps.tests.outcome == 'failure'
uses: viaalink/cicd@v2
with:
# ...the job's permissions and your Relay secrets: see the Viaalink CI/CD README
password: ${{ secrets.VIA_TERMINAL_PASSWORD }}
tunnel-name: wire-${{ github.run_id }}
expose: |
18082 mitmwebWhen a test fails, just test-layer4 stops and leaves its stack running, so the mitmweb that saw the failing test (one mitmweb with all three decoders, on port 18082) is still there. Open its address, sign in, and read what the test really sent. When the job ends, the address answers 404.
Use it in class
The film and the demo make a lesson on how an application talks to a database. Students need the demo running on their own laptop, nothing else.
- Watch the film to the first bug (Postgres, the empty category). Stop. Ask: did the database have nothing, or did the app ask the wrong question? How would you find out?
- Let them find it. In the demo, switch the Postgres tab to MITM and click Electronics. The answer is in the
BINDline. - Do the other three alone: the MySQL error the app swallowed, the MariaDB greeting, the Redis cart. Each takes one click and one line of transcript.
- Compare with logs. Turn on
log_statementin Postgres orMONITORin Redis. What does the log show, and what does it miss? (The answer: the reply.) - For the advanced group: read
looks_like_redis()above, then write a test withbytewise()that sends a Redis command one byte at a time.
Why not just turn on the logs?
You can. Every one of these databases can log queries. This is what it takes:
| Database | Setting | What you get | What is missing |
|---|---|---|---|
| PostgreSQL | log_statement = 'all' | statements and their parameters | the answer: no rows, no row count |
| MySQL and MariaDB | general_log = 'ON' | every statement, from every client | the answer, and the error the client got |
| Redis | MONITOR | every command, from every client | the replies; and it slows a busy server down |
That is four settings, in four formats, in four places. Each needs administrator rights on the database server, which you often do not have on a managed database. And the log mixes all clients together, while the bug you are after belongs to one connection.
The larger difference is the answer. Three of the four bugs above were only visible in what the database sent back: zero rows, an error, a server greeting. A query log records the question.
Logs are still the right tool for other jobs. Use them for a permanent record, for auditing, and for finding slow queries over days. Reading the wire is for the moment you ask “what did this click just do?“.
Good to know
- It reads plain connections. When a client turns on TLS, the decoder says so and leaves the connection alone.
- What you read is real data. Staging is often a copy of production, so turn the inspector off when you are done.
Turn it off when you are done
via net applyThe file does not ask for inspect, so applying it turns the inspector off. The local addresses now lead straight to the databases, the app keeps running with the same settings, and nothing is recorded.
Get started
- Viaalink CLI: install it, write the
via.yamlabove, runvia net apply --inspect. - Viaalink Relay: to reach the inspector’s page from somewhere else.
- The decoders on GitHub
- The demo, the tests
- Viaalink CI/CD: to read the wire of a failing CI job
- @viaalink/caddy-api-client on npm
The narration in the film uses an AI voice clone of Kelvin’s voice. The screen recording is real: a shop that talks to four running databases.