diff --git a/README.md b/README.md index 78f0227..95a1b2d 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ ctxd login # Prompt for an API key and store it ctxd status # Check whether an API key is configured ctxd install-app # Open the app installation page ctxd search "text:deployment" -ctxd search text:test application:slack +ctxd search application:slack text:test ctxd fetch doc-123 ctxd profile ctxd logout # Remove the stored API key @@ -54,7 +54,7 @@ from ctxd import Client client = Client(api_key="") -results = client.search("text:deployment application:slack") +results = client.search("application:slack text:deployment") profile = client.get_profile() document = client.fetch_document("doc-123") ``` @@ -65,7 +65,7 @@ API key example: from ctxd import Client client = Client(api_key="") -results = client.search("text:deployment application:slack") +results = client.search("application:slack text:deployment") ``` Async example: diff --git a/src/ctxd/cli.py b/src/ctxd/cli.py index 43b52a2..91bd289 100644 --- a/src/ctxd/cli.py +++ b/src/ctxd/cli.py @@ -5,6 +5,7 @@ import json import os import re +import shlex import sys import webbrowser from typing import Sequence @@ -31,7 +32,9 @@ def main(argv: Sequence[str] | None = None) -> int: client = Client() if args.command == "search": - result = client.search(_normalize_search_query(args.query)) + query = _normalize_search_query(args.query) + _validate_search_query(query) + result = client.search(query) return _emit_result(result.model_dump(), as_json=True) if args.command == "fetch": result = client.fetch_document(args.document_uid) @@ -58,7 +61,7 @@ def _build_parser() -> argparse.ArgumentParser: "Examples:\n" " ctxd login\n" " ctxd install-app\n" - " ctxd search text:deployment application:slack\n" + " ctxd search application:slack text:deployment\n" " ctxd fetch doc-123 --json" ), formatter_class=argparse.RawDescriptionHelpFormatter, @@ -112,12 +115,19 @@ def _build_parser() -> argparse.ArgumentParser: help="Search indexed app content and print JSON results.", description=( "Search indexed app content using ctxd DSL. Search output is always JSON. " - "The query can be quoted or passed as separate tokens." + "The query can be passed as separate tokens." ), epilog=( "Examples:\n" - " ctxd search text:deployment application:slack\n" - ' ctxd search "text:deployment application:slack"' + " ctxd search text:deployment\n" + " ctxd search application:slack text:deployment\n" + "\n" + "Query format:\n" + " application: text:\n" + " application: is optional; omit it to search all connected apps.\n" + " If application: is present, it must be the first token.\n" + " Only one application filter is supported.\n" + " Use one text term; multi-word, quoted, and parenthesized text values are not supported." ), formatter_class=argparse.RawDescriptionHelpFormatter, ) @@ -125,7 +135,7 @@ def _build_parser() -> argparse.ArgumentParser: "query", nargs="+", metavar="QUERY", - help="Search query or DSL tokens, for example: text:deployment application:slack.", + help="Search query tokens, for example: application:slack text:deployment.", ) fetch_parser = subparsers.add_parser( @@ -155,29 +165,116 @@ def _build_parser() -> argparse.ArgumentParser: def _normalize_search_query(query_tokens: Sequence[str]) -> str: - normalized_tokens = [ - _quote_shell_stripped_text_token(token) for token in query_tokens - ] - return " ".join(normalized_tokens) + return " ".join(query_tokens) -def _quote_shell_stripped_text_token(token: str) -> str: - if not token.lower().startswith("text:"): - return token +def _validate_search_query(query: str) -> None: + _validate_raw_text_filters(query) + tokens = _split_search_query(query) + _validate_application_filters(tokens) + _validate_boolean_operators(tokens) + _validate_text_filters(tokens) + _validate_application_scoped_search_shape(tokens) - value = token[5:] - if not value or not re.search(r"\s", value): - return token - stripped_value = value.strip() - if ( - stripped_value.startswith(("\"", "'", "(")) - or stripped_value.endswith(("\"", "'", ")")) - ): - return token +def _split_search_query(query: str) -> list[str]: + try: + return shlex.split(query) + except ValueError: + return query.split() + + +def _validate_raw_text_filters(query: str) -> None: + if re.search(r"(?i)(?:^|\s)text:[\"'()]", query): + raise ValueError( + "Invalid search query: quoted and parenthesized text values are not supported. " + "Use a single text term, for example text:incident." + ) + + +def _validate_application_filters(tokens: Sequence[str]) -> None: + application_positions: list[int] = [] + for index, token in enumerate(tokens): + if not token.lower().startswith("application:"): + continue + + value = token[len("application:") :] + if not value: + raise ValueError( + "Invalid search query: application: requires an app name, for example application:slack." + ) + if value.startswith("("): + raise ValueError( + "Invalid search query: grouped application filters are not supported. " + "Use one leading application filter, for example application:google_drive text:onboarding." + ) + application_positions.append(index) + + if not application_positions: + return + if application_positions[0] != 0: + raise ValueError( + "Invalid search query: application: must be the first token, " + "for example application:slack text:deployment." + ) + if len(application_positions) > 1: + raise ValueError( + "Invalid search query: only one application filter is supported. " + "Omit application: to search all connected apps." + ) + - escaped_value = stripped_value.replace("\\", "\\\\").replace('"', '\\"') - return f'text:"{escaped_value}"' +def _validate_text_filters(tokens: Sequence[str]) -> None: + text_positions: list[int] = [] + for index, token in enumerate(tokens): + if not token.lower().startswith("text:"): + continue + + text_positions.append(index) + value = token[len("text:") :] + if value.startswith(("\"", "'", "(")) or value.endswith(("\"", "'", ")")): + raise ValueError( + "Invalid search query: quoted and parenthesized text values are not supported. " + "Use a single text term, for example text:incident." + ) + if re.search(r"\s", value): + raise ValueError( + "Invalid search query: multi-word text values are not supported by the current DSL. " + "Use a single text term, for example text:incident." + ) + if index + 1 < len(tokens) and not tokens[index + 1].lower().startswith( + ("application:", "text:") + ): + raise ValueError( + "Invalid search query: multi-word text values are not supported by the current DSL. " + "Use a single text term, for example text:incident." + ) + + if len(text_positions) > 1: + raise ValueError( + "Invalid search query: only one text filter is supported. " + "Use a single text term, for example text:incident." + ) + + +def _validate_boolean_operators(tokens: Sequence[str]) -> None: + operators = {"AND", "OR"} + for token in tokens: + if token in operators: + raise ValueError( + "Invalid search query: AND/OR clauses are not supported. " + "Use application: text:, or omit application: to search all apps." + ) + + +def _validate_application_scoped_search_shape(tokens: Sequence[str]) -> None: + if not tokens or not tokens[0].lower().startswith("application:"): + return + if len(tokens) != 2 or not tokens[1].lower().startswith("text:"): + raise ValueError( + "Invalid search query: application: must be followed by one text: filter, " + "for example application:slack text:deployment." + ) def _handle_login(args: argparse.Namespace) -> int: @@ -311,6 +408,14 @@ def _emit_result(payload: dict, *, as_json: bool) -> int: def _payload_has_error(payload: dict) -> bool: + if "results" in payload: + return bool(payload.get("error") or payload.get("dsl_parse_error")) if payload.get("error"): return True - return bool(payload.get("dsl_parse_error")) + if payload.get("dsl_parse_error"): + return True + return "error" in payload and _document_payload_is_unresolved(payload) + + +def _document_payload_is_unresolved(payload: dict) -> bool: + return not any(payload.get(key) for key in ("id", "title", "text", "url")) diff --git a/tests/test_cli.py b/tests/test_cli.py index 4476784..3a6ca3c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -35,7 +35,7 @@ def test_cli_help_describes_commands() -> None: assert "Store an API key for future CLI and SDK calls." in output assert "install-app" in output assert "Open the app installation page" in output - assert "ctxd search text:deployment application:slack" in output + assert "ctxd search application:slack text:deployment" in output def test_cli_search_help_describes_query_and_json_output() -> None: @@ -49,7 +49,12 @@ def test_cli_search_help_describes_query_and_json_output() -> None: assert "Search indexed app content using ctxd DSL." in output assert "Search output is always JSON." in output assert "QUERY" in output - assert "text:deployment application:slack" in output + assert "ctxd search text:deployment" in output + assert "ctxd search application:slack text:deployment" in output + assert "application: is optional" in output + assert "must be the first token" in output + assert "Only one application filter is supported" in output + assert "multi-word, quoted, and parenthesized text values are not supported" in output def test_cli_profile_json_calls_sdk() -> None: @@ -339,6 +344,32 @@ def test_cli_fetch_returns_document() -> None: assert "Deploy completed successfully." in output +def test_cli_fetch_returns_nonzero_exit_code_for_unresolved_document() -> None: + stdout = StringIO() + document = DocumentResult(error="Document UID could not be resolved.") + + with patch( + "ctxd.cli.Client.fetch_document", return_value=document + ), redirect_stdout(stdout): + exit_code = main(["fetch", "missing-doc"]) + + assert exit_code == 1 + assert stdout.getvalue() == "Error: Document UID could not be resolved.\n" + + +def test_cli_fetch_json_returns_nonzero_exit_code_for_unresolved_document() -> None: + stdout = StringIO() + document = DocumentResult(error="Document UID could not be resolved.") + + with patch( + "ctxd.cli.Client.fetch_document", return_value=document + ), redirect_stdout(stdout): + exit_code = main(["fetch", "missing-doc", "--json"]) + + assert exit_code == 1 + assert '"error": "Document UID could not be resolved."' in stdout.getvalue() + + def test_cli_search_returns_nonzero_exit_code_for_payload_errors() -> None: stdout = StringIO() @@ -356,6 +387,153 @@ def test_cli_search_returns_nonzero_exit_code_for_payload_errors() -> None: assert '"error": "bad query"' in stdout.getvalue() +def test_cli_search_rejects_empty_application_filter() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(["search", "application:"]) + + assert exit_code == 1 + search.assert_not_called() + assert "application: requires an app name" in stderr.getvalue() + + +def test_cli_search_rejects_grouped_application_filter() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main( + ["search", "application:(google_drive OR slack)", "text:onboarding"] + ) + + assert exit_code == 1 + search.assert_not_called() + assert "grouped application filters are not supported" in stderr.getvalue() + + +def test_cli_search_rejects_application_filter_after_text() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main( + [ + "search", + "text:onboarding", + "application:google_drive", + ] + ) + + assert exit_code == 1 + search.assert_not_called() + assert "application: must be the first token" in stderr.getvalue() + + +def test_cli_search_rejects_repeated_application_filters() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main( + [ + "search", + "application:google_drive", + "application:slack", + "text:onboarding", + ] + ) + + assert exit_code == 1 + search.assert_not_called() + assert "only one application filter is supported" in stderr.getvalue() + + +def test_cli_search_rejects_boolean_operators() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(["search", "text:incident", "AND", "text:response"]) + + assert exit_code == 1 + search.assert_not_called() + assert "AND/OR clauses are not supported" in stderr.getvalue() + + +@pytest.mark.parametrize("term", ["and", "or"]) +def test_cli_search_allows_lowercase_and_or_as_text_terms(term: str) -> None: + stdout = StringIO() + + with patch( + "ctxd.cli.Client.search", + return_value=type( + "SearchResultLike", + (), + { + "model_dump": lambda self: { + "results": [], + "error": None, + "dsl_parse_error": None, + } + }, + )(), + ) as search, redirect_stdout(stdout): + exit_code = main(["search", f"text:{term}"]) + + assert exit_code == 0 + search.assert_called_once_with(f"text:{term}") + assert '"results": []' in stdout.getvalue() + + +def test_cli_search_rejects_quoted_text_filter() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(["search", "application:slack", 'text:"incident response"']) + + assert exit_code == 1 + search.assert_not_called() + assert "quoted and parenthesized text values are not supported" in stderr.getvalue() + + +def test_cli_search_rejects_parenthesized_text_filter() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(["search", "application:slack", "text:(incident response)"]) + + assert exit_code == 1 + search.assert_not_called() + assert "quoted and parenthesized text values are not supported" in stderr.getvalue() + + +def test_cli_search_accepts_leading_application_filter() -> None: + stdout = StringIO() + + with patch( + "ctxd.cli.Client.search", + return_value=type( + "SearchResultLike", + (), + { + "model_dump": lambda self: { + "results": [], + "error": None, + "dsl_parse_error": None, + } + }, + )(), + ) as search, redirect_stdout(stdout): + exit_code = main( + [ + "search", + "application:google_drive", + "text:onboarding", + ] + ) + + assert exit_code == 0 + search.assert_called_once_with("application:google_drive text:onboarding") + assert '"results": []' in stdout.getvalue() + + def test_cli_search_prints_clean_message_for_network_errors( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -424,35 +602,66 @@ def test_cli_search_accepts_unquoted_query_tokens() -> None: }, )(), ) as search, redirect_stdout(stdout): - exit_code = main(["search", "text:test", "application:slack"]) + exit_code = main(["search", "application:slack", "text:test"]) assert exit_code == 0 - search.assert_called_once_with("text:test application:slack") + search.assert_called_once_with("application:slack text:test") assert '"results": []' in stdout.getvalue() -def test_cli_search_restores_shell_stripped_text_quotes() -> None: - stdout = StringIO() +def test_cli_search_rejects_shell_stripped_multi_word_text_filter() -> None: + stderr = StringIO() - with patch( - "ctxd.cli.Client.search", - return_value=type( - "SearchResultLike", - (), - { - "model_dump": lambda self: { - "results": [], - "error": None, - "dsl_parse_error": None, - } - }, - )(), - ) as search, redirect_stdout(stdout): - exit_code = main(["search", "text:deployment process", "application:slack"]) + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(["search", "application:slack", "text:deployment process"]) - assert exit_code == 0 - search.assert_called_once_with('text:"deployment process" application:slack') - assert '"results": []' in stdout.getvalue() + assert exit_code == 1 + search.assert_not_called() + assert "multi-word text values are not supported" in stderr.getvalue() + + +def test_cli_search_rejects_text_continuation_terms() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(["search", "application:slack", "text:deployment", "process"]) + + assert exit_code == 1 + search.assert_not_called() + assert "multi-word text values are not supported" in stderr.getvalue() + + +def test_cli_search_rejects_repeated_text_filters() -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main( + ["search", "application:slack", "text:incident", "text:response"] + ) + + assert exit_code == 1 + search.assert_not_called() + assert "only one text filter is supported" in stderr.getvalue() + + +@pytest.mark.parametrize( + "query", + [ + ["search", "application:slack"], + ["search", "application:slack", "deployment"], + ], +) +def test_cli_search_rejects_application_filter_without_text_filter( + query: list[str], +) -> None: + stderr = StringIO() + + with patch("ctxd.cli.Client.search") as search, patch("sys.stderr", stderr): + exit_code = main(query) + + assert exit_code == 1 + search.assert_not_called() + assert "must be followed by one text:" in stderr.getvalue() def test_cli_search_outputs_json_for_empty_success() -> None: