diff --git a/.azuredevops/adversarial-benchmark.yml b/.azuredevops/adversarial-benchmark.yml index 54fb5fbe7f..1dc3bc4b3f 100644 --- a/.azuredevops/adversarial-benchmark.yml +++ b/.azuredevops/adversarial-benchmark.yml @@ -260,8 +260,7 @@ jobs: fi echo "start-server" > "$artifact_dir/phase.txt" - uv run pyrit_scan \ - --start-server \ + uv run pyrit_scan start-server \ --config-file "$config_file" \ --log-level "$LOG_LEVEL_INPUT" \ --startup-timeout 180 diff --git a/doc/code/scenarios/3_adaptive_scenarios.ipynb b/doc/code/scenarios/3_adaptive_scenarios.ipynb index 608a28e5d0..0e9e84683a 100644 --- a/doc/code/scenarios/3_adaptive_scenarios.ipynb +++ b/doc/code/scenarios/3_adaptive_scenarios.ipynb @@ -928,15 +928,15 @@ "\n", "```bash\n", "# Basic run with defaults\n", - "pyrit_scan --scenario TextAdaptive --target openai_chat\n", + "pyrit_scan run adaptive.text_adaptive --target openai_chat\n", "\n", "# Tune max attempts and restrict techniques\n", - "pyrit_scan --scenario TextAdaptive --target openai_chat \\\n", + "pyrit_scan run adaptive.text_adaptive --target openai_chat \\\n", " --params max_attempts_per_objective=5 \\\n", " --techniques single_turn\n", "\n", "# Use specific datasets and limit size\n", - "pyrit_scan --scenario TextAdaptive --target openai_chat \\\n", + "pyrit_scan run adaptive.text_adaptive --target openai_chat \\\n", " --datasets airt_hate airt_violence \\\n", " --max-total 10\n", "```" diff --git a/doc/code/scenarios/3_adaptive_scenarios.py b/doc/code/scenarios/3_adaptive_scenarios.py index 4da1bc5c7d..ea3e397fc8 100644 --- a/doc/code/scenarios/3_adaptive_scenarios.py +++ b/doc/code/scenarios/3_adaptive_scenarios.py @@ -322,15 +322,15 @@ def _technique_label(result) -> str: # # ```bash # # Basic run with defaults -# pyrit_scan --scenario TextAdaptive --target openai_chat +# pyrit_scan run adaptive.text_adaptive --target openai_chat # # # Tune max attempts and restrict techniques -# pyrit_scan --scenario TextAdaptive --target openai_chat \ +# pyrit_scan run adaptive.text_adaptive --target openai_chat \ # --params max_attempts_per_objective=5 \ # --techniques single_turn # # # Use specific datasets and limit size -# pyrit_scan --scenario TextAdaptive --target openai_chat \ +# pyrit_scan run adaptive.text_adaptive --target openai_chat \ # --datasets airt_hate airt_violence \ # --max-total 10 # ``` diff --git a/doc/scanner/airt.ipynb b/doc/scanner/airt.ipynb index fc8bbcfc6c..e84901fb9b 100644 --- a/doc/scanner/airt.ipynb +++ b/doc/scanner/airt.ipynb @@ -730,7 +730,7 @@ "sends each objective without translation and is included by default.\n", "\n", "```bash\n", - "pyrit_scan airt.multilingual \\\n", + "pyrit_scan run airt.multilingual \\\n", " --initializers target \\\n", " --target openai_chat \\\n", " --datasets harmbench \\\n", diff --git a/doc/scanner/airt.py b/doc/scanner/airt.py index c412ab6621..87a3ad70e9 100644 --- a/doc/scanner/airt.py +++ b/doc/scanner/airt.py @@ -213,7 +213,7 @@ # sends each objective without translation and is included by default. # # ```bash -# pyrit_scan airt.multilingual \ +# pyrit_scan run airt.multilingual \ # --initializers target \ # --target openai_chat \ # --datasets harmbench \ diff --git a/doc/scanner/garak.ipynb b/doc/scanner/garak.ipynb index 4b3f1143a4..50c7320488 100644 --- a/doc/scanner/garak.ipynb +++ b/doc/scanner/garak.ipynb @@ -458,8 +458,8 @@ "**CLI examples:**\n", "\n", "```bash\n", - "pyrit_scan garak.figstep --target openai_chat --datasets figstep --max-total 1\n", - "pyrit_scan garak.figstep --target openai_chat --datasets figstep_pro --max-total 1\n", + "pyrit_scan run garak.figstep --target openai_chat --datasets figstep --max-total 1\n", + "pyrit_scan run garak.figstep --target openai_chat --datasets figstep_pro --max-total 1\n", "```\n", "\n", "> **Note:** The objective target must natively support multi-piece user messages and accept text\n", @@ -1504,7 +1504,7 @@ "**CLI example:**\n", "\n", "```bash\n", - "pyrit_scan garak.system_prompt_extraction --target openai_chat --techniques direct_requests\n", + "pyrit_scan run garak.system_prompt_extraction --target openai_chat --techniques direct_requests\n", "```\n", "\n", "**Available techniques** (9 categories): DirectRequests, RolePlayingAttacks, EncodingBasedAttacks,\n", @@ -1681,10 +1681,10 @@ "\n", "```bash\n", "# Run the default Rust technique.\n", - "pyrit_scan garak.package_hallucination --target openai_chat\n", + "pyrit_scan run garak.package_hallucination --target openai_chat\n", "\n", "# Select another supported language.\n", - "pyrit_scan garak.package_hallucination --target openai_chat --techniques dart\n", + "pyrit_scan run garak.package_hallucination --target openai_chat --techniques dart\n", "```\n", "\n", "**Available techniques** (7 languages): Python, JavaScript, Ruby, Rust, Dart, Perl, Raku.\n", @@ -1842,7 +1842,7 @@ "**CLI example:**\n", "\n", "```bash\n", - "pyrit_scan garak.audio_achilles_heel --target azure_openai_realtime --max-total 2\n", + "pyrit_scan run garak.audio_achilles_heel --target azure_openai_realtime --max-total 2\n", "```\n", "\n", "> **Note:** The objective target must accept `audio_path` input (i.e. be multimodal). The example\n", diff --git a/doc/scanner/garak.py b/doc/scanner/garak.py index 33b72d4a44..525e70d3ec 100644 --- a/doc/scanner/garak.py +++ b/doc/scanner/garak.py @@ -181,8 +181,8 @@ # **CLI examples:** # # ```bash -# pyrit_scan garak.figstep --target openai_chat --datasets figstep --max-total 1 -# pyrit_scan garak.figstep --target openai_chat --datasets figstep_pro --max-total 1 +# pyrit_scan run garak.figstep --target openai_chat --datasets figstep --max-total 1 +# pyrit_scan run garak.figstep --target openai_chat --datasets figstep_pro --max-total 1 # ``` # # > **Note:** The objective target must natively support multi-piece user messages and accept text @@ -486,7 +486,7 @@ # **CLI example:** # # ```bash -# pyrit_scan garak.system_prompt_extraction --target openai_chat --techniques direct_requests +# pyrit_scan run garak.system_prompt_extraction --target openai_chat --techniques direct_requests # ``` # # **Available techniques** (9 categories): DirectRequests, RolePlayingAttacks, EncodingBasedAttacks, @@ -530,10 +530,10 @@ # # ```bash # # Run the default Rust technique. -# pyrit_scan garak.package_hallucination --target openai_chat +# pyrit_scan run garak.package_hallucination --target openai_chat # # # Select another supported language. -# pyrit_scan garak.package_hallucination --target openai_chat --techniques dart +# pyrit_scan run garak.package_hallucination --target openai_chat --techniques dart # ``` # # **Available techniques** (7 languages): Python, JavaScript, Ruby, Rust, Dart, Perl, Raku. @@ -572,7 +572,7 @@ # **CLI example:** # # ```bash -# pyrit_scan garak.audio_achilles_heel --target azure_openai_realtime --max-total 2 +# pyrit_scan run garak.audio_achilles_heel --target azure_openai_realtime --max-total 2 # ``` # # > **Note:** The objective target must accept `audio_path` input (i.e. be multimodal). The example diff --git a/pyrit/cli/pyrit_scan.py b/pyrit/cli/pyrit_scan.py index 95446f3516..2d6e7fa11a 100644 --- a/pyrit/cli/pyrit_scan.py +++ b/pyrit/cli/pyrit_scan.py @@ -283,9 +283,9 @@ def _build_global_parser() -> ArgumentParser: """ Union of every option group. - Used *only* by the legacy shim to strip options and locate a verb; it is never - attached to a command. Keeping it a union (rather than the per-command groups) - lets the shim reorder any option placed before a verb, regardless of which + Used *only* by ``_move_verb_to_front`` to strip options and locate a verb; it is + never attached to a command. Keeping it a union (rather than the per-command + groups) lets any option placed before a verb be reordered, regardless of which command ultimately owns it. Returns: @@ -517,7 +517,7 @@ def _discover_verbs() -> frozenset[str]: return frozenset[str]() -#: Every valid subcommand verb (used by the legacy-argv shim to detect new-style calls). +#: Every valid subcommand verb (used by ``_move_verb_to_front`` to find the verb). #: Derived from _build_parser so adding/renaming a subcommand can't leave this stale. _KNOWN_VERBS: frozenset[str] = _discover_verbs() @@ -636,84 +636,30 @@ def _extract_scenario_args(*, parsed: Namespace) -> dict[str, Any]: } -#: Legacy "mode flag" → new subcommand verb, used by the back-compat shim. -#: ``--start-server`` is intentionally absent: it stays a global modifier flag and -#: only maps to the ``start-server`` verb when it appears with no other command. -_LEGACY_COMMAND_FLAGS: dict[str, str] = { - "--list-scenarios": "list-scenarios", - "--list-initializers": "list-initializers", - "--list-targets": "list-targets", - "--list-converters": "list-converters", - "--list-datasets": "list-datasets", - "--add-initializer": "add-initializer", - "--stop-server": "stop-server", -} - - -def _warn_legacy(*, old: str, new: str) -> None: - """Warn (visibly and via ``DeprecationWarning``) about a legacy ``pyrit_scan`` invocation.""" - from pyrit.common import print_deprecation_message - - print_deprecation_message(old_item=f"pyrit_scan {old}", new_item=f"pyrit_scan {new}", removed_in="1.3.0") - # DeprecationWarning is suppressed by default in a CLI, so also print a visible note. - print(f"Note: 'pyrit_scan {old}' is deprecated; use 'pyrit_scan {new}' instead.", file=sys.stderr) - - -def _translate_legacy_argv(argv: list[str]) -> list[str]: +def _move_verb_to_front(argv: list[str]) -> list[str]: """ - Rewrite legacy flag-style invocations into the new subcommand form. + Move a verb that follows global options to the front of the argument list. - Back-compat shim for one release. Maps ``--list-scenarios`` → ``list-scenarios`` - etc., a bare ```` → ``run `` (implicit run), and a standalone - ``--start-server`` → the ``start-server`` verb, emitting a deprecation warning - for each. It also (without warning) moves a new-style verb to the front when it - was placed after global options (e.g. ``--server-url X list-scenarios``), so - globals work before or after the verb. New-style calls that already start with a - verb pass through untouched, as does the brand-new ``scenario-results`` surface - (no legacy form). Delete this function when the deprecation window closes. + Global options may be given before or after the verb (for example + ``--server-url X list-scenarios``). The verb's sub-parser has to see them, so a + verb found after the global options is moved to the front. Anything else, + including top-level ``--help``, is returned unchanged for argparse to handle. Args: argv (list[str]): The raw argument list (already ``sys.argv[1:]``). Returns: - list[str]: The possibly-rewritten argument list to feed to argparse. + list[str]: The argument list with the verb first, when one was found. """ if not argv or argv[0] in _KNOWN_VERBS or argv[0] in ("-h", "--help"): return argv - # A legacy command flag anywhere in argv → prepend its verb, drop the flag. - for index, token in enumerate(argv): - verb = _LEGACY_COMMAND_FLAGS.get(token) - if verb is not None: - _warn_legacy(old=token, new=verb) - return [verb, *argv[:index], *argv[index + 1 :]] - - # No legacy command flag. Strip global options with the global parser and - # inspect what remains. + # Strip global options with the global parser and see whether a verb follows. _, leftover = _build_global_parser().parse_known_args(argv) - if leftover: - if leftover[0] in _KNOWN_VERBS: - # A new-style verb placed after global options (e.g. - # ``--server-url X list-scenarios``). Move the verb to the front so its - # sub-parser sees the globals. This is valid ordering, not a legacy - # form, so it does not warn. - verb = leftover[0] - index = argv.index(verb) - return [verb, *argv[:index], *argv[index + 1 :]] - if leftover[0] in ("-h", "--help"): - # Global options followed by top-level help (e.g. ``--server-url X --help``). - # Leave argv untouched so the root parser prints its own help instead of - # misreading ``--help`` as an implicit scenario name. - return argv - # Otherwise it is a bare scenario name (+ run flags) → implicit run. - _warn_legacy(old=" (implicit run)", new="run ") - return ["run", *argv] - - # Only global options remained: a standalone --start-server means "just start". - if "--start-server" in argv: - _warn_legacy(old="--start-server", new="start-server") - return ["start-server", *[token for token in argv if token != "--start-server"]] - + if leftover and leftover[0] in _KNOWN_VERBS: + verb = leftover[0] + index = argv.index(verb) + return [verb, *argv[:index], *argv[index + 1 :]] return argv @@ -721,11 +667,11 @@ def parse_args(args: list[str] | None = None) -> Namespace: """ Parse command-line arguments (pass 1 — tolerant of scenario-declared flags). - The raw argv is first run through ``_translate_legacy_argv`` (the back-compat - shim). Pass 1 then uses ``parse_known_args`` so scenario-specific flags (e.g. + The raw argv is first run through ``_move_verb_to_front``, so global options + work before or after the verb. Pass 1 then uses ``parse_known_args`` so scenario-specific flags (e.g. ``--max-turns 7``) don't error before we've fetched the scenario's declared parameters. Unknown leftovers are stashed on the Namespace as ``_unknown_args``, - and the translated argv as ``_translated_args``, for the ``run`` reparse. + and the reordered argv as ``_translated_args``, for the ``run`` reparse. Args: args: Argument list (``sys.argv[1:]`` when None). @@ -734,7 +680,7 @@ def parse_args(args: list[str] | None = None) -> Namespace: Namespace: Parsed command-line arguments. """ raw_args = list(args) if args is not None else list(sys.argv[1:]) - translated = _translate_legacy_argv(raw_args) + translated = _move_verb_to_front(raw_args) parser = _build_parser(add_help=True) parsed, unknown = parser.parse_known_args(translated) parsed._unknown_args = unknown @@ -1531,10 +1477,20 @@ def main(args: list[str] | None = None) -> int: except SystemExit as e: return e.code if isinstance(e.code, int) else 1 - # No verb at all: show the top-level help listing the subcommands. + # No verb at all: show the top-level help listing the subcommands. Arguments + # without a verb (such as a scenario name or a flag) are a usage error. if getattr(parsed_args, "command", None) is None: - _build_parser().print_help() - return 0 + parser = _build_parser() + if not parsed_args._translated_args: + parser.print_help() + return 0 + parser.print_usage(sys.stderr) + print( + f"{parser.prog}: error: a command is required " + f"(got: {' '.join(parsed_args._translated_args)}); see '{parser.prog} --help'", + file=sys.stderr, + ) + return 2 # Unknown flags are only expected for `run` (scenario-declared flags, resolved # in the reparse). For any other verb they are genuinely unrecognized. diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index e85fc01a06..d2f1992b67 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -587,7 +587,7 @@ def supported_parameters(cls) -> list[Parameter]: common case). Override *this* method only to **remove or replace** a common input, composing against ``super().supported_parameters()``. - Implemented as a classmethod so ``--list-scenarios`` can introspect without + Implemented as a classmethod so ``list-scenarios`` can introspect without instantiating. Returns: diff --git a/pyrit/setup/initializers/preload_scenario_metadata.py b/pyrit/setup/initializers/preload_scenario_metadata.py index 687aaaf4aa..0dc09de2b3 100644 --- a/pyrit/setup/initializers/preload_scenario_metadata.py +++ b/pyrit/setup/initializers/preload_scenario_metadata.py @@ -7,7 +7,7 @@ Each registered ``Scenario`` is instantiated once so the registry can read the strategy class, default strategy, and default dataset configuration off the instance. The results are cached on ``Registry._metadata_cache``; the -first ``--list-scenarios`` / GUI call is then a cache hit. Per-scenario +first ``list-scenarios`` / GUI call is then a cache hit. Per-scenario instantiation failures surface loudly here at startup rather than later. """ diff --git a/tests/unit/cli/test_pyrit_scan.py b/tests/unit/cli/test_pyrit_scan.py index 86b3100ff2..8e674dfe2c 100644 --- a/tests/unit/cli/test_pyrit_scan.py +++ b/tests/unit/cli/test_pyrit_scan.py @@ -331,57 +331,62 @@ def test_client_handlers_cover_every_post_client_verb(self): assert set(pyrit_scan._CLIENT_HANDLERS) == expected -class TestLegacyArgvShim: - """The back-compat shim maps old flag forms to verbs and warns.""" +class TestVerbPlacement: + """Global options work before or after the verb; arguments without a verb are a usage error.""" - def test_legacy_list_flag_maps_to_verb(self): - with pytest.warns(DeprecationWarning, match="list-scenarios"): - args = pyrit_scan.parse_args(["--list-scenarios"]) + def test_new_style_verb(self): + args = pyrit_scan.parse_args(["list-scenarios"]) assert args.command == "list-scenarios" - def test_legacy_stop_server_flag_maps_to_verb(self): - with pytest.warns(DeprecationWarning, match="stop-server"): - args = pyrit_scan.parse_args(["--stop-server"]) - assert args.command == "stop-server" - - def test_legacy_add_initializer_flag_maps_to_verb(self): - with pytest.warns(DeprecationWarning, match="add-initializer"): - args = pyrit_scan.parse_args(["--add-initializer", "a.py", "b.py"]) - assert args.command == "add-initializer" - assert args.files == ["a.py", "b.py"] - - def test_legacy_flag_preserves_globals(self): - with pytest.warns(DeprecationWarning): - args = pyrit_scan.parse_args(["--server-url", "http://x", "--list-targets"]) - assert args.command == "list-targets" + def test_global_before_verb_moves_verb_to_front(self): + args = pyrit_scan.parse_args(["--server-url", "http://x", "list-scenarios"]) + assert args.command == "list-scenarios" assert args.server_url == "http://x" - def test_implicit_run_maps_to_run_verb(self): - with pytest.warns(DeprecationWarning, match="run "): - args = pyrit_scan.parse_args(["foundry", "--target", "t"]) - assert args.command == "run" - assert args.scenario_name == "foundry" - assert args.target == "t" - - def test_standalone_start_server_flag_maps_to_verb(self): - with pytest.warns(DeprecationWarning, match="start-server"): - args = pyrit_scan.parse_args(["--start-server"]) + def test_start_server_verb_with_benchmark_pipeline_options(self): + # The form .azuredevops/adversarial-benchmark.yml uses. + args = pyrit_scan.parse_args( + ["start-server", "--config-file", "conf.yaml", "--log-level", "INFO", "--startup-timeout", "180"] + ) assert args.command == "start-server" + assert args.startup_timeout == 180 + assert not args._unknown_args - def test_new_style_verb_does_not_warn(self, recwarn): - args = pyrit_scan.parse_args(["list-scenarios"]) - assert args.command == "list-scenarios" - assert not [w for w in recwarn if issubclass(w.category, DeprecationWarning)] + def test_start_server_modifier_before_verb(self): + args = pyrit_scan.parse_args(["--start-server", "list-targets"]) + assert args.command == "list-targets" + assert args.start_server is True - def test_legacy_flag_prints_visible_note(self, capsys): - with pytest.warns(DeprecationWarning): - pyrit_scan.parse_args(["--list-scenarios"]) - assert "Note:" in capsys.readouterr().err + @pytest.mark.parametrize( + "argv", + [ + ["--list-scenarios"], + ["--list-initializers"], + ["--list-targets"], + ["--list-converters"], + ["--list-datasets"], + ["--add-initializer", "a.py", "b.py"], + ["--stop-server"], + ["--server-url", "http://x", "--list-targets"], + ["foundry", "--target", "t"], + ["--start-server"], + ], + ) + def test_removed_flag_style_forms_are_usage_errors(self, argv, capsys): + with patch.object(pyrit_scan, "_run_async") as mock_run: + assert pyrit_scan.main(argv) == 2 + mock_run.assert_not_called() + assert "error:" in capsys.readouterr().err + + def test_commandless_arguments_error_names_them(self, capsys): + assert pyrit_scan.main(["--server-url", "http://x", "--list-targets"]) == 2 + err = capsys.readouterr().err + assert "a command is required" in err + assert "--server-url http://x --list-targets" in err - def test_global_before_verb_does_not_warn(self, recwarn): - args = pyrit_scan.parse_args(["--server-url", "http://x", "list-scenarios"]) - assert args.command == "list-scenarios" - assert not [w for w in recwarn if issubclass(w.category, DeprecationWarning)] + def test_no_arguments_shows_help(self, capsys): + assert pyrit_scan.main([]) == 0 + assert "" in capsys.readouterr().out @pytest.mark.parametrize("value", ["0", "-1", "inf", "nan", "slow"]) def test_parse_args_rejects_invalid_startup_timeout(self, value):