DEV Community

Sergey Shinder
Sergey Shinder

Posted on

Our carrier moved its labels to URL safe base64 and Python decoded some of them without an error into something that was not a PDF

Our label service asks a parcel carrier's API for a label and gets back JSON with the PDF inside it as a base64 string. A Python worker decodes it with base64.b64decode and sends the bytes to the depot print server.

In October the carrier moved its label endpoint to a new API version. One line in the changelog said labels were now encoded with the URL and filename safe alphabet. That alphabet uses a minus sign and an underscore where standard base64 uses a plus sign and a slash.

The next morning most label requests failed with binascii.Error: Incorrect padding, which was loud and quickly traced. What worried us more were the ones that did not fail. About a fifth of the labels decoded without any error, were sent to the printers and came out as blank pages or half a label.

b64decode does not validate by default. The documentation says that with validate left false, characters outside the base64 alphabet are discarded before the padding is checked. Every minus and every underscore in the carrier's string was silently dropped. If the number dropped left a length the decoder could accept, it decoded the rest, and from the first dropped character onwards every byte was shifted and wrong. The first bytes, including the %PDF header, often came through intact, so the file looked like a PDF to anything that only glanced at it.

The worker now maps the minus and underscore back to plus and slash, adds the padding the new version leaves off, and calls b64decode with validate=True, so any character outside the alphabet is an error and not a deletion. Every other decode of data from outside got the same flag. After decoding, the worker checks that the bytes start with %PDF- and that the document opens with a PDF library before it reaches a printer, and a label that fails goes back to the queue with the reason. The carrier's sandbox for the new version is now in our contract tests, and the changelog feed goes to the integration channel.

The decoder had a choice between failing and guessing. Its default was to guess, and a guessed label looks like a label until somebody tries to scan it.

– Sergey Shinder

Top comments (0)