]> git.ipfire.org Git - thirdparty/postgresql.git/commitdiff
Fix truncation rules for base64 encoding
authorDaniel Gustafsson <dgustafsson@postgresql.org>
Fri, 17 Jul 2026 13:40:16 +0000 (15:40 +0200)
committerDaniel Gustafsson <dgustafsson@postgresql.org>
Fri, 17 Jul 2026 13:40:16 +0000 (15:40 +0200)
Commit e1d917182 added support for base64url encoding, a base64 variant
intended to be safe for usage in URLs and filenames.  The padding rules
for base64url and base64 differ in that base64url require no extra '='
padding, but the commit unintentionally relaxed this requirement for
base64 as well.  Fix by making sure that the truncation logic check
for the encoding and add a test to make sure.

Backpatch down to v19 where support for base64url was introduced.

Author: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: David E. Wheeler <david@justatheory.com>
Discussion: https://postgr.es/m/3258FC72-F5E1-40B9-B5D7-64478CAF7728@yesql.se
Backpatch-through: 19

src/backend/utils/adt/encode.c
src/test/regress/expected/strings.out
src/test/regress/sql/strings.sql

index 9ea3ddb49ec0346f0ca140307ef68bf86212b80b..b9d4f2811d76c8b68e3494e135ecc7b699816b30 100644 (file)
@@ -583,12 +583,12 @@ pg_base64_decode_internal(const char *src, size_t len, char *dst, bool url)
                }
        }
 
-       if (pos == 2)
+       if (url && pos == 2)
        {
                buf <<= 12;
                *p++ = (buf >> 16) & 0xFF;
        }
-       else if (pos == 3)
+       else if (url && pos == 3)
        {
                buf <<= 6;
                *p++ = (buf >> 16) & 0xFF;
index a49b75fa1f9932efa3bc54a8533c34c8f3089f5f..313c50394650a55bc1ddc9cfb18878cc6b4d023f 100644 (file)
@@ -2810,6 +2810,10 @@ SELECT decode('AQ', 'base64url');    -- \x01
  \x01
 (1 row)
 
+-- Make sure the same 1 byte input isn't accepted as base64
+SELECT decode('AQ', 'base64');    -- \x01
+ERROR:  invalid base64 end sequence
+HINT:  Input data is missing padding, is truncated, or is otherwise corrupted.
 -- 2 byte input
 SELECT encode('\x0102'::bytea, 'base64url');  -- AQI
  encode 
index 5ae0e7da31a38b15041242c97ed4bc66f3555340..38946e8954df2a8490526e8aad8b5d9353b52a10 100644 (file)
@@ -909,6 +909,9 @@ SELECT decode('', 'base64url');  -- ''
 SELECT encode('\x01', 'base64url');  -- AQ
 SELECT decode('AQ', 'base64url');    -- \x01
 
+-- Make sure the same 1 byte input isn't accepted as base64
+SELECT decode('AQ', 'base64');    -- \x01
+
 -- 2 byte input
 SELECT encode('\x0102'::bytea, 'base64url');  -- AQI
 SELECT decode('AQI', 'base64url');            -- \x0102