Skip to content

base64.encode silently truncates output when the binary stream performs short writes #158696

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: "Encode a file; input and output are binary files." — base64.encode documentation. Binary raw streams may return a write count smaller than the supplied buffer.

Expected: b'AA==\n'

Actual: b'A'

import base64, binascii, io

class PrefixWriter(io.RawIOBase):
    def __init__(self, limit):
        super().__init__()
        self.limit, self.data = limit, bytearray()
    def writable(self):
        return True
    def write(self, b):
        n = min(len(b), self.limit)
        self.data.extend(b[:n])
        return n

p, limit = b'\x00', 1
src, dst = io.BytesIO(p), PrefixWriter(limit)
if not (isinstance(p, bytes) and src.readable() and dst.writable() and limit > 0):
    print("REFUTATION REJECTED: invalid binary stream input")
else:
    base64.encode(src, dst)
    actual = bytes(dst.data)
    expected = binascii.b2a_base64(p)
    if actual != expected:
        print("REFUTATION CONFIRMED:", (p, limit), "actual:", actual, "expected:", expected)
    else:
        print("REFUTATION REJECTED: actual matches expected")

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library base64:

REFUTATION CONFIRMED: (b'\x00', 1) actual: b'A' expected: b'AA==\n'

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/base64-20261003-020052-c1

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions