Skip to content

Fix ValueError/IndexError crash in SafeLoader for malformed numeric scalars (#898)#920

Open
Nicolas0315 wants to merge 1 commit intoyaml:mainfrom
Nicolas0315:fix/safe-loader-malformed-numeric-crash
Open

Fix ValueError/IndexError crash in SafeLoader for malformed numeric scalars (#898)#920
Nicolas0315 wants to merge 1 commit intoyaml:mainfrom
Nicolas0315:fix/safe-loader-malformed-numeric-crash

Conversation

@Nicolas0315
Copy link
Copy Markdown

Summary

Fix uncaught ValueError/IndexError in SafeLoader when parsing malformed numeric scalars like 0x_, !!float +_, and !!float 1::3.

Root Cause

construct_yaml_int and construct_yaml_float strip underscores from the scalar value before parsing, but don't handle the case where stripping leaves an empty or invalid string:

Input After replace('_', '') Failure
0x_ 0x int('', 16)ValueError
0b_ 0b int('', 2)ValueError
!!float +_ + → ``(empty after sign strip) value[0]IndexError
!!float 1::3 1::3 float('') (empty split part) → ValueError

Fix

Wrap the parsing logic in try/except to convert ValueError and IndexError into ConstructorError, which is the expected exception type for invalid YAML values. This matches the behavior of other constructors in PyYAML (e.g. construct_yaml_binary).

Testing

import yaml

# All now raise ConstructorError instead of ValueError/IndexError:
yaml.safe_load('0x_')        # ConstructorError ✓
yaml.safe_load('0b_')        # ConstructorError ✓  
yaml.safe_load('!!float +_') # ConstructorError ✓
yaml.safe_load('!!float 1::3') # ConstructorError ✓

# Normal values still work:
yaml.safe_load('42')        # 42 ✓
yaml.safe_load('0x1F')      # 31 ✓
yaml.safe_load('3.14')      # 3.14 ✓

Fixes #898

…calars

Wrap construct_yaml_int and construct_yaml_float in try/except to
catch ValueError and IndexError from malformed inputs like '0x_',
'!!float +_', and '!!float 1::3'. These previously bubbled up as
uncaught exceptions instead of ConstructorError.

After underscore removal, values like '0x_' become '0x' which causes
int('', 16) to raise ValueError. Similarly, '!!float +_' becomes an
empty string after removing the sign, causing IndexError on value[0].

The fix delegates to private _construct_yaml_int/_construct_yaml_float
methods and wraps them with proper ConstructorError conversion.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Malformed Numeric Scalars Crash SafeLoader with ValueError

1 participant