You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fix(orchestration): use base64 encoding to prevent quote stripping in docker exec
This commit consolidates several improvements and fixes to shell command
execution within orchestration:
- Use base64 encoding for `docker exec` commands to prevent argument
parsing and quote stripping issues.
- Centralize base64 shell wrapping into utility functions.
- Apply `shlex.quote` to docker run/exec flags and shell wrapping.
- Use `printf` instead of `echo` for known_hosts population.
- Add comprehensive tests for shell utilities and orchestration.
- Update documentation on shell execution and security guidelines.
Copy file name to clipboardExpand all lines: DEVELOPERS.md
+31Lines changed: 31 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -114,6 +114,37 @@ from sparkrun.orchestration.ssh import run_remote_script
114
114
result = run_remote_script(host, script_string, timeout=120, **ssh_kwargs)
115
115
```
116
116
117
+
### Shell Execution & Security
118
+
119
+
Sparkrun frequently dynamically generates bash scripts and Docker commands that interpolate user-provided inputs (like container names, image names, or environment variables). To prevent shell injection and handle spaces/special characters, you MUST adhere to the following rules:
120
+
121
+
1.**Python `shlex.quote`**: When building commands in Python (e.g., `docker run` flags), wrap all interpolated values with `shlex.quote`:
122
+
```python
123
+
import shlex
124
+
cmd =f"docker run --name {shlex.quote(container_name)}{shlex.quote(image)}"
125
+
```
126
+
127
+
2.**Base64 Command Wrapping**: When passing complex commands (especially those with nested quotes or JSON) into `bash -c` or over SSH, use the `b64_encode_cmd` and `b64_wrap_bash` utilities from `sparkrun.utils.shell`:
3.**Use `printf` instead of `echo`**: Inside generated bash scripts (`.sh` files), never use `echo` to output interpolated Python variables. If a variable starts with a hyphen (e.g., `-n`), `echo` may interpret it as a flag. Instead, use `printf` with a format string:
136
+
```bash
137
+
# DANGEROUS: echo "Launching {container_name}"
138
+
# SAFE:
139
+
printf"Launching %%s\n""{container_name}"
140
+
```
141
+
*Note: In Python string formatting (used to populate the scripts), `%` must be escaped as `%%`.*
142
+
143
+
4.**Environment Variables**: When exporting variables in generated bash scripts, quote the interpolated value using `shlex.quote` in Python and omit quotes in the bash script:
0 commit comments