Skip to content

Commit a51cb87

Browse files
committed
Fix OAS 3.0 byte format validation to enforce strict base64
1 parent 0625d81 commit a51cb87

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

openapi_schema_validator/_format.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,13 @@ def is_byte(instance: object) -> bool:
6868
if not isinstance(instance, (str, bytes)):
6969
return True
7070
if isinstance(instance, str):
71-
instance = instance.encode()
71+
instance = instance.encode("ascii", errors="strict")
7272

73-
encoded = b64encode(b64decode(instance))
74-
return encoded == instance
73+
try:
74+
b64decode(instance, validate=True)
75+
except (binascii.Error, ValueError):
76+
return False
77+
return True
7578

7679

7780
def is_password(instance: object) -> bool:

tests/integration/test_validators.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,10 @@ def test_nullable_enum_with_none(self, validator_class):
297297
"value",
298298
[
299299
b64encode(b"string").decode(),
300+
b64encode(b"\x00\x01\x02").decode(),
301+
"",
302+
"AQ==",
303+
"SGVsbG8=",
300304
],
301305
)
302306
def test_string_format_byte_valid(self, validator_class, value):
@@ -309,7 +313,19 @@ def test_string_format_byte_valid(self, validator_class, value):
309313

310314
assert result is None
311315

312-
@pytest.mark.parametrize("value", ["string"])
316+
@pytest.mark.parametrize(
317+
"value",
318+
[
319+
"string",
320+
"SGVsbG8",
321+
"SGVsbG8===",
322+
"SGVsbG8$",
323+
"SGVsbG8 ",
324+
"SGVsbG8\n",
325+
"SGVsbG8_",
326+
"SGVsbG8-",
327+
],
328+
)
313329
def test_string_format_byte_invalid(self, validator_class, value):
314330
schema = {"type": "string", "format": "byte"}
315331
validator = validator_class(

0 commit comments

Comments
 (0)