Skip to content

Commit 6920d2c

Browse files
authored
Escape Rich markup in airflowctl variable and pool commands (#76419)
User-supplied inputs such as file paths, imported variable keys, and server error responses containing square brackets or Rich markup tags can cause unhandled rich.errors.MarkupError crashes when printed via rich.print or Console().print. Escaping these strings ensures special characters are treated as literal text rather than formatting tags.
1 parent 596dd41 commit 6920d2c

4 files changed

Lines changed: 83 additions & 7 deletions

File tree

‎airflow-ctl/src/airflowctl/ctl/commands/pool_command.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import rich
2626
from pydantic import ValidationError
27+
from rich.markup import escape
2728

2829
from airflowctl.api.client import NEW_API_CLIENT, Client, ClientKind, provide_api_client
2930
from airflowctl.api.datamodels.generated import (
@@ -79,7 +80,7 @@ def export(args, api_client: Client = NEW_API_CLIENT) -> None:
7980
file_path = Path(args.file)
8081
with open(file_path, "w") as f:
8182
json.dump(pools_list, f, indent=4, sort_keys=True)
82-
rich.print(f"Exported {pools_response.total_entries} pool(s) to {args.file}")
83+
rich.print(f"Exported {pools_response.total_entries} pool(s) to {escape(str(args.file))}")
8384
else:
8485
AirflowConsole().print_as(data=pools_list, output=args.output)
8586
except Exception as e:

‎airflow-ctl/src/airflowctl/ctl/commands/variable_command.py‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,12 @@
3636

3737

3838
def _print_file_error(message: str, file_path: str) -> None:
39-
Console().print(f"[red]{message}: {file_path}", soft_wrap=True)
39+
Console().print(f"[red]{message}: {escape(file_path)}[/red]", soft_wrap=True)
4040

4141

4242
@provide_api_client(kind=ClientKind.CLI)
4343
def import_(args, api_client=NEW_API_CLIENT) -> list[str]:
4444
"""Import variables from a given file."""
45-
success_message = "[green]Import successful! success: {success}[/green]"
46-
errors_message = "[red]Import failed! errors: {errors}[/red]"
47-
4845
if not os.path.exists(args.file):
4946
_print_file_error("Missing variable file", args.file)
5047
sys.exit(1)
@@ -87,8 +84,8 @@ def import_(args, api_client=NEW_API_CLIENT) -> list[str]:
8784
)
8885
result = api_client.variables.bulk(variables=bulk_body)
8986
if result.create.errors:
90-
rich.print(errors_message.format(errors=result.create.errors))
87+
rich.print(f"[red]Import failed! errors: {escape(str(result.create.errors))}[/red]")
9188
sys.exit(1)
9289

93-
rich.print(success_message.format(success=result.create.success))
90+
rich.print(f"[green]Import successful! success: {escape(str(result.create.success))}[/green]")
9491
return result.create.success

‎airflow-ctl/tests/airflow_ctl/ctl/commands/test_pool_command.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,3 +312,36 @@ def test_export_failure(self, mock_client, tmp_path):
312312

313313
with pytest.raises(SystemExit, match="Failed to export pools: API Error"):
314314
pool_command.export(mock.MagicMock(file=export_file, output="json"))
315+
316+
def test_export_json_file_path_containing_markup(self, mock_client, tmp_path, capsys):
317+
"""Test that exporting to a file path containing markup tags does not crash."""
318+
markup_dir = tmp_path / "dir["
319+
markup_dir.mkdir()
320+
export_file = markup_dir / "test].json"
321+
mock_pools = mock.MagicMock()
322+
mock_pools.pools = [
323+
type(
324+
"Pool",
325+
(),
326+
{
327+
"name": "p",
328+
"slots": 1,
329+
"description": "",
330+
"include_deferred": False,
331+
"occupied_slots": 0,
332+
"running_slots": 0,
333+
"queued_slots": 0,
334+
"scheduled_slots": 0,
335+
"open_slots": 1,
336+
"deferred_slots": 0,
337+
"team_name": None,
338+
},
339+
)()
340+
]
341+
mock_pools.total_entries = 1
342+
mock_client.pools.list.return_value = mock_pools
343+
344+
pool_command.export(mock.MagicMock(file=export_file, output="json"))
345+
346+
out = capsys.readouterr().out.replace("\n", "")
347+
assert str(export_file) in out

‎airflow-ctl/tests/airflow_ctl/ctl/commands/test_variable_command.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,48 @@ def test_import_error(self, api_client_maker, tmp_path, monkeypatch):
193193
self.parser.parse_args(["variables", "import", expected_json_path.as_posix()]),
194194
api_client=api_client,
195195
)
196+
197+
def test_print_file_error_containing_markup(self, capsys):
198+
variable_command._print_file_error("Missing variable file", "/tmp/[/x]/vars.json")
199+
output = capsys.readouterr().out
200+
assert "/tmp/[/x]/vars.json" in output
201+
202+
def test_import_success_prints_variable_keys_containing_markup(self, tmp_path, monkeypatch, capsys):
203+
bulk_response = BulkResponse(
204+
create=BulkActionResponse(success=["key_[/x]"], errors=[]), update=None, delete=None
205+
)
206+
api_client = SimpleNamespace(variables=SimpleNamespace(bulk=lambda variables: bulk_response))
207+
monkeypatch.chdir(tmp_path)
208+
expected_json_path = tmp_path / self.export_file_name
209+
expected_json_path.write_text(json.dumps({"key_[/x]": "value"}))
210+
211+
response = variable_command.import_(
212+
self.parser.parse_args(["variables", "import", expected_json_path.as_posix()]),
213+
api_client=api_client,
214+
)
215+
assert response == ["key_[/x]"]
216+
output = capsys.readouterr().out
217+
assert "key_[/x]" in output
218+
219+
def test_import_error_containing_markup(self, tmp_path, monkeypatch, capsys):
220+
bulk_response = BulkResponse(
221+
create=BulkActionResponse(
222+
success=[],
223+
errors=[{"error": "Failed for [/x] key", "status_code": 400}],
224+
),
225+
update=None,
226+
delete=None,
227+
)
228+
api_client = SimpleNamespace(variables=SimpleNamespace(bulk=lambda variables: bulk_response))
229+
monkeypatch.chdir(tmp_path)
230+
expected_json_path = tmp_path / self.export_file_name
231+
expected_json_path.write_text(json.dumps({self.key: self.value}))
232+
233+
with pytest.raises(SystemExit) as exit_info:
234+
variable_command.import_(
235+
self.parser.parse_args(["variables", "import", expected_json_path.as_posix()]),
236+
api_client=api_client,
237+
)
238+
assert exit_info.value.code == 1
239+
output = capsys.readouterr().out
240+
assert "[/x]" in output

0 commit comments

Comments
 (0)