0
# Safe Operations
1
2
Safe YAML operations designed for processing untrusted input. These functions use SafeLoader and SafeDumper which only handle basic YAML types (strings, numbers, booleans, lists, dictionaries, and null values), preventing execution of arbitrary Python code.
3
4
## Capabilities
5
6
### Safe Loading
7
8
Load YAML documents safely by restricting parsing to basic YAML types only. This is the recommended approach for processing YAML from untrusted sources.
9
10
```python { .api }
11
def safe_load(stream):
12
"""
13
Parse the first YAML document in a stream and produce the corresponding Python object.
14
15
Resolve only basic YAML tags. This is known to be safe for untrusted input.
16
17
Args:
18
stream (str | bytes | IO): YAML content as string, bytes, or file-like object
19
20
Returns:
21
Any: Python object representing the YAML document
22
23
Raises:
24
YAMLError: If the document cannot be parsed
25
MarkedYAMLError: If there's a syntax error with position information
26
"""
27
28
def safe_load_all(stream):
29
"""
30
Parse all YAML documents in a stream and produce corresponding Python objects.
31
32
Resolve only basic YAML tags. This is known to be safe for untrusted input.
33
34
Args:
35
stream (str | bytes | IO): YAML content containing multiple documents
36
37
Yields:
38
Any: Python objects representing each YAML document
39
40
Raises:
41
YAMLError: If any document cannot be parsed
42
MarkedYAMLError: If there's a syntax error with position information
43
"""
44
```
45
46
#### Usage Examples
47
48
```python
49
import yaml
50
51
# Load a single document
52
config = yaml.safe_load("""
53
database:
54
host: localhost
55
port: 5432
56
name: myapp
57
credentials:
58
username: user
59
password: secret
60
""")
61
62
print(config['database']['host']) # localhost
63
64
# Load multiple documents
65
documents = yaml.safe_load_all("""
66
---
67
name: Development Config
68
database:
69
host: dev.example.com
70
---
71
name: Production Config
72
database:
73
host: prod.example.com
74
""")
75
76
for doc in documents:
77
print(f"Config: {doc['name']}")
78
print(f"Host: {doc['database']['host']}")
79
```
80
81
### Safe Dumping
82
83
Generate YAML output using only basic YAML tags, ensuring the output can be safely processed by any YAML parser.
84
85
```python { .api }
86
def safe_dump(data, stream=None, **kwds):
87
"""
88
Serialize a Python object into a YAML stream.
89
Produce only basic YAML tags.
90
91
Args:
92
data (Any): Python object to serialize
93
stream (IO, optional): Output stream. If None, return as string
94
**kwds: Additional keyword arguments for formatting
95
96
Keyword Arguments:
97
default_flow_style (bool): Use flow style for collections (default: False)
98
canonical (bool): Produce canonical YAML (default: False)
99
indent (int): Number of spaces for indentation (default: 2)
100
width (int): Maximum line width (default: 80)
101
allow_unicode (bool): Allow unicode characters (default: True)
102
line_break (str): Line break character(s) (default: platform default)
103
encoding (str): Output encoding for byte streams (default: 'utf-8')
104
explicit_start (bool): Write document start marker (default: False)
105
explicit_end (bool): Write document end marker (default: False)
106
version (tuple): YAML version to use (default: (1, 1))
107
tags (dict): Custom tag mappings
108
sort_keys (bool): Sort dictionary keys (default: True)
109
110
Returns:
111
str | None: YAML string if stream is None, otherwise None
112
113
Raises:
114
RepresenterError: If an object cannot be represented
115
"""
116
117
def safe_dump_all(documents, stream=None, **kwds):
118
"""
119
Serialize a sequence of Python objects into a YAML stream.
120
Produce only basic YAML tags.
121
122
Args:
123
documents (Iterable[Any]): Sequence of Python objects to serialize
124
stream (IO, optional): Output stream. If None, return as string
125
**kwds: Additional keyword arguments (same as safe_dump)
126
127
Returns:
128
str | None: YAML string if stream is None, otherwise None
129
130
Raises:
131
RepresenterError: If any object cannot be represented
132
"""
133
```
134
135
#### Usage Examples
136
137
```python
138
import yaml
139
140
data = {
141
'application': 'MyApp',
142
'version': '1.0.0',
143
'features': ['auth', 'api', 'ui'],
144
'settings': {
145
'debug': False,
146
'max_connections': 100
147
}
148
}
149
150
# Dump to string with default formatting
151
yaml_output = yaml.safe_dump(data)
152
print(yaml_output)
153
154
# Dump with custom formatting
155
yaml_formatted = yaml.safe_dump(
156
data,
157
default_flow_style=False,
158
indent=4,
159
width=120,
160
sort_keys=False
161
)
162
print(yaml_formatted)
163
164
# Dump multiple documents
165
documents = [
166
{'name': 'Config 1', 'value': 100},
167
{'name': 'Config 2', 'value': 200}
168
]
169
170
yaml_multi = yaml.safe_dump_all(
171
documents,
172
explicit_start=True,
173
explicit_end=False
174
)
175
print(yaml_multi)
176
177
# Dump to file
178
with open('config.yaml', 'w') as f:
179
yaml.safe_dump(data, f, default_flow_style=False)
180
```
181
182
## Supported Data Types
183
184
Safe operations support the following Python data types:
185
186
- **Scalars**: `str`, `int`, `float`, `bool`, `None`
187
- **Collections**: `list`, `tuple`, `dict`
188
- **Special values**: YAML null, boolean true/false
189
190
### Type Mapping
191
192
| Python Type | YAML Tag | Example |
193
|-------------|----------|---------|
194
| `None` | `!!null` | `null` |
195
| `bool` | `!!bool` | `true`, `false` |
196
| `int` | `!!int` | `42`, `0x2A`, `0o52` |
197
| `float` | `!!float` | `3.14`, `1e10`, `.inf`, `.nan` |
198
| `str` | `!!str` | `"hello"`, `'world'`, `plain` |
199
| `list` | `!!seq` | `[1, 2, 3]` or block sequence |
200
| `dict` | `!!map` | `{a: 1, b: 2}` or block mapping |
201
202
## Security Benefits
203
204
Safe operations provide protection against:
205
206
- **Code execution**: Cannot instantiate arbitrary Python classes
207
- **File system access**: Cannot read/write files through YAML tags
208
- **Import statements**: Cannot import modules or access built-ins
209
- **Object instantiation**: Limited to basic Python types
210
211
This makes safe operations suitable for:
212
- Configuration files from untrusted sources
213
- API payloads containing YAML data
214
- User-provided configuration or data files
215
- Any scenario where YAML content cannot be fully trusted