From 2fffadb2a4ca8cdb5cb74a6df6f309021eb6b7c8 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 12:15:59 +0800 Subject: [PATCH 1/2] feat: address remaining Surfaces CLI, Toolkit, and MCP issues Signed-off-by: tercel --- .../fixtures/structured_flags.json | 30 +- cli/docs/features/builtin-group.md | 1 + cli/docs/features/core-dispatcher.md | 12 +- cli/docs/features/schema-parser.md | 22 + cli/docs/features/security.md | 37 +- cli/python/CHANGELOG.md | 6 + cli/python/src/apcore_cli/__main__.py | 20 + cli/python/src/apcore_cli/builtin_group.py | 1 + cli/python/src/apcore_cli/cli.py | 49 ++- cli/python/src/apcore_cli/config.py | 9 +- cli/python/src/apcore_cli/discovery.py | 10 +- cli/python/src/apcore_cli/factory.py | 13 +- cli/python/src/apcore_cli/input_limits.py | 72 +++ cli/python/src/apcore_cli/schema_parser.py | 99 ++++- cli/python/src/apcore_cli/security/auth.py | 24 + .../src/apcore_cli/security/device_login.py | 181 ++++++++ .../conformance/test_structured_flags.py | 43 ++ cli/python/tests/test_builtin_group.py | 3 +- cli/python/tests/test_device_login.py | 133 ++++++ cli/python/tests/test_openapi_cmd.py | 2 +- cli/python/tests/test_security/test_auth.py | 1 + cli/rust/CHANGELOG.md | 6 + cli/rust/src/builtin_group.rs | 7 +- cli/rust/src/cli.rs | 302 ++++++++++--- cli/rust/src/config.rs | 12 +- cli/rust/src/lib.rs | 4 + cli/rust/src/main.rs | 23 +- cli/rust/src/schema_parser.rs | 111 ++++- cli/rust/src/security/auth.rs | 159 ++++++- cli/rust/src/security/device_login.rs | 414 ++++++++++++++++++ cli/rust/src/security/mod.rs | 1 + cli/rust/src/shell.rs | 8 +- .../tests/conformance_structured_flags.rs | 86 ++++ cli/rust/tests/device_login.rs | 44 ++ cli/rust/tests/test_config.rs | 6 +- cli/rust/tests/test_e2e.rs | 54 +++ cli/typescript/CHANGELOG.md | 6 + cli/typescript/src/builtin-group.ts | 1 + cli/typescript/src/discovery.ts | 7 +- cli/typescript/src/input-limits.ts | 50 +++ cli/typescript/src/main.ts | 139 +++--- cli/typescript/src/schema-parser.ts | 76 +++- cli/typescript/src/security/auth.ts | 28 +- .../src/security/config-encryptor.ts | 4 +- cli/typescript/src/security/device-login.ts | 185 ++++++++ .../tests/apcli-integration.test.ts | 4 +- cli/typescript/tests/builtin-group.test.ts | 6 +- cli/typescript/tests/device-login.test.ts | 114 +++++ cli/typescript/tests/structured-flags.test.ts | 52 ++- mcp/docs/features/mcp-server-factory.md | 30 +- mcp/python/CHANGELOG.md | 10 + mcp/python/src/apcore_mcp/apcore_mcp.py | 6 +- .../apcore_mcp/server/async_task_bridge.py | 5 + mcp/python/src/apcore_mcp/server/factory.py | 26 +- .../tests/test_acl_approval_gating_e2e.py | 63 ++- mcp/rust/CHANGELOG.md | 10 + mcp/rust/src/apcore_mcp.rs | 75 +++- mcp/rust/src/server/factory.rs | 12 +- mcp/rust/src/server/server.rs | 38 +- mcp/typescript/CHANGELOG.md | 10 + mcp/typescript/src/index.ts | 4 +- .../src/server/async-task-bridge.ts | 5 + mcp/typescript/src/server/factory.ts | 20 +- .../tests/acl-approval-gating-e2e.test.ts | 60 ++- mcp/typescript/tests/config-bus.test.ts | 2 +- toolkit/docs/features/device-auth.md | 18 +- toolkit/docs/features/openapi-scanner.md | 41 +- toolkit/python/CHANGELOG.md | 4 + toolkit/python/README.md | 1 + toolkit/python/src/apcore_toolkit/__init__.py | 10 +- .../python/src/apcore_toolkit/auth/tokens.py | 10 +- .../src/apcore_toolkit/openapi_scanner.py | 26 +- toolkit/python/tests/test_device_auth.py | 14 + .../tests/test_openapi_scanner_module_id.py | 56 ++- toolkit/rust/CHANGELOG.md | 4 + toolkit/rust/README.md | 1 + toolkit/rust/src/auth/store.rs | 14 + toolkit/rust/src/auth/token.rs | 5 + toolkit/rust/src/lib.rs | 4 +- toolkit/rust/src/openapi_scanner.rs | 19 +- .../rust/tests/openapi_scan_conformance.rs | 15 +- toolkit/typescript/CHANGELOG.md | 1 + toolkit/typescript/README.md | 1 + toolkit/typescript/src/auth/token-set.ts | 21 +- toolkit/typescript/src/browser/index.ts | 2 +- toolkit/typescript/src/index.ts | 2 +- toolkit/typescript/src/openapi-scanner.ts | 36 +- .../tests/device-auth-store.test.ts | 11 + .../typescript/tests/openapi-scanner.test.ts | 11 +- 89 files changed, 2989 insertions(+), 391 deletions(-) create mode 100644 cli/python/src/apcore_cli/input_limits.py create mode 100644 cli/python/src/apcore_cli/security/device_login.py create mode 100644 cli/python/tests/test_device_login.py create mode 100644 cli/rust/src/security/device_login.rs create mode 100644 cli/rust/tests/device_login.rs create mode 100644 cli/typescript/src/input-limits.ts create mode 100644 cli/typescript/src/security/device-login.ts create mode 100644 cli/typescript/tests/device-login.test.ts diff --git a/cli/conformance/fixtures/structured_flags.json b/cli/conformance/fixtures/structured_flags.json index f6bf7f46..67a54012 100644 --- a/cli/conformance/fixtures/structured_flags.json +++ b/cli/conformance/fixtures/structured_flags.json @@ -5,7 +5,10 @@ "properties": { "filters": { "type": "object" }, "labels": { "type": "array", "items": { "type": "string" } }, - "note": { "type": "string" }, + "note": { "type": "string", "x-cli-positional": 1 }, + "count": { "type": "integer", "x-cli-positional": 2 }, + "thresholds": { "type": "array", "items": { "type": "number" } }, + "toggles": { "type": "array", "items": { "type": "boolean" } }, "maybe_filters": { "anyOf": [{ "type": "object" }, { "type": "null" }] }, "maybe_labels": { "oneOf": [{ "type": "array", "items": { "type": "string" } }, { "type": "null" }] }, "nullable_labels": { "type": ["array", "null"], "items": { "type": "string" } }, @@ -24,6 +27,31 @@ "args": ["--filters", "{}", "--labels", "[]"], "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": [] } } }, + { + "id": "repeat_scalar_flags", + "args": ["--filters", "{}", "--labels", "one", "--labels", "two"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": ["one", "two"] } } + }, + { + "id": "positional_parameter", + "args": ["from-position", "7", "--filters", "{}", "--labels", "one"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": ["one"], "note": "from-position", "count": 7 } } + }, + { + "id": "scalar_flags_keep_json_types", + "args": ["--filters", "{}", "--labels", "one", "--thresholds", "1", "--thresholds", "2.5", "--toggles", "true", "--toggles", "false"], + "expected": { "exit_code": 0, "calls": 1, "input": { "filters": {}, "labels": ["one"], "thresholds": [1, 2.5], "toggles": [true, false] } } + }, + { + "id": "duplicate_parameter_sources", + "args": ["from-position", "--filters", "{}", "--labels", "one", "--note", "from-flag"], + "expected": { "exit_code": 45, "calls": 0 } + }, + { + "id": "malformed_array", + "args": ["--filters", "{}", "--labels", "["], + "expected": { "exit_code": 45, "calls": 0 } + }, { "id": "nullable_structured_values", "args": ["--filters", "{}", "--labels", "[]", "--maybe-filters", "{\"enabled\":true}", "--maybe-labels", "[\"choice\"]", "--nullable-labels", "[\"direct\"]"], diff --git a/cli/docs/features/builtin-group.md b/cli/docs/features/builtin-group.md index f43f857c..d89049d3 100644 --- a/cli/docs/features/builtin-group.md +++ b/cli/docs/features/builtin-group.md @@ -128,6 +128,7 @@ exits with code 47 before dispatching a command if any registration fails. | `apcli config get / set` | `system_cmd.py` | Renamed from root `config`. | | `apcli completion ` | `shell.py` | Renamed from root `completion`. | | `apcli describe-pipeline` | `strategy.py` | Renamed from root `describe-pipeline`. | +| `apcli login` | Security Manager | Signs in using the configured device authorization provider. | ### 4.2 Configuration Schema diff --git a/cli/docs/features/core-dispatcher.md b/cli/docs/features/core-dispatcher.md index aa805ac8..4599aad4 100644 --- a/cli/docs/features/core-dispatcher.md +++ b/cli/docs/features/core-dispatcher.md @@ -44,6 +44,16 @@ The Core Dispatcher is the primary entry point for `apcore-cli`. It provides the ## 4. Implementation Details +### Input size limit + +Generated commands and `apcli exec` default to 10 MiB (10,485,760 bytes) for +input read from stdin and any JSON files accepted by the command. Precedence is +`--max-input-bytes`, `APCORE_CLI_STDIN_BUFFER_LIMIT`, +`apcore-cli.stdin_buffer_limit` in `apcore.yaml` (with legacy +`cli.stdin_buffer_limit` accepted), then the default. Limits are positive +integers up to `9007199254740991`. `--large-input` disables the limit for +the invocation. File input includes `@file` on object flags. + ## Contract: LazyModuleGroup.__init__ ### Inputs @@ -112,7 +122,7 @@ The Core Dispatcher is the primary entry point for `apcore-cli`. It provides the ### Inputs - stdin_flag: str | None, required — Input source: `None` or `""` = CLI only; `"-"` = stdin; any other string = file path. - validates: STDIN must be ≤10 MB unless `large_input=True`; STDIN/file content must be valid JSON object + validates: STDIN/file content must respect the configured byte limit and parse as a JSON object reject_with: SystemExit(2) — on oversized input, invalid JSON, or non-object JSON - cli_kwargs: dict[str, Any], required — Parsed CLI keyword arguments; None values are stripped before merge. - large_input: bool, optional — When True, bypasses the 10 MB size guard. Default: `False`. diff --git a/cli/docs/features/schema-parser.md b/cli/docs/features/schema-parser.md index b894633a..6ade3c51 100644 --- a/cli/docs/features/schema-parser.md +++ b/cli/docs/features/schema-parser.md @@ -16,6 +16,28 @@ description: "Schema Parser (FE-02) converting a module's JSON Schema input_sche The Schema Parser converts a module's JSON Schema `input_schema` into Click CLI options. It handles type mapping, boolean flag pairs, enum choices, required enforcement, help text generation, and `$ref`/`$defs` resolution. The parser produces a list of `click.Option` objects that are appended to the dynamically generated module command. +### Positional and structured inputs + +In all three SDKs, a schema property of type `string`, `integer`, or `number` +can opt into a positional argument through `x-cli-positional`. The indices +are unique integers starting at `1` with no gaps. Original flags and whole +JSON input remain available. Supplying both a positional and its flag for the +same property is a validation error. + +For a module with a positional `job_id`, a string array `stage`, and an object +`options`, either form below supplies the same inputs. + +```sh +apcore-cli render job-42 --stage a --stage b --options @options.json +apcore-cli render --job-id job-42 --stage '["a","b"]' --options '{"quality":"high"}' +``` + +Repeated flags also support boolean, integer, and number arrays. Single JSON +arrays remain valid. Objects accept JSON text or a UTF-8 JSON file with +`@path`. The input schema validates the decoded values before dispatch. +The dispatcher applies its [input byte limit](core-dispatcher.md#input-size-limit) +to these files. + --- ## 2. Requirements Traceability diff --git a/cli/docs/features/security.md b/cli/docs/features/security.md index bc24e17b..b76719d7 100644 --- a/cli/docs/features/security.md +++ b/cli/docs/features/security.md @@ -174,6 +174,36 @@ Module execution rejects an enabled sandbox combined with `--trace`, `--strategy ## Contract: AuthProvider.authenticate_request +### Device authorization + +Configure a public device-flow client in `apcore.yaml`. + +```yaml +auth: + device: + client_id: my-cli + issuer: https://auth.example.com + scope: [api.read] + token_storage: keyring +``` + +The client discovers endpoints from `issuer`. Set +`device_authorization_endpoint` and `token_endpoint` to use explicit +endpoints. Client configuration and verification links accept HTTPS and +loopback HTTP. Automatic browser launch uses HTTPS. Run +`apcore-cli apcli login --no-browser` to enter the code manually. Login +prints progress to stderr and stores the resulting credentials in the OS +keyring. Use `token_storage: file` to opt into Toolkit's user-only +credential file on a host without a usable keyring. + +For applications making authorized HTTP requests, use Python's +`AuthProvider.authenticate_request`, TypeScript's async `authenticateRequest`, +or Rust's async `authenticate_request_async` for the intended API. +Configured API keys take precedence. Otherwise, the provider loads the +device credential and refreshes it if needed before supplying the bearer +header. Local module execution has no need for a token. Built-in OpenAPI +proxy execution is tracked under [FE-15b](openapi-import.md). + ### Inputs - headers: dict, required — HTTP headers dict to augment with the Authorization header. @@ -186,9 +216,8 @@ Module execution rejects an enabled sandbox combined with `--trace`, `--strategy - On no key or malformed key: raises AuthenticationError ### Properties -- async: depends_on_language — Python and Rust expose `authenticate_request` as synchronous (the underlying keyring APIs on those platforms are blocking). TypeScript exposes it as `async` because Node.js `keytar` is asynchronous. Callers MUST treat the return as awaitable in TypeScript and as a direct return in Python/Rust. A sync façade in TypeScript (e.g., a `warm()` method that pre-loads the cached API key into a private field, after which `authenticate_request` is synchronous) is acceptable as an alternative implementation strategy if cross-language sync parity is desired by an embedder. -- thread_safe: true (reads config and env; no mutable shared state) -- pure: false (reads env vars and config file) +- async: depends_on_language — Python exposes a synchronous method. TypeScript's method and Rust's device-capable method are asynchronous. Rust also provides a synchronous method for API keys. +- pure: false (reads configuration and credentials and may refresh a device token) --- @@ -458,7 +487,7 @@ Logic steps: Logic steps: 1. Call `key = self.get_api_key()`. -2. If `key is None`: raise `AuthenticationError("Remote registry requires authentication. Set --api-key, APCORE_AUTH_API_KEY, or auth.api_key in config.")`. +2. If `key is None` and device authorization is configured, obtain a valid device bearer token. If neither credential is available, raise `AuthenticationError`. 3. If `"\r" in key` or `"\n" in key`: raise `AuthenticationError("Malformed API key: contains invalid characters (CR or LF). Re-export the variable or update the config without trailing newlines.")`. This is a defensive guard against header injection / shell-newline-bleed (a stray `\n` from `export VAR="$(...)"` would otherwise produce a multi-line `Authorization` header). 4. Mutate `headers` in place: `headers["Authorization"] = f"Bearer {key.strip()}"`. 5. Return `headers` — the same reference as the input. Callers that share the headers dict observe the new `Authorization` entry without re-reading the return value. diff --git a/cli/python/CHANGELOG.md b/cli/python/CHANGELOG.md index 0e79a858..faed50a3 100644 --- a/cli/python/CHANGELOG.md +++ b/cli/python/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [0.14.2a2] - Unreleased +### Added + +- Configure positional arguments with `x-cli-positional`, repeat scalar array flags, and load object arguments with `@file`. [Issues #59 and #121](https://github.com/aiperceivable/apcore-surfaces/issues/121) +- Add `--max-input-bytes` and consistent large-input overrides on generated commands and `apcli exec`. [Issue #121](https://github.com/aiperceivable/apcore-surfaces/issues/121) +- Add `apcli login` for device authorization and refresh credentials on authenticated application requests. [Issue #89](https://github.com/aiperceivable/apcore-surfaces/issues/89) + ### Changed - Require Core `1.0.0b1`. diff --git a/cli/python/src/apcore_cli/__main__.py b/cli/python/src/apcore_cli/__main__.py index 41dd060a..2569020a 100644 --- a/cli/python/src/apcore_cli/__main__.py +++ b/cli/python/src/apcore_cli/__main__.py @@ -45,6 +45,25 @@ def _extract_argv_option_repeatable(argv: list[str] | None, flag: str) -> list[s return out +def _is_device_login(argv: list[str]) -> bool: + """Recognize the standalone login command before filesystem discovery.""" + value_options = { + "--extensions-dir", "--commands-dir", "--binding", "--allowed-prefix", "--acl", + "--identity-id", "--identity-type", "--role", "--log-level", + } + arguments = iter(argv) + for argument in arguments: + if argument == "--": + return list(arguments)[:2] == ["apcli", "login"] + name, equals, _ = argument.partition("=") + if name in value_options: + if not equals: + next(arguments, None) + elif argument != "--all-options": + return argument == "apcli" and next(arguments, None) == "login" + return False + + def main(prog_name: str | None = None) -> None: """Main entry point for apcore-cli. @@ -70,6 +89,7 @@ def main(prog_name: str | None = None) -> None: binding_path=bind_path, allowed_prefixes=allowed_prefixes, acl=acl_path, + _login_only=_is_device_login(sys.argv[1:]), version=_sdk_version, description=f"{prog_name or 'apcore-cli'} — execute apcore modules from the command line", ) diff --git a/cli/python/src/apcore_cli/builtin_group.py b/cli/python/src/apcore_cli/builtin_group.py index 9026d1ca..f2ed2701 100644 --- a/cli/python/src/apcore_cli/builtin_group.py +++ b/cli/python/src/apcore_cli/builtin_group.py @@ -101,6 +101,7 @@ class ApcliConfig(TypedDict, total=False): # the canonical set from 13 to 15. "acl", "openapi", + "login", } ) diff --git a/cli/python/src/apcore_cli/cli.py b/cli/python/src/apcore_cli/cli.py index ea790b3e..683cfed9 100644 --- a/cli/python/src/apcore_cli/cli.py +++ b/cli/python/src/apcore_cli/cli.py @@ -11,7 +11,6 @@ import time from collections.abc import Callable, Mapping from contextlib import aclosing -from pathlib import Path from typing import TYPE_CHECKING, Any import click @@ -30,6 +29,7 @@ EXIT_SCHEMA_CIRCULAR_REF, EXIT_SCHEMA_VALIDATION_ERROR, ) +from apcore_cli.input_limits import read_input_text, resolve_input_limit from apcore_cli.module_errors import ( ErrorStream, InvalidCliInputError, @@ -51,7 +51,13 @@ UnresolvableRefError, resolve_refs, ) -from apcore_cli.schema_parser import extract_structured_flags, reconvert_enum_values, schema_to_click_options +from apcore_cli.schema_parser import ( + build_positionals, + extract_structured_flags, + merge_positionals, + reconvert_enum_values, + schema_to_click_options, +) # Re-exported: get_audit_logger/set_audit_logger live in security.audit (not # defined here) so that acl_loader.py — which cli.py imports above — can also @@ -698,6 +704,7 @@ def build_module_command( try: schema_options = schema_to_click_options(resolved_schema, max_help_length=help_text_max_length) + positionals = build_positionals(resolved_schema, schema_options) except ValueError as e: click.echo(f"Error: Module '{module_id}' schema error: {e}", err=True) exit_with(2) @@ -707,6 +714,7 @@ def callback(**kwargs: Any) -> None: stdin_input = kwargs.pop("input", None) auto_approve = kwargs.pop("yes", False) large_input = kwargs.pop("large_input", False) + max_input_bytes = kwargs.pop("max_input_bytes", None) output_format = kwargs.pop("format", None) output_fields = kwargs.pop("fields", None) sandbox_flag = kwargs.pop("sandbox", False) @@ -733,9 +741,11 @@ def callback(**kwargs: Any) -> None: _check_sandbox_options( sandbox=sandbox_flag, trace=trace_flag, strategy=strategy_name, stream=stream_flag, dry_run=dry_run ) - # 1. Decode explicit structured flags, then merge with JSON input. - structured, structured_defaults = extract_structured_flags(kwargs, schema_options) - merged = {**structured_defaults, **_read_module_input(stdin_input, kwargs, large_input), **structured} + # Decode property and document inputs with the same byte limit. + merge_positionals(kwargs, positionals) + input_limit = resolve_input_limit(large_input, max_input_bytes) + structured, structured_defaults = extract_structured_flags(kwargs, schema_options, input_limit) + merged = {**structured_defaults, **_merge_module_input(stdin_input, kwargs, input_limit), **structured} # 2. Reconvert enum values to original types merged = reconvert_enum_values(merged, schema_options) @@ -1057,7 +1067,15 @@ async def _do_stream() -> None: ["--large-input"], is_flag=True, default=False, - help="Allow stdin input larger than 10MB (default limit protects against accidental pipes).", + help="Disable the byte limit for stdin and JSON files.", + hidden=_hide, + ) + ) + cmd.params.append( + click.Option( + ["--max-input-bytes"], + type=click.IntRange(min=1, max=9_007_199_254_740_991), + help="Maximum bytes per stdin or JSON file input (default 10 MiB).", hidden=_hide, ) ) @@ -1156,6 +1174,7 @@ async def _do_stream() -> None: "input", "yes", "large_input", + "max_input_bytes", "format", "fields", "sandbox", @@ -1180,6 +1199,7 @@ async def _do_stream() -> None: # Add schema-generated options cmd.params.extend(schema_options) + cmd.params.extend(argument for argument, _ in positionals) return cmd @@ -1230,6 +1250,15 @@ def _read_module_input( stdin_flag: str | None, cli_kwargs: dict[str, Any], large_input: bool = False, + max_input_bytes: int | None = None, +) -> dict[str, Any]: + return _merge_module_input(stdin_flag, cli_kwargs, resolve_input_limit(large_input, max_input_bytes)) + + +def _merge_module_input( + stdin_flag: str | None, + cli_kwargs: dict[str, Any], + input_limit: int | None, ) -> dict[str, Any]: # Remove None values from CLI kwargs cli_kwargs_non_none = {k: v for k, v in cli_kwargs.items() if v is not None} @@ -1239,13 +1268,7 @@ def _read_module_input( from_stdin = stdin_flag == "-" source_label = "STDIN" if from_stdin else f"--input file '{stdin_flag}'" - try: - raw = sys.stdin.read() if from_stdin else Path(stdin_flag).read_text(encoding="utf-8") - except (OSError, UnicodeError) as error: - raise InvalidCliInputError(f"Could not read {source_label}: {error}.") from error - - if len(raw.encode("utf-8")) > 10_485_760 and not large_input: - raise InvalidCliInputError(f"{source_label} input exceeds 10MB limit. Use --large-input to override.") + raw = read_input_text(stdin_flag, source_label, input_limit) if not raw: return cli_kwargs_non_none diff --git a/cli/python/src/apcore_cli/config.py b/cli/python/src/apcore_cli/config.py index 158d2e34..fc61894d 100644 --- a/cli/python/src/apcore_cli/config.py +++ b/cli/python/src/apcore_cli/config.py @@ -86,13 +86,8 @@ class ConfigResolver: "expose.include": [], "expose.exclude": [], } - # Audit D9 (config cleanup): the unused entries `sandbox.enabled`, - # `cli.stdin_buffer_limit`, `cli.auto_approve`, and the four - # `apcore-cli.*` namespace aliases were removed in v0.6.x. None of - # them were ever read by `resolve()` at runtime — sandbox/auto-approve - # come from CLI flags, the stdin buffer is hard-coded, and the - # namespace aliases are registered separately via the Config Bus - # `register_namespace()` call in `apcore_cli/__init__.py`. + # Sandbox and auto-approve are CLI flags. The input reader supplies its + # own stdin/file limit default after checking both configuration aliases. def __init__( self, diff --git a/cli/python/src/apcore_cli/discovery.py b/cli/python/src/apcore_cli/discovery.py index 81d2dfbd..0ea41543 100644 --- a/cli/python/src/apcore_cli/discovery.py +++ b/cli/python/src/apcore_cli/discovery.py @@ -340,6 +340,12 @@ def register_exec_command( default=None, help="JSON object passed as input to the module. Use '-' to read JSON from stdin.", ) + @click.option("--large-input", is_flag=True, help="Disable the byte limit for stdin JSON.") + @click.option( + "--max-input-bytes", + type=click.IntRange(min=1, max=9_007_199_254_740_991), + help="Maximum bytes of stdin JSON (default 10 MiB).", + ) @click.option("-y", "--yes", "auto_approve", is_flag=True, default=False, help="Auto-approve.") @click.option( "--approval-timeout", @@ -365,6 +371,8 @@ def exec_cmd( output_format: str | None, fields: str | None, stdin_input: str | None, + large_input: bool, + max_input_bytes: int | None, auto_approve: bool, approval_timeout: int | None, sandbox: bool, @@ -393,7 +401,7 @@ def exec_cmd( raise ModuleNotFoundError(f"Module '{module_id}' not found.") if stdin_input == "-": - merged = _read_module_input("-", {}) + merged = _read_module_input("-", {}, large_input, max_input_bytes) elif stdin_input is not None: try: parsed = json.loads(stdin_input) diff --git a/cli/python/src/apcore_cli/factory.py b/cli/python/src/apcore_cli/factory.py index 26adac68..5e588930 100644 --- a/cli/python/src/apcore_cli/factory.py +++ b/cli/python/src/apcore_cli/factory.py @@ -52,6 +52,7 @@ from apcore_cli.init_cmd import register_init_command from apcore_cli.openapi_cmd import register_openapi_command from apcore_cli.security.audit import AuditLogger +from apcore_cli.security.device_login import register_login_command from apcore_cli.shell import ( configure_man_help, register_completion_command, @@ -100,6 +101,7 @@ def create_cli( builtin_group_name: str = "apcli", acl: str | Any | None = None, *, + _login_only: bool = False, print_result: bool = True, on_result: Callable[[Any, str], None] | None = None, on_error: Callable[[Any], None] | None = None, @@ -212,6 +214,12 @@ def create_cli( if app is not None: registry = app.registry executor = app.executor + if _login_only: + # Standalone login needs no module discovery. Keep the normal root + # options and apcli visibility of the standalone command tree. + from apcore import Registry + + registry = Registry() # FE-14 §4.2: lock in "the executor was caller-supplied" BEFORE the # discovery paths below may construct one. Attachment is skipped for an @@ -641,7 +649,7 @@ def cli( # allowed to claim the new name either. cli._reserved_group_names = frozenset({apcli_cfg.name}) # type: ignore[attr-defined] - # Dispatch the 15-entry subcommand registrar table (FE-13 §4.9). + # Dispatch the subcommand registrar table (FE-13 §4.9). _register_apcli_subcommands( apcli_group, apcli_cfg, @@ -842,7 +850,7 @@ def _register_apcli_subcommands( error_stream: Any = None, extra_input: Mapping[str, Any] | Callable[[], Mapping[str, Any]] | None = None, ) -> None: - """Register the 15 canonical apcli subcommands, filtered by visibility. + """Register the canonical apcli subcommands, filtered by visibility. Mirrors ``_registerApcliSubcommands`` in ``../apcore-cli-typescript/src/main.ts``. Each entry declares whether it @@ -893,6 +901,7 @@ def _register_apcli_subcommands( ("acl", True, lambda: register_acl_command(apcli_group, executor, acl, acl_source)), # FE-15a registers nothing and needs neither registry nor executor. ("openapi", False, lambda: register_openapi_command(apcli_group)), + ("login", False, lambda: register_login_command(apcli_group)), ] mode = apcli_cfg.resolve_visibility() diff --git a/cli/python/src/apcore_cli/input_limits.py b/cli/python/src/apcore_cli/input_limits.py new file mode 100644 index 00000000..b2c3d704 --- /dev/null +++ b/cli/python/src/apcore_cli/input_limits.py @@ -0,0 +1,72 @@ +"""Byte limits for JSON streamed from stdin or read from a file.""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path +from typing import BinaryIO + +from apcore_cli.config import ConfigResolver +from apcore_cli.module_errors import InvalidCliInputError + +DEFAULT_INPUT_LIMIT = 10 * 1024 * 1024 +_MAX_LIMIT = (1 << 53) - 1 +_READ_SIZE = 64 * 1024 + + +def resolve_input_limit(large_input: bool, max_input_bytes: int | None) -> int | None: + if large_input: + return None + value = max_input_bytes + if value is None: + value = ConfigResolver().resolve("apcore-cli.stdin_buffer_limit", env_var="APCORE_CLI_STDIN_BUFFER_LIMIT") + if value is None: + return DEFAULT_INPUT_LIMIT + if isinstance(value, str) and re.fullmatch(r"[0-9]{1,16}", value): + value = int(value) + if type(value) is not int or not 1 <= value <= _MAX_LIMIT: + raise InvalidCliInputError("Input size limit must be a positive integer of at most 9007199254740991 bytes.") + return value + + +def _too_large(label: str, limit: int) -> InvalidCliInputError: + size = "10 MiB" if limit == DEFAULT_INPUT_LIMIT else f"{limit} byte" + return InvalidCliInputError(f"{label} input exceeds the {size} limit. Use --large-input to override.") + + +def _read_bytes(stream: BinaryIO, label: str, limit: int | None) -> bytes: + if limit is None: + return stream.read() + data = bytearray() + while len(data) <= limit: + chunk = stream.read(min(_READ_SIZE, limit + 1 - len(data))) + if not chunk: + return bytes(data) + data.extend(chunk) + raise _too_large(label, limit) + + +def read_input_text(path: str, label: str, limit: int | None) -> str: + try: + if path != "-": + with Path(path).open("rb") as stream: + return _read_bytes(stream, label, limit).decode("utf-8") + stream = getattr(sys.stdin, "buffer", None) + if stream is not None: + return _read_bytes(stream, label, limit).decode("utf-8") + # Embedders may supply a text-only stdin. Bound each read and count + # encoded bytes so multibyte characters use the same limit. + if limit is None: + return sys.stdin.read() + chunks: list[str] = [] + size = 0 + while size <= limit: + chunk = sys.stdin.read(min(_READ_SIZE, limit + 1 - size)) + if not chunk: + return "".join(chunks) + chunks.append(chunk) + size += len(chunk.encode("utf-8")) + raise _too_large(label, limit) + except (OSError, UnicodeError) as error: + raise InvalidCliInputError(f"Could not read {label}: {error}.") from error diff --git a/cli/python/src/apcore_cli/schema_parser.py b/cli/python/src/apcore_cli/schema_parser.py index 3054686d..beec1fa2 100644 --- a/cli/python/src/apcore_cli/schema_parser.py +++ b/cli/python/src/apcore_cli/schema_parser.py @@ -4,13 +4,17 @@ import json import logging +import math from copy import deepcopy +from pathlib import Path from typing import Any, NoReturn import click from click.core import ParameterSource from apcore_cli.exit import exit_with +from apcore_cli.input_limits import DEFAULT_INPUT_LIMIT, read_input_text +from apcore_cli.module_errors import InvalidCliInputError from apcore_cli.security.sandbox import SchemaValidationError logger = logging.getLogger("apcore_cli.schema_parser") @@ -18,6 +22,8 @@ # Sentinel for boolean flag marker _BOOLEAN_FLAG = object() _JSON_CONTAINER_TYPES = {"object", "array"} +_POSITIONAL_TYPES = {"string", "integer", "number"} +_SCALAR_ITEM_TYPES = _POSITIONAL_TYPES | {"boolean"} # Property names that collide with built-in CLI options — schema_to_click_options # rejects these early so the error surfaces at schema-parse time, not at invocation. @@ -27,6 +33,8 @@ "input", "yes", "large_input", + "max_input_bytes", + "max-input-bytes", "fields", "sandbox", "all_options", @@ -218,7 +226,22 @@ def schema_to_click_options(schema: dict, max_help_length: int = 1000) -> list[c elif _is_structured_option(prop_schema): # Keep native schema defaults intact and let the module callback # decode user input via its existing schema error/exit handling. - option = click.Option([flag_name], type=click.UNPROCESSED, metavar="JSON", default=default, help=help_text) + item = prop_schema.get("items") + item_type = item.get("type") if prop_schema.get("type") == "array" and isinstance(item, dict) else None + repeated = isinstance(item_type, str) and item_type in _SCALAR_ITEM_TYPES + allow_file = prop_schema.get("type") == "object" + metavar = "VALUE|JSON" if repeated else "JSON|@FILE" if allow_file else "JSON" + option = click.Option( + [flag_name], + type=click.UNPROCESSED, + metavar=metavar, + multiple=repeated, + default=None if repeated else default, + help=help_text, + ) + option._structured_default = default + option._item_type = item_type if repeated else None + option._allow_file = allow_file elif "enum" in prop_schema and click_type is not _BOOLEAN_FLAG: enum_values = prop_schema["enum"] if not enum_values: @@ -258,12 +281,49 @@ def schema_to_click_options(schema: dict, max_help_length: int = 1000) -> list[c return options +def build_positionals(schema: dict, options: list[click.Option]) -> list[tuple[click.Argument, click.Option]]: + """Bind opted-in scalar properties to contiguous, optional arguments.""" + by_flag = {option.opts[0]: option for option in options} + names = {option.name for option in options} + indexed: dict[int, tuple[click.Argument, click.Option]] = {} + for property_name, prop_schema in schema.get("properties", {}).items(): + if "x-cli-positional" not in prop_schema: + continue + index = prop_schema["x-cli-positional"] + if type(index) is not int or index < 1 or index in indexed: + raise ValueError("x-cli-positional indices must be unique positive integers.") + prop_type = prop_schema.get("type") + if not isinstance(prop_type, str) or prop_type not in _POSITIONAL_TYPES: + raise ValueError(f"x-cli-positional is only supported on scalar property '{property_name}'.") + flag_name = property_name.replace("_", "-") + option = by_flag[f"--{flag_name}"] + name = f"_apcore_positional_{index}" + while name in names: + name = f"_{name}" + argument = click.Argument([name], required=False, type=option.type, metavar=f"[{flag_name}]") + indexed[index] = argument, option + if sorted(indexed) != list(range(1, len(indexed) + 1)): + raise ValueError("x-cli-positional indices must be consecutive starting at 1.") + return [indexed[index] for index in sorted(indexed)] + + +def merge_positionals(values: dict[str, Any], positionals: list[tuple[click.Argument, click.Option]]) -> None: + context = click.get_current_context() + for argument, option in positionals: + value = values.pop(argument.name, None) + if value is None: + continue + if context.get_parameter_source(option.name) == ParameterSource.COMMANDLINE: + raise SchemaValidationError(f"Provide '{option.opts[0]}' either as a flag or a positional argument.") + values[option.name] = value + + def _reject_json_constant(constant: str) -> NoReturn: raise ValueError(f"Invalid JSON constant: {constant}") def extract_structured_flags( - values: dict[str, Any], options: list[click.Option] + values: dict[str, Any], options: list[click.Option], input_limit: int | None = DEFAULT_INPUT_LIMIT ) -> tuple[dict[str, Any], dict[str, Any]]: """Pop structured options and return their decoded values and native defaults.""" context = click.get_current_context(silent=True) @@ -274,21 +334,52 @@ def extract_structured_flags( if option.type is not click.UNPROCESSED or name is None: continue value = values.pop(name, None) + source = context.get_parameter_source(name) if context is not None else None + if source == ParameterSource.DEFAULT: + value = getattr(option, "_structured_default", value) + if value is not None: + defaults[name] = deepcopy(value) + continue if value is None: continue - source = context.get_parameter_source(name) if context is not None else None - if source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP): + if source == ParameterSource.DEFAULT_MAP: + if getattr(option, "_item_type", None) and isinstance(value, tuple): + value = list(value) defaults[name] = deepcopy(value) continue try: + item_type = getattr(option, "_item_type", None) + if item_type and isinstance(value, tuple): + if len(value) == 1 and value[0].lstrip().startswith("["): + explicit[name] = json.loads(value[0], parse_constant=_reject_json_constant) + else: + explicit[name] = [_parse_scalar_item(item, item_type) for item in value] + continue + if isinstance(value, str) and getattr(option, "_allow_file", False) and value.startswith("@"): + path = str(Path(value[1:]).absolute()) + value = read_input_text(path, f"file for '{option.opts[0]}'", input_limit) explicit[name] = ( json.loads(value, parse_constant=_reject_json_constant) if isinstance(value, str) else value ) + except InvalidCliInputError as error: + raise SchemaValidationError(str(error)) from error except (ValueError, RecursionError) as error: raise SchemaValidationError(f"Option '{option.opts[0]}' must contain valid JSON.") from error return explicit, defaults +def _parse_scalar_item(value: str, item_type: str) -> Any: + if item_type == "string": + return value + parsed = json.loads(value, parse_constant=_reject_json_constant) + valid_types = {"integer": (int, float), "number": (int, float), "boolean": (bool,)} + if type(parsed) not in valid_types[item_type]: + raise ValueError(f"Expected a JSON {item_type}.") + if isinstance(parsed, float) and (not math.isfinite(parsed) or item_type == "integer" and not parsed.is_integer()): + raise ValueError(f"Expected a finite {item_type}.") + return parsed + + def reconvert_enum_values(kwargs: dict[str, Any], options: list[click.Option]) -> dict[str, Any]: """Reconvert enum values from string back to their original types.""" result = dict(kwargs) diff --git a/cli/python/src/apcore_cli/security/auth.py b/cli/python/src/apcore_cli/security/auth.py index 3f82f4e3..6e58b44b 100644 --- a/cli/python/src/apcore_cli/security/auth.py +++ b/cli/python/src/apcore_cli/security/auth.py @@ -2,9 +2,12 @@ from __future__ import annotations +from threading import Lock from typing import TYPE_CHECKING if TYPE_CHECKING: + from apcore_toolkit.auth import DeviceAuthClient + from apcore_cli.config import ConfigResolver from apcore_cli.security.config_encryptor import ConfigEncryptor @@ -29,6 +32,8 @@ def __init__( ) -> None: self._config = config self._encryptor = encryptor + self._device_client: DeviceAuthClient | None = None + self._device_lock = Lock() def _get_encryptor(self) -> ConfigEncryptor: if self._encryptor is not None: @@ -56,6 +61,25 @@ def get_api_key(self) -> str | None: def authenticate_request(self, headers: dict) -> dict: key = self.get_api_key() + if key is None and self._config.resolve_object("auth.device") is not None: + from apcore_toolkit.auth import AuthError + + from apcore_cli.security.device_login import create_device_auth_client + + try: + with self._device_lock: + client = self._device_client + if client is None: + self._device_client = client = create_device_auth_client(self._config) + if client is not None: + token = client.ensure_valid() + if token.token_type.lower() != "bearer" or not token.access_token or any( + not 33 <= ord(char) <= 126 for char in token.access_token + ): + raise AuthenticationError("The device provider must return a bearer credential.") + key = token.access_token + except (AuthError, OSError): + raise AuthenticationError("Device authentication failed. Run 'apcli login' to sign in again.") from None if key is None: raise AuthenticationError( "Remote registry requires authentication. " diff --git a/cli/python/src/apcore_cli/security/device_login.py b/cli/python/src/apcore_cli/security/device_login.py new file mode 100644 index 00000000..72b33937 --- /dev/null +++ b/cli/python/src/apcore_cli/security/device_login.py @@ -0,0 +1,181 @@ +"""CLI configuration, credential storage, and terminal UI for device login.""" + +from __future__ import annotations + +import hashlib +import json +import webbrowser +from contextlib import suppress +from urllib.parse import urlsplit + +import click +import keyring +from apcore_toolkit.auth import ( + AuthError, + ConfigurationError, + CredentialPermissionError, + DeviceAuthClient, + DeviceAuthConfig, + DeviceCodeGrant, + DeviceCodeResponse, + FileTokenStore, + HttpxTransport, + TokenSet, +) + +from apcore_cli.config import ConfigResolver +from apcore_cli.exit import exit_with +from apcore_cli.exit_codes import EXIT_ACL_DENIED, EXIT_CONFIG_INVALID + + +class _KeyringTokenStore: + _SERVICE = "apcore-cli-device-auth" + + @staticmethod + def _account(key: str) -> str: + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + def load(self, key: str) -> TokenSet | None: + try: + record = keyring.get_password(self._SERVICE, self._account(key)) + return TokenSet.from_dict(json.loads(record)) if record is not None else None + except (keyring.errors.KeyringError, ValueError, TypeError, KeyError) as exc: + raise CredentialPermissionError("Could not read the device credential from the OS keyring.") from exc + + def save(self, key: str, tokens: TokenSet) -> None: + try: + keyring.set_password(self._SERVICE, self._account(key), json.dumps(tokens.to_dict())) + except keyring.errors.KeyringError as exc: + raise CredentialPermissionError("Could not save the device credential to the OS keyring.") from exc + + def clear(self, key: str) -> None: + account = self._account(key) + try: + if keyring.get_password(self._SERVICE, account) is not None: + keyring.delete_password(self._SERVICE, account) + except keyring.errors.KeyringError as exc: + raise CredentialPermissionError("Could not remove the device credential from the OS keyring.") from exc + + +class _InteractiveDeviceCodeGrant(DeviceCodeGrant): + def request_device_code(self) -> DeviceCodeResponse: + code = super().request_device_code() + if ( + not _safe_verification_url(code.verification_uri) + or not code.user_code.strip() + or not code.user_code.isprintable() + ): + raise ConfigurationError("The provider returned unsafe device login instructions.") + return code + + +def create_device_auth_client(config: ConfigResolver) -> DeviceAuthClient | None: + """Build the configured public OAuth client for this CLI, if enabled.""" + settings = config.resolve_object("auth.device") + if settings is None: + return None + if not isinstance(settings, dict): + raise ConfigurationError("auth.device must be a mapping.") + + def read_text(key: str) -> str | None: + value = settings.get(key) + if value is not None and (not isinstance(value, str) or not value.strip()): + raise ConfigurationError(f"auth.device.{key} must be a non-empty string.") + return value + + def read_url(key: str) -> str | None: + value = read_text(key) + if value is not None and not _safe_verification_url(value): + raise ConfigurationError(f"auth.device.{key} must be an HTTPS URL (or HTTP on loopback).") + return value + + client_id = read_text("client_id") + if not client_id: + raise ConfigurationError("auth.device.client_id is required.") + scope = settings.get("scope", []) + if not isinstance(scope, list) or any(not isinstance(value, str) for value in scope): + raise ConfigurationError("auth.device.scope must be a list of strings.") + storage = read_text("token_storage") or "keyring" + if storage not in {"keyring", "file"}: + raise ConfigurationError("auth.device.token_storage must be 'keyring' or 'file'.") + + device_config = DeviceAuthConfig( + client_id=client_id, + issuer=read_url("issuer"), + device_authorization_endpoint=read_url("device_authorization_endpoint"), + token_endpoint=read_url("token_endpoint"), + scope=scope, + http_timeout=30, + ) + if not (device_config.device_authorization_endpoint and device_config.token_endpoint): + device_config = device_config.discover() + if not all( + endpoint and _safe_verification_url(endpoint) + for endpoint in (device_config.device_authorization_endpoint, device_config.token_endpoint) + ): + raise ConfigurationError("Discovery did not return usable device authorization and token endpoints.") + transport = HttpxTransport(timeout=device_config.http_timeout) + return DeviceAuthClient( + device_config, + store=FileTokenStore() if storage == "file" else _KeyringTokenStore(), + transport=transport, + grant=_InteractiveDeviceCodeGrant(device_config, transport), + ) + + +def _safe_verification_url(value: str) -> bool: + if "\\" in value or any(ord(char) <= 32 or ord(char) == 127 for char in value): + return False + try: + url = urlsplit(value) + return bool( + url.hostname + and url.username is None + and ( + url.scheme == "https" + or (url.scheme == "http" and url.hostname in {"localhost", "127.0.0.1", "::1"}) + ) + ) + except ValueError: + return False + + +def register_login_command(apcli: click.Group) -> None: + @apcli.command("login") + @click.option("--no-browser", is_flag=True, help="Print the verification address without opening a browser.") + def login(no_browser: bool) -> None: + """Sign in using the configured device authorization provider.""" + + def show_code( + verification_uri: str, + user_code: str, + verification_uri_complete: str | None, + expires_in: int, + ) -> None: + click.echo(f"Open {verification_uri} and enter code {user_code} (expires in {expires_in}s).", err=True) + if not no_browser and urlsplit(verification_uri).scheme == "https": + url = verification_uri + if verification_uri_complete and _safe_verification_url(verification_uri_complete): + complete = urlsplit(verification_uri_complete) + if complete.scheme == "https" and complete.netloc == urlsplit(verification_uri).netloc: + url = verification_uri_complete + with suppress(webbrowser.Error): + webbrowser.open(url) + + def show_poll(attempt: int, interval: int, elapsed: float) -> None: + if attempt == 1: + click.echo("Waiting for approval in your browser…", err=True) + + try: + client = create_device_auth_client(ConfigResolver()) + if client is None: + raise ConfigurationError("Set auth.device in apcore.yaml before running apcli login.") + client.login(on_user_code=show_code, on_poll=show_poll, timeout_seconds=900) + except ConfigurationError: + click.echo("Device login configuration error. Check auth.device in apcore.yaml.", err=True) + exit_with(EXIT_CONFIG_INVALID) + except (AuthError, OSError): + click.echo("Device login failed. Check the provider and credential store.", err=True) + exit_with(EXIT_ACL_DENIED) + else: + click.echo("Signed in.", err=True) diff --git a/cli/python/tests/conformance/test_structured_flags.py b/cli/python/tests/conformance/test_structured_flags.py index 774871e6..46f04241 100644 --- a/cli/python/tests/conformance/test_structured_flags.py +++ b/cli/python/tests/conformance/test_structured_flags.py @@ -114,6 +114,49 @@ def test_non_json_literals_fail_before_execution() -> None: assert module.calls == [] +def test_object_flag_reads_bounded_utf8_json_file(tmp_path: Path) -> None: + payload = '{"label":"é"}' + path = tmp_path / "filters.json" + path.write_text(payload, encoding="utf-8") + command, module = _command(_FIXTURE["schema"]) + args = ["--filters", f"@{path}", "--labels", "one"] + limit = len(payload.encode("utf-8")) + runner = CliRunner() + + accepted = runner.invoke(command, [*args, "--max-input-bytes", str(limit)]) + rejected = runner.invoke(command, [*args, "--max-input-bytes", str(limit - 1)]) + assert accepted.exit_code == 0, accepted.output + assert rejected.exit_code == EXIT_SCHEMA_VALIDATION_ERROR, rejected.output + assert module.calls == [{"filters": {"label": "é"}, "labels": ["one"]}] + + +def test_generated_and_generic_stdin_limit_precedence(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + from apcore_cli.discovery import register_exec_command + + module = _CaptureModule(_FIXTURE["schema"]) + registry = Registry() + registry.register("test.structured_flags", module) + descriptor = registry.get_definition("test.structured_flags") + assert descriptor is not None + executor = Executor(registry) + command = build_module_command(descriptor, executor) + group = click.Group() + register_exec_command(group, registry, executor) + payload = '{"filters":{},"labels":["é"]}' + limit = len(payload.encode("utf-8")) + monkeypatch.setenv("APCORE_CLI_STDIN_BUFFER_LIMIT", "1") + monkeypatch.chdir(tmp_path) + Path("apcore.yaml").write_text(f"cli:\n stdin_buffer_limit: {limit}\n", encoding="utf-8") + runner = CliRunner() + for cli, prefix in ((command, []), (group, ["exec", "test.structured_flags"])): + args = [*prefix, "--input", "-"] + assert runner.invoke(cli, args, input=payload).exit_code == 2 + assert runner.invoke(cli, [*args, "--max-input-bytes", str(limit)], input=payload).exit_code == 0 + assert runner.invoke(cli, [*args, "--large-input"], input=payload).exit_code == 0 + monkeypatch.delenv("APCORE_CLI_STDIN_BUFFER_LIMIT") + assert runner.invoke(command, ["--input", "-"], input=payload).exit_code == 0 + + def test_nullable_and_enum_container_flags_use_the_schema_validator() -> None: schema = deepcopy(_FIXTURE["schema"]) schema["properties"]["filters"] = {"type": ["object", "null"]} diff --git a/cli/python/tests/test_builtin_group.py b/cli/python/tests/test_builtin_group.py index 46a780d8..9944ee25 100644 --- a/cli/python/tests/test_builtin_group.py +++ b/cli/python/tests/test_builtin_group.py @@ -380,9 +380,10 @@ def test_subcommand_names_are_frozen(self): "describe-pipeline", "acl", "openapi", + "login", ): assert name in APCLI_SUBCOMMAND_NAMES - assert len(APCLI_SUBCOMMAND_NAMES) == 15 + assert len(APCLI_SUBCOMMAND_NAMES) == 16 def test_registrar_table_covers_the_canonical_set(self): """Drift guard: every name in the set must have a registrar row.""" diff --git a/cli/python/tests/test_device_login.py b/cli/python/tests/test_device_login.py new file mode 100644 index 00000000..ec82032d --- /dev/null +++ b/cli/python/tests/test_device_login.py @@ -0,0 +1,133 @@ +import json +import sys +import time + +import pytest +from apcore_toolkit.auth import ConfigurationError, FileTokenStore, HttpResponse, TokenSet + +from apcore_cli.__main__ import main +from apcore_cli.config import ConfigResolver +from apcore_cli.security.auth import AuthProvider + + +@pytest.fixture +def device_config(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) + monkeypatch.delenv("APCORE_AUTH_API_KEY", raising=False) + config = tmp_path / "apcore.yaml" + config.write_text( + "auth:\n device:\n client_id: test-cli\n" + " issuer: https://auth.example.test\n" + " device_authorization_endpoint: https://auth.example.test/device\n" + " token_endpoint: https://auth.example.test/token\n" + " token_storage: file\n", + encoding="utf-8", + ) + return config + + +@pytest.mark.parametrize("root_options", [[], ["--log-level", "WARNING", "--extensions-dir=missing"]]) +def test_login_displays_instructions_without_printing_tokens(device_config, monkeypatch, capsys, root_options): + from apcore_cli.security import device_login + + opened = [] + monkeypatch.setattr(device_login.webbrowser, "open", opened.append) + store = FileTokenStore(device_config.parent / "credentials.json") + monkeypatch.setattr(device_login, "FileTokenStore", lambda: store) + + def login(client, *, on_user_code, on_poll, timeout_seconds): + assert timeout_seconds == 900 + on_user_code( + verification_uri="https://auth.example.test/verify", + verification_uri_complete=None, + user_code="TEST-CODE", + expires_in=60, + ) + on_poll(attempt=1, interval=1, elapsed=0) + tokens = TokenSet("test-access-secret", refresh_token="test-refresh-secret") + client.store.save(client.store_key, tokens) + return tokens + + monkeypatch.setattr(device_login.DeviceAuthClient, "login", login) + monkeypatch.setattr(sys, "argv", ["apcore-cli", *root_options, "apcli", "login", "--no-browser"]) + with pytest.raises(SystemExit) as result: + main() + assert result.value.code == 0 + output = capsys.readouterr() + assert "TEST-CODE" in output.err + assert "https://auth.example.test/verify" in output.err + assert "test-access-secret" not in output.out + output.err + assert "test-refresh-secret" not in output.out + output.err + assert not opened + assert store.load("https://auth.example.test|test-cli").access_token == "test-access-secret" + + +def test_auth_provider_uses_refreshed_token(device_config, monkeypatch, tmp_path): + from apcore_cli.security import device_login + + store = FileTokenStore(tmp_path / "credentials.json") + monkeypatch.setattr(device_login, "FileTokenStore", lambda: store) + key = "https://auth.example.test|test-cli" + store.save(key, TokenSet("expired", expires_at=int(time.time()) - 1, refresh_token="refresh")) + calls = [] + + def send(_transport, request): + calls.append(request.url) + return HttpResponse(200, json.dumps({ + "access_token": "fresh", "expires_in": 3600, "refresh_token": "rotated", + }), "application/json") + + monkeypatch.setattr("apcore_toolkit.auth.transport.HttpxTransport.send", send) + provider = AuthProvider(ConfigResolver(config_path=str(device_config))) + assert provider.authenticate_request({}) == {"Authorization": "Bearer fresh"} + assert provider.authenticate_request({}) == {"Authorization": "Bearer fresh"} + assert calls == ["https://auth.example.test/token"] + assert store.load(key).refresh_token == "rotated" + + +def test_unsafe_verification_address_fails_before_polling(device_config, monkeypatch): + from apcore_cli.security.device_login import create_device_auth_client + + requests = [] + + def send(_transport, request): + requests.append(request.url) + return HttpResponse( + 200, + json.dumps({"verification_uri": "file:///path", "user_code": "ABCD", "device_code": "opaque"}), + "application/json", + ) + + monkeypatch.setattr("apcore_toolkit.auth.transport.HttpxTransport.send", send) + client = create_device_auth_client(ConfigResolver(config_path=str(device_config))) + assert client is not None + with pytest.raises(ConfigurationError, match="unsafe device login instructions"): + client.login() + assert requests == ["https://auth.example.test/device"] + + +def test_default_keyring_storage_isolated_by_client(device_config, monkeypatch): + from apcore_cli.security import device_login + + device_config.write_text(device_config.read_text().replace(" token_storage: file\n", "")) + records: dict[tuple[str, str], str] = {} + monkeypatch.setattr(device_login.keyring, "get_password", lambda service, account: records.get((service, account))) + monkeypatch.setattr( + device_login.keyring, + "set_password", + lambda service, account, value: records.__setitem__((service, account), value), + ) + monkeypatch.setattr( + device_login.keyring, "delete_password", lambda service, account: records.pop((service, account)) + ) + client = device_login.create_device_auth_client(ConfigResolver(config_path=str(device_config))) + assert client is not None + tokens = TokenSet("sample-token", refresh_token="sample-refresh") + client.store.save(client.store_key, tokens) + assert client.store.load(client.store_key) == tokens + assert client.store.load("https://auth.example.test|other-cli") is None + assert all(service == "apcore-cli-device-auth" and len(account) == 64 for service, account in records) + client.store.clear(client.store_key) + client.store.clear(client.store_key) + assert records == {} diff --git a/cli/python/tests/test_openapi_cmd.py b/cli/python/tests/test_openapi_cmd.py index 1faf1958..d03cb2a4 100644 --- a/cli/python/tests/test_openapi_cmd.py +++ b/cli/python/tests/test_openapi_cmd.py @@ -696,7 +696,7 @@ def test_openapi_is_in_the_canonical_subcommand_set(self): assert "openapi" in APCLI_SUBCOMMAND_NAMES assert "acl" in APCLI_SUBCOMMAND_NAMES - assert len(APCLI_SUBCOMMAND_NAMES) == 15 + assert len(APCLI_SUBCOMMAND_NAMES) == 16 @pytest.mark.parametrize("style", ["csv", "jsonl", "markdown", "skill"]) diff --git a/cli/python/tests/test_security/test_auth.py b/cli/python/tests/test_security/test_auth.py index b1bd8b21..f6e6cc8f 100644 --- a/cli/python/tests/test_security/test_auth.py +++ b/cli/python/tests/test_security/test_auth.py @@ -10,6 +10,7 @@ def _make_config(api_key=None): config = MagicMock() config.resolve.return_value = api_key + config.resolve_object.return_value = None return config diff --git a/cli/rust/CHANGELOG.md b/cli/rust/CHANGELOG.md index 72b7ef5f..4c7ae140 100644 --- a/cli/rust/CHANGELOG.md +++ b/cli/rust/CHANGELOG.md @@ -5,6 +5,12 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.14.2-alpha.2] - Unreleased +### Added + +- Configure positional arguments with `x-cli-positional`, repeat scalar array flags, and load object arguments with `@file`. [Issues #59 and #121](https://github.com/aiperceivable/apcore-surfaces/issues/121) +- Add `--max-input-bytes` and consistent large-input overrides on generated commands and `apcli exec`. [Issue #121](https://github.com/aiperceivable/apcore-surfaces/issues/121) +- Add `apcli login` for device authorization and refresh credentials on authenticated application requests. [Issue #89](https://github.com/aiperceivable/apcore-surfaces/issues/89) + ### Changed - Require Core `1.0.0-beta.1`. diff --git a/cli/rust/src/builtin_group.rs b/cli/rust/src/builtin_group.rs index 8c596053..670b67ca 100644 --- a/cli/rust/src/builtin_group.rs +++ b/cli/rust/src/builtin_group.rs @@ -45,6 +45,7 @@ pub const APCLI_SUBCOMMAND_NAMES: &[&str] = &[ // FE-14 / FE-15a (v0.12.0): the canonical set grew from 13 to 15. "acl", "openapi", + "login", ]; /// Default name of the built-in command group. @@ -701,9 +702,8 @@ mod tests { // ----- Constants ----- #[test] - fn apcli_subcommand_names_has_15_entries() { - // 13 through v0.11.0; FE-14 added `acl` and FE-15a added `openapi`. - assert_eq!(APCLI_SUBCOMMAND_NAMES.len(), 15); + fn apcli_subcommand_names_has_16_entries() { + assert_eq!(APCLI_SUBCOMMAND_NAMES.len(), 16); } #[test] @@ -724,6 +724,7 @@ mod tests { "describe-pipeline", "acl", "openapi", + "login", ] { assert!( APCLI_SUBCOMMAND_NAMES.contains(expected), diff --git a/cli/rust/src/cli.rs b/cli/rust/src/cli.rs index be1bfa5e..87d88ce9 100644 --- a/cli/rust/src/cli.rs +++ b/cli/rust/src/cli.rs @@ -38,7 +38,7 @@ pub enum CliError { #[error("json parse error: {0}")] JsonParse(String), - #[error("input too large (limit {limit} bytes, got {actual} bytes)")] + #[error("input too large (limit {limit} bytes, got at least {actual} bytes)")] InputTooLarge { limit: usize, actual: usize }, #[error("expected JSON object, got a different type")] @@ -241,9 +241,8 @@ fn audit_error(module_id: &str, input: &Value, exit_code: i32, duration_ms: u64) // exec_command — clap subcommand builder for `exec` // --------------------------------------------------------------------------- -/// Add the standard dispatch flags (--input, --yes, --large-input, --format, -/// --sandbox) to a clap Command. Used by both `exec_command()` and the external -/// subcommand re-parser in main.rs. +/// Add the standard dispatch flags to a clap Command. Used by both +/// `exec_command()` and the external subcommand re-parser in main.rs. pub fn add_dispatch_flags(cmd: clap::Command) -> clap::Command { use clap::{Arg, ArgAction}; let hide = !is_all_options_help(); @@ -272,11 +271,15 @@ pub fn add_dispatch_flags(cmd: clap::Command) -> clap::Command { Arg::new("large-input") .long("large-input") .action(ArgAction::SetTrue) - .help( - "Allow stdin input larger than 10MB \ - (default limit protects against \ - accidental pipes)", - ) + .help("Disable the byte limit for stdin and JSON files.") + .hide(hide), + ) + .arg( + Arg::new("max-input-bytes") + .long("max-input-bytes") + .value_name("BYTES") + .value_parser(parse_input_limit) + .help("Maximum bytes per stdin or JSON file input (default 10 MiB).") .hide(hide), ) .arg( @@ -431,6 +434,7 @@ const RESERVED_FLAG_NAMES: &[&str] = &[ "format", "input", "large-input", + "max-input-bytes", "sandbox", "strategy", "stream", @@ -445,9 +449,9 @@ const RESERVED_FLAG_NAMES: &[&str] = &[ /// * its `name` set to `module_def.name` /// * its `about` derived from the module descriptor (empty if unavailable) /// * the built-in dispatch flags (`--input`, `--yes`/`-y`, `--large-input`, -/// `--format`, `--sandbox`, `--dry-run`, `--trace`, `--stream`, `--strict-stream`, `--strategy`, +/// `--max-input-bytes`, `--format`, `--sandbox`, `--dry-run`, `--trace`, `--stream`, `--strict-stream`, `--strategy`, /// `--fields`, `--approval-timeout`, `--approval-token`) -/// * schema-derived flags from `schema_to_clap_args` +/// * schema-derived flags and positional arguments from `schema_to_clap_args` /// /// The executor is NOT embedded in the `clap::Command` — clap has no /// user-data attachment. Dispatch is handled separately by `dispatch_module` @@ -554,7 +558,64 @@ pub fn build_module_command_with_limit( // collect_input // --------------------------------------------------------------------------- -const STDIN_SIZE_LIMIT_BYTES: usize = 10 * 1024 * 1024; // 10 MiB +const STDIN_SIZE_LIMIT_BYTES: u64 = 10 * 1024 * 1024; // 10 MiB +const MAX_INPUT_LIMIT: u64 = 9_007_199_254_740_991; + +fn parse_input_limit(value: &str) -> Result { + value + .parse::() + .ok() + .filter(|limit| { + value.len() <= 16 + && value.bytes().all(|byte| byte.is_ascii_digit()) + && (1..=MAX_INPUT_LIMIT).contains(limit) + }) + .ok_or("Input size limit must be a positive integer of at most 9007199254740991 bytes.") +} + +fn dispatch_input_limit(matches: &clap::ArgMatches) -> Result, &'static str> { + if matches.get_flag("large-input") { + return Ok(None); + } + if let Ok(Some(limit)) = matches.try_get_one::("max-input-bytes") { + return Ok(Some(*limit)); + } + let resolver = crate::config::ConfigResolver::new(None, Some(PathBuf::from("apcore.yaml"))); + resolver + .resolve( + "apcore-cli.stdin_buffer_limit", + None, + Some("APCORE_CLI_STDIN_BUFFER_LIMIT"), + ) + .as_deref() + .map_or(Ok(Some(STDIN_SIZE_LIMIT_BYTES)), |value| { + parse_input_limit(value).map(Some) + }) +} + +fn read_input_bytes(reader: impl Read, limit: Option) -> Result, CliError> { + let mut buf = Vec::new(); + reader + .take(limit.map_or(u64::MAX, |limit| limit + 1)) + .read_to_end(&mut buf) + .map_err(|e| CliError::StdinRead(e.to_string()))?; + if let Some(limit) = limit.filter(|limit| buf.len() as u64 > *limit) { + return Err(CliError::InputTooLarge { + limit: limit as usize, + actual: buf.len(), + }); + } + Ok(buf) +} + +fn input_limit_error(limit: usize) -> String { + let size = if limit as u64 == STDIN_SIZE_LIMIT_BYTES { + "10 MiB".to_string() + } else { + format!("{limit} byte") + }; + format!("Input exceeds the {size} limit. Use --large-input to override.") +} /// Inner implementation: accepts any `Read` source for testability. /// @@ -570,7 +631,21 @@ pub fn collect_input_from_reader( stdin_flag: Option<&str>, cli_kwargs: HashMap, large_input: bool, - mut reader: R, + reader: R, +) -> Result, CliError> { + collect_input_from_reader_with_limit( + stdin_flag, + cli_kwargs, + (!large_input).then_some(STDIN_SIZE_LIMIT_BYTES), + reader, + ) +} + +fn collect_input_from_reader_with_limit( + stdin_flag: Option<&str>, + cli_kwargs: HashMap, + limit: Option, + reader: impl Read, ) -> Result, CliError> { // Drop Null values from CLI kwargs. let cli_non_null: HashMap = cli_kwargs @@ -582,17 +657,7 @@ pub fn collect_input_from_reader( return Ok(cli_non_null); } - let mut buf = Vec::new(); - reader - .read_to_end(&mut buf) - .map_err(|e| CliError::StdinRead(e.to_string()))?; - - if !large_input && buf.len() > STDIN_SIZE_LIMIT_BYTES { - return Err(CliError::InputTooLarge { - limit: STDIN_SIZE_LIMIT_BYTES, - actual: buf.len(), - }); - } + let buf = read_input_bytes(reader, limit)?; if buf.is_empty() { return Ok(cli_non_null); @@ -633,19 +698,31 @@ pub fn collect_input( stdin_flag: Option<&str>, cli_kwargs: HashMap, large_input: bool, +) -> Result, CliError> { + collect_input_with_limit( + stdin_flag, + cli_kwargs, + (!large_input).then_some(STDIN_SIZE_LIMIT_BYTES), + ) +} + +fn collect_input_with_limit( + stdin_flag: Option<&str>, + cli_kwargs: HashMap, + limit: Option, ) -> Result, CliError> { match stdin_flag { None | Some("") => { - collect_input_from_reader(None, cli_kwargs, large_input, std::io::stdin()) + collect_input_from_reader_with_limit(None, cli_kwargs, limit, std::io::empty()) } Some("-") => { - collect_input_from_reader(Some("-"), cli_kwargs, large_input, std::io::stdin()) + collect_input_from_reader_with_limit(Some("-"), cli_kwargs, limit, std::io::stdin()) } Some(path) => { let file = std::fs::File::open(path).map_err(|e| { CliError::StdinRead(format!("cannot open input file '{}': {}", path, e)) })?; - collect_input_from_reader(Some("-"), cli_kwargs, large_input, file) + collect_input_from_reader_with_limit(Some("-"), cli_kwargs, limit, file) } } } @@ -1063,12 +1140,74 @@ struct CliInputs { structured_defaults: HashMap, } +fn decode_structured_flag( + flag: &str, + property: &Value, + values: &[&str], + input_limit: Option, +) -> Result { + let invalid_json = || format!("Option '--{flag}' must contain valid JSON."); + let raw = values.first().copied().ok_or_else(invalid_json)?; + if let Some(kind) = crate::schema_parser::repeated_item_type(property) { + if values.len() == 1 && raw.trim_start().starts_with('[') { + return serde_json::from_str(raw).map_err(|_| invalid_json()); + } + let parse_item = |item: &&str| { + if kind == "string" { + return Ok(Value::String((*item).to_owned())); + } + let value: Value = serde_json::from_str(item).map_err(|_| invalid_json())?; + let valid = match kind { + "integer" => value.as_f64().is_some_and(|number| number.fract() == 0.0), + "number" => value.is_number(), + "boolean" => value.is_boolean(), + _ => false, + }; + valid.then_some(value).ok_or_else(invalid_json) + }; + return values + .iter() + .map(parse_item) + .collect::, _>>() + .map(Value::Array); + } + if let Some(path) = raw + .strip_prefix('@') + .filter(|_| property["type"].as_str() == Some("object")) + { + let file = std::fs::File::open(path) + .map_err(|error| format!("Could not read file for '--{flag}': {error}."))?; + let bytes = read_input_bytes(file, input_limit).map_err(|error| match error { + CliError::InputTooLarge { limit, .. } => { + format!("File for '--{flag}': {}", input_limit_error(limit)) + } + _ => format!("Could not read file for '--{flag}': {error}."), + })?; + return serde_json::from_slice(&bytes).map_err(|_| invalid_json()); + } + serde_json::from_str(raw).map_err(|_| invalid_json()) +} + +fn read_scalar_arg(matches: &clap::ArgMatches, id: &str) -> Option { + if let Ok(Some(value)) = matches.try_get_one::(id) { + return Some(value.clone()); + } + matches + .try_get_one::(id) + .ok() + .flatten() + .map(|path| path.to_string_lossy().into_owned()) +} + /// Read schema-derived flags and keep explicit structured values separate from defaults. fn extract_cli_kwargs( matches: &clap::ArgMatches, module_def: &apcore::registry::registry::ModuleDescriptor, + input_limit: Option, ) -> Result { - use crate::schema_parser::{is_structured_option, schema_to_clap_args}; + use crate::schema_parser::{ + is_structured_option, positional_properties, prop_name_to_flag_name, schema_to_clap_args, + }; let resolved = crate::ref_resolver::resolve_refs( &module_def.input_schema, @@ -1083,6 +1222,9 @@ fn extract_cli_kwargs( let mut inputs = CliInputs::default(); for arg in &schema_args.args { + let Some(flag) = arg.get_long() else { + continue; + }; if matches!( arg.get_action(), clap::ArgAction::SetTrue | clap::ArgAction::SetFalse @@ -1090,11 +1232,9 @@ fn extract_cli_kwargs( continue; } let id = arg.get_id().as_str(); - // Use try_get_one to avoid panicking when the arg doesn't exist - // in ArgMatches (e.g. exec subcommand doesn't have schema-derived flags). - if let Ok(Some(value)) = matches.try_get_one::(id) { - let property = &schema["properties"][id]; - if is_structured_option(property) { + let property = &schema["properties"][id]; + if is_structured_option(property) { + if let Ok(Some(values)) = matches.try_get_many::(id) { if matches.value_source(id) == Some(clap::parser::ValueSource::DefaultValue) { if let Some(default) = property.get("default") { inputs @@ -1102,27 +1242,53 @@ fn extract_cli_kwargs( .insert(id.to_owned(), default.clone()); } } else { - let value = serde_json::from_str(value).map_err(|_| { - format!( - "Option '--{}' must contain valid JSON.", - arg.get_long().unwrap_or(id) - ) - })?; + let values = values.map(String::as_str).collect::>(); + let value = decode_structured_flag(flag, property, &values, input_limit)?; inputs.structured_flags.insert(id.to_owned(), value); } - } else { - inputs - .kwargs - .insert(id.to_owned(), Value::String(value.clone())); } - } else if let Ok(Some(value)) = matches.try_get_one::(id) { - inputs.kwargs.insert( - id.to_owned(), - Value::String(value.to_string_lossy().to_string()), - ); + continue; + } + // Use try_get_one to avoid panicking when the arg doesn't exist + // in ArgMatches (e.g. exec subcommand doesn't have schema-derived flags). + if let Some(value) = read_scalar_arg(matches, id) { + inputs.kwargs.insert(id.to_owned(), Value::String(value)); } } + for positional in positional_properties(schema).map_err(|error| error.to_string())? { + let explicit = read_scalar_arg(matches, &positional.id); + if explicit.is_some() + && matches.value_source(positional.name) == Some(clap::parser::ValueSource::CommandLine) + { + return Err(format!( + "Provide '--{}' either as a flag or a positional argument.", + prop_name_to_flag_name(positional.name), + )); + } + let raw = explicit.or_else(|| { + inputs + .kwargs + .get(positional.name) + .and_then(Value::as_str) + .map(str::to_owned) + }); + let Some(raw) = raw else { + continue; + }; + let value = match schema["properties"][positional.name]["type"].as_str() { + Some("integer") => raw.parse::().ok().map(Value::from), + Some("number") => raw + .parse::() + .ok() + .and_then(serde_json::Number::from_f64) + .map(Value::Number), + _ => Some(Value::String(raw)), + } + .ok_or_else(|| format!("Invalid value for argument '{}'.", positional.name))?; + inputs.kwargs.insert(positional.name.to_owned(), value); + } + inputs .kwargs .extend(reconcile_bool_pairs(matches, &schema_args.bool_pairs)); @@ -1515,7 +1681,8 @@ async fn run_module_dispatch( // 3. Extract built-in flags from matches. let stdin_flag = matches.get_one::("input").map(|s| s.as_str()); let auto_approve = matches.get_flag("yes"); - let large_input = matches.get_flag("large-input"); + let input_limit = + dispatch_input_limit(matches).map_err(|message| errors.invalid_input(message))?; let format_flag = matches.get_one::("format").cloned(); let fields_flag = matches.get_one::("fields").cloned(); let dry_run = matches.get_flag("dry-run"); @@ -1542,7 +1709,7 @@ async fn run_module_dispatch( let cli_ctx = crate::acl_cmd::identity_context(); // 4. Decode schema-derived flags before validation and module execution. - let cli_inputs = extract_cli_kwargs(matches, &module_def).map_err(|message| { + let cli_inputs = extract_cli_kwargs(matches, &module_def, input_limit).map_err(|message| { errors.fail( EXIT_SCHEMA_VALIDATION_ERROR, "SCHEMA_VALIDATION_ERROR", @@ -1553,16 +1720,19 @@ async fn run_module_dispatch( // 5. Collect and merge input (exit 2 on errors). let input = match stdin_flag { Some(source) if source.trim_start().starts_with(['{', '[']) => { - collect_input_from_reader(Some("-"), cli_inputs.kwargs, large_input, source.as_bytes()) + collect_input_from_reader_with_limit( + Some("-"), + cli_inputs.kwargs, + input_limit, + source.as_bytes(), + ) } - _ => collect_input(stdin_flag, cli_inputs.kwargs, large_input), + _ => collect_input_with_limit(stdin_flag, cli_inputs.kwargs, input_limit), }; let mut merged = match input { Ok(m) => m, - Err(CliError::InputTooLarge { .. }) => { - return Err( - errors.invalid_input("Input exceeds 10MB limit. Use --large-input to override.") - ); + Err(CliError::InputTooLarge { limit, .. }) => { + return Err(errors.invalid_input(input_limit_error(limit))); } Err(CliError::JsonParse(detail)) => { return Err( @@ -2229,6 +2399,22 @@ mod tests { assert!(matches!(err, CliError::InputTooLarge { .. })); } + #[test] + fn test_collect_input_stops_at_the_first_excess_byte() { + let mut reader = std::io::Cursor::new([b'x'; 64]); + let err = + collect_input_from_reader_with_limit(Some("-"), HashMap::new(), Some(7), &mut reader) + .unwrap_err(); + assert!(matches!( + err, + CliError::InputTooLarge { + limit: 7, + actual: 8 + } + )); + assert_eq!(reader.position(), 8); + } + #[test] fn test_collect_input_large_input_allowed() { use std::io::Cursor; @@ -2442,8 +2628,7 @@ mod tests { #[test] fn test_apcli_subcommand_names_matches_spec() { - // Spec §4.1 subcommand table — 15 entries registered under `apcli` - // (13 through v0.11.0, plus FE-14 `acl` and FE-15a `openapi`). + // Spec §4.1 subcommand table. let expected: &[&str] = &[ "list", "describe", @@ -2460,6 +2645,7 @@ mod tests { "describe-pipeline", "acl", "openapi", + "login", ]; assert_eq!(crate::builtin_group::APCLI_SUBCOMMAND_NAMES, expected); } diff --git a/cli/rust/src/config.rs b/cli/rust/src/config.rs index ba2fbb58..1b986b6b 100644 --- a/cli/rust/src/config.rs +++ b/cli/rust/src/config.rs @@ -40,16 +40,8 @@ pub struct ConfigResolver { impl ConfigResolver { /// Default configuration values. /// - /// Audit D9 (config cleanup, v0.6.x): the entries `sandbox.enabled`, - /// `cli.auto_approve`, `cli.stdin_buffer_limit`, and the four - /// `apcore-cli.*` namespace aliases were removed because no production - /// code path reads them via `resolve()`. Sandbox is configured via the - /// `--sandbox` CLI flag, auto-approve via `--yes`, the stdin buffer is - /// hard-coded, and namespace aliases are registered separately by - /// `apcore`'s Config Bus when the parent crate calls - /// `apcore::Config::register_namespace`. The cross-key file-lookup - /// mechanism (`alternate_key`) still works regardless — it does not - /// depend on these DEFAULTS entries. + /// The dispatcher supplies the default for `cli.stdin_buffer_limit`. + /// Config file overrides can use either spelling in `NAMESPACE_MAP`. pub const DEFAULTS: &'static [(&'static str, &'static str)] = &[ ("extensions.root", "./extensions"), ("logging.level", "WARNING"), diff --git a/cli/rust/src/lib.rs b/cli/rust/src/lib.rs index 65894144..26b72002 100644 --- a/cli/rust/src/lib.rs +++ b/cli/rust/src/lib.rs @@ -143,6 +143,10 @@ pub fn register_apcli_subcommands( // FE-15a: `openapi` needs neither registry nor executor — it reads a // document and writes files (spec §4.7). ("openapi", Box::new(openapi_cmd::register_openapi_command)), + ( + "login", + Box::new(security::device_login::register_login_command), + ), ]; // The six system subcommands register atomically: either all appear (the diff --git a/cli/rust/src/main.rs b/cli/rust/src/main.rs index accba20d..6f356c11 100644 --- a/cli/rust/src/main.rs +++ b/cli/rust/src/main.rs @@ -736,18 +736,29 @@ async fn main() { .is_some(); apcore_cli::set_system_modules_available(system_modules_available); - // Build and parse CLI. The standalone binary explicitly passes its - // SDK package version through `create_cli_with` so `--version` is - // wired up. `create_cli` (the no-version factory) is reserved for - // embedders that do not want to leak the SDK's own version through - // their host CLI's `--version` flag (issue #18 opt-in semantics). - let cmd = create_cli_with( + // Parse the configured command tree before requiring a module directory. + // The device login command requires only auth.device configuration. + let cmd = build_cli_command( extensions_dir, None, + false, Some(env!("CARGO_PKG_VERSION").to_string()), None, ); let matches = cmd.get_matches(); + if let Some(login) = matches + .subcommand() + .filter(|(name, _)| apcore_cli::builtin_group::is_reserved_group_name(name)) + .and_then(|(_, group)| group.subcommand_matches("login")) + { + apcore_cli::exit::exit_with( + apcore_cli::security::device_login::dispatch_login(login).await, + ); + } + if let Err(error) = validate_extensions_dir(&extensions_dir_for_discovery) { + eprintln!("Error: {error}"); + apcore_cli::exit::exit_with(EXIT_CONFIG_NOT_FOUND); + } // FE-14 §4.3: publish the identity assertion before any dispatch path // builds a Context. Empty assertions clear the cell, so a run with no diff --git a/cli/rust/src/schema_parser.rs b/cli/rust/src/schema_parser.rs index 9641b374..052ce181 100644 --- a/cli/rust/src/schema_parser.rs +++ b/cli/rust/src/schema_parser.rs @@ -1,7 +1,7 @@ // apcore-cli — JSON Schema → clap Arg translator. // Protocol spec: FE-09 (schema_to_clap_args, reconvert_enum_values) -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use clap::Arg; @@ -19,6 +19,7 @@ pub const RESERVED_PROPERTY_NAMES: &[&str] = &[ "input", "yes", "large_input", + "max_input_bytes", "format", "fields", "sandbox", @@ -47,6 +48,8 @@ pub enum SchemaParserError { /// Caller must exit 48. #[error("Schema property '{name}' conflicts with built-in CLI flag")] ReservedPropertyName { name: String }, + #[error("{0}")] + InvalidPositional(String), } // --------------------------------------------------------------------------- @@ -163,6 +166,66 @@ pub(crate) fn is_structured_option(prop_schema: &Value) -> bool { } } +pub(crate) fn repeated_item_type(prop_schema: &Value) -> Option<&str> { + if prop_schema["type"].as_str() != Some("array") { + return None; + } + prop_schema["items"]["type"] + .as_str() + .filter(|kind| matches!(*kind, "string" | "integer" | "number" | "boolean")) +} + +pub(crate) struct PositionalProperty<'a> { + pub(crate) name: &'a str, + pub(crate) id: String, +} + +pub(crate) fn positional_properties( + schema: &Value, +) -> Result>, SchemaParserError> { + let Some(properties) = schema["properties"].as_object() else { + return Ok(Vec::new()); + }; + let mut indexed = BTreeMap::new(); + for (name, property) in properties { + let Some(index) = property.get("x-cli-positional") else { + continue; + }; + let index = index + .as_u64() + .filter(|index| *index > 0 && !indexed.contains_key(index)) + .ok_or_else(|| { + SchemaParserError::InvalidPositional( + "x-cli-positional indices must be unique positive integers.".into(), + ) + })?; + if !matches!( + property["type"].as_str(), + Some("string" | "integer" | "number") + ) { + return Err(SchemaParserError::InvalidPositional(format!( + "x-cli-positional is only supported on scalar property '{name}'." + ))); + } + indexed.insert(index, name.as_str()); + } + if indexed.keys().copied().ne(1..=indexed.len() as u64) { + return Err(SchemaParserError::InvalidPositional( + "x-cli-positional indices must be consecutive starting at 1.".into(), + )); + } + Ok(indexed + .into_iter() + .map(|(index, name)| { + let mut id = format!("_apcore_positional_{index}"); + while properties.contains_key(&id) { + id.insert(0, '_'); + } + PositionalProperty { name, id } + }) + .collect()) +} + /// Map a single schema property to a clap::Arg. /// /// Returns an error only for flag collisions (detected at schema_to_clap_args level). @@ -173,7 +236,14 @@ pub fn map_type(prop_name: &str, prop_schema: &Value) -> Result(args: &'a [clap::Arg], long: &str) -> Option<&'a clap::Arg> { args.iter().find(|a| a.get_long() == Some(long)) diff --git a/cli/rust/src/security/auth.rs b/cli/rust/src/security/auth.rs index 49eb8582..24b88626 100644 --- a/cli/rust/src/security/auth.rs +++ b/cli/rust/src/security/auth.rs @@ -8,10 +8,15 @@ // AuthProvider::authenticate_request into its request builder. Tracked as the // successor to audit finding D5-AUTH-UNWIRED in the project review. +use std::collections::HashMap; + +use apcore_toolkit::auth::DeviceAuthClient; use thiserror::Error; +use tokio::sync::Mutex; use crate::config::ConfigResolver; use crate::security::config_encryptor::{ConfigDecryptionError, ConfigEncryptor}; +use crate::security::device_login::{create_client, DeviceLoginError}; // --------------------------------------------------------------------------- // AuthenticationError @@ -69,6 +74,8 @@ pub enum AuthenticationError { pub struct AuthProvider { config: ConfigResolver, encryptor: Option, + /// Serializes credential refreshes made by this provider. + device_client: Mutex>, } impl AuthProvider { @@ -78,6 +85,7 @@ impl AuthProvider { Self { config, encryptor: None, + device_client: Mutex::new(None), } } @@ -87,6 +95,7 @@ impl AuthProvider { Self { config, encryptor: Some(encryptor), + device_client: Mutex::new(None), } } @@ -145,11 +154,73 @@ impl AuthProvider { /// * `AuthenticationError::MalformedApiKey` — key contains CR/LF that HTTP rejects. pub fn authenticate_request( &self, - mut headers: std::collections::HashMap, - ) -> Result, AuthenticationError> { + headers: HashMap, + ) -> Result, AuthenticationError> { let key = self .get_api_key()? .ok_or(AuthenticationError::MissingApiKey)?; + Self::insert_bearer(headers, &key) + } + + /// Add a configured API key or a current device credential to an HTTP request. + /// + /// Static API keys retain precedence. Otherwise, a configured device client + /// loads its stored tokens and refreshes an expiring access token. + pub async fn authenticate_request_async( + &self, + headers: HashMap, + ) -> Result, AuthenticationError> { + if let Some(key) = self.get_api_key()? { + return Self::insert_bearer(headers, &key); + } + let mut device_client = self.device_client.lock().await; + if device_client.is_none() { + *device_client = create_client(&self.config) + .await + .map_err(|error| match error { + DeviceLoginError::Configuration(message) => AuthenticationError::RequestError( + format!("Device login configuration error: {message}"), + ), + DeviceLoginError::Authorization => Self::device_authentication_error(), + })?; + } + let client = device_client + .as_ref() + .ok_or(AuthenticationError::MissingApiKey)?; + Self::insert_device_credential(headers, client).await + } + + async fn insert_device_credential( + headers: HashMap, + client: &DeviceAuthClient, + ) -> Result, AuthenticationError> { + let token = client + .ensure_valid_default() + .await + .map_err(|_| Self::device_authentication_error())?; + if !token.token_type.eq_ignore_ascii_case("bearer") + || token.access_token.is_empty() + || token + .access_token + .bytes() + .any(|byte| !byte.is_ascii_graphic()) + { + return Err(Self::device_authentication_error()); + } + Self::insert_bearer(headers, &token.access_token) + } + + fn device_authentication_error() -> AuthenticationError { + AuthenticationError::RequestError( + "Device authentication failed. Run apcli login and check the configured provider." + .into(), + ) + } + + fn insert_bearer( + mut headers: HashMap, + key: &str, + ) -> Result, AuthenticationError> { // Reject ANY '\r' or '\n' (any position) — spec security.md:94. // Trimming first would silently accept "abc\n" and emit // `Authorization: Bearer abc`, bypassing the header-injection guard @@ -208,6 +279,11 @@ impl AuthProvider { #[cfg(test)] mod tests { use super::*; + use apcore_toolkit::auth::{ + DeviceAuthConfig, FileTokenStore, HttpResponse, HttpTransport, RequestBody, TokenSet, + TokenStore, TransportError, + }; + use std::sync::Arc; use std::sync::Mutex; // Serialize all tests that touch APCORE_AUTH_API_KEY to prevent races. @@ -224,6 +300,85 @@ mod tests { ConfigResolver::new(None, None) } + #[tokio::test] + async fn async_authentication_prefers_the_static_key() { + let scratch = tempfile::tempdir().unwrap(); + let config_file = scratch.path().join("apcore.yaml"); + std::fs::write(&config_file, "auth: {device: {client_id: ''}}").unwrap(); + let flags = HashMap::from([("--api-key".to_owned(), Some("configured-key".to_owned()))]); + let provider = AuthProvider::new(ConfigResolver::new(Some(flags), Some(config_file))); + let headers = provider + .authenticate_request_async(HashMap::new()) + .await + .unwrap(); + assert_eq!(headers["Authorization"], "Bearer configured-key"); + } + + struct RefreshResponse; + + #[async_trait::async_trait] + impl HttpTransport for RefreshResponse { + async fn get( + &self, + _url: &str, + _headers: &HashMap, + ) -> Result { + panic!("explicit endpoints need no discovery"); + } + + async fn post( + &self, + url: &str, + _headers: &HashMap, + body: RequestBody, + ) -> Result { + assert_eq!(url, "https://provider.example/token"); + assert!(body.as_str().contains("grant_type=refresh_token")); + assert!(body.as_str().contains("refresh_token=old-refresh")); + Ok(HttpResponse { + status: 200, + content_type: Some("application/json".into()), + body: r#"{"access_token":"new-access","refresh_token":"new-refresh"}"#.into(), + }) + } + } + + #[tokio::test] + async fn device_bearer_refreshes_and_persists_rotated_credentials() { + let scratch = tempfile::tempdir().unwrap(); + let store = Arc::new(FileTokenStore::at(scratch.path().join("credentials.json"))); + let config = DeviceAuthConfig { + device_authorization_endpoint: Some("https://provider.example/device".into()), + token_endpoint: Some("https://provider.example/token".into()), + ..DeviceAuthConfig::new("cli") + }; + let client = DeviceAuthClient::new(config, store.clone()) + .unwrap() + .with_transport(Arc::new(RefreshResponse)); + store + .save( + client.store_key(), + &TokenSet { + access_token: "old-access".into(), + token_type: "Bearer".into(), + expires_at: Some(1), + refresh_token: Some("old-refresh".into()), + scope: vec![], + obtained_at: 0, + }, + ) + .await + .unwrap(); + for _ in 0..2 { + let headers = AuthProvider::insert_device_credential(HashMap::new(), &client) + .await + .unwrap(); + assert_eq!(headers["Authorization"], "Bearer new-access"); + } + let rotated = store.load(client.store_key()).await.unwrap().unwrap(); + assert_eq!(rotated.refresh_token.as_deref(), Some("new-refresh")); + } + #[test] fn test_get_api_key_from_env_var() { let _guard = ENV_LOCK.lock().unwrap(); diff --git a/cli/rust/src/security/device_login.rs b/cli/rust/src/security/device_login.rs new file mode 100644 index 00000000..4cfb3e75 --- /dev/null +++ b/cli/rust/src/security/device_login.rs @@ -0,0 +1,414 @@ +//! Configured device authorization and terminal presentation. + +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::{Arc, LazyLock}; +use std::time::Duration; + +use apcore_toolkit::auth::{ + DeviceAuthClient, DeviceAuthConfig, DeviceAuthError, FileTokenStore, LoginCallbacks, + ReqwestTransport, TokenSet, TokenStore, TokenStoreError, UserCodeEvent, +}; +use async_trait::async_trait; +use reqwest::Url; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use tokio::sync::Notify; + +use crate::config::ConfigResolver; + +const KEYRING_SERVICE: &str = "apcore-cli-device-auth"; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum DeviceLoginError { + #[error("{0}")] + Configuration(&'static str), + #[error("Device login failed. Check the provider and credential store.")] + Authorization, +} + +impl From for DeviceLoginError { + fn from(error: DeviceAuthError) -> Self { + match error { + DeviceAuthError::Config(_) => { + Self::Configuration("Check the issuer and endpoints configured under auth.device.") + } + _ => Self::Authorization, + } + } +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "lowercase")] +enum TokenStorage { + #[default] + Keyring, + File, +} + +#[derive(Deserialize)] +struct DeviceSettings { + client_id: String, + issuer: Option, + device_authorization_endpoint: Option, + token_endpoint: Option, + #[serde(default)] + scope: Vec, + #[serde(default)] + token_storage: TokenStorage, +} + +pub(crate) async fn create_client( + resolver: &ConfigResolver, +) -> Result, DeviceLoginError> { + let Some(value) = resolver + .resolve_object("auth.device") + .filter(|value| !value.is_null()) + else { + return Ok(None); + }; + let settings: DeviceSettings = serde_yaml_ng::from_value(value).map_err(|_| { + DeviceLoginError::Configuration( + "auth.device requires a client_id, optional scope list, and token_storage keyring or file.", + ) + })?; + if settings.client_id.trim().is_empty() { + return Err(DeviceLoginError::Configuration( + "auth.device.client_id is required.", + )); + } + validate_url(settings.issuer.as_deref())?; + let mut config = DeviceAuthConfig { + client_id: settings.client_id, + issuer: settings.issuer, + device_authorization_endpoint: settings.device_authorization_endpoint, + token_endpoint: settings.token_endpoint, + scope: settings.scope, + http_timeout_seconds: Some(30.0), + ..DeviceAuthConfig::default() + }; + validate_url(config.device_authorization_endpoint.as_deref())?; + validate_url(config.token_endpoint.as_deref())?; + let http = reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|_| { + DeviceLoginError::Configuration("Could not configure device authorization HTTP.") + })?; + config.hooks.http_client = Some(Arc::new(ReqwestTransport::new(http))); + if config.device_authorization_endpoint.is_none() || config.token_endpoint.is_none() { + config = config.discover().await?; + validate_url(config.device_authorization_endpoint.as_deref())?; + validate_url(config.token_endpoint.as_deref())?; + } + let store: Arc = match settings.token_storage { + TokenStorage::Keyring => Arc::new(KeyringTokenStore), + TokenStorage::File => Arc::new(FileTokenStore::default()), + }; + Ok(Some(DeviceAuthClient::new(config, store)?)) +} + +fn safe_url(value: &str) -> Option { + static UNSAFE_TEXT: LazyLock = + LazyLock::new(|| regex::Regex::new(r"\p{C}").expect("valid regex")); + if UNSAFE_TEXT.is_match(value) || value.chars().any(|c| c.is_whitespace() || c == '\\') { + return None; + } + let url = Url::parse(value).ok()?; + let host = url.host_str()?; + if !url.username().is_empty() || url.password().is_some() { + return None; + } + match url.scheme() { + "https" => Some(url), + "http" if matches!(host, "localhost" | "127.0.0.1" | "[::1]") => Some(url), + _ => None, + } +} + +fn validate_url(value: Option<&str>) -> Result<(), DeviceLoginError> { + if value.is_some_and(|url| safe_url(url).is_none()) { + return Err(DeviceLoginError::Configuration( + "auth.device issuer and endpoints must use HTTPS or HTTP on loopback.", + )); + } + Ok(()) +} + +struct KeyringTokenStore; + +impl KeyringTokenStore { + fn entry(key: &str) -> Result { + let account = format!("{:x}", Sha256::digest(key.as_bytes())); + keyring::Entry::new(KEYRING_SERVICE, &account) + .map_err(|_| Self::error("Could not open the OS keyring.")) + } + + fn error(message: &'static str) -> TokenStoreError { + TokenStoreError::Io { + path: "OS keyring".to_owned(), + source: std::io::Error::other(message), + } + } +} + +#[async_trait] +impl TokenStore for KeyringTokenStore { + async fn load(&self, key: &str) -> Result, TokenStoreError> { + match Self::entry(key)?.get_password() { + Ok(record) => serde_json::from_str(&record) + .map(Some) + .map_err(|_| Self::error("Could not decode the stored credential.")), + Err(keyring::Error::NoEntry) => Ok(None), + Err(_) => Err(Self::error("Could not read the stored credential.")), + } + } + + async fn save(&self, key: &str, tokens: &TokenSet) -> Result<(), TokenStoreError> { + let record = serde_json::to_string(tokens) + .map_err(|_| Self::error("Could not encode the credential."))?; + Self::entry(key)? + .set_password(&record) + .map_err(|_| Self::error("Could not save the credential.")) + } + + async fn clear(&self, key: &str) -> Result<(), TokenStoreError> { + match Self::entry(key)?.delete_password() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(_) => Err(Self::error("Could not remove the stored credential.")), + } + } +} + +/// Add the device login command when enabled by apcli visibility. +pub(crate) fn register_login_command(group: clap::Command) -> clap::Command { + group.subcommand( + clap::Command::new("login") + .about("Sign in using the configured device authorization provider.") + .arg( + clap::Arg::new("no-browser") + .long("no-browser") + .action(clap::ArgAction::SetTrue) + .help("Print the verification address without opening a browser."), + ), + ) +} + +fn browser_url(event: &UserCodeEvent, verification: &Url) -> Url { + event + .verification_uri_complete + .as_deref() + .and_then(safe_url) + .filter(|complete| complete.origin() == verification.origin()) + .unwrap_or_else(|| verification.clone()) +} + +fn open_browser(url: &str) { + #[cfg(target_os = "macos")] + let (program, args) = ("open", vec![url]); + #[cfg(target_os = "windows")] + let (program, args) = ("rundll32.exe", vec!["url.dll,FileProtocolHandler", url]); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let (program, args) = ("xdg-open", vec![url]); + if let Ok(mut browser) = tokio::process::Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + { + tokio::spawn(async move { + let _ = browser.wait().await; + }); + } +} + +async fn run_login(client: &DeviceAuthClient, no_browser: bool) -> Result<(), DeviceLoginError> { + static UNSAFE_CODE: LazyLock = + LazyLock::new(|| regex::Regex::new(r"\p{C}").expect("valid regex")); + let rejected = Arc::new(Notify::new()); + let rejected_instructions = Arc::clone(&rejected); + let callbacks = LoginCallbacks { + on_user_code: Some(Arc::new(move |event| { + let Some(verification) = safe_url(&event.verification_uri) else { + rejected_instructions.notify_one(); + return; + }; + if event.user_code.trim().is_empty() || UNSAFE_CODE.is_match(&event.user_code) { + rejected_instructions.notify_one(); + return; + } + eprintln!( + "Open {} and enter code {} (expires in {}s).", + verification, event.user_code, event.expires_in + ); + if !no_browser && verification.scheme() == "https" { + open_browser(browser_url(event, &verification).as_str()); + } + })), + on_poll: Some(Arc::new(|event| { + if event.attempt == 1 { + eprintln!("Waiting for approval in your browser…"); + } + })), + timeout_seconds: Some(900.0), + }; + tokio::select! { + biased; + _ = rejected.notified() => Err(DeviceLoginError::Configuration( + "The provider returned unsafe device login instructions.", + )), + result = client.login(&callbacks) => { + result.map_err(DeviceLoginError::from)?; + eprintln!("Signed in."); + Ok(()) + } + } +} + +/// Run apcli login and return the corresponding process exit code. +pub async fn dispatch_login(matches: &clap::ArgMatches) -> i32 { + let config = ConfigResolver::new(None, Some(PathBuf::from("apcore.yaml"))); + let result = async { + let client = create_client(&config) + .await? + .ok_or(DeviceLoginError::Configuration( + "Set auth.device in apcore.yaml before running apcli login.", + ))?; + run_login(&client, matches.get_flag("no-browser")).await + } + .await; + + match result { + Ok(()) => crate::EXIT_SUCCESS, + Err(DeviceLoginError::Configuration(message)) => { + eprintln!("Device login configuration error: {message}"); + crate::EXIT_CONFIG_NOT_FOUND + } + Err(error) => { + eprintln!("{error}"); + crate::EXIT_ACL_DENIED + } + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use apcore_toolkit::auth::{HttpResponse, HttpTransport, RequestBody, TransportError}; + + use super::*; + + struct DeviceFlow { + verification_uri: &'static str, + polls: std::sync::atomic::AtomicUsize, + } + + #[async_trait] + impl HttpTransport for DeviceFlow { + async fn get( + &self, + _url: &str, + _headers: &HashMap, + ) -> Result { + panic!("explicit endpoints need no discovery"); + } + + async fn post( + &self, + url: &str, + _headers: &HashMap, + body: RequestBody, + ) -> Result { + let response = if url.ends_with("/device") { + assert!(body.as_str().contains("client_id=cli")); + serde_json::json!({ + "device_code": "device-secret", + "user_code": "TEST-123", + "verification_uri": self.verification_uri, + "interval": 1 + }) + } else { + assert!(body.as_str().contains("device_code=device-secret")); + self.polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + serde_json::json!({ + "access_token": "test-token", + "refresh_token": "test-refresh", + }) + }; + Ok(HttpResponse { + status: 200, + content_type: Some("application/json".into()), + body: response.to_string(), + }) + } + } + + #[tokio::test] + async fn login_uses_toolkit_flow_and_persists_only_the_token_set() { + let scratch = tempfile::tempdir().unwrap(); + let token_path = scratch.path().join("credentials.json"); + let store = Arc::new(FileTokenStore::at(&token_path)); + let config = DeviceAuthConfig { + device_authorization_endpoint: Some("https://provider.example/device".into()), + token_endpoint: Some("https://provider.example/token".into()), + ..DeviceAuthConfig::new("cli") + }; + let flow = Arc::new(DeviceFlow { + verification_uri: "https://provider.example/verify", + polls: Default::default(), + }); + let client = DeviceAuthClient::new(config, store.clone()) + .unwrap() + .with_transport(flow) + .with_sleep(Arc::new(|_| Box::pin(async {}))); + run_login(&client, true).await.unwrap(); + let persisted = store.load(client.store_key()).await.unwrap().unwrap(); + assert_eq!(persisted.access_token, "test-token"); + assert_eq!(persisted.refresh_token.as_deref(), Some("test-refresh")); + let record = std::fs::read_to_string(token_path).unwrap(); + assert!(!record.contains("device-secret")); + assert!(!record.contains("TEST-123")); + } + + #[tokio::test] + async fn unsafe_device_instructions_stop_login_before_polling() { + let config = DeviceAuthConfig { + device_authorization_endpoint: Some("https://provider.example/device".into()), + token_endpoint: Some("https://provider.example/token".into()), + ..DeviceAuthConfig::new("cli") + }; + let flow = Arc::new(DeviceFlow { + verification_uri: "https://user:secret@provider.example/verify", + polls: Default::default(), + }); + let client = DeviceAuthClient::without_store(config) + .unwrap() + .with_transport(flow.clone()); + let result = run_login(&client, true).await; + assert!(matches!(result, Err(DeviceLoginError::Configuration(_)))); + assert_eq!(flow.polls.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[test] + fn browser_complete_url_must_use_the_verification_origin() { + let explicit = safe_url("https://provider.example/verify").unwrap(); + let mut event = UserCodeEvent { + verification_uri: explicit.to_string(), + verification_uri_complete: Some("https://other.example/verify?code=ABC".into()), + user_code: "ABC".into(), + expires_in: 60, + }; + assert_eq!(browser_url(&event, &explicit), explicit); + event.verification_uri_complete = Some("https://provider.example/verify?code=ABC".into()); + assert_eq!( + browser_url(&event, &explicit).as_str(), + "https://provider.example/verify?code=ABC", + ); + assert!(safe_url("http://[::1]/verify").is_some()); + assert!(safe_url("http://provider.example/verify").is_none()); + assert!(safe_url("https://example.com\u{202e}/verify").is_none()); + } +} diff --git a/cli/rust/src/security/mod.rs b/cli/rust/src/security/mod.rs index 187731cb..d4669ec8 100644 --- a/cli/rust/src/security/mod.rs +++ b/cli/rust/src/security/mod.rs @@ -4,6 +4,7 @@ pub mod audit; pub mod auth; pub mod config_encryptor; +pub mod device_login; pub mod sandbox; pub use audit::{AuditLogError, AuditLogger}; diff --git a/cli/rust/src/shell.rs b/cli/rust/src/shell.rs index 7c672f7a..cbfc1f06 100644 --- a/cli/rust/src/shell.rs +++ b/cli/rust/src/shell.rs @@ -40,6 +40,7 @@ pub const KNOWN_BUILTINS: &[&str] = &[ "health", "init", "list", + "login", "man", "openapi", "reload", @@ -66,6 +67,10 @@ pub const KNOWN_BUILTIN_DESCRIPTIONS: &[(&str, &str)] = &[ ("health", "Show module or registry health status"), ("init", "Scaffolding commands"), ("list", "List available modules"), + ( + "login", + "Sign in using the configured device authorization provider", + ), ("man", "Generate man page"), ("openapi", "Import an OpenAPI document as module artifacts"), ("reload", "Reload a module's definition"), @@ -965,8 +970,7 @@ mod tests { #[test] fn test_known_builtins_has_expected_count() { - // 14 through v0.11.0; FE-14 added `acl` and FE-15a added `openapi`. - assert_eq!(KNOWN_BUILTINS.len(), 16); + assert_eq!(KNOWN_BUILTINS.len(), 17); } #[test] diff --git a/cli/rust/tests/conformance_structured_flags.rs b/cli/rust/tests/conformance_structured_flags.rs index eece3ce1..08961552 100644 --- a/cli/rust/tests/conformance_structured_flags.rs +++ b/cli/rust/tests/conformance_structured_flags.rs @@ -131,6 +131,92 @@ async fn generated_commands_decode_structured_flags_from_shared_fixture() { } } +#[tokio::test] +async fn object_flags_read_json_files_under_the_input_limit() { + use std::io::Write; + + let schema = json!({ + "type": "object", + "properties": {"filters": {"type": "object"}}, + "required": ["filters"], + }); + let mut file = tempfile::NamedTempFile::new().unwrap(); + file.write_all(br#"{"enabled":true}"#).unwrap(); + let option = format!("@{}", file.path().display()); + for (id, limit, exit_code, input) in [ + ( + "within limit", + "16", + 0, + Some(json!({"filters": {"enabled": true}})), + ), + ("over limit", "15", 45, None), + ] { + run_case( + &schema, + &[ + "--filters".into(), + option.clone(), + "--max-input-bytes".into(), + limit.into(), + ], + id, + &Expected { + exit_code, + calls: usize::from(exit_code == 0), + input, + }, + ) + .await; + } +} + +#[tokio::test] +async fn positional_order_and_scalar_types_follow_the_schema() { + let schema = json!({ + "type": "object", + "properties": { + "a_number": {"type": "number", "x-cli-positional": 2}, + "z_integer": {"type": "integer", "x-cli-positional": 1}, + "samples": {"type": "array", "items": {"type": "number"}}, + "states": {"type": "array", "items": {"type": "boolean"}}, + "counts": {"type": "array", "items": {"type": "integer"}}, + }, + "required": ["a_number", "z_integer", "samples", "states", "counts"], + }); + let flags = [ + "--samples", + "-3.5", + "--samples", + "2", + "--states", + "true", + "--states", + "false", + "--counts", + "7.0", + "--counts", + "3", + ]; + let expected = Expected { + exit_code: 0, + calls: 1, + input: Some( + json!({"a_number": 2.5, "z_integer": -17, "samples": [-3.5, 2], "states": [true, false], "counts": [7.0, 3]}), + ), + }; + for (id, args) in [ + ("ordered typed positionals", ["-17", "2.5"]), + ( + "compatible typed flags", + ["--z-integer=-17", "--a-number=2.5"], + ), + ] { + let args: Vec = args.into_iter().chain(flags).map(str::to_owned).collect(); + run_case(&schema, &args, id, &expected).await; + } +} + #[tokio::test] async fn structured_defaults_follow_json_input_and_explicit_flag_precedence() { let schema = json!({ diff --git a/cli/rust/tests/device_login.rs b/cli/rust/tests/device_login.rs new file mode 100644 index 00000000..e80a2414 --- /dev/null +++ b/cli/rust/tests/device_login.rs @@ -0,0 +1,44 @@ +use std::process::Command; + +#[test] +fn login_needs_no_extensions_directory() { + let project = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_apcore-cli")) + .current_dir(project.path()) + .env("APCORE_CLI_APCLI", "1") + .args(["apcli", "login", "--no-browser"]) + .output() + .unwrap(); + + assert_eq!( + output.status.code(), + Some(apcore_cli::EXIT_CONFIG_NOT_FOUND) + ); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("Set auth.device in apcore.yaml")); +} + +#[test] +fn login_help_and_global_flags_work_without_module_directory() { + let project = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_apcore-cli")) + .current_dir(project.path()) + .env("APCORE_CLI_APCLI", "1") + .args(["--extensions-dir", "missing", "apcli", "login", "--help"]) + .output() + .unwrap(); + assert!(output.status.success()); + assert!(String::from_utf8_lossy(&output.stdout).contains("--no-browser")); + + let output = Command::new(env!("CARGO_BIN_EXE_apcore-cli")) + .current_dir(project.path()) + .env("APCORE_CLI_APCLI", "1") + .args(["--extensions-dir", "missing", "apcli", "list"]) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(apcore_cli::EXIT_CONFIG_NOT_FOUND) + ); + assert!(String::from_utf8_lossy(&output.stderr).contains("missing")); +} diff --git a/cli/rust/tests/test_config.rs b/cli/rust/tests/test_config.rs index 24dffbd3..039daba2 100644 --- a/cli/rust/tests/test_config.rs +++ b/cli/rust/tests/test_config.rs @@ -25,10 +25,8 @@ fn test_config_resolver_with_cli_flags() { #[test] fn test_defaults_contains_expected_keys() { - // Audit D9 (v0.6.x): sandbox.enabled and cli.stdin_buffer_limit were - // removed because they were never read by resolve() at runtime. The - // canonical set of resolvable keys is verified by the unit tests in - // src/config.rs (test_defaults_contains_expected_keys + test_deleted_keys_absent). + // Sandbox is enabled by a flag, and input dispatch owns the default + // byte limit. These keys need no ConfigResolver default. let resolver = ConfigResolver::new(None, None); for key in [ "extensions.root", diff --git a/cli/rust/tests/test_e2e.rs b/cli/rust/tests/test_e2e.rs index 4e721a56..00487613 100644 --- a/cli/rust/tests/test_e2e.rs +++ b/cli/rust/tests/test_e2e.rs @@ -170,6 +170,60 @@ fn test_e2e_stdin_piping() { ); } +#[test] +fn test_e2e_input_byte_limit_precedence() { + let temp = tempfile::tempdir().unwrap(); + let extensions = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/extensions"); + let input = temp.path().join("input.json"); + std::fs::write(&input, br#"{"a":1,"b":2}"#).unwrap(); + std::fs::write( + temp.path().join("apcore.yaml"), + "cli:\n stdin_buffer_limit: 1\n", + ) + .unwrap(); + + for mode in [&["math.add"][..], &["apcli", "exec", "math.add"][..]] { + for (case, env, flags, expected) in [ + ("yaml limit", None, &[][..], 2), + ("env overrides yaml", Some("13"), &[][..], 0), + ( + "flag overrides env", + Some("13"), + &["--max-input-bytes", "12"][..], + 2, + ), + ("large input bypass", Some("1"), &["--large-input"][..], 0), + ( + "invalid flag", + None, + &["--max-input-bytes", "9007199254740992"][..], + 2, + ), + ] { + let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_apcore-cli")); + command + .current_dir(temp.path()) + .arg("--extensions-dir") + .arg(&extensions) + .args(mode) + .arg("--input") + .arg(&input) + .args(flags) + .env_remove("APCORE_CLI_STDIN_BUFFER_LIMIT"); + if let Some(limit) = env { + command.env("APCORE_CLI_STDIN_BUFFER_LIMIT", limit); + } + let out = command.output().unwrap(); + assert_eq!( + out.status.code(), + Some(expected), + "{mode:?} {case}: {}", + String::from_utf8_lossy(&out.stderr), + ); + } + } +} + #[test] fn test_e2e_unknown_module_exits_44() { let out = run_apcore(&[ diff --git a/cli/typescript/CHANGELOG.md b/cli/typescript/CHANGELOG.md index a31127a8..66fdf287 100644 --- a/cli/typescript/CHANGELOG.md +++ b/cli/typescript/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [0.14.2-alpha.2] - Unreleased +### Added + +- Configure positional arguments with `x-cli-positional`, repeat scalar array flags, and load object arguments with `@file`. [Issues #59 and #121](https://github.com/aiperceivable/apcore-surfaces/issues/121) +- Add `--max-input-bytes` and consistent large-input overrides on generated commands and `apcli exec`. [Issue #121](https://github.com/aiperceivable/apcore-surfaces/issues/121) +- Add `apcli login` for device authorization and refresh credentials on authenticated application requests. [Issue #89](https://github.com/aiperceivable/apcore-surfaces/issues/89) + ### Changed - Require `apcore-js@1.0.0-beta.1` as the runtime peer and development dependency. diff --git a/cli/typescript/src/builtin-group.ts b/cli/typescript/src/builtin-group.ts index 1149b91a..d9a46862 100644 --- a/cli/typescript/src/builtin-group.ts +++ b/cli/typescript/src/builtin-group.ts @@ -161,6 +161,7 @@ export const APCLI_SUBCOMMAND_NAMES: ReadonlySet = new Set([ "acl", // FE-15a — OpenAPI import. Needs neither registry nor executor. "openapi", + "login", ]); // --------------------------------------------------------------------------- diff --git a/cli/typescript/src/discovery.ts b/cli/typescript/src/discovery.ts index 5ee71fe7..cc5b214c 100644 --- a/cli/typescript/src/discovery.ts +++ b/cli/typescript/src/discovery.ts @@ -18,6 +18,7 @@ import { reportModuleError, resolveModuleError } from "./error-output.js"; import { validateModuleId, collectInput, readModuleInput, validateSandboxOptions } from "./main.js"; import type { ModuleResultOptions } from "./main.js"; import { assertValidModuleId } from "./validate.js"; +import { parseMaxInputBytes } from "./input-limits.js"; import { formatExecResult, formatModuleDetail, @@ -273,6 +274,8 @@ export function registerExecCommand( "--input ", "JSON object passed as input to the module. Use '-' to read JSON from stdin.", ) + .option("--large-input", "Disable the byte limit for stdin JSON.", false) + .option("--max-input-bytes ", "Maximum bytes of stdin JSON (default 10 MiB).", parseMaxInputBytes) .option("-y, --yes", "Auto-approve if the module declares requires_approval.", false) .option( "--approval-timeout ", @@ -291,6 +294,8 @@ export function registerExecCommand( format?: string; fields?: string; input?: string; + largeInput: boolean; + maxInputBytes?: string; yes: boolean; approvalTimeout?: number; sandbox: boolean; @@ -314,7 +319,7 @@ export function registerExecCommand( if (!moduleDef) throw new ModuleNotFoundError(`Module '${moduleId}' not found.`); if (opts.input === "-") { - merged = await readModuleInput("-", {}); + merged = await readModuleInput("-", {}, opts.largeInput, opts.maxInputBytes); } else if (opts.input !== undefined) { let parsed: unknown; try { diff --git a/cli/typescript/src/input-limits.ts b/cli/typescript/src/input-limits.ts new file mode 100644 index 00000000..57c21f9b --- /dev/null +++ b/cli/typescript/src/input-limits.ts @@ -0,0 +1,50 @@ +import { createReadStream } from "node:fs"; +import { InvalidArgumentError } from "commander"; +import { ConfigResolver } from "./config.js"; +import { InvalidCliInputError } from "./errors.js"; + +const DEFAULT_INPUT_LIMIT = 10 * 1024 * 1024; +const LIMIT_MESSAGE = "Input size limit must be a positive integer of at most 9007199254740991 bytes."; + +function parseLimit(raw: unknown): number | undefined { + const limit: unknown = typeof raw === "string" && /^[0-9]{1,16}$/.test(raw) ? Number(raw) : raw; + return typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0 ? limit : undefined; +} + +export function parseMaxInputBytes(value: string): string { + if (parseLimit(value) === undefined) throw new InvalidArgumentError(LIMIT_MESSAGE); + return value; +} + +export function resolveInputLimit(largeInput: boolean | undefined, maxInputBytes?: string): number | undefined { + if (largeInput) return undefined; + const config = new ConfigResolver(); + const raw = maxInputBytes ?? config.resolve("apcore-cli.stdin_buffer_limit", undefined, "APCORE_CLI_STDIN_BUFFER_LIMIT"); + if (raw === undefined || raw === null) return DEFAULT_INPUT_LIMIT; + const limit = parseLimit(raw); + if (limit === undefined) throw new InvalidCliInputError(LIMIT_MESSAGE); + return limit; +} + +export async function readInputText(source: string, label: string, limit: number | undefined): Promise { + const fromStdin = source === "-"; + const chunks: Buffer[] = []; + let size = 0; + try { + const stream = fromStdin ? process.stdin : createReadStream(source, { end: limit }); + for await (const chunk of stream.iterator({ destroyOnReturn: !fromStdin })) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8"); + size += buffer.byteLength; + if (limit !== undefined && size > limit) { + const maximum = limit === DEFAULT_INPUT_LIMIT ? "10 MiB" : `${limit} byte`; + throw new InvalidCliInputError(`${label} input exceeds the ${maximum} limit. Use --large-input to override.`); + } + chunks.push(buffer); + } + return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(Buffer.concat(chunks, size)); + } catch (error) { + if (error instanceof InvalidCliInputError) throw error; + const input = fromStdin ? label : `input ${label}`; + throw new InvalidCliInputError(`Could not read ${input}: ${error instanceof Error ? error.message : String(error)}.`); + } +} diff --git a/cli/typescript/src/main.ts b/cli/typescript/src/main.ts index a354f598..2920fbdf 100644 --- a/cli/typescript/src/main.ts +++ b/cli/typescript/src/main.ts @@ -7,16 +7,16 @@ * F11 (extra commands) */ -import { readFileSync } from "node:fs"; import * as path from "node:path"; -import { Command, CommanderError, Option } from "commander"; +import { Argument, Command, CommanderError, Option } from "commander"; import packageInfo from "../package.json" with { type: "json" }; import { EXIT_CODES, exitCodeForError, MaxDepthExceededError, CircularRefError, UnresolvableRefError, SchemaValidationError, ModuleExecutionError, InvalidCliInputError } from "./errors.js"; import { exitWith } from "./exit.js"; import { reportModuleError, resolveModuleError } from "./error-output.js"; import type { ErrorStream } from "./error-output.js"; import { resolveRefs } from "./ref-resolver.js"; -import { schemaToCliOptions } from "./schema-parser.js"; +import { decodeStructuredFlag, getPositionalOptions, schemaToCliOptions } from "./schema-parser.js"; +import { parseMaxInputBytes, readInputText, resolveInputLimit } from "./input-limits.js"; import { checkApproval } from "./approval.js"; import { getAnnotation } from "./annotations.js"; import { formatExecResult, formatPreflightResult, firstFailedExitCode, resolveFormat } from "./output.js"; @@ -43,6 +43,7 @@ import { import { registerPipelineCommand } from "./strategy.js"; import { registerAclCommand } from "./acl-cmd.js"; import { registerOpenapiCommand } from "./openapi-cmd.js"; +import { registerLoginCommand } from "./security/device-login.js"; import { executeStrictStream, validateStrictStreamOptions } from "./strict-stream.js"; import { assertDelegatedAccess, @@ -218,6 +219,10 @@ export interface OptionConfig { parseArg?: (value: string) => unknown; /** Decode an explicit structured option in the module command's error boundary. */ parseStructuredArg?: (value: string) => unknown; + /** Item type of a plain scalar array that accepts repeated arguments. */ + structuredArrayItemType?: string; + /** Whether an object option supports a JSON file with the @file convention. */ + structuredFileInput?: boolean; } // --------------------------------------------------------------------------- @@ -843,7 +848,7 @@ interface _RegistrarEntry { } /** - * Central dispatcher for the 15 canonical apcli subcommands. Called once per + * Central dispatcher for the canonical apcli subcommands. Called once per * createCli invocation after the apcli Commander group is built. Honors * {@link ApcliGroup.resolveVisibility} for include/exclude modes, and skips * entries whose `requiresExecutor: true` flag is not satisfied. @@ -896,6 +901,7 @@ function _registerApcliSubcommands( // executor and never touches the registry, so it works in standalone mode // where no registry is wired (T-OAPI-27). { name: "openapi", requiresExecutor: false, register: (g) => registerOpenapiCommand(g) }, + { name: "login", requiresExecutor: false, register: (g) => registerLoginCommand(g) }, ]; // The six system subcommands register atomically: either all appear (the @@ -1160,7 +1166,9 @@ export function buildModuleCommand( // Built-in options (hidden unless --all-options) const inputOpt = new Option("--input ", "Read JSON input from a file path, or use '-' to read from stdin pipe"); const yesOpt = new Option("-y, --yes", "Skip interactive approval prompts (for scripts and CI)").default(false); - const largeInputOpt = new Option("--large-input", "Allow stdin input larger than 10MB (default limit protects against accidental pipes)").default(false); + const largeInputOpt = new Option("--large-input", "Disable the byte limit for stdin and JSON files.").default(false); + const maxInputBytesOpt = new Option("--max-input-bytes ", "Maximum bytes per stdin or JSON file input (default 10 MiB).") + .argParser(parseMaxInputBytes); const formatOpt = new Option("--format ", "Output format: json, table, csv, yaml, jsonl.") .choices(["json", "table", "csv", "yaml", "jsonl"]); const fieldsOpt = new Option("--fields ", "Comma-separated dot-paths to select from the result (e.g., 'status,data.count')."); @@ -1184,6 +1192,7 @@ export function buildModuleCommand( inputOpt.hideHelp(); yesOpt.hideHelp(); largeInputOpt.hideHelp(); + maxInputBytesOpt.hideHelp(); formatOpt.hideHelp(); fieldsOpt.hideHelp(); dryRunOpt.hideHelp(); @@ -1198,6 +1207,7 @@ export function buildModuleCommand( cmd.addOption(inputOpt); cmd.addOption(yesOpt); cmd.addOption(largeInputOpt); + cmd.addOption(maxInputBytesOpt); cmd.addOption(formatOpt); cmd.addOption(fieldsOpt); cmd.addOption(sandboxOpt); @@ -1229,8 +1239,15 @@ export function buildModuleCommand( const schemaFlags: [OptionConfig, string][] = []; for (const opt of schemaOptions) { const flagBase = opt.name.replace(/_/g, "-"); - const option = new Option(opt.isBooleanFlag ? `--${flagBase}` : opt.flags, opt.description) - .default(opt.defaultValue); + const option = new Option(opt.isBooleanFlag ? `--${flagBase}` : opt.flags, opt.description); + if (opt.structuredArrayItemType) { + option.argParser((value: string, previous: string[] = []) => { + previous.push(value); + return previous; + }); + } else { + option.default(opt.defaultValue); + } // Commander strips "no-" from the key by default. Keep it on declarations // from the schema so only the generated boolean counterparts negate flags. if (option.negate) { @@ -1247,12 +1264,30 @@ export function buildModuleCommand( } } + let positionals: typeof schemaFlags; + try { + positionals = getPositionalOptions(resolvedSchema, schemaFlags); + } catch (error) { + if (!(error instanceof SchemaValidationError)) throw error; + process.stderr.write(`Error: Module '${moduleId}' schema error: ${error.message}\n`); + exitWith(EXIT_CODES.INVALID_CLI_INPUT); + } + for (const [positional] of positionals) { + const name = positional.name.replace(/_/g, "-"); + const argument = new Argument(`[${name}]`, positional.description); + if (positional.choices) argument.choices(positional.choices); + if (positional.parseArg) argument.argParser(positional.parseArg); + cmd.addArgument(argument); + } + // Action callback - cmd.action(async (options: Record) => { + cmd.action(async (...args: unknown[]) => { + const options = cmd.opts>(); // Pop built-in options const stdinFlag = options.input as string | undefined; const autoApprove = options.yes as boolean; const largeInput = options.largeInput as boolean; + const maxInputBytes = options.maxInputBytes as string | undefined; const outputFormat = options.format as string | undefined; const outputFields = options.fields as string | undefined; const sandboxEnabled = options.sandbox as boolean; @@ -1278,18 +1313,32 @@ export function buildModuleCommand( if (strictStreamFlag) validateStrictStreamOptions(executor, sandboxEnabled, traceFlag, strategyName); } // 1. Collect and merge input + const inputLimit = resolveInputLimit(largeInput, maxInputBytes); const schemaKwargs: Record = {}; const structuredFlags: Record = {}; + const structuredDefaults: Record = {}; for (const [opt, key] of schemaFlags) { - if (!Object.hasOwn(options, key)) continue; const value = options[key]; - if (opt.parseStructuredArg && typeof value === "string" && cmd.getOptionValueSource(key) === "cli") { - structuredFlags[opt.name] = opt.parseStructuredArg(value); - } else { + if (opt.parseStructuredArg) { + if ((typeof value === "string" || Array.isArray(value)) && cmd.getOptionValueSource(key) === "cli") { + structuredFlags[opt.name] = await decodeStructuredFlag(opt, value, inputLimit); + } else if (opt.defaultValue !== undefined && opt.defaultValue !== null) { + structuredDefaults[opt.name] = opt.defaultValue; + } + } else if (Object.hasOwn(options, key)) { schemaKwargs[opt.name] = value; } } - merged = { ...await readModuleInput(stdinFlag, schemaKwargs, largeInput), ...structuredFlags }; + for (const [index, [positional, key]] of positionals.entries()) { + const value = args[index]; + if (value === undefined) continue; + if (cmd.getOptionValueSource(key) === "cli") { + const flag = positional.flags.split(" ")[0]; + throw new SchemaValidationError(`Provide '${flag}' either as a flag or a positional argument.`); + } + schemaKwargs[positional.name] = value; + } + merged = { ...structuredDefaults, ...await mergeModuleInput(stdinFlag, schemaKwargs, inputLimit), ...structuredFlags }; // 2. Reconvert enum values const reconverted = reconvertEnumValues(merged, schemaOptions); @@ -1563,6 +1612,15 @@ export async function readModuleInput( stdinFlag: string | undefined, cliKwargs: Record, largeInput?: boolean, + maxInputBytes?: string, +): Promise> { + return mergeModuleInput(stdinFlag, cliKwargs, resolveInputLimit(largeInput, maxInputBytes)); +} + +async function mergeModuleInput( + stdinFlag: string | undefined, + cliKwargs: Record, + inputLimit: number | undefined, ): Promise> { // Remove null/undefined values from CLI kwargs const cliKwargsNonNull: Record = {}; @@ -1576,32 +1634,8 @@ export async function readModuleInput( return cliKwargsNonNull; } - let raw: string; - let source: string; - if (stdinFlag === "-") { - source = "STDIN"; - try { - raw = await readStdin(); - } catch (error) { - throw new InvalidCliInputError(`Could not read STDIN: ${error instanceof Error ? error.message : String(error)}`); - } - } else { - // File-path source (help text: "JSON input file or '-' for stdin") - source = `file '${stdinFlag}'`; - try { - raw = readFileSync(stdinFlag, "utf-8"); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - throw new InvalidCliInputError(`Could not read input ${source}: ${msg}`); - } - } - - const rawSize = Buffer.byteLength(raw, "utf-8"); - if (rawSize > 10_485_760 && !largeInput) { - throw new InvalidCliInputError( - `${source} input exceeds 10MB limit. Use --large-input to override.`, - ); - } + const source = stdinFlag === "-" ? "STDIN" : `file '${stdinFlag}'`; + const raw = await readInputText(stdinFlag, source, inputLimit); if (!raw) { return cliKwargsNonNull; @@ -1624,33 +1658,6 @@ export async function readModuleInput( return { ...(parsed as Record), ...cliKwargsNonNull }; } -/** - * Read all data from stdin with proper cleanup. - */ -function readStdin(): Promise { - return new Promise((resolve, reject) => { - const chunks: Buffer[] = []; - const onData = (chunk: Buffer) => chunks.push(chunk); - const onEnd = () => { - cleanup(); - resolve(Buffer.concat(chunks).toString("utf-8")); - }; - const onError = (err: Error) => { - cleanup(); - reject(err); - }; - const cleanup = () => { - process.stdin.removeListener("data", onData); - process.stdin.removeListener("end", onEnd); - process.stdin.removeListener("error", onError); - }; - process.stdin.on("data", onData); - process.stdin.on("end", onEnd); - process.stdin.on("error", onError); - process.stdin.resume(); - }); -} - // --------------------------------------------------------------------------- // reconvertEnumValues // --------------------------------------------------------------------------- diff --git a/cli/typescript/src/schema-parser.ts b/cli/typescript/src/schema-parser.ts index c9c1669b..e36fef92 100644 --- a/cli/typescript/src/schema-parser.ts +++ b/cli/typescript/src/schema-parser.ts @@ -4,9 +4,11 @@ * Protocol spec: Schema-driven argument parsing */ +import { resolve } from "node:path"; import type { OptionConfig } from "./main.js"; -import { EXIT_CODES, SchemaValidationError } from "./errors.js"; +import { EXIT_CODES, InvalidCliInputError, SchemaValidationError } from "./errors.js"; import { exitWith } from "./exit.js"; +import { readInputText } from "./input-limits.js"; import { warn as logWarn } from "./logger.js"; import { structuredOptionTypes } from "./ref-resolver.js"; @@ -90,13 +92,76 @@ function parseStructuredValue(value: string, flag: string, types: readonly strin return decoded; } +const POSITIONAL_TYPES = new Set(["string", "integer", "number"]); +const SCALAR_ITEM_TYPES = new Set([...POSITIONAL_TYPES, "boolean"]); + +type SchemaFlag = [option: OptionConfig, key: string]; + +export function getPositionalOptions(schema: Record, flags: SchemaFlag[]): SchemaFlag[] { + const properties = (schema.properties ?? {}) as Record>; + const byIndex = new Map(); + for (const flag of flags) { + const [option] = flag; + const property = properties[option.name]; + if (!Object.hasOwn(property, "x-cli-positional")) continue; + const index = property["x-cli-positional"]; + if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 1 || byIndex.has(index)) { + throw new SchemaValidationError("x-cli-positional indices must be unique positive integers."); + } + if (typeof property.type !== "string" || !POSITIONAL_TYPES.has(property.type)) { + throw new SchemaValidationError(`x-cli-positional is only supported on scalar property '${option.name}'.`); + } + byIndex.set(index, flag); + } + const positionals: SchemaFlag[] = []; + for (let index = 1; index <= byIndex.size; index += 1) { + const option = byIndex.get(index); + if (!option) throw new SchemaValidationError("x-cli-positional indices must be consecutive starting at 1."); + positionals.push(option); + } + return positionals; +} + +export async function decodeStructuredFlag( + option: OptionConfig, + value: string | string[], + inputLimit: number | undefined, +): Promise { + const flag = option.flags.split(" ")[0]; + const parse = option.parseStructuredArg; + if (!parse) throw new SchemaValidationError(`${flag} has no structured input parser.`); + if (Array.isArray(value)) { + if (value.length === 1 && value[0].trimStart().startsWith("[")) return parse(value[0]); + const type = option.structuredArrayItemType; + if (!type) throw new SchemaValidationError(`${flag} does not support repeated inputs.`); + if (type === "string") return value; + return value.map(item => { + const expectedType = type === "integer" ? "number" : type; + const decoded = parseStructuredValue(item, flag, [expectedType]); + if (typeof decoded === "number" && (!Number.isFinite(decoded) || (type === "integer" && !Number.isInteger(decoded)))) { + throw new SchemaValidationError(`${flag} must contain a finite ${type}.`); + } + return decoded; + }); + } + if (option.structuredFileInput && value.startsWith("@")) { + try { + value = await readInputText(resolve(value.slice(1)), `file for '${flag}'`, inputLimit); + } catch (error) { + if (error instanceof InvalidCliInputError) throw new SchemaValidationError(error.message); + throw error; + } + } + return parse(value); +} + // --------------------------------------------------------------------------- // schemaToCliOptions // --------------------------------------------------------------------------- /** Reserved CLI option names that cannot be used by schema properties. */ const RESERVED_NAMES = new Set([ - "input", "yes", "large_input", "format", "fields", "sandbox", + "input", "yes", "large_input", "max_input_bytes", "max-input-bytes", "format", "fields", "sandbox", "all_options", "dry_run", "trace", "stream", "strict_stream", "strategy", "approval_timeout", "approval_token", ]); @@ -166,13 +231,18 @@ export function schemaToCliOptions( const defaultValue = propSchema.default as unknown; if (structuredTypes) { + const itemType = (propSchema.items as Record | undefined)?.type; + const repeated = propSchema.type === "array" && typeof itemType === "string" && SCALAR_ITEM_TYPES.has(itemType); + const allowFile = propSchema.type === "object"; options.push({ name: propName, - flags: `${flagName} `, + flags: `${flagName} <${repeated ? "VALUE|JSON" : allowFile ? "JSON|@FILE" : "json"}>`, description: helpText, defaultValue, required: isRequired, parseStructuredArg: value => parseStructuredValue(value, flagName, structuredTypes), + structuredArrayItemType: repeated ? itemType : undefined, + structuredFileInput: allowFile, }); } else if (typeResult === BOOLEAN_FLAG) { // Boolean flag pair: --flag/--no-flag diff --git a/cli/typescript/src/security/auth.ts b/cli/typescript/src/security/auth.ts index fc2bca54..e610fcc0 100644 --- a/cli/typescript/src/security/auth.ts +++ b/cli/typescript/src/security/auth.ts @@ -7,6 +7,8 @@ import type { ConfigResolver } from "../config.js"; import { AuthenticationError, ConfigDecryptionError } from "../errors.js"; import { ConfigEncryptor } from "./config-encryptor.js"; +import { createDeviceAuthClient } from "./device-login.js"; +import type { DeviceAuthClient, TokenSet } from "apcore-toolkit"; // --------------------------------------------------------------------------- // AuthProvider @@ -18,6 +20,8 @@ import { ConfigEncryptor } from "./config-encryptor.js"; export class AuthProvider { private readonly config: ConfigResolver; private readonly _encryptor?: ConfigEncryptor; + private deviceClient?: DeviceAuthClient; + private deviceCredential?: Promise; constructor(config: ConfigResolver, encryptor?: ConfigEncryptor) { this.config = config; @@ -86,7 +90,24 @@ export class AuthProvider { async authenticateRequest( headers: Record, ): Promise> { - const key = await this.getApiKey(); + let key = await this.getApiKey(); + if (key === null) { + let token: TokenSet | undefined; + try { + this.deviceCredential ??= this.ensureDeviceCredential().finally(() => { + this.deviceCredential = undefined; + }); + token = await this.deviceCredential; + } catch { + throw new AuthenticationError("Device authentication failed. Run 'apcli login' to sign in again."); + } + if (token) { + if (token.tokenType.toLowerCase() !== "bearer" || !/^[\x21-\x7e]+$/u.test(token.accessToken)) { + throw new AuthenticationError("The device provider must return a bearer credential."); + } + key = token.accessToken; + } + } if (!key) { throw new AuthenticationError( "Remote registry requires authentication. " + @@ -105,6 +126,11 @@ export class AuthProvider { return headers; } + private async ensureDeviceCredential(): Promise { + this.deviceClient ??= await createDeviceAuthClient(this.config) ?? undefined; + return this.deviceClient?.ensureValid(); + } + /** * Handle an HTTP response status code for auth-related errors. */ diff --git a/cli/typescript/src/security/config-encryptor.ts b/cli/typescript/src/security/config-encryptor.ts index a5b5e0f7..582f3d03 100644 --- a/cli/typescript/src/security/config-encryptor.ts +++ b/cli/typescript/src/security/config-encryptor.ts @@ -20,7 +20,7 @@ const V1_STATIC_SALT = Buffer.from("apcore-cli-config-v1"); // --------------------------------------------------------------------------- let keytarModule: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any -async function getKeytar(): Promise { // eslint-disable-line @typescript-eslint/no-explicit-any +export async function getKeytar(): Promise { if (keytarModule) return keytarModule; try { keytarModule = await import("keytar"); @@ -36,7 +36,7 @@ async function getKeytar(): Promise { // eslint-disable-line @typescript-es * coverage). Pass `null` to clear and fall back to real-keytar discovery * on the next call. Production code MUST NOT call this. */ -export function _setKeytarForTesting(mod: unknown): void { // eslint-disable-line @typescript-eslint/no-explicit-any +export function _setKeytarForTesting(mod: unknown): void { keytarModule = mod; } diff --git a/cli/typescript/src/security/device-login.ts b/cli/typescript/src/security/device-login.ts new file mode 100644 index 00000000..6f4146dd --- /dev/null +++ b/cli/typescript/src/security/device-login.ts @@ -0,0 +1,185 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + DeviceAuthClient, + DeviceAuthConfig, + DeviceAuthConfigError, + DeviceAuthError, + DeviceCodeGrant, + FileTokenStore, + TokenSet, + type DeviceAuthorization, + type GrantContext, + type TokenStore, +} from "apcore-toolkit"; +import type { Command } from "commander"; +import { ConfigResolver } from "../config.js"; +import { EXIT_CODES } from "../errors.js"; +import { exitWith } from "../exit.js"; +import { getKeytar } from "./config-encryptor.js"; + +const KEYRING_SERVICE = "apcore-cli-device-auth"; + +class KeyringTokenStore implements TokenStore { + private account(key: string): string { + return createHash("sha256").update(key).digest("hex"); + } + + private async keyring() { + const keytar = await getKeytar(); + if (!keytar) { + throw new DeviceAuthError("OS keyring is unavailable. Configure auth.device.token_storage to use a file."); + } + return keytar; + } + + async load(key: string): Promise { + const keyring = await this.keyring(); + const raw = await keyring.getPassword(KEYRING_SERVICE, this.account(key)); + return raw === null ? null : TokenSet.fromRecord(JSON.parse(raw)); + } + + async save(key: string, tokens: TokenSet): Promise { + const keyring = await this.keyring(); + const record = tokens.toRecord(); + await keyring.setPassword(KEYRING_SERVICE, this.account(key), JSON.stringify({ + access_token: record.accessToken, + token_type: record.tokenType, + expires_at: record.expiresAt, + refresh_token: record.refreshToken, + scope: record.scope, + obtained_at: record.obtainedAt, + })); + } + + async clear(key: string): Promise { + const keyring = await this.keyring(); + await keyring.deletePassword(KEYRING_SERVICE, this.account(key)); + } +} + +function safeUrl(value: string): URL | null { + if (!/^https?:\/\//iu.test(value) || /[\x00-\x20\x7f\\]/u.test(value)) return null; + try { + const url = new URL(value); + if (!url.hostname || url.username || url.password) return null; + if (url.protocol === "https:" || ( + url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) + )) return url; + } catch { + // The provider or configuration supplied a malformed URL. + } + return null; +} + +class InteractiveDeviceCodeGrant extends DeviceCodeGrant { + override async requestDeviceCode(context: GrantContext): Promise { + const code = await super.requestDeviceCode(context); + if (!safeUrl(code.verificationUri) || !code.userCode.trim() || /\p{C}/u.test(code.userCode)) { + throw new DeviceAuthConfigError("The provider returned unsafe device login instructions."); + } + return code; + } +} + +export async function createDeviceAuthClient(config: ConfigResolver): Promise { + const settings = config.resolveObject("auth.device"); + if (settings === null || settings === undefined) return null; + if (typeof settings !== "object" || Array.isArray(settings)) { + throw new DeviceAuthConfigError("auth.device must be a mapping."); + } + const values = settings as Record; + const readText = (key: string): string | undefined => { + const value = values[key]; + if (value === null || value === undefined) return undefined; + if (typeof value !== "string" || value.trim() === "") { + throw new DeviceAuthConfigError(`auth.device.${key} must be a non-empty string.`); + } + return value; + }; + const readUrl = (key: string): string | undefined => { + const value = readText(key); + if (value !== undefined && !safeUrl(value)) { + throw new DeviceAuthConfigError(`auth.device.${key} must be an HTTPS URL (or HTTP on loopback).`); + } + return value; + }; + const clientId = readText("client_id"); + if (!clientId) throw new DeviceAuthConfigError("auth.device.client_id is required."); + const scope = Object.hasOwn(values, "scope") ? values.scope : []; + if (!Array.isArray(scope) || scope.some((value) => typeof value !== "string")) { + throw new DeviceAuthConfigError("auth.device.scope must be a list of strings."); + } + const storage = readText("token_storage") ?? "keyring"; + if (storage !== "keyring" && storage !== "file") { + throw new DeviceAuthConfigError("auth.device.token_storage must be 'keyring' or 'file'."); + } + let deviceConfig = new DeviceAuthConfig({ + clientId, + issuer: readUrl("issuer"), + deviceAuthorizationEndpoint: readUrl("device_authorization_endpoint"), + tokenEndpoint: readUrl("token_endpoint"), + scope, + httpTimeoutMs: 30_000, + fetchImpl: (input, init) => fetch(input, { ...init, redirect: "error" }), + }); + if (!deviceConfig.deviceAuthorizationEndpoint || !deviceConfig.tokenEndpoint) { + deviceConfig = await deviceConfig.discover(); + if (!deviceConfig.deviceAuthorizationEndpoint || !deviceConfig.tokenEndpoint || + !safeUrl(deviceConfig.deviceAuthorizationEndpoint) || !safeUrl(deviceConfig.tokenEndpoint)) { + throw new DeviceAuthConfigError("Discovery did not return usable device authorization and token endpoints."); + } + } + return new DeviceAuthClient(deviceConfig, { + store: storage === "file" ? new FileTokenStore() : new KeyringTokenStore(), + grant: new InteractiveDeviceCodeGrant(), + }); +} + +function openBrowser(url: string): void { + const [program, ...args] = process.platform === "darwin" + ? ["open", url] + : process.platform === "win32" + ? ["rundll32.exe", "url.dll,FileProtocolHandler", url] + : ["xdg-open", url]; + execFile(program, args, () => { /* Manual instructions are already visible. */ }).unref(); +} + +export function registerLoginCommand(apcli: Command): void { + apcli.command("login") + .description("Sign in using the configured device authorization provider.") + .option("--no-browser", "Print the verification address without opening a browser.") + .action(async (options: { browser: boolean }) => { + try { + const client = await createDeviceAuthClient(new ConfigResolver()); + if (!client) { + throw new DeviceAuthConfigError("Set auth.device in apcore.yaml before running apcli login."); + } + await client.login({ + onUserCode: ({ verificationUri, verificationUriComplete, userCode, expiresIn }) => { + const url = safeUrl(verificationUri); + if (!url) return; + process.stderr.write(`Open ${verificationUri} and enter code ${userCode} (expires in ${expiresIn}s).\n`); + if (options.browser && url.protocol === "https:") { + const complete = verificationUriComplete ? safeUrl(verificationUriComplete) : null; + openBrowser(complete?.origin === url.origin ? complete.href : url.href); + } + }, + onPoll: ({ attempt }) => { + if (attempt === 1) process.stderr.write("Waiting for approval in your browser…\n"); + }, + timeoutSeconds: 900, + }); + } catch (error) { + if (error instanceof DeviceAuthConfigError) { + process.stderr.write("Device login configuration error. Check auth.device in apcore.yaml.\n"); + exitWith(EXIT_CODES.CONFIG_INVALID); + return; + } + process.stderr.write("Device login failed. Check the provider and credential store.\n"); + exitWith(EXIT_CODES.ACL_DENIED); + return; + } + process.stderr.write("Signed in.\n"); + }); +} diff --git a/cli/typescript/tests/apcli-integration.test.ts b/cli/typescript/tests/apcli-integration.test.ts index 1b1b835d..ee34f6ed 100644 --- a/cli/typescript/tests/apcli-integration.test.ts +++ b/cli/typescript/tests/apcli-integration.test.ts @@ -44,7 +44,7 @@ describe("RESERVED_GROUP_NAMES + APCLI_SUBCOMMAND_NAMES", () => { expect(RESERVED_GROUP_NAMES.has("apcli")).toBe(true); }); - it("APCLI_SUBCOMMAND_NAMES contains the 15 canonical subcommands", () => { + it("APCLI_SUBCOMMAND_NAMES contains the canonical subcommands", () => { const expected = ["list", "describe", "exec", "validate", "init", "health", "usage", "enable", "disable", "reload", "config", "completion", "describe-pipeline", "acl", "openapi"]; @@ -246,7 +246,7 @@ describe("createCli — apcli group structure", () => { expect(subs).toContain("exec"); // FE-12 guarantee }); - it("apcli has all 15 canonical subcommands under mode=all when system modules available", () => { + it("apcli has all canonical subcommands under mode=all when system modules are available", () => { // D10-004: the six system subcommands register only when the executor's // registry exposes `system.health.summary` (probe passes). Provide it here. const registry = makeRegistry(["system.health.summary"]); diff --git a/cli/typescript/tests/builtin-group.test.ts b/cli/typescript/tests/builtin-group.test.ts index 64acd003..d7bef7e7 100644 --- a/cli/typescript/tests/builtin-group.test.ts +++ b/cli/typescript/tests/builtin-group.test.ts @@ -588,9 +588,8 @@ describe("ApcliGroup unknown subcommand warnings (Issue 7)", () => { warnSpy.mockRestore(); }); - it("APCLI_SUBCOMMAND_NAMES exports all 15 canonical names", () => { - // 13 through v0.11; FE-14 added `acl` and FE-15a added `openapi`. - expect(APCLI_SUBCOMMAND_NAMES.size).toBe(15); + it("APCLI_SUBCOMMAND_NAMES exports all 16 canonical names", () => { + expect(APCLI_SUBCOMMAND_NAMES.size).toBe(16); for (const name of [ "list", "describe", @@ -607,6 +606,7 @@ describe("ApcliGroup unknown subcommand warnings (Issue 7)", () => { "describe-pipeline", "acl", "openapi", + "login", ]) { expect(APCLI_SUBCOMMAND_NAMES.has(name)).toBe(true); } diff --git a/cli/typescript/tests/device-login.test.ts b/cli/typescript/tests/device-login.test.ts new file mode 100644 index 00000000..3c2a3313 --- /dev/null +++ b/cli/typescript/tests/device-login.test.ts @@ -0,0 +1,114 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DeviceAuthClient, TokenSet } from "apcore-toolkit"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ConfigResolver } from "../src/config.js"; +import { createCli } from "../src/main.js"; +import { AuthProvider } from "../src/security/auth.js"; +import { _setKeytarForTesting } from "../src/security/config-encryptor.js"; +import { createDeviceAuthClient } from "../src/security/device-login.js"; + +describe("device login", () => { + let dir: string; + let configPath: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "apcore-cli-device-test-")); + configPath = join(dir, "apcore.yaml"); + writeFileSync(configPath, [ + "auth:", + " device:", + " client_id: test-cli", + " issuer: https://auth.example.test", + " device_authorization_endpoint: https://auth.example.test/device", + " token_endpoint: https://auth.example.test/token", + " token_storage: file", + ].join("\n")); + vi.stubEnv("APCORE_AUTH_API_KEY", ""); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + _setKeytarForTesting(null); + rmSync(dir, { recursive: true, force: true }); + }); + + const tokens = new TokenSet({ + accessToken: "test-access-secret", + tokenType: "Bearer", + expiresAt: null, + refreshToken: "test-refresh-secret", + scope: [], + obtainedAt: 0, + }); + + it("prints the verification address and code on stderr without printing tokens", async () => { + const settings = new ConfigResolver(undefined, configPath).resolveObject("auth.device"); + const resolveObject = ConfigResolver.prototype.resolveObject; + vi.spyOn(ConfigResolver.prototype, "resolveObject").mockImplementation(function (this: ConfigResolver, key) { + return key === "auth.device" ? settings : resolveObject.call(this, key); + }); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + vi.spyOn(DeviceAuthClient.prototype, "login").mockImplementation(async (options) => { + options?.onUserCode?.({ + verificationUri: "https://auth.example.test/verify", + verificationUriComplete: null, + userCode: "TEST-CODE", + expiresIn: 60, + }); + return tokens; + }); + const cli = await createCli(); + await cli.parseAsync(["apcli", "login", "--no-browser"], { from: "user" }); + const output = stderr.mock.calls.map(([chunk]) => String(chunk)).join(""); + expect(output).toContain("https://auth.example.test/verify"); + expect(output).toContain("TEST-CODE"); + expect(output).not.toContain("test-access-secret"); + expect(output).not.toContain("test-refresh-secret"); + }); + + it("uses the device client's validated token for requests", async () => { + const ensureValid = vi.spyOn(DeviceAuthClient.prototype, "ensureValid").mockResolvedValue(tokens); + const provider = new AuthProvider(new ConfigResolver(undefined, configPath)); + const headers = await Promise.all([provider.authenticateRequest({}), provider.authenticateRequest({})]); + expect(headers).toEqual([ + { Authorization: "Bearer test-access-secret" }, + { Authorization: "Bearer test-access-secret" }, + ]); + expect(ensureValid).toHaveBeenCalledOnce(); + }); + + it("rejects an unsafe verification address before polling", async () => { + const fetch = vi.fn(async () => Response.json({ + verification_uri: "file:///path", + user_code: "ABCD", + device_code: "opaque", + })); + vi.stubGlobal("fetch", fetch); + const client = await createDeviceAuthClient(new ConfigResolver(undefined, configPath)); + await expect(client?.login()).rejects.toThrow("unsafe device login instructions"); + expect(fetch).toHaveBeenCalledOnce(); + }); + + it("stores a device credential in the configured OS keyring", async () => { + writeFileSync(configPath, readFileSync(configPath, "utf-8").replace(" token_storage: file", "")); + const records = new Map(); + _setKeytarForTesting({ + getPassword: async (service: string, account: string) => records.get(`${service}:${account}`) ?? null, + setPassword: async (service: string, account: string, record: string) => { + records.set(`${service}:${account}`, record); + }, + deletePassword: async (service: string, account: string) => records.delete(`${service}:${account}`), + }); + const client = await createDeviceAuthClient(new ConfigResolver(undefined, configPath)); + if (!client) throw new Error("Expected a configured device auth client"); + await client.store.save(client.storeKey, tokens); + expect(await client.store.load(client.storeKey)).toEqual(tokens); + expect([...records.keys()]).toEqual([expect.stringMatching(/^apcore-cli-device-auth:[a-f0-9]{64}$/)]); + await client.store.clear(client.storeKey); + expect(records.size).toBe(0); + }); +}); diff --git a/cli/typescript/tests/structured-flags.test.ts b/cli/typescript/tests/structured-flags.test.ts index bbc21203..327e5fae 100644 --- a/cli/typescript/tests/structured-flags.test.ts +++ b/cli/typescript/tests/structured-flags.test.ts @@ -1,8 +1,11 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { Readable } from "node:stream"; import { Executor, Registry } from "apcore-js"; +import { Command } from "commander"; import { describe, expect, it, vi } from "vitest"; +import { registerExecCommand } from "../src/discovery.js"; import { buildModuleCommand } from "../src/main.js"; interface FixtureCase { @@ -18,7 +21,7 @@ const fixture = JSON.parse(readFileSync( test_cases: FixtureCase[]; }; -async function invoke(args: string[], inputSchema = fixture.schema) { +async function invoke(args: string[], inputSchema = fixture.schema, generic = false) { const moduleId = "test.structured"; const inputs: Record[] = []; const registry = new Registry(); @@ -36,11 +39,15 @@ async function invoke(args: string[], inputSchema = fixture.schema) { const executor = Executor.fromRegistry(registry); const validate = vi.spyOn(executor, "validate"); const exit = vi.fn(); - const cmd = buildModuleCommand(descriptor, executor, 1000, undefined, undefined, { exit, printResult: false }); + const options = { exit, printResult: false }; + const cmd = generic + ? new Command().exitOverride() + : buildModuleCommand(descriptor, executor, 1000, undefined, undefined, options); + if (generic) registerExecCommand(cmd, registry, executor, options); const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true); const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); try { - await cmd.parseAsync(args, { from: "user" }); + await cmd.parseAsync(generic ? ["exec", moduleId, ...args] : args, { from: "user" }); return { inputs, preflightInputs: validate.mock.calls.map(([, input]) => input), @@ -62,6 +69,45 @@ describe("structured generated flags", () => { if (expected.input) expect(result.inputs[0]).toEqual(expected.input); }); + it("reads an object option file within the UTF-8 byte limit", async () => { + const directory = mkdtempSync(join(tmpdir(), "apcore-cli-object-")); + const file = join(directory, "object.json"); + const payload = '{"label":"é"}'; + try { + writeFileSync(file, payload); + const args = ["--filters", `@${file}`, "--labels", "one", "--max-input-bytes"]; + const limit = Buffer.byteLength(payload); + const accepted = await invoke([...args, String(limit)]); + const rejected = await invoke([...args, String(limit - 1)]); + expect(accepted.inputs).toEqual([{ filters: { label: "é" }, labels: ["one"] }]); + expect(rejected.exitCode).toBe(45); + expect(rejected.inputs).toEqual([]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + + it.each([false, true])("applies invocation and env limits to stdin (generic=%s)", async generic => { + const payload = '{"filters":{},"labels":["é"]}'; + const bytes = Buffer.from(payload, "utf8"); + const stdin = vi.spyOn(process.stdin, "iterator") + .mockImplementation(() => Readable.from([bytes]).iterator()); + vi.stubEnv("APCORE_CLI_STDIN_BUFFER_LIMIT", "1"); + try { + const args = ["--input", "-"]; + const rejected = await invoke(args, fixture.schema, generic); + expect(rejected.exitCode).toBe(2); + expect(rejected.inputs).toEqual([]); + const explicit = await invoke([...args, "--max-input-bytes", String(bytes.length)], fixture.schema, generic); + const bypassed = await invoke([...args, "--large-input"], fixture.schema, generic); + expect(explicit.inputs).toEqual([{ filters: {}, labels: ["é"] }]); + expect(bypassed.inputs).toEqual(explicit.inputs); + } finally { + stdin.mockRestore(); + vi.unstubAllEnvs(); + } + }); + it("passes the decoded values into preflight without running the module", async () => { const sample = fixture.test_cases.find(test => test.id === "objects_and_arrays"); if (!sample?.expected.input) throw new Error("Expected input case missing"); diff --git a/mcp/docs/features/mcp-server-factory.md b/mcp/docs/features/mcp-server-factory.md index b8cc4fa9..cde2ce64 100644 --- a/mcp/docs/features/mcp-server-factory.md +++ b/mcp/docs/features/mcp-server-factory.md @@ -312,6 +312,34 @@ specific configuration that closes each gap. This is a warning only — it MUST from starting. See aiperceivable/apcore-mcp#15(b); the underlying accessor was itself blocked on aiperceivable/apcore#97 until apcore 0.28.0. +## Approval preflight discovery + +The approval annotation in `tools/list` describes the registered module. ACL rules and execution +policy can require approval for particular callers or arguments. The server advertises a separate +extension in `initialize` when its module preview tool is available. + +```json +{ + "capabilities": { + "extensions": { + "com.aiperceivable/approval-preflight": { + "toolListApproval": "static", + "previewTool": "__apcore_module_preview" + } + } + } +} +``` + +Clients can call `previewTool` with the target `module_id`, the intended `arguments`, and the same +authenticated session as the planned call. Read `requires_approval` on a successful preflight to +show the server's current assessment. The server still enforces current policy during execution. + +The capability depends on the preview tool and its Core validation handler. It applies to servers +with or without management resources, and conveys no information about the loaded ACL or the +caller's permissions. Ordinary MCP clients can continue calling tools without using the extension. +See [issue #114](https://github.com/aiperceivable/apcore-surfaces/issues/114). + ## Error Handling - **Registry Empty**: If no modules are found, the factory logs a warning and produces an empty tool list rather than an error. @@ -391,7 +419,7 @@ The three Contract blocks below define each step. For HTTP transport, `build_ini ### Inputs - name: str, required, validates[non-empty, max 255 chars], reject_with=ValueError - version: str, optional, default="0.1.0" -- management_surfaces: `{health, usage, manifest, control}` of bool, optional, default=None — **since v0.19.0**. When any field is `True`, `capabilities.extensions["com.aiperceivable/management"]` is added with `surfaces` set to the true fields and `protocolVersion` set to the PROTOCOL_SPEC version this adapter's `system.*` projection targets (see [System Management Extension](./system-management-extension.md)). When omitted or all-`False`, `capabilities.extensions` is absent entirely — never present with an empty `surfaces` array. Passing `None`/omitting it is fully backward compatible with pre-v0.19.0 callers. +- management_surfaces: `{health, usage, manifest, control}` of bool, optional, default=None — **since v0.19.0**. When any field is `True`, `capabilities.extensions["com.aiperceivable/management"]` is added with `surfaces` set to the true fields and `protocolVersion` set to the PROTOCOL_SPEC version this adapter's `system.*` projection targets (see [System Management Extension](./system-management-extension.md)). When omitted or all-`False`, the management entry is omitted. ### Errors - ValueError — when name is empty or exceeds 255 chars diff --git a/mcp/python/CHANGELOG.md b/mcp/python/CHANGELOG.md index 19362554..5404c29b 100644 --- a/mcp/python/CHANGELOG.md +++ b/mcp/python/CHANGELOG.md @@ -17,6 +17,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Require Core `1.0.0b1` and verify wire cancellation in the shared stdio and Streamable HTTP suite. [PR #133](https://github.com/aiperceivable/apcore-surfaces/pull/133) +### Known limitations + +- MCP `tools/list` reports the module's static approval annotation. An ACL or + execution policy can still require approval for a specific call. When + `initialize` advertises `com.aiperceivable/approval-preflight`, use + its `previewTool` with the intended arguments and the same authenticated + session to check `requires_approval` before calling the tool. The server + enforces approval during execution. + [Issue #114](https://github.com/aiperceivable/apcore-surfaces/issues/114) + ## [0.23.5a1] - Unreleased ### Fixed diff --git a/mcp/python/src/apcore_mcp/apcore_mcp.py b/mcp/python/src/apcore_mcp/apcore_mcp.py index 5308389a..c01e73d8 100644 --- a/mcp/python/src/apcore_mcp/apcore_mcp.py +++ b/mcp/python/src/apcore_mcp/apcore_mcp.py @@ -773,7 +773,11 @@ def _build_server_components(self) -> tuple[Any, Any, list, Any, str]: # system.* surfaces are actually registered. management_surfaces = _compute_management_surfaces(self._registry) init_options = factory.build_init_options( - server, name=self._name, version=version, management_surfaces=management_surfaces + server, + name=self._name, + version=version, + management_surfaces=management_surfaces, + async_bridge=async_bridge, ) # [aiperceivable/apcore-mcp#15(b)] Advisory-only startup check: warn diff --git a/mcp/python/src/apcore_mcp/server/async_task_bridge.py b/mcp/python/src/apcore_mcp/server/async_task_bridge.py index b0e78bf7..b08241c1 100644 --- a/mcp/python/src/apcore_mcp/server/async_task_bridge.py +++ b/mcp/python/src/apcore_mcp/server/async_task_bridge.py @@ -116,6 +116,11 @@ class AsyncTaskBridge: DEFAULT_MAX_CONCURRENT = 10 DEFAULT_MAX_TASKS = 1000 + @property + def supports_preview(self) -> bool: + """Whether the module preview can run the Core validation preflight.""" + return callable(getattr(self._executor, "validate", None)) + def __init__( self, manager: AsyncTaskManager, diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 1f2dac40..039ef7d3 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -113,6 +113,7 @@ def is_readonly_system_module(module_id: str) -> bool: # array is emitted in. _MANAGEMENT_EXTENSION_KEY = "com.aiperceivable/management" _MANAGEMENT_SURFACE_ORDER = ("health", "usage", "manifest", "control") +_APPROVAL_PREFLIGHT_EXTENSION_KEY = "com.aiperceivable/approval-preflight" # apcore's PROTOCOL_SPEC version as of this file's last sync (PROTOCOL_SPEC.md # header, apcore repo, 2026-08-31: "Version: 1.30.0"). apcore does not export # this as a runtime constant (`apcore.__version__` is the *package* version, @@ -1049,6 +1050,7 @@ def build_init_options( version: str, *, management_surfaces: dict[str, bool] | None = None, + async_bridge: AsyncTaskBridge | None = None, ) -> InitializationOptions: """Build InitializationOptions for running the server. @@ -1067,6 +1069,8 @@ def build_init_options( purely additive discovery, not a behaviour gate. ``None`` or all-false omits the capability entirely, matching pre-#16 behaviour. + async_bridge: The bridge registered for this server. A working + preview handler enables the approval preflight capability. Returns: InitializationOptions ready for server.run(). @@ -1084,20 +1088,22 @@ def build_init_options( experimental_capabilities={}, ) + extensions: dict[str, dict[str, Any]] = {} if management_surfaces: surfaces = [key for key in _MANAGEMENT_SURFACE_ORDER if management_surfaces.get(key)] if surfaces: - # `ServerCapabilities` declares `model_config = ConfigDict(extra="allow")`, - # so setting an undeclared attribute is a supported way to add a - # top-level capability key this MCP SDK version has no dedicated - # field for -- it round-trips through model_dump()/model_dump_json() - # like any other field. - capabilities.extensions = { # type: ignore[attr-defined] - _MANAGEMENT_EXTENSION_KEY: { - "surfaces": surfaces, - "protocolVersion": _PROTOCOL_SPEC_VERSION, - } + extensions[_MANAGEMENT_EXTENSION_KEY] = { + "surfaces": surfaces, + "protocolVersion": _PROTOCOL_SPEC_VERSION, } + if async_bridge is not None and async_bridge.supports_preview: + extensions[_APPROVAL_PREFLIGHT_EXTENSION_KEY] = { + "toolListApproval": "static", + "previewTool": "__apcore_module_preview", + } + if extensions: + # ServerCapabilities allows extra fields and serializes them on the wire. + capabilities.extensions = extensions # type: ignore[attr-defined] return InitializationOptions( server_name=name, diff --git a/mcp/python/tests/test_acl_approval_gating_e2e.py b/mcp/python/tests/test_acl_approval_gating_e2e.py index de5550c7..31adb60d 100644 --- a/mcp/python/tests/test_acl_approval_gating_e2e.py +++ b/mcp/python/tests/test_acl_approval_gating_e2e.py @@ -21,18 +21,23 @@ from __future__ import annotations +import json from typing import Any +import anyio import pytest from apcore import Executor, Registry from apcore.acl import ACL, ACLRule from apcore.approval import ApprovalRequest, ApprovalResult +from mcp import ClientSession from mcp import types as mcp_types from mcp.server.lowlevel import Server from pydantic import AnyUrl, BaseModel +from apcore_mcp import APCoreMCP from apcore_mcp.server.factory import MCPServerFactory from apcore_mcp.server.router import ExecutionRouter +from apcore_mcp.server.transport import TransportManager class _Inputs(BaseModel): @@ -72,7 +77,7 @@ async def check_approval(self, approval_id: str) -> ApprovalResult: return ApprovalResult(status="approved", approved_by="test", approval_id=approval_id) -def _build_router() -> tuple[ExecutionRouter, _RecordingApprovalHandler]: +def _build_executor() -> tuple[Executor, _RecordingApprovalHandler]: """A real executor whose only approval source is an argument-scoped ACL rule.""" registry = Registry() registry.register("files.delete", _DeleteModule()) @@ -96,12 +101,13 @@ def _build_router() -> tuple[ExecutionRouter, _RecordingApprovalHandler]: handler = _RecordingApprovalHandler() executor = Executor(registry=registry, acl=acl, approval_handler=handler) - return ExecutionRouter(executor), handler + return executor, handler @pytest.mark.asyncio async def test_call_matching_the_argument_scoped_rule_is_gated() -> None: - router, handler = _build_router() + executor, handler = _build_executor() + router = ExecutionRouter(executor) content, is_error, _trace = await router.handle_call("files.delete", {"path": "/tmp/x", "recursive": True}) @@ -115,7 +121,8 @@ async def test_call_matching_the_argument_scoped_rule_is_gated() -> None: @pytest.mark.asyncio async def test_call_not_matching_the_rule_is_not_gated() -> None: - router, handler = _build_router() + executor, handler = _build_executor() + router = ExecutionRouter(executor) content, is_error, _trace = await router.handle_call("files.delete", {"path": "/tmp/x"}) @@ -126,6 +133,54 @@ async def test_call_not_matching_the_rule_is_not_gated() -> None: ) +@pytest.mark.parametrize("async_tasks", [True, False]) +async def test_initialize_advertises_call_approval_preflight_when_available(async_tasks: bool) -> None: + from apcore.config import Config + from apcore.sys_modules.registration import register_sys_modules + + executor, handler = _build_executor() + register_sys_modules( + registry=executor.registry, + executor=executor, + config=Config(data={"sys_modules": {"enabled": True}}), + ) + mcp = APCoreMCP(executor, async_tasks=async_tasks) + server, _, _, init, _ = mcp._build_server_components() + send_client, read_server = anyio.create_memory_object_stream(10) + send_server, read_client = anyio.create_memory_object_stream(10) + with anyio.fail_after(5): + async with anyio.create_task_group() as group: + group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") + async with ClientSession(read_client, send_client) as session: + initialized = await session.initialize() + capabilities = initialized.capabilities.model_dump(exclude_none=True) + extensions = capabilities["extensions"] + assert "com.aiperceivable/management" in extensions + approval_preflight = extensions.get("com.aiperceivable/approval-preflight") + tools = {tool.name: tool for tool in (await session.list_tools()).tools} + assert (tools["files.delete"].meta or {}).get("requiresApproval") is not True + assert ("__apcore_module_preview" in tools) is async_tasks + if async_tasks: + assert approval_preflight == { + "toolListApproval": "static", + "previewTool": "__apcore_module_preview", + } + for arguments, expected in [ + ({"path": "/tmp/x", "recursive": True}, True), + ({"path": "/tmp/x"}, False), + ]: + result = await session.call_tool( + approval_preflight["previewTool"], + {"module_id": "files.delete", "arguments": arguments}, + ) + assert not result.isError + assert json.loads(result.content[0].text)["requires_approval"] is expected + else: + assert approval_preflight is None + assert not handler.requests + group.cancel_scope.cancel() + + # --------------------------------------------------------------------------- # The same enforcement must hold on the `resources/read` path, which is the # claim aiperceivable/apcore-mcp#15 makes: "Every `apcore://system.*` read diff --git a/mcp/rust/CHANGELOG.md b/mcp/rust/CHANGELOG.md index b4f525c5..ccd962e9 100644 --- a/mcp/rust/CHANGELOG.md +++ b/mcp/rust/CHANGELOG.md @@ -17,6 +17,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Require Core `1.0.0-beta.1` and verify wire cancellation in the shared stdio and Streamable HTTP suite. [PR #133](https://github.com/aiperceivable/apcore-surfaces/pull/133) +### Known limitations + +- MCP `tools/list` reports the module's static approval annotation. An ACL or + execution policy can still require approval for a specific call. When + `initialize` advertises `com.aiperceivable/approval-preflight`, use + its `previewTool` with the intended arguments and the same authenticated + session to check `requires_approval` before calling the tool. The server + enforces approval during execution. + [Issue #114](https://github.com/aiperceivable/apcore-surfaces/issues/114) + ## [0.23.5-alpha.1] - Unreleased ### Fixed diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 0a58e6a0..585eda74 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -5930,9 +5930,7 @@ mod tests { } /// A real executor whose only approval source is an argument-scoped ACL rule. - fn acl_gated_router( - seen: Arc>>, - ) -> crate::server::router::ExecutionRouter { + fn acl_gated_executor(seen: Arc>>) -> (Executor, Arc) { let registry = Arc::new(apcore::registry::registry::Registry::default()); let descriptor = ModuleDescriptor { module_id: "files.delete".to_string(), @@ -5995,10 +5993,16 @@ mod tests { ) .expect("ACL should build"); - let mut executor = Executor::new(registry, Arc::new(Config::default())); + let mut executor = Executor::new(Arc::clone(®istry), Arc::new(Config::default())); executor.set_acl(acl); executor.set_approval_handler(Box::new(RecordingApprovalHandler { seen })); + (executor, registry) + } + fn acl_gated_router( + seen: Arc>>, + ) -> crate::server::router::ExecutionRouter { + let (executor, _) = acl_gated_executor(seen); let adapter = ApcoreExecutorAdapter { inner: Arc::new(executor), strategy: None, @@ -6053,6 +6057,69 @@ mod tests { ); } + #[tokio::test] + async fn initialize_advertises_call_approval_preflight() { + use crate::server::transport::McpHandler; + + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let (executor, registry) = acl_gated_executor(Arc::clone(&seen)); + let mut config = Config::default(); + config.set("sys_modules.enabled", json!(true)); + apcore::sys_modules::register_sys_modules(registry, &executor, &config, None).unwrap(); + let bridge = APCoreMCP::builder() + .backend(Arc::new(executor)) + .build() + .unwrap(); + let (server, _, _, init_options, _, _) = bridge.build_server_components().unwrap(); + let handler = ServerHandler::from_server(&server, init_options).unwrap(); + + let reply = handler + .handle_message(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}})) + .await + .unwrap(); + let extensions = &reply["result"]["capabilities"]["extensions"]; + assert!(extensions["com.aiperceivable/management"].is_object()); + let preflight = &extensions["com.aiperceivable/approval-preflight"]; + assert_eq!( + preflight, + &json!({"toolListApproval": "static", "previewTool": "__apcore_module_preview"}) + ); + let preview_tool = preflight["previewTool"].as_str().unwrap(); + let reply = handler + .handle_message(json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}})) + .await + .unwrap(); + let tools = reply["result"]["tools"].as_array().unwrap(); + assert!(tools.iter().any(|tool| tool["name"] == preview_tool)); + let listed_module = tools + .iter() + .find(|tool| tool["name"] == "files.delete") + .unwrap(); + assert_ne!(listed_module["_meta"]["requiresApproval"], true); + + for (arguments, expected) in [ + (json!({"path": "/tmp/x", "recursive": true}), true), + (json!({"path": "/tmp/x"}), false), + ] { + let reply = handler + .handle_message(json!({ + "jsonrpc":"2.0", "id":3, "method":"tools/call", + "params": { + "name": preview_tool, + "arguments": {"module_id": "files.delete", "arguments": arguments}, + }, + })) + .await + .unwrap(); + let result = &reply["result"]; + assert_eq!(result["isError"], false, "{result}"); + let text = result["content"][0]["text"].as_str().unwrap(); + let body: Value = serde_json::from_str(text).unwrap(); + assert_eq!(body["requires_approval"], expected); + } + assert!(seen.lock().unwrap().is_empty()); + } + // ── ACL enforcement on apcore:// management resource reads ────────────── // // aiperceivable/apcore-mcp#15 claims every `apcore://system.*` read diff --git a/mcp/rust/src/server/factory.rs b/mcp/rust/src/server/factory.rs index 6248da9f..c8bec6de 100644 --- a/mcp/rust/src/server/factory.rs +++ b/mcp/rust/src/server/factory.rs @@ -15,7 +15,7 @@ use apcore::registry::{ModuleDescriptor, Registry}; use crate::adapters::annotations::{AnnotationMapper, McpAnnotations}; use crate::artifacts::{MCPArtifactStore, ARTIFACT_URI_PREFIX}; use crate::auth::middleware::AUTH_IDENTITY; -use crate::server::async_task_bridge::AsyncTaskBridge; +use crate::server::async_task_bridge::{AsyncTaskBridge, META_TOOL_PREVIEW}; use crate::server::router::ExecutionRouter; use crate::server::server::{FactoryError, MCPServer, MCPServerConfig}; use crate::server::types::{ @@ -206,6 +206,7 @@ pub fn is_readonly_system_resource_module_id(module_id: &str) -> bool { /// `capabilities.extensions` when at least one management surface /// (health / usage / manifest / control) is registered. pub const MANAGEMENT_EXTENSION_ID: &str = "com.aiperceivable/management"; +const APPROVAL_PREFLIGHT_EXTENSION_ID: &str = "com.aiperceivable/approval-preflight"; /// The apcore PROTOCOL_SPEC version this bridge's `system.*` surface /// implements, reported in the `com.aiperceivable/management` extension. @@ -905,6 +906,8 @@ impl MCPServerFactory { tools: Vec, router: Arc, ) { + server.approval_preview = router.async_bridge().is_some() + && tools.iter().any(|tool| tool.name == META_TOOL_PREVIEW); let tools = Arc::new(tools); // Share the router's session registry with the transport layer. The @@ -1237,7 +1240,12 @@ impl MCPServerFactory { None }; - let extensions = management.and_then(ManagementCapabilities::to_extensions_value); + let mut extensions = management.and_then(ManagementCapabilities::to_extensions_value); + if server.approval_preview { + extensions.get_or_insert_with(|| serde_json::json!({})) + [APPROVAL_PREFLIGHT_EXTENSION_ID] = + serde_json::json!({"toolListApproval": "static", "previewTool": META_TOOL_PREVIEW}); + } InitializationOptions { server_name: name.to_string(), diff --git a/mcp/rust/src/server/server.rs b/mcp/rust/src/server/server.rs index 093446f3..d13ca982 100644 --- a/mcp/rust/src/server/server.rs +++ b/mcp/rust/src/server/server.rs @@ -285,6 +285,8 @@ pub struct MCPServer { pub(crate) list_tools_handler: Option Vec + Send + Sync>>, /// Handler for `call_tool` requests. pub(crate) call_tool_handler: Option, + /// Whether the registered tool handlers include a working approval preview. + pub(crate) approval_preview: bool, /// Handler for `list_resources` requests. pub(crate) list_resources_handler: Option Vec + Send + Sync>>, /// Handler for `read_resource` requests. @@ -320,6 +322,7 @@ impl MCPServer { registry_or_executor: None, list_tools_handler: None, call_tool_handler: None, + approval_preview: false, list_resources_handler: None, read_resource_handler: None, list_resource_templates_handler: None, @@ -339,6 +342,7 @@ impl MCPServer { registry_or_executor: Some(registry_or_executor), list_tools_handler: None, call_tool_handler: None, + approval_preview: false, list_resources_handler: None, read_resource_handler: None, list_resource_templates_handler: None, @@ -459,27 +463,12 @@ impl MCPServer { let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>(); // Build a transport handler from the registered tool handlers, if any. - let init_options = InitializationOptions { - server_name: self.config.name.clone(), - server_version: self - .config - .version - .clone() - .unwrap_or_else(|| crate::VERSION.to_string()), - capabilities: crate::server::types::ServerCapabilities { - tools: if self.has_tool_handlers() { - Some(crate::server::types::ToolsCapability { list_changed: true }) - } else { - None - }, - resources: if self.has_resource_handlers() { - Some(crate::server::types::ResourcesCapability { list_changed: true }) - } else { - None - }, - extensions: None, - }, - }; + let init_options = super::factory::MCPServerFactory::new().build_init_options( + self, + &self.config.name, + crate::VERSION, + None, + ); let handler: Option> = ServerHandler::from_server(self, init_options) .map(|h| Arc::new(h) as Arc); @@ -814,11 +803,8 @@ impl crate::server::transport::McpHandler for ServerHandler { "tools": { "listChanged": true }, "resources": { "listChanged": false } }); - // aiperceivable/apcore-mcp#16: broadcast the - // `com.aiperceivable/management` extension when this server - // exposes at least one management surface. A client that - // never declares support for it is unaffected either way — - // this key gates nothing. + // Advertise the enabled discovery extensions. Their presence + // has no effect on a client's access to resources or tools. if let Some(ref extensions) = self.init_options.capabilities.extensions { capabilities["extensions"] = extensions.clone(); } diff --git a/mcp/typescript/CHANGELOG.md b/mcp/typescript/CHANGELOG.md index d7d13147..4758273c 100644 --- a/mcp/typescript/CHANGELOG.md +++ b/mcp/typescript/CHANGELOG.md @@ -17,6 +17,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Require `apcore-js@1.0.0-beta.1` and verify wire cancellation in the shared stdio and Streamable HTTP suite. [PR #133](https://github.com/aiperceivable/apcore-surfaces/pull/133) +### Known limitations + +- MCP `tools/list` reports the module's static approval annotation. An ACL or + execution policy can still require approval for a specific call. When + `initialize` advertises `com.aiperceivable/approval-preflight`, use + its `previewTool` with the intended arguments and the same authenticated + session to check `requires_approval` before calling the tool. The server + enforces approval during execution. + [Issue #114](https://github.com/aiperceivable/apcore-surfaces/issues/114) + ## [0.23.9-alpha.1] - Unreleased ### Fixed diff --git a/mcp/typescript/src/index.ts b/mcp/typescript/src/index.ts index 6e2435ee..d5fae4e8 100644 --- a/mcp/typescript/src/index.ts +++ b/mcp/typescript/src/index.ts @@ -974,7 +974,7 @@ async function serveInternal( asyncTaskBridge: asyncBridge ?? undefined, }); const createSessionServer = () => { - const server = factory.createServer(name, version, managementSurfaces); + const server = factory.createServer(name, version, managementSurfaces, asyncBridge); factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); factory.registerResourceHandlers(server, registry, router); return server; @@ -1323,7 +1323,7 @@ export async function asyncServe( asyncTaskBridge: asyncBridge ?? undefined, }); const createSessionServer = () => { - const server = factory.createServer(name, version, managementSurfaces); + const server = factory.createServer(name, version, managementSurfaces, asyncBridge); factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); factory.registerResourceHandlers(server, registry, router); return server; diff --git a/mcp/typescript/src/server/async-task-bridge.ts b/mcp/typescript/src/server/async-task-bridge.ts index c0506aa1..92fc3945 100644 --- a/mcp/typescript/src/server/async-task-bridge.ts +++ b/mcp/typescript/src/server/async-task-bridge.ts @@ -278,6 +278,11 @@ export class AsyncTaskBridge { return this._enabled; } + /** Whether the exposed module preview can run the Core validation preflight. */ + get supportsPreview(): boolean { + return this._enabled && typeof this._executor?.validate === "function"; + } + /** Expose the underlying manager (used by server lifecycle for shutdown). */ get manager(): AsyncTaskManagerLike { return this._manager; diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index 5e7ee080..7bb25701 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -34,7 +34,7 @@ import type { Registry, ModuleDescriptor, JsonSchema } from "../types.js"; import type { ExecutionRouter } from "./router.js"; import type { HandleCallExtra } from "./router.js"; import { buildTraceparent } from "./trace-context.js"; -import { APCORE_META_TOOL_PREFIX, AsyncTaskBridge } from "./async-task-bridge.js"; +import { APCORE_META_TOOL_PREFIX, AsyncTaskBridge, META_TOOL_NAMES } from "./async-task-bridge.js"; import { ApprovalBridge } from "./approval-bridge.js"; import { approvalPrincipal, isApprovalResumeToken } from "../adapters/approval.js"; import { enableApprovalReplies, type ApprovalReplyCapture, type PendingApprovalReply } from "../approval-reply.js"; @@ -64,6 +64,7 @@ const AI_INTENT_KEYS = ["x-when-to-use", "x-when-not-to-use", "x-common-mistakes * Stable from first publication per SEP-2133. */ const MANAGEMENT_EXTENSION_ID = "com.aiperceivable/management"; +const APPROVAL_PREFLIGHT_EXTENSION_ID = "com.aiperceivable/approval-preflight"; /** * PROTOCOL_SPEC version advertised alongside the management extension. @@ -157,6 +158,7 @@ export class MCPServerFactory { name: string = "apcore-mcp", version: string = "0.1.0", managementSurfaces?: ManagementSurfaces | null, + asyncBridge?: AsyncTaskBridge | null, ): Server { // [D10-002] Cross-language parity: the spec mandates a non-empty name // no longer than 255 chars. Python and Rust both throw on violation @@ -180,6 +182,7 @@ export class MCPServerFactory { tools: { listChanged: true }, resources: { listChanged: true }, }; + const extensions: Record = {}; // aiperceivable/apcore-mcp#16 phase A: advertise the unofficial // `com.aiperceivable/management` extension (SEP-2133) ONLY when at @@ -194,14 +197,19 @@ export class MCPServerFactory { ["health", "usage", "manifest", "control"] as const ).filter((key) => managementSurfaces[key]); if (surfaces.length > 0) { - capabilities.extensions = { - [MANAGEMENT_EXTENSION_ID]: { - surfaces, - protocolVersion: MANAGEMENT_EXTENSION_PROTOCOL_VERSION, - }, + extensions[MANAGEMENT_EXTENSION_ID] = { + surfaces, + protocolVersion: MANAGEMENT_EXTENSION_PROTOCOL_VERSION, }; } } + if (asyncBridge?.supportsPreview) { + extensions[APPROVAL_PREFLIGHT_EXTENSION_ID] = { + toolListApproval: "static", + previewTool: META_TOOL_NAMES.PREVIEW, + }; + } + if (Object.keys(extensions).length > 0) capabilities.extensions = extensions; const server = new Server({ name, version }, { capabilities }); observeStructuredProtocol(server); diff --git a/mcp/typescript/tests/acl-approval-gating-e2e.test.ts b/mcp/typescript/tests/acl-approval-gating-e2e.test.ts index 1da60282..1b881453 100644 --- a/mcp/typescript/tests/acl-approval-gating-e2e.test.ts +++ b/mcp/typescript/tests/acl-approval-gating-e2e.test.ts @@ -23,7 +23,10 @@ import { registerSysModules } from 'apcore-js/sys-modules'; */ import { describe, expect, it } from "vitest"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { createAsyncTaskBridge } from "../src/server/async-task-bridge.js"; import { ExecutionRouter } from "../src/server/router.js"; import { MCPServerFactory } from "../src/server/factory.js"; @@ -73,10 +76,7 @@ class RecordingApprovalHandler { } /** A real executor whose only approval source is an argument-scoped ACL rule. */ -async function buildRouter(): Promise<{ - router: ExecutionRouter; - handler: RecordingApprovalHandler; -}> { +async function buildExecutor() { const apcore = await import("apcore-js"); const registry = new apcore.Registry(); @@ -108,12 +108,13 @@ async function buildRouter(): Promise<{ approvalHandler: handler as never, }); - return { router: new ExecutionRouter(executor as never), handler }; + return { executor, handler, registry }; } describe("ACL-sourced approval gating over a real tools/call", () => { it("gates a call that matches the argument-scoped rule", async () => { - const { router, handler } = await buildRouter(); + const { executor, handler } = await buildExecutor(); + const router = new ExecutionRouter(executor as never); const [content, isError] = await router.handleCall(MODULE_ID, { path: "/tmp/x", @@ -129,7 +130,8 @@ describe("ACL-sourced approval gating over a real tools/call", () => { }); it("does not gate a call that does not match the rule", async () => { - const { router, handler } = await buildRouter(); + const { executor, handler } = await buildExecutor(); + const router = new ExecutionRouter(executor as never); const [content, isError] = await router.handleCall(MODULE_ID, { path: "/tmp/x" }); @@ -139,6 +141,50 @@ describe("ACL-sourced approval gating over a real tools/call", () => { "a call without `recursive` does not match the approval rule and MUST NOT be put to a human — gating it would be the over-refusal §6.1.7 exists to prevent", ).toEqual([]); }); + + it.each([true, false])("advertises approval preflight when available (async tasks: %s)", async (enabled) => { + const { executor, handler, registry } = await buildExecutor(); + const bridge = enabled ? await createAsyncTaskBridge(executor, { enabled: true }) : null; + const router = new ExecutionRouter(executor as never, { asyncTaskBridge: bridge ?? undefined }); + const factory = new MCPServerFactory(); + const server = factory.createServer("test", "1.0.0", { + health: true, usage: false, manifest: false, control: false, + }, bridge); + factory.registerHandlers(server, factory.buildTools(registry as never), router, { + asyncTaskBridge: bridge ?? undefined, + }); + const client = new Client({ name: "test", version: "1.0.0" }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + try { + await server.connect(serverTransport); + await client.connect(clientTransport); + const extensions = client.getServerCapabilities()?.extensions; + expect(extensions?.["com.aiperceivable/management"]).toBeDefined(); + const preflight = extensions?.["com.aiperceivable/approval-preflight"]; + const { tools } = await client.listTools(); + expect(tools.find(tool => tool.name === MODULE_ID)?._meta?.requiresApproval).not.toBe(true); + expect(tools.some(tool => tool.name === "__apcore_module_preview")).toBe(enabled); + if (enabled) { + expect(preflight).toEqual({ toolListApproval: "static", previewTool: "__apcore_module_preview" }); + for (const [args, expected] of [[{ path: "/tmp/x", recursive: true }, true], [{ path: "/tmp/x" }, false]] as const) { + const result = await client.callTool({ + name: preflight!.previewTool as string, + arguments: { module_id: MODULE_ID, arguments: args }, + }); + expect(result.isError).not.toBe(true); + const content = result.content as { text: string }[]; + expect(JSON.parse(content[0].text).requires_approval).toBe(expected); + } + } else { + expect(preflight).toBeUndefined(); + } + expect(handler.requests).toEqual([]); + } finally { + await client.close(); + await server.close(); + await bridge?.manager.shutdown?.(); + } + }); }); /** diff --git a/mcp/typescript/tests/config-bus.test.ts b/mcp/typescript/tests/config-bus.test.ts index ac06495e..2804228f 100644 --- a/mcp/typescript/tests/config-bus.test.ts +++ b/mcp/typescript/tests/config-bus.test.ts @@ -204,7 +204,7 @@ describe("MCP project YAML through Core Config.load", () => { ); const { MCPServerFactory } = await import("../src/server/factory.js"); expect(vi.mocked(MCPServerFactory).mock.results.at(-1)?.value.createServer) - .toHaveBeenCalledWith("yaml-server", expect.any(String), expect.anything()); + .toHaveBeenCalledWith("yaml-server", expect.any(String), expect.anything(), null); } finally { rmSync(directory, { recursive: true, force: true }); } diff --git a/toolkit/docs/features/device-auth.md b/toolkit/docs/features/device-auth.md index 3498b362..bf5528f6 100644 --- a/toolkit/docs/features/device-auth.md +++ b/toolkit/docs/features/device-auth.md @@ -1,5 +1,5 @@ --- -description: "PROPOSED (not implemented) RFC 8628 Device Authorization Flow client: a deterministic polling state machine, TokenSet lifecycle, and a portable TokenStore protocol — protocol only, no terminal UI." +description: "RFC 8628 Device Authorization Flow client with polling, TokenSet lifecycle, and a portable TokenStore protocol." --- # Device Authorization Flow — V1 Proposal @@ -9,9 +9,8 @@ description: "PROPOSED (not implemented) RFC 8628 Device Authorization Flow clie `FileTokenStore`, `Grant` / `DeviceCodeGrant` and the four extension hooks ship in `apcore-toolkit-{python,typescript,rust}` 0.12.0, asserted behaviourally equivalent by the shared 65-case corpus below. Rust gates it - behind a `device-auth` cargo feature. **Phase 3 — the terminal UI half in - `apcore-cli-*` — has not started**; the toolkit still writes nothing to a - terminal, by design. + behind a `device-auth` cargo feature. The CLI's `apcli login` command + supplies the terminal interface. This document is the relocated, re-scoped form of a proposal originally filed against `apcore-cli` as "Standardized RFC 8628 (Device Authorization @@ -1983,17 +1982,16 @@ In `apcore-toolkit-{python,typescript,rust}`: 8. Docs: flip this file's status banner, update `overview.md`, `README.md`, `mkdocs.yml`. -### Phase 3 — `apcore-cli` (separate PR per SDK) +### Phase 3 — `apcore-cli` 1. A `login` command rendering the user code, opening the browser, and showing poll progress via the callbacks. -2. A `KeychainTokenStore` **adapting the existing `config_encryptor`** (OS - keyring + AES-256-GCM fallback, already shipped in all three CLI SDKs) to - the toolkit's `TokenStore` protocol. This is an adapter, not a new - integration. +2. A `TokenStore` adapter for the OS keyring, with explicit opt-in to + Toolkit's file store where the keyring is unavailable. 3. Extend the existing `AuthProvider` to source its bearer token from the device-auth client when configured, keeping the static API-key path as-is. -4. Wire `as_auth_header_factory()` into the existing HTTP-proxy path. +4. Applications call the device-capable `AuthProvider` before sending requests + to their configured API. Built-in CLI proxy dispatch is tracked as FE-15b. ### Phase 4 — Ecosystem note diff --git a/toolkit/docs/features/openapi-scanner.md b/toolkit/docs/features/openapi-scanner.md index 23ab3383..4af71c70 100644 --- a/toolkit/docs/features/openapi-scanner.md +++ b/toolkit/docs/features/openapi-scanner.md @@ -300,6 +300,30 @@ for step 4. It is also idempotent, and segment-local — `normalize(a.b)` is the `.`-join of `normalize(a)` and `normalize(b)` with empty results dropped — which is why the path branch may normalise one segment at a time. +### Toolkit API + +Import `normalize_module_id` and `legality_warning` from the Toolkit package +root in Python and Rust. TypeScript exports `normalizeModuleId` and +`legalityWarning` from both the root and browser entry points. + +The normalizer returns the same candidate the scanner would use for a supplied +ID. Dots retain their namespace meaning and existing runs of underscores in a +legal ID are preserved. `normalize_module_id("API.2FA")` returns +`"api.2_fa"`. `legality_warning("api.2_fa")` reports the segment `"2_fa"` +so the caller can choose a different name. An empty result also produces a +warning. The diagnostic returns `None` (`null` in TypeScript) when the +candidate satisfies the structural grammar. The registry checks the length +and reserved namespaces, and scanners handle collisions with `deduplicate_ids`. + +For converting a bare name to one segment, Core's +[`canonicalize_name`](https://github.com/aiperceivable/apcore/blob/main/PROTOCOL_SPEC.md#221-bare-name-canonicalization) +applies its single-segment contract. It treats dots as name punctuation and +reports a diagnostic on non-ASCII input. The Toolkit API applies the +scanner's established ASCII projection to a dotted module ID, with each +non-ASCII code point replaced by one underscore before case folding. + +### Scanner integration + The scanner applies `normalize_module_id` a second time, to the **final** `module_id` — after the `derive_module_id` hook, `base_path_prefix` and the `transform_module` hook — so the alphabet holds for every emitted ID, not only @@ -421,13 +445,9 @@ made for the same reason, and one rule for both branches is what keeps an `operationId` and a path segment spelled alike from deriving differently. Two rules follow from the invariant: -- **Runs of `_` are kept.** PROTOCOL_SPEC §2.7 also says a segment MUST NOT - contain `__`, but no apcore registry enforces that constraint, and apcore's - own A02 implementations emit `__`. Collapsing runs here would rename every - FastAPI-generated ID that registers today, for a rule the protocol does not - apply to itself. That tension is apcore's to resolve — by enforcing the - constraint everywhere or by dropping it — not a scanner's to settle - unilaterally, so the legality check uses the pattern the registries enforce. +- **Runs of `_` are kept.** The grammar in PROTOCOL_SPEC §2.7 accepts runs + of underscores. Preserving them keeps existing IDs such as FastAPI's + `read_item_items__item_id__get` stable. - **A trailing `_` is stripped only in `derive_module_id`'s `operationId` branch**, which reproduces what V1's `sanitize` did (`getUser_` → `get_user`). The final normalisation does not strip it, so a legal ID a hook @@ -493,10 +513,9 @@ module_id '' is not a legal apcore module ID: segment '' must match where `` is the first dot-separated segment that is not a full match of `^[a-z][a-z0-9_]*$` (for an empty ID, the empty string). A consumer that -registers modules decides what to do with it — drop it, or pass a hook. The -scanner checks only the alphabet: the 192-character limit and the reserved -first segments of PROTOCOL_SPEC §2.5 remain the registry's to enforce, per -module, where the rules are defined. +registers modules decides what to do with it — drop it, or pass a hook. +`legality_warning` checks the structure of the ID. The registry enforces the +192-character limit and the reserved first segments of PROTOCOL_SPEC §2.5. **Collisions remain possible and are handled downstream.** Two operations may legitimately carry the same `operationId` in a malformed spec, and diff --git a/toolkit/python/CHANGELOG.md b/toolkit/python/CHANGELOG.md index 3cfbc3ef..c22792d3 100644 --- a/toolkit/python/CHANGELOG.md +++ b/toolkit/python/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. ## [0.15.1a2] - Unreleased +### Added + +- Export `normalize_module_id` and `legality_warning` for adapters that need the OpenAPI scanner's dotted-ID policy. [Issue #117](https://github.com/aiperceivable/apcore-surfaces/issues/117) + ### Changed - Extend the supported Core dependency range through `1.0.0b1`. The minimum remains `0.33.0`. diff --git a/toolkit/python/README.md b/toolkit/python/README.md index eb5916d7..2f8622bc 100644 --- a/toolkit/python/README.md +++ b/toolkit/python/README.md @@ -59,6 +59,7 @@ pip install apcore-toolkit | `format_jsonl` _(v0.7.0)_ | Byte-equivalent JSON Lines emitter — canonical compact JSON per row, LF terminator | | `OpenAPIScanner` _(v0.11.0)_ | Scans a parsed OpenAPI 3.0/3.1 document into `ScannedModule` instances, one per operation; supports `include`/`exclude` filters, deprecation handling, and `transform_operation` / `derive_module_id` / `transform_module` hooks. Every emitted `module_id` (including hook output and `base_path_prefix`) is normalised to snake_case, and an ID that is already legal (e.g. FastAPI's `read_item_items__item_id__get`) is left unchanged; one still illegal for an apcore registry (a digit-leading segment such as `v1.2fa.post`) is emitted with a warning | | `derive_module_id` / `load_spec` _(v0.11.0)_ | `derive_module_id` computes the default module ID for an OpenAPI path/method/operation, normalised to apcore's Canonical ID alphabet (`getUserById` → `get_user_by_id`, `GET /user-profiles/{userId}` → `user_profiles.user_id.get`, `GET /` → `root.get`); `load_spec` is a convenience helper that fetches/parses an OpenAPI document from a local path or `http(s)://` URL | +| `normalize_module_id` / `legality_warning` | Apply the scanner's ASCII normalization to a dotted ID and check its segment grammar. Check the returned candidate before registration because an empty ID or a digit-leading segment yields a warning | | `TuiViewModel` family _(v0.11.0)_ | `modules_to_view_model` builds a byte-equivalent `TuiViewModel` (columns, rows, filter/sort intent, tag-color rules) from scanned modules; `format_view_model` renders it to canonical compact JSON. Supporting types: `Column`, `Row`, `Cell`, `Sort`, `Filter`, `TonePalette`, `ToneRule`, `Group` | | `flatten_pydantic_params` | Converts Pydantic model parameters to flat kwargs | | `resolve_target` | Resolves "module.path:function_name" to callable | diff --git a/toolkit/python/src/apcore_toolkit/__init__.py b/toolkit/python/src/apcore_toolkit/__init__.py index 10362165..32f4e757 100644 --- a/toolkit/python/src/apcore_toolkit/__init__.py +++ b/toolkit/python/src/apcore_toolkit/__init__.py @@ -58,7 +58,13 @@ run_verifier_chain, ) from apcore_toolkit.output.yaml_writer import YAMLWriter -from apcore_toolkit.openapi_scanner import OpenAPIScanner, derive_module_id, load_spec +from apcore_toolkit.openapi_scanner import ( + OpenAPIScanner, + derive_module_id, + legality_warning, + load_spec, + normalize_module_id, +) from apcore_toolkit.openapi_parameters import OpenApiParameterProblem, OpenApiProxyInputs from apcore_toolkit.openapi_proxy import ( EffectiveProxyHazard, @@ -183,10 +189,12 @@ "get_writer", "has_path_params", "infer_annotations_from_method", + "legality_warning", "load_spec", "module_to_dict", "modules_to_dicts", "modules_to_view_model", + "normalize_module_id", "proxy_uses_json_body", "read_proxy_route", "resolve_http_verb", diff --git a/toolkit/python/src/apcore_toolkit/auth/tokens.py b/toolkit/python/src/apcore_toolkit/auth/tokens.py index ff69302e..9fa3f891 100644 --- a/toolkit/python/src/apcore_toolkit/auth/tokens.py +++ b/toolkit/python/src/apcore_toolkit/auth/tokens.py @@ -169,15 +169,15 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls, data: Mapping[str, Any]) -> TokenSet: """Inverse of :meth:`to_dict`, tolerant of a sparse stored record.""" - access_token = data.get("access_token") + access_token = data.get("access_token", data.get("accessToken")) if not isinstance(access_token, str): raise ValueError("stored credential has no access_token") - refresh_token = data.get("refresh_token") + refresh_token = data.get("refresh_token", data.get("refreshToken")) return cls( access_token=access_token, - token_type=_normalise_token_type(data.get("token_type")), - expires_at=coerce_int(data.get("expires_at")), + token_type=_normalise_token_type(data.get("token_type", data.get("tokenType"))), + expires_at=coerce_int(data.get("expires_at", data.get("expiresAt"))), refresh_token=refresh_token if isinstance(refresh_token, str) and refresh_token else None, scope=_normalise_scope(data.get("scope")), - obtained_at=coerce_int(data.get("obtained_at")) or 0, + obtained_at=coerce_int(data.get("obtained_at", data.get("obtainedAt"))) or 0, ) diff --git a/toolkit/python/src/apcore_toolkit/openapi_scanner.py b/toolkit/python/src/apcore_toolkit/openapi_scanner.py index 47fe91ef..319d2783 100644 --- a/toolkit/python/src/apcore_toolkit/openapi_scanner.py +++ b/toolkit/python/src/apcore_toolkit/openapi_scanner.py @@ -23,7 +23,7 @@ from apcore_toolkit.scanner import BaseScanner from apcore_toolkit.types import ScannedModule -__all__ = ["OpenAPIScanner", "derive_module_id", "load_spec"] +__all__ = ["OpenAPIScanner", "derive_module_id", "legality_warning", "load_spec", "normalize_module_id"] class _OpenApiScanOptions(TypedDict, total=False): @@ -56,7 +56,7 @@ class _OpenApiScanOptions(TypedDict, total=False): _LEGAL_SEGMENT_RE = re.compile(r"[a-z][a-z0-9_]*") -def _normalize_module_id(candidate: str) -> str: +def normalize_module_id(candidate: str) -> str: """Normalise a module-id candidate into apcore's Canonical ID alphabet. Implements ``normalize_module_id`` from ``apcore-toolkit/docs/features/ @@ -80,8 +80,7 @@ def _normalize_module_id(candidate: str) -> str: :func:`derive_module_id`'s ``operationId`` branch strips it. Also idempotent and segment-local. The result can still be illegal — a segment beginning with a digit, or empty — because repairing either - would invent a name; the scanner reports that with a warning. - Private: the scanner owns the alphabet, and hooks choose only the words. + would invent a name. Use :func:`legality_warning` to check the result. """ candidate = _ACRONYM_BOUNDARY_RE.sub(r"\1_\2", candidate) candidate = _WORD_BOUNDARY_RE.sub(r"\1_\2", candidate) @@ -91,14 +90,13 @@ def _normalize_module_id(candidate: str) -> str: return ".".join(seg for seg in segments if seg) -def _legality_warning(module_id: str) -> str | None: - """Return the pinned warning if *module_id* is not a legal apcore ID. +def legality_warning(module_id: str) -> str | None: + """Return a warning for the first malformed ID segment, or ``None``. - Checks only the alphabet the registries enforce (PROTOCOL_SPEC §2.7's - pattern): the first dot-separated segment that is not a full match of + Checks the structural grammar in PROTOCOL_SPEC §2.7: the first + dot-separated segment that is not a full match of ``^[a-z][a-z0-9_]*$`` is named — for an empty ID, the empty string. - §2.7's no-``__`` clause, the length limit and reserved first segments - are the registry's to enforce, not the scanner's. + The registry enforces the full ID length limit and reserved namespaces. """ for segment in module_id.split("."): if _LEGAL_SEGMENT_RE.fullmatch(segment) is None: @@ -144,7 +142,7 @@ def derive_module_id(path: str, method: str, operation: dict[str, Any]) -> str: if isinstance(operation_id, str) and operation_id != "": # The trailing-"_" strip belongs to this branch only: the scanner's # final normalisation must not rewrite a legal ID a hook returned. - candidate = _normalize_module_id(operation_id).rstrip("_") + candidate = normalize_module_id(operation_id).rstrip("_") if candidate: return candidate @@ -152,7 +150,7 @@ def derive_module_id(path: str, method: str, operation: dict[str, Any]) -> str: for seg in path.split("/"): if len(seg) >= 2 and seg.startswith("{") and seg.endswith("}"): seg = seg[1:-1] - part = _normalize_module_id(seg) + part = normalize_module_id(seg) if part: parts.append(part) @@ -459,7 +457,7 @@ def _scan( # emitted ID. A legal ID passes through unchanged. `replace()` # rather than mutation: a `transform_module` hook may still hold # the object it returned. - final_id = _normalize_module_id(module.module_id) + final_id = normalize_module_id(module.module_id) if final_id != module.module_id: module = replace(module, module_id=final_id) @@ -474,7 +472,7 @@ def _scan( @staticmethod def _with_legality_warning(module: ScannedModule) -> ScannedModule: """Append the pinned legality warning if *module*'s ID is still illegal.""" - warning = _legality_warning(module.module_id) + warning = legality_warning(module.module_id) if warning is None: return module return replace(module, warnings=[*module.warnings, warning]) diff --git a/toolkit/python/tests/test_device_auth.py b/toolkit/python/tests/test_device_auth.py index 947fab5c..9cdb9899 100644 --- a/toolkit/python/tests/test_device_auth.py +++ b/toolkit/python/tests/test_device_auth.py @@ -105,6 +105,20 @@ def test_file_store_load_missing_returns_none(tmp_path: Path) -> None: assert store.load("k") is None +def test_file_store_loads_typescript_credentials(tmp_path: Path) -> None: + path = tmp_path / "credentials.json" + path.write_text(json.dumps({ + "provider|client": { + "accessToken": "sample", "tokenType": "Bearer", "expiresAt": 60, + "refreshToken": "refresh", "scope": ["read"], "obtainedAt": 10, + }, + })) + path.chmod(0o600) + assert FileTokenStore(path).load("provider|client") == TokenSet( + "sample", expires_at=60, refresh_token="refresh", scope=["read"], obtained_at=10 + ) + + def test_file_store_clear_is_idempotent(tmp_path: Path) -> None: store = FileTokenStore(tmp_path / "credentials.json") store.clear("absent") # no file at all diff --git a/toolkit/python/tests/test_openapi_scanner_module_id.py b/toolkit/python/tests/test_openapi_scanner_module_id.py index aea51cab..9032a4c4 100644 --- a/toolkit/python/tests/test_openapi_scanner_module_id.py +++ b/toolkit/python/tests/test_openapi_scanner_module_id.py @@ -22,12 +22,7 @@ import apcore_toolkit import apcore_toolkit.openapi_scanner as openapi_scanner_module -from apcore_toolkit.openapi_scanner import ( - OpenAPIScanner, - _legality_warning, - _normalize_module_id, - derive_module_id, -) +from apcore_toolkit import OpenAPIScanner, derive_module_id, legality_warning, normalize_module_id from apcore_toolkit.types import ScannedModule _BASE = {"openapi": "3.0.3", "info": {"title": "t", "version": "1.0.0"}} @@ -47,7 +42,7 @@ def _expected_warning(module_id: str, segment: str) -> str: # --------------------------------------------------------------------------- -# _normalize_module_id +# normalize_module_id # --------------------------------------------------------------------------- @@ -68,7 +63,7 @@ def _expected_warning(module_id: str, segment: str) -> str: ], ) def test_normalize_acronym_boundaries(raw: str, expected: str) -> None: - assert _normalize_module_id(raw) == expected + assert normalize_module_id(raw) == expected @pytest.mark.parametrize( @@ -82,7 +77,7 @@ def test_normalize_acronym_boundaries(raw: str, expected: str) -> None: ], ) def test_normalize_digits(raw: str, expected: str) -> None: - assert _normalize_module_id(raw) == expected + assert normalize_module_id(raw) == expected @pytest.mark.parametrize( @@ -110,7 +105,7 @@ def test_normalize_digits(raw: str, expected: str) -> None: ], ) def test_normalize_separators_and_underscore_runs(raw: str, expected: str) -> None: - assert _normalize_module_id(raw) == expected + assert normalize_module_id(raw) == expected @pytest.mark.parametrize( @@ -136,14 +131,14 @@ def test_normalize_separators_and_underscore_runs(raw: str, expected: str) -> No ], ) def test_normalize_non_ascii_never_survives(raw: str, expected: str) -> None: - result = _normalize_module_id(raw) + result = normalize_module_id(raw) assert result == expected assert result.isascii() @pytest.mark.parametrize("raw", ["", "_", "___", ".", "_._", "-", "\U0001f600", "\u212a"]) def test_normalize_can_return_empty(raw: str) -> None: - assert _normalize_module_id(raw) == "" + assert normalize_module_id(raw) == "" _IDEMPOTENCE_PROBES = [ @@ -166,8 +161,8 @@ def test_normalize_can_return_empty(raw: str) -> None: @pytest.mark.parametrize("raw", _IDEMPOTENCE_PROBES) def test_normalize_is_idempotent_and_in_alphabet(raw: str) -> None: - once = _normalize_module_id(raw) - assert _normalize_module_id(once) == once + once = normalize_module_id(raw) + assert normalize_module_id(once) == once assert re.fullmatch(r"[a-z0-9_.]*", once) for segment in once.split(".") if once else []: assert segment, "empty segments are dropped" @@ -188,7 +183,7 @@ def test_normalize_is_idempotent_and_in_alphabet(raw: str) -> None: def test_normalize_returns_a_legal_id_unchanged(legal_id: str) -> None: """The spec's MUST: a name apcore already accepts is never rewritten.""" assert MODULE_ID_PATTERN.fullmatch(legal_id) - assert _normalize_module_id(legal_id) == legal_id + assert normalize_module_id(legal_id) == legal_id def test_normalize_returns_every_short_legal_id_unchanged() -> None: @@ -200,7 +195,7 @@ def test_normalize_returns_every_short_legal_id_unchanged() -> None: candidate = "".join(chars) if MODULE_ID_PATTERN.fullmatch(candidate): checked += 1 - assert _normalize_module_id(candidate) == candidate + assert normalize_module_id(candidate) == candidate assert checked == 516 @@ -209,16 +204,19 @@ def test_normalize_is_segment_local() -> None: may normalise one segment at a time.""" pieces = ["getUser", "-x-", "", "__y", "Kz", "a b", "2fa", "HTTPServer"] for left, right in itertools.product(pieces, repeat=2): - joined = ".".join(part for part in (_normalize_module_id(left), _normalize_module_id(right)) if part) - assert _normalize_module_id(f"{left}.{right}") == joined + joined = ".".join(part for part in (normalize_module_id(left), normalize_module_id(right)) if part) + assert normalize_module_id(f"{left}.{right}") == joined + +def test_normalize_and_diagnostic_are_public_api() -> None: + for name in ("normalize_module_id", "legality_warning"): + assert name in openapi_scanner_module.__all__ + assert name in apcore_toolkit.__all__ + assert getattr(apcore_toolkit, name) is getattr(openapi_scanner_module, name) -def test_normalize_is_not_public_api() -> None: - """The scanner owns the alphabet; the helper is deliberately private.""" - assert "normalize_module_id" not in openapi_scanner_module.__all__ - assert "_normalize_module_id" not in openapi_scanner_module.__all__ - assert not hasattr(apcore_toolkit, "normalize_module_id") - assert "normalize_module_id" not in apcore_toolkit.__all__ + candidate = apcore_toolkit.normalize_module_id("API.2FA") + assert candidate == "api.2_fa" + assert apcore_toolkit.legality_warning(candidate) == _expected_warning(candidate, "2_fa") # --------------------------------------------------------------------------- @@ -264,13 +262,13 @@ def test_derive_module_id(path: str, method: str, operation: dict[str, Any], exp # --------------------------------------------------------------------------- -# _legality_warning +# legality_warning # --------------------------------------------------------------------------- @pytest.mark.parametrize("module_id", ["users.get", "get_user_by_id", "v2_items", "a.b_c.d9"]) def test_legality_warning_none_for_legal_ids(module_id: str) -> None: - assert _legality_warning(module_id) is None + assert legality_warning(module_id) is None @pytest.mark.parametrize( @@ -283,7 +281,7 @@ def test_legality_warning_none_for_legal_ids(module_id: str) -> None: ], ) def test_legality_warning_names_first_bad_segment(module_id: str, segment: str) -> None: - assert _legality_warning(module_id) == _expected_warning(module_id, segment) + assert legality_warning(module_id) == _expected_warning(module_id, segment) def test_legality_check_does_not_accept_trailing_newline() -> None: @@ -291,7 +289,7 @@ def test_legality_check_does_not_accept_trailing_newline() -> None: would accept `"abc\\n"` where JavaScript and Rust reject it. The check uses `fullmatch`. Unreachable from the scanner (normalisation replaces `\\n`), pinned here so a refactor to `^...$` cannot quietly reintroduce it.""" - assert _legality_warning("abc\n") == _expected_warning("abc\n", "abc\n") + assert legality_warning("abc\n") == _expected_warning("abc\n", "abc\n") # --------------------------------------------------------------------------- @@ -472,7 +470,7 @@ def test_long_capital_run_is_linear_time() -> None: # inserts the `_` in the same place. crafted = "A" * 200_000 + "b" start = time.perf_counter() - result = _normalize_module_id(crafted) + result = normalize_module_id(crafted) elapsed = time.perf_counter() - start assert result == "a" * 199_999 + "_ab" assert elapsed < 2.0, f"normalisation took {elapsed:.2f}s on a 200,001-character input" diff --git a/toolkit/rust/CHANGELOG.md b/toolkit/rust/CHANGELOG.md index 7f2ed5ca..32cfb41a 100644 --- a/toolkit/rust/CHANGELOG.md +++ b/toolkit/rust/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. ## [0.15.1-alpha.2] - Unreleased +### Added + +- Export `normalize_module_id` and `legality_warning` for adapters that need the OpenAPI scanner's dotted-ID policy. [Issue #117](https://github.com/aiperceivable/apcore-surfaces/issues/117) + ### Changed - Resolve Core `1.0.0-beta.1` in the release lockfile. The manifest continues to support Core `0.33.0` through `1.0.0-beta.1`. diff --git a/toolkit/rust/README.md b/toolkit/rust/README.md index 72c7f2ab..03f4514b 100644 --- a/toolkit/rust/README.md +++ b/toolkit/rust/README.md @@ -37,6 +37,7 @@ apcore-toolkit = { version = "0.15", default-features = false } | `OpenAPIScanner` | Scans an OpenAPI spec into `ScannedModule` values; configured via `ScanOptions` (hooks: `DeriveModuleIdHook`, `TransformOperationHook`, `TransformModuleHook`) | | `ScanOptions` / `ScannerError` | Configuration struct and `thiserror`-derived error enum for `OpenAPIScanner` | | `derive_module_id` | Default module-ID derivation for an OpenAPI operation (`operationId`, else path + method), in apcore's Canonical ID alphabet (`getUserById` → `get_user_by_id`) | +| `normalize_module_id` / `legality_warning` | Apply the scanner's ASCII normalization to a dotted ID and check its segment grammar. Check the returned candidate before registration because an empty ID or a digit-leading segment yields a warning | | `load_spec` / `load_spec_with_options` | Loads an OpenAPI spec document from a file or URL (feature: `http-proxy`) | | `YAMLWriter` | Generates `.binding.yaml` files for `apcore::BindingLoader` | | `BindingLoader` | Parses `.binding.yaml` files back into `ScannedModule` values (pure-data inverse of `YAMLWriter`, with loose/strict modes) | diff --git a/toolkit/rust/src/auth/store.rs b/toolkit/rust/src/auth/store.rs index fb9b40ca..050c5ecd 100644 --- a/toolkit/rust/src/auth/store.rs +++ b/toolkit/rust/src/auth/store.rs @@ -352,6 +352,20 @@ mod tests { assert_eq!(loaded, token("t1")); } + #[test] + fn test_token_record_loads_typescript_credentials() { + let loaded: TokenSet = serde_json::from_value(serde_json::json!({ + "accessToken": "t1", + "tokenType": "Bearer", + "expiresAt": 4600, + "refreshToken": "r1", + "scope": ["openid"], + "obtainedAt": 1000, + })) + .expect("load TypeScript token record"); + assert_eq!(loaded, token("t1")); + } + #[test] fn test_file_store_keeps_other_keys_on_save() { let dir = TempDir::new().expect("temp dir"); diff --git a/toolkit/rust/src/auth/token.rs b/toolkit/rust/src/auth/token.rs index 2d3c45dd..0d3696ab 100644 --- a/toolkit/rust/src/auth/token.rs +++ b/toolkit/rust/src/auth/token.rs @@ -28,19 +28,24 @@ pub const REDACTED: &str = ""; #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TokenSet { /// The bearer credential. Opaque: never parsed. + #[serde(alias = "accessToken")] pub access_token: String, /// Normalised to `"Bearer"` casing on read; servers vary. + #[serde(alias = "tokenType")] pub token_type: String, /// Wall-clock Unix seconds at which the access token expires. `None` when /// the server stated no lifetime, in which case the token never /// auto-expires. + #[serde(alias = "expiresAt")] pub expires_at: Option, /// Present only when the server issued one. Rotation is assumed. + #[serde(alias = "refreshToken")] pub refresh_token: Option, /// Granted scopes, split on spaces per RFC 6749. Empty when absent. pub scope: Vec, /// Wall-clock Unix seconds at which this record was created. Diagnostics /// and store-format migration only. + #[serde(alias = "obtainedAt")] pub obtained_at: i64, } diff --git a/toolkit/rust/src/lib.rs b/toolkit/rust/src/lib.rs index 53b04b20..a8872c5f 100644 --- a/toolkit/rust/src/lib.rs +++ b/toolkit/rust/src/lib.rs @@ -87,8 +87,8 @@ pub use openapi::{ }; pub use openapi_parameters::{OpenApiParameterProblem, OpenApiParameterScope, OpenApiProxyInputs}; pub use openapi_scanner::{ - derive_module_id, DeriveModuleIdHook, OpenAPIScanner, ScanOptions, ScannerError, - TransformModuleHook, TransformOperationHook, + derive_module_id, legality_warning, normalize_module_id, DeriveModuleIdHook, OpenAPIScanner, + ScanOptions, ScannerError, TransformModuleHook, TransformOperationHook, }; pub use output::errors::WriteError; pub use output::registry_writer::{HandlerFactory, HandlerFn, RegistryWriter}; diff --git a/toolkit/rust/src/openapi_scanner.rs b/toolkit/rust/src/openapi_scanner.rs index 76eb83f6..501c2de0 100644 --- a/toolkit/rust/src/openapi_scanner.rs +++ b/toolkit/rust/src/openapi_scanner.rs @@ -112,10 +112,9 @@ pub enum ScannerError { /// (`read_item_items__item_id__get`, FastAPI's default `operationId` /// shape, is registrable as-is and stays so), and the function is /// idempotent on its own output. The result can be empty, and can still be -/// illegal when a segment begins with a digit (`v1.2fa.post`) — repairing -/// that would invent a name, so the scanner warns instead (see -/// [`legality_warning`]). -fn normalize_module_id(raw: &str) -> String { +/// malformed when a segment begins with a digit (`v1.2fa.post`). Use +/// [`legality_warning`] to check the result. +pub fn normalize_module_id(raw: &str) -> String { // `${1}_${2}`, not `$1_$2`: the `regex` crate reads `$1_` as a group // *named* `1_`, which does not exist and expands to the empty string. let acronyms_split = ACRONYM_BOUNDARY_RE.replace_all(raw, "${1}_${2}"); @@ -131,14 +130,12 @@ fn normalize_module_id(raw: &str) -> String { .join(".") } -/// The pinned warning for an emitted `module_id` that is still not a legal -/// apcore ID after normalisation and deduplication, or `None` when it is -/// legal. +/// Return the scanner's warning for the first malformed dot-separated segment +/// of `module_id`, or `None` if every segment fully matches `^[a-z][a-z0-9_]*$`. /// -/// Names the first `.`-segment failing `^[a-z][a-z0-9_]*$`; an empty ID -/// has exactly one segment, the empty string. See "What normalisation will -/// not repair" in `apcore-toolkit/docs/features/openapi-scanner.md`. -fn legality_warning(module_id: &str) -> Option { +/// An empty ID has one malformed segment, the empty string. The registry +/// enforces the full ID length limit and reserved namespaces. +pub fn legality_warning(module_id: &str) -> Option { let segment = module_id .split('.') .find(|segment| !LEGAL_SEGMENT_RE.is_match(segment))?; diff --git a/toolkit/rust/tests/openapi_scan_conformance.rs b/toolkit/rust/tests/openapi_scan_conformance.rs index 241600ed..ab530648 100644 --- a/toolkit/rust/tests/openapi_scan_conformance.rs +++ b/toolkit/rust/tests/openapi_scan_conformance.rs @@ -21,9 +21,22 @@ use std::path::PathBuf; -use apcore_toolkit::{OpenAPIScanner, ScanOptions, ScannedModule, ScannerError}; +use apcore_toolkit::{ + legality_warning, normalize_module_id, OpenAPIScanner, ScanOptions, ScannedModule, ScannerError, +}; use serde_json::{json, Value}; +#[test] +fn module_id_normalization_and_diagnostics_are_exported() { + let candidate = normalize_module_id("API.2FA"); + assert_eq!(candidate, "api.2_fa"); + assert_eq!( + legality_warning(&candidate).as_deref(), + Some("module_id 'api.2_fa' is not a legal apcore module ID: segment '2_fa' must match ^[a-z][a-z0-9_]*$; name this operation with a derive_module_id or transform_module hook"), + ); + assert_eq!(legality_warning("read_item_items__item_id__get"), None); +} + fn conformance_dir() -> PathBuf { std::env::var_os("CONFORMANCE_FIXTURES").map_or_else( || PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../conformance/fixtures"), diff --git a/toolkit/typescript/CHANGELOG.md b/toolkit/typescript/CHANGELOG.md index 5e930653..039d4618 100644 --- a/toolkit/typescript/CHANGELOG.md +++ b/toolkit/typescript/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file. ### Added - Export delegated JWT verification for host adapters that bind caller delegation to a verified transport identity. +- Export `normalizeModuleId` and `legalityWarning` from the root and browser entry points for adapters that need the OpenAPI scanner's dotted-ID policy. [Issue #117](https://github.com/aiperceivable/apcore-surfaces/issues/117) ### Changed diff --git a/toolkit/typescript/README.md b/toolkit/typescript/README.md index f7ba199b..d8cb010a 100644 --- a/toolkit/typescript/README.md +++ b/toolkit/typescript/README.md @@ -273,6 +273,7 @@ The **Browser** column marks whether a symbol is also re-exported from | `OpenAPIScanner` _(v0.11.0)_ | ✓ | Turn an OpenAPI 3.x document into `ScannedModule[]`. Pure and synchronous — no I/O. Every `moduleId` is in apcore's Canonical ID alphabet, including IDs from `basePathPrefix` and the hooks, and an ID apcore already accepts is never rewritten (FastAPI's `read_item_items__item_id__get` passes through); one still illegal (a digit-leading segment such as `v1.2fa.post`) is emitted with a warning naming the emitted ID | | `OpenAPIScanOptions` _(v0.11.0)_ | ✓ | Options for `OpenAPIScanner.scan()` | | `deriveModuleId()` _(v0.11.0)_ | ✓ | Derive a stable, byte-identical `moduleId` for an OpenAPI operation, in snake_case (`getUserById` → `get_user_by_id`, `GET /user-profiles/{userId}` → `user_profiles.user_id.get`); primary subject of the cross-SDK conformance corpus | +| `normalizeModuleId()` / `legalityWarning()` | ✓ | Apply the scanner's ASCII normalization to a dotted ID and check its segment grammar. Check the returned candidate before registration because an empty ID or a digit-leading segment yields a warning | | `InvalidSpecError` _(v0.11.0)_ | ✓ | Thrown by `OpenAPIScanner.scan()` when the input isn't a recognisable OpenAPI 3.0.x/3.1.x document | | `loadSpec()` _(v0.11.0)_ | | Fetch/parse an OpenAPI document from a local filesystem path or an `http(s)://` URL | | `LoadSpecOptions` _(v0.11.0)_ | | Options for `loadSpec()` | diff --git a/toolkit/typescript/src/auth/token-set.ts b/toolkit/typescript/src/auth/token-set.ts index 856d58e3..a5e27280 100644 --- a/toolkit/typescript/src/auth/token-set.ts +++ b/toolkit/typescript/src/auth/token-set.ts @@ -161,18 +161,23 @@ export class TokenSet { }; } - /** Rebuild from {@link toRecord} output; returns `null` for an unusable record. */ + /** Read a stored record from any Toolkit SDK, or return `null` if unusable. */ static fromRecord(record: unknown): TokenSet | null { if (typeof record !== 'object' || record === null || Array.isArray(record)) return null; - const r = record as Partial; - if (typeof r.accessToken !== 'string' || r.accessToken === '') return null; + const r = record as Record; + const accessToken = r.accessToken ?? r.access_token; + if (typeof accessToken !== 'string' || accessToken === '') return null; + const tokenType = r.tokenType ?? r.token_type; + const expiresAt = r.expiresAt ?? r.expires_at; + const refreshToken = r.refreshToken ?? r.refresh_token; + const obtainedAt = r.obtainedAt ?? r.obtained_at; return new TokenSet({ - accessToken: r.accessToken, - tokenType: normaliseTokenType(typeof r.tokenType === 'string' ? r.tokenType : null), - expiresAt: typeof r.expiresAt === 'number' ? r.expiresAt : null, - refreshToken: typeof r.refreshToken === 'string' ? r.refreshToken : null, + accessToken, + tokenType: normaliseTokenType(typeof tokenType === 'string' ? tokenType : null), + expiresAt: typeof expiresAt === 'number' ? expiresAt : null, + refreshToken: typeof refreshToken === 'string' ? refreshToken : null, scope: Array.isArray(r.scope) ? r.scope.filter((s): s is string => typeof s === 'string') : [], - obtainedAt: typeof r.obtainedAt === 'number' ? r.obtainedAt : 0, + obtainedAt: typeof obtainedAt === 'number' ? obtainedAt : 0, }); } diff --git a/toolkit/typescript/src/browser/index.ts b/toolkit/typescript/src/browser/index.ts index 5e1a9180..7e34e86a 100644 --- a/toolkit/typescript/src/browser/index.ts +++ b/toolkit/typescript/src/browser/index.ts @@ -104,7 +104,7 @@ export type { // with no Node.js dependency. `loadSpec` (in `../openapi-loader.js`) is // intentionally NOT re-exported here — its local-file-path branch needs // Node's `fs`, matching how `BindingLoader` stays Node-only above. -export { OpenAPIScanner, deriveModuleId, InvalidSpecError } from '../openapi-scanner.js'; +export { OpenAPIScanner, deriveModuleId, InvalidSpecError, legalityWarning, normalizeModuleId } from '../openapi-scanner.js'; export type { OpenAPIScanOptions } from '../openapi-scanner.js'; // ---- TUI view model (pure data, no Node.js dependency) -------------------- diff --git a/toolkit/typescript/src/index.ts b/toolkit/typescript/src/index.ts index 4212aa90..543a411a 100644 --- a/toolkit/typescript/src/index.ts +++ b/toolkit/typescript/src/index.ts @@ -86,7 +86,7 @@ export type { ProxyRegistry, } from './output/http-proxy-writer.js'; export { getWriter } from './output/factory.js'; -export { OpenAPIScanner, deriveModuleId, InvalidSpecError } from './openapi-scanner.js'; +export { OpenAPIScanner, deriveModuleId, InvalidSpecError, legalityWarning, normalizeModuleId } from './openapi-scanner.js'; export type { OpenAPIScanOptions } from './openapi-scanner.js'; export { loadSpec } from './openapi-loader.js'; export type { LoadSpecOptions } from './openapi-loader.js'; diff --git a/toolkit/typescript/src/openapi-scanner.ts b/toolkit/typescript/src/openapi-scanner.ts index cc950b34..6a217ba7 100644 --- a/toolkit/typescript/src/openapi-scanner.ts +++ b/toolkit/typescript/src/openapi-scanner.ts @@ -92,12 +92,8 @@ const LEGAL_SEGMENT_RE = /^[a-z][a-z0-9_]*$/; * step is the identity on the Canonical ID grammar. So runs of `_` are kept * (FastAPI's `read_item_items__item_id__get` passes through) and a trailing * `_` is kept (a hook's `abc_` passes through). The function is also - * idempotent. The result can still be illegal (a segment beginning with a - * digit, or empty); the scanner reports that, this function does not. - * - * @internal Exported from this file for unit tests only. It is deliberately - * not re-exported from `apcore-toolkit` or `apcore-toolkit/browser`: the - * public surface is {@link deriveModuleId} and {@link OpenAPIScanner.scan}. + * idempotent. The result can still have a segment beginning with a digit, + * or be empty. Use {@link legalityWarning} to check the result. */ export function normalizeModuleId(s: string): string { const ascii = s @@ -113,22 +109,14 @@ export function normalizeModuleId(s: string): string { } /** - * The first dot-separated segment of `moduleId` that is not a full match of - * `^[a-z][a-z0-9_]*$`, or `null` when every segment is legal. An empty ID - * has one segment, the empty string, which fails. - */ -function illegalSegment(moduleId: string): string | null { - for (const seg of moduleId.split('.')) { - if (!LEGAL_SEGMENT_RE.test(seg)) return seg; - } - return null; -} - -/** - * The pinned legality warning (spec § What normalisation will not repair). - * The snake_case names are part of the byte-pinned text in every SDK. + * Return the scanner's warning for the first malformed dot-separated segment + * of `moduleId`, or `null` if every segment fully matches `^[a-z][a-z0-9_]*$`. + * An empty ID has one malformed segment, the empty string. + * The registry enforces the full ID length limit and reserved namespaces. */ -function legalityWarning(moduleId: string, segment: string): string { +export function legalityWarning(moduleId: string): string | null { + const segment = moduleId.split('.').find((value) => !LEGAL_SEGMENT_RE.test(value)); + if (segment === undefined) return null; return ( `module_id '${moduleId}' is not a legal apcore module ID: segment '${segment}' ` + 'must match ^[a-z][a-z0-9_]*$; name this operation with a derive_module_id ' + @@ -535,10 +523,8 @@ export class OpenAPIScanner extends BaseScanner { // names the ID actually emitted (`3ds_2`, not `3ds`) and follows any // rename warning. return modules.map((m) => { - const badSegment = illegalSegment(m.moduleId); - return badSegment === null - ? m - : cloneModule(m, { warnings: [...m.warnings, legalityWarning(m.moduleId, badSegment)] }); + const warning = legalityWarning(m.moduleId); + return warning === null ? m : cloneModule(m, { warnings: [...m.warnings, warning] }); }); } diff --git a/toolkit/typescript/tests/device-auth-store.test.ts b/toolkit/typescript/tests/device-auth-store.test.ts index 7dff817e..d502f807 100644 --- a/toolkit/typescript/tests/device-auth-store.test.ts +++ b/toolkit/typescript/tests/device-auth-store.test.ts @@ -232,6 +232,17 @@ describe('FileTokenStore — record handling', () => { expect(loaded?.obtainedAt).toBe(1000); }); + it('loads a credential written by the Python and Rust SDKs', async () => { + const { store, path } = makeStore(); + writeFileSync(path, JSON.stringify({ + [KEY]: { + access_token: 'access-value', token_type: 'Bearer', expires_at: 4600, + refresh_token: 'refresh-value', scope: ['openid'], obtained_at: 1000, + }, + }), { mode: 0o600 }); + expect((await store.load(KEY))?.toRecord()).toEqual(sampleTokens().toRecord()); + }); + it('clears idempotently, including a key that was never stored', async () => { const { store } = makeStore(); await expect(store.clear(KEY)).resolves.toBeUndefined(); diff --git a/toolkit/typescript/tests/openapi-scanner.test.ts b/toolkit/typescript/tests/openapi-scanner.test.ts index 0a6a1837..2ef63edd 100644 --- a/toolkit/typescript/tests/openapi-scanner.test.ts +++ b/toolkit/typescript/tests/openapi-scanner.test.ts @@ -145,11 +145,12 @@ describe('normalizeModuleId', () => { } }); - it('is not re-exported from either package entry point', () => { - expect('normalizeModuleId' in rootEntry).toBe(false); - expect('normalizeModuleId' in browserEntry).toBe(false); - expect(typeof rootEntry.deriveModuleId).toBe('function'); - expect(typeof browserEntry.deriveModuleId).toBe('function'); + it.each([rootEntry, browserEntry])('exports normalization and diagnostics from the package', (entry) => { + const candidate = entry.normalizeModuleId('API.2FA'); + expect(candidate).toBe('api.2_fa'); + expect(entry.legalityWarning(candidate)).toBe(legalityWarning(candidate, '2_fa')); + expect(entry.legalityWarning('read_item_items__item_id__get')).toBeNull(); + expect(entry.legalityWarning('abc\n')).toBe(legalityWarning('abc\n', 'abc\n')); }); }); From 2bec53b6a292b176b0ffab03383adb35b0d8adf7 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 12:35:47 +0800 Subject: [PATCH 2/2] fix: address Surfaces CLI and MCP review findings Signed-off-by: tercel --- .../src/apcore_cli/security/device_login.py | 10 ++- cli/python/tests/test_device_login.py | 42 ++++++++++ cli/rust/src/cli.rs | 56 ++++++++++--- cli/rust/src/main.rs | 20 +++-- cli/rust/src/schema_parser.rs | 73 ++++++++-------- cli/rust/tests/test_e2e.rs | 60 +++++++++++++ cli/rust/tests/test_schema_parser.rs | 13 ++- cli/typescript/src/main.ts | 6 +- cli/typescript/src/schema-parser.ts | 20 ++++- cli/typescript/src/security/device-login.ts | 6 +- cli/typescript/tests/device-login.test.ts | 19 ++++- cli/typescript/tests/structured-flags.test.ts | 25 ++++++ mcp/docs/features/async-task-bridge.md | 8 +- mcp/docs/features/mcp-server-factory.md | 8 ++ .../apcore_mcp/server/async_task_bridge.py | 3 +- mcp/python/src/apcore_mcp/server/factory.py | 58 ++++++++++++- .../tests/server/test_versioned_tool_wire.py | 84 ++++++++++++++++++- mcp/typescript/src/server/factory.ts | 31 ++++--- mcp/typescript/src/server/router.ts | 9 +- .../tests/acl-approval-gating-e2e.test.ts | 23 +++-- 20 files changed, 477 insertions(+), 97 deletions(-) diff --git a/cli/python/src/apcore_cli/security/device_login.py b/cli/python/src/apcore_cli/security/device_login.py index 72b33937..86e72c97 100644 --- a/cli/python/src/apcore_cli/security/device_login.py +++ b/cli/python/src/apcore_cli/security/device_login.py @@ -6,6 +6,7 @@ import json import webbrowser from contextlib import suppress +from threading import Thread from urllib.parse import urlsplit import click @@ -128,6 +129,7 @@ def _safe_verification_url(value: str) -> bool: return False try: url = urlsplit(value) + _ = url.port # urllib checks the port while reading this property. return bool( url.hostname and url.username is None @@ -140,6 +142,11 @@ def _safe_verification_url(value: str) -> bool: return False +def _open_browser(url: str) -> None: + with suppress(webbrowser.Error, OSError): + webbrowser.open(url) + + def register_login_command(apcli: click.Group) -> None: @apcli.command("login") @click.option("--no-browser", is_flag=True, help="Print the verification address without opening a browser.") @@ -159,8 +166,7 @@ def show_code( complete = urlsplit(verification_uri_complete) if complete.scheme == "https" and complete.netloc == urlsplit(verification_uri).netloc: url = verification_uri_complete - with suppress(webbrowser.Error): - webbrowser.open(url) + Thread(target=_open_browser, args=(url,), daemon=True).start() def show_poll(attempt: int, interval: int, elapsed: float) -> None: if attempt == 1: diff --git a/cli/python/tests/test_device_login.py b/cli/python/tests/test_device_login.py index ec82032d..1cb38aef 100644 --- a/cli/python/tests/test_device_login.py +++ b/cli/python/tests/test_device_login.py @@ -1,6 +1,7 @@ import json import sys import time +from threading import Event import pytest from apcore_toolkit.auth import ConfigurationError, FileTokenStore, HttpResponse, TokenSet @@ -107,6 +108,47 @@ def send(_transport, request): assert requests == ["https://auth.example.test/device"] +def test_login_rejects_an_invalid_endpoint_port(device_config, monkeypatch, capsys): + device_config.write_text(device_config.read_text().replace("/device", ":wrong/device")) + monkeypatch.setattr(sys, "argv", ["apcore-cli", "apcli", "login", "--no-browser"]) + with pytest.raises(SystemExit) as result: + main() + assert result.value.code == 47 + assert "Device login configuration error" in capsys.readouterr().err + + +def test_browser_launcher_does_not_hold_up_polling(device_config, monkeypatch): + from apcore_cli.security import device_login + + opened, release, returned = Event(), Event(), Event() + + def open_browser(_url): + opened.set() + release.wait(timeout=2) + returned.set() + + def login(_client, *, on_user_code, on_poll, timeout_seconds): + on_user_code( + verification_uri="https://auth.example.test/verify", + verification_uri_complete=None, + user_code="ABCD", + expires_in=60, + ) + assert opened.wait(timeout=1) + assert not returned.is_set() + return TokenSet("sample-token") + + monkeypatch.setattr(device_login.webbrowser, "open", open_browser) + monkeypatch.setattr(device_login.DeviceAuthClient, "login", login) + monkeypatch.setattr(sys, "argv", ["apcore-cli", "apcli", "login"]) + try: + with pytest.raises(SystemExit) as result: + main() + assert result.value.code == 0 + finally: + release.set() + + def test_default_keyring_storage_isolated_by_client(device_config, monkeypatch): from apcore_cli.security import device_login diff --git a/cli/rust/src/cli.rs b/cli/rust/src/cli.rs index 87d88ce9..20f27580 100644 --- a/cli/rust/src/cli.rs +++ b/cli/rust/src/cli.rs @@ -479,6 +479,42 @@ pub fn build_module_command_with_limit( module_def: &apcore::registry::registry::ModuleDescriptor, help_text_max_length: usize, ) -> Result { + let generated = build_module_command_parts(module_def, help_text_max_length)?; + // The embeddable builder retains a flag-only command when a positional + // declaration is malformed. The standalone CLI reports that configuration error. + Ok(generated + .command + .args(generated.positionals.unwrap_or_default())) +} + +/// Build the standalone generated command and report positional configuration errors. +#[doc(hidden)] +pub fn build_standalone_module_command( + module_def: &apcore::registry::registry::ModuleDescriptor, +) -> Result { + let generated = build_module_command_parts(module_def, crate::schema_parser::HELP_TEXT_MAX_LEN) + .map_err(|error| (error.exit_code(), error.to_string()))?; + let positionals = generated.positionals.map_err(|message| { + ( + crate::EXIT_SCHEMA_CIRCULAR_REF, + format!( + "schema parse error for module '{}': {message}", + module_def.module_id + ), + ) + })?; + Ok(generated.command.args(positionals)) +} + +struct GeneratedModuleCommand { + command: clap::Command, + positionals: Result, String>, +} + +fn build_module_command_parts( + module_def: &apcore::registry::registry::ModuleDescriptor, + help_text_max_length: usize, +) -> Result { let module_id = &module_def.module_id; // Guard: reject reserved command names immediately (FE-13 §4.10). @@ -544,14 +580,14 @@ pub fn build_module_command_with_limit( } let footer = footer_parts.join("\n"); - let mut cmd = add_dispatch_flags(clap::Command::new(module_id.clone()).after_help(footer)); - - // Attach schema-derived args. - for arg in schema_args.args { - cmd = cmd.arg(arg); - } - - Ok(cmd) + let positionals = + crate::schema_parser::generate_positional_args(&resolved_schema, &schema_args.args); + let command = add_dispatch_flags(clap::Command::new(module_id.clone()).after_help(footer)) + .args(schema_args.args); + Ok(GeneratedModuleCommand { + command, + positionals, + }) } // --------------------------------------------------------------------------- @@ -1256,7 +1292,7 @@ fn extract_cli_kwargs( } } - for positional in positional_properties(schema).map_err(|error| error.to_string())? { + for positional in positional_properties(schema).unwrap_or_default() { let explicit = read_scalar_arg(matches, &positional.id); if explicit.is_some() && matches.value_source(positional.name) == Some(clap::parser::ValueSource::CommandLine) @@ -1723,7 +1759,7 @@ async fn run_module_dispatch( collect_input_from_reader_with_limit( Some("-"), cli_inputs.kwargs, - input_limit, + None, source.as_bytes(), ) } diff --git a/cli/rust/src/main.rs b/cli/rust/src/main.rs index 6f356c11..1efcd595 100644 --- a/cli/rust/src/main.rs +++ b/cli/rust/src/main.rs @@ -986,16 +986,18 @@ async fn main() { // If found, build the full command with --a, --b, etc. from input_schema. // If not found, use basic dispatch flags (dispatch_module will exit 44). let temp_cmd = match registry_provider.get_module_descriptor(&external) { - Some(descriptor) => match apcore_cli::build_module_command(&descriptor) { - Ok(cmd) => cmd.no_binary_name(true), - Err(e) => { - // Surface schema-resolution failures with the - // protocol-spec exit code rather than degrading - // silently to an empty command (review #8). - eprintln!("Error: {e}"); - apcore_cli::exit::exit_with(e.exit_code()); + Some(descriptor) => { + match apcore_cli::cli::build_standalone_module_command(&descriptor) { + Ok(cmd) => cmd.no_binary_name(true), + Err((exit_code, message)) => { + // Surface schema-resolution failures with the + // protocol-spec exit code rather than degrading + // silently to an empty command (review #8). + eprintln!("Error: {message}"); + apcore_cli::exit::exit_with(exit_code); + } } - }, + } None => apcore_cli::cli::add_dispatch_flags( clap::Command::new(&external).no_binary_name(true), ), diff --git a/cli/rust/src/schema_parser.rs b/cli/rust/src/schema_parser.rs index 052ce181..23798003 100644 --- a/cli/rust/src/schema_parser.rs +++ b/cli/rust/src/schema_parser.rs @@ -48,8 +48,6 @@ pub enum SchemaParserError { /// Caller must exit 48. #[error("Schema property '{name}' conflicts with built-in CLI flag")] ReservedPropertyName { name: String }, - #[error("{0}")] - InvalidPositional(String), } // --------------------------------------------------------------------------- @@ -180,9 +178,7 @@ pub(crate) struct PositionalProperty<'a> { pub(crate) id: String, } -pub(crate) fn positional_properties( - schema: &Value, -) -> Result>, SchemaParserError> { +pub(crate) fn positional_properties(schema: &Value) -> Result>, String> { let Some(properties) = schema["properties"].as_object() else { return Ok(Vec::new()); }; @@ -195,24 +191,20 @@ pub(crate) fn positional_properties( .as_u64() .filter(|index| *index > 0 && !indexed.contains_key(index)) .ok_or_else(|| { - SchemaParserError::InvalidPositional( - "x-cli-positional indices must be unique positive integers.".into(), - ) + "x-cli-positional indices must be unique positive integers.".to_string() })?; if !matches!( property["type"].as_str(), Some("string" | "integer" | "number") ) { - return Err(SchemaParserError::InvalidPositional(format!( + return Err(format!( "x-cli-positional is only supported on scalar property '{name}'." - ))); + )); } indexed.insert(index, name.as_str()); } if indexed.keys().copied().ne(1..=indexed.len() as u64) { - return Err(SchemaParserError::InvalidPositional( - "x-cli-positional indices must be consecutive starting at 1.".into(), - )); + return Err("x-cli-positional indices must be consecutive starting at 1.".into()); } Ok(indexed .into_iter() @@ -512,26 +504,6 @@ pub fn schema_to_clap_args_with_limit( args.push(arg); } - for (index, positional) in positional_properties(schema)?.into_iter().enumerate() { - let flag = args - .iter() - .find(|arg| arg.get_id().as_str() == positional.name) - .expect("scalar positional property has a matching flag"); - let numeric = matches!( - properties[positional.name]["type"].as_str(), - Some("integer" | "number") - ); - let mut arg = Arg::new(positional.id) - .index(index + 1) - .value_name(prop_name_to_flag_name(positional.name)) - .value_parser(flag.get_value_parser().clone()) - .allow_negative_numbers(numeric); - if let Some(help) = flag.get_help() { - arg = arg.help(help.clone()); - } - args.push(arg); - } - Ok(SchemaArgs { args, bool_pairs, @@ -539,6 +511,33 @@ pub fn schema_to_clap_args_with_limit( }) } +/// Compose generated-command positionals from the existing flag definitions. +pub(crate) fn generate_positional_args(schema: &Value, flags: &[Arg]) -> Result, String> { + positional_properties(schema)? + .into_iter() + .enumerate() + .map(|(index, positional)| { + let flag = flags + .iter() + .find(|arg| arg.get_id().as_str() == positional.name) + .ok_or_else(|| format!("Positional property '{}' has no flag.", positional.name))?; + let numeric = matches!( + schema["properties"][positional.name]["type"].as_str(), + Some("integer" | "number") + ); + let mut arg = Arg::new(positional.id) + .index(index + 1) + .value_name(prop_name_to_flag_name(positional.name)) + .value_parser(flag.get_value_parser().clone()) + .allow_negative_numbers(numeric); + if let Some(help) = flag.get_help() { + arg = arg.help(help.clone()); + } + Ok(arg) + }) + .collect() +} + // --------------------------------------------------------------------------- // reconvert_enum_values // --------------------------------------------------------------------------- @@ -628,11 +627,9 @@ mod tests { json!({"a": {"type": "number", "x-cli-positional": 0}}), json!({"a": {"type": "integer", "x-cli-positional": "1"}}), ] { - let result = schema_to_clap_args(&json!({"properties": properties}), None); - assert!(matches!( - result, - Err(SchemaParserError::InvalidPositional(_)) - )); + let schema = json!({"properties": properties}); + let flags = schema_to_clap_args(&schema, None).unwrap(); + assert!(generate_positional_args(&schema, &flags.args).is_err()); } } diff --git a/cli/rust/tests/test_e2e.rs b/cli/rust/tests/test_e2e.rs index 00487613..f7060df8 100644 --- a/cli/rust/tests/test_e2e.rs +++ b/cli/rust/tests/test_e2e.rs @@ -224,6 +224,25 @@ fn test_e2e_input_byte_limit_precedence() { } } +#[test] +fn test_e2e_inline_json_is_available_with_a_smaller_file_limit() { + for command in [&["math.add"][..], &["apcli", "exec", "math.add"][..]] { + let args: Vec<_> = ["--extensions-dir", "./examples/extensions"] + .into_iter() + .chain(command.iter().copied()) + .chain(["--max-input-bytes", "1", "--input", r#"{"a":1,"b":2}"#]) + .collect(); + let out = run_apcore(&args); + assert_eq!( + out.status.code(), + Some(0), + "{command:?}: {}", + String::from_utf8_lossy(&out.stderr), + ); + assert!(String::from_utf8_lossy(&out.stdout).contains("\"sum\"")); + } +} + #[test] fn test_e2e_unknown_module_exits_44() { let out = run_apcore(&[ @@ -455,6 +474,47 @@ fn script_extensions_dir(script: &str, output_schema: serde_json::Value) -> temp tmp } +#[test] +fn test_e2e_invalid_positional_metadata_only_blocks_the_generated_command() { + let tmp = script_extensions_dir( + "#!/bin/sh\nprintf '{}'", + serde_json::json!({"type": "object"}), + ); + let manifest_path = tmp.path().join("test/script/module.json"); + let mut manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(&manifest_path).unwrap()).unwrap(); + manifest["input_schema"]["properties"]["message"]["x-cli-positional"] = serde_json::json!(2); + std::fs::write(&manifest_path, manifest.to_string()).unwrap(); + let extensions = tmp.path().to_str().unwrap(); + + let generated = run_apcore(&["--extensions-dir", extensions, "test.script", "--help"]); + assert_eq!( + generated.status.code(), + Some(apcore_cli::EXIT_SCHEMA_CIRCULAR_REF) + ); + assert!( + String::from_utf8_lossy(&generated.stderr) + .contains("x-cli-positional indices must be consecutive starting at 1."), + "{}", + String::from_utf8_lossy(&generated.stderr) + ); + let generic = run_apcore(&[ + "--extensions-dir", + extensions, + "apcli", + "exec", + "test.script", + "--input", + r#"{"message":"hello"}"#, + ]); + assert_eq!( + generic.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&generic.stderr) + ); +} + #[test] fn test_e2e_null_exec_result_writes_zero_bytes_to_stdout() { // `format_exec_result` returns "" for a `Value::Null` result (see diff --git a/cli/rust/tests/test_schema_parser.rs b/cli/rust/tests/test_schema_parser.rs index a60c3a66..7e74de33 100644 --- a/cli/rust/tests/test_schema_parser.rs +++ b/cli/rust/tests/test_schema_parser.rs @@ -5,7 +5,7 @@ mod common; use std::collections::HashMap; -use apcore_cli::schema_parser::{reconvert_enum_values, schema_to_clap_args}; +use apcore_cli::schema_parser::{reconvert_enum_values, schema_to_clap_args, SchemaParserError}; use serde_json::{json, Value}; fn find_arg<'a>(args: &'a [clap::Arg], long: &str) -> Option<&'a clap::Arg> { @@ -28,6 +28,17 @@ fn test_schema_to_clap_args_empty_schema() { assert!(result.enum_maps.is_empty()); } +#[test] +fn test_schema_parser_error_is_exhaustive() { + let schema = json!({"properties": {"input": {"type": "string"}}}); + let error = schema_to_clap_args(&schema, None).unwrap_err(); + let name = match error { + SchemaParserError::ReservedPropertyName { name } => name, + SchemaParserError::FlagCollision { flag_name, .. } => flag_name, + }; + assert_eq!(name, "input"); +} + #[test] fn test_schema_to_clap_args_string_property() { let schema = json!({ diff --git a/cli/typescript/src/main.ts b/cli/typescript/src/main.ts index 2920fbdf..1be37003 100644 --- a/cli/typescript/src/main.ts +++ b/cli/typescript/src/main.ts @@ -1169,6 +1169,10 @@ export function buildModuleCommand( const largeInputOpt = new Option("--large-input", "Disable the byte limit for stdin and JSON files.").default(false); const maxInputBytesOpt = new Option("--max-input-bytes ", "Maximum bytes per stdin or JSON file input (default 10 MiB).") .argParser(parseMaxInputBytes); + // Commander normally maps this to maxInputBytes, which can also be a + // module's schema option. Schema attribute names cannot contain hyphens. + const maxInputBytesKey = "--max-input-bytes"; + maxInputBytesOpt.attributeName = () => maxInputBytesKey; const formatOpt = new Option("--format ", "Output format: json, table, csv, yaml, jsonl.") .choices(["json", "table", "csv", "yaml", "jsonl"]); const fieldsOpt = new Option("--fields ", "Comma-separated dot-paths to select from the result (e.g., 'status,data.count')."); @@ -1287,7 +1291,7 @@ export function buildModuleCommand( const stdinFlag = options.input as string | undefined; const autoApprove = options.yes as boolean; const largeInput = options.largeInput as boolean; - const maxInputBytes = options.maxInputBytes as string | undefined; + const maxInputBytes = options[maxInputBytesKey] as string | undefined; const outputFormat = options.format as string | undefined; const outputFields = options.fields as string | undefined; const sandboxEnabled = options.sandbox as boolean; diff --git a/cli/typescript/src/schema-parser.ts b/cli/typescript/src/schema-parser.ts index e36fef92..d52dbcf5 100644 --- a/cli/typescript/src/schema-parser.ts +++ b/cli/typescript/src/schema-parser.ts @@ -5,6 +5,7 @@ */ import { resolve } from "node:path"; +import { InvalidArgumentError } from "commander"; import type { OptionConfig } from "./main.js"; import { EXIT_CODES, InvalidCliInputError, SchemaValidationError } from "./errors.js"; import { exitWith } from "./exit.js"; @@ -94,6 +95,8 @@ function parseStructuredValue(value: string, flag: string, types: readonly strin const POSITIONAL_TYPES = new Set(["string", "integer", "number"]); const SCALAR_ITEM_TYPES = new Set([...POSITIONAL_TYPES, "boolean"]); +const INTEGER_ARGUMENT = /^[+-]?\d+$/u; +const NUMBER_ARGUMENT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u; type SchemaFlag = [option: OptionConfig, key: string]; @@ -101,7 +104,7 @@ export function getPositionalOptions(schema: Record, flags: Sch const properties = (schema.properties ?? {}) as Record>; const byIndex = new Map(); for (const flag of flags) { - const [option] = flag; + const [option, key] = flag; const property = properties[option.name]; if (!Object.hasOwn(property, "x-cli-positional")) continue; const index = property["x-cli-positional"]; @@ -111,7 +114,20 @@ export function getPositionalOptions(schema: Record, flags: Sch if (typeof property.type !== "string" || !POSITIONAL_TYPES.has(property.type)) { throw new SchemaValidationError(`x-cli-positional is only supported on scalar property '${option.name}'.`); } - byIndex.set(index, flag); + if (option.parseArg && (property.type === "integer" || property.type === "number")) { + const integer = property.type === "integer"; + const pattern = integer ? INTEGER_ARGUMENT : NUMBER_ARGUMENT; + const parseArg = (value: string): number => { + const number = Number(value); + if (!pattern.test(value) || !(integer ? Number.isSafeInteger(number) : Number.isFinite(number))) { + throw new InvalidArgumentError(integer ? "Expected an integer." : "Expected a finite number."); + } + return number; + }; + byIndex.set(index, [{ ...option, parseArg }, key]); + } else { + byIndex.set(index, flag); + } } const positionals: SchemaFlag[] = []; for (let index = 1; index <= byIndex.size; index += 1) { diff --git a/cli/typescript/src/security/device-login.ts b/cli/typescript/src/security/device-login.ts index 6f4146dd..a23423f1 100644 --- a/cli/typescript/src/security/device-login.ts +++ b/cli/typescript/src/security/device-login.ts @@ -1,4 +1,4 @@ -import { execFile } from "node:child_process"; +import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { DeviceAuthClient, @@ -142,7 +142,9 @@ function openBrowser(url: string): void { : process.platform === "win32" ? ["rundll32.exe", "url.dll,FileProtocolHandler", url] : ["xdg-open", url]; - execFile(program, args, () => { /* Manual instructions are already visible. */ }).unref(); + const browser = spawn(program, args, { detached: true, stdio: "ignore" }); + browser.once("error", () => { /* Manual instructions are already visible. */ }); + browser.unref(); } export function registerLoginCommand(apcli: Command): void { diff --git a/cli/typescript/tests/device-login.test.ts b/cli/typescript/tests/device-login.test.ts index 3c2a3313..161ecd11 100644 --- a/cli/typescript/tests/device-login.test.ts +++ b/cli/typescript/tests/device-login.test.ts @@ -1,3 +1,4 @@ +import * as childProcess from "node:child_process"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -9,6 +10,8 @@ import { AuthProvider } from "../src/security/auth.js"; import { _setKeytarForTesting } from "../src/security/config-encryptor.js"; import { createDeviceAuthClient } from "../src/security/device-login.js"; +vi.mock("node:child_process", { spy: true }); + describe("device login", () => { let dir: string; let configPath: string; @@ -45,7 +48,7 @@ describe("device login", () => { obtainedAt: 0, }); - it("prints the verification address and code on stderr without printing tokens", async () => { + it.each([true, false])("prints verification instructions without printing tokens (manual=%s)", async (manual) => { const settings = new ConfigResolver(undefined, configPath).resolveObject("auth.device"); const resolveObject = ConfigResolver.prototype.resolveObject; vi.spyOn(ConfigResolver.prototype, "resolveObject").mockImplementation(function (this: ConfigResolver, key) { @@ -61,13 +64,25 @@ describe("device login", () => { }); return tokens; }); + const browser = { once: vi.fn(), unref: vi.fn() }; + const launch = vi.spyOn(childProcess, "spawn").mockReturnValue(browser as unknown as childProcess.ChildProcess); const cli = await createCli(); - await cli.parseAsync(["apcli", "login", "--no-browser"], { from: "user" }); + await cli.parseAsync(["apcli", "login", ...(manual ? ["--no-browser"] : [])], { from: "user" }); const output = stderr.mock.calls.map(([chunk]) => String(chunk)).join(""); expect(output).toContain("https://auth.example.test/verify"); expect(output).toContain("TEST-CODE"); expect(output).not.toContain("test-access-secret"); expect(output).not.toContain("test-refresh-secret"); + if (manual) { + expect(launch).not.toHaveBeenCalled(); + } else { + expect(launch).toHaveBeenCalledWith( + expect.any(String), + expect.arrayContaining(["https://auth.example.test/verify"]), + { detached: true, stdio: "ignore" }, + ); + expect(browser.unref).toHaveBeenCalledOnce(); + } }); it("uses the device client's validated token for requests", async () => { diff --git a/cli/typescript/tests/structured-flags.test.ts b/cli/typescript/tests/structured-flags.test.ts index 327e5fae..eea86632 100644 --- a/cli/typescript/tests/structured-flags.test.ts +++ b/cli/typescript/tests/structured-flags.test.ts @@ -62,6 +62,31 @@ async function invoke(args: string[], inputSchema = fixture.schema, generic = fa } describe("structured generated flags", () => { + it("keeps a schema maxInputBytes flag independent from the built-in limit", async () => { + const schema = { + type: "object", + properties: { maxInputBytes: { type: "string" } }, + required: ["maxInputBytes"], + }; + const named = await invoke(["--maxInputBytes", "normal-text", "--max-input-bytes", "99"], schema); + expect(named.inputs).toEqual([{ maxInputBytes: "normal-text" }]); + expect((await invoke(["--max-input-bytes", "99"], schema)).inputs).toEqual([]); + }); + + it.each([ + ["integer", "10.5"], + ["integer", "19x"], + ["number", "19x"], + ["number", "1e1000"], + ])("rejects a positional %s that cannot be parsed in full (%s)", async (type, value) => { + const schema = { + type: "object", + properties: { count: { type, "x-cli-positional": 1 } }, + required: ["count"], + }; + await expect(invoke([value], schema)).rejects.toMatchObject({ code: "commander.invalidArgument" }); + }); + it.each(fixture.test_cases)("$id", async ({ args, expected }) => { const result = await invoke(args); expect(result.exitCode).toBe(expected.exit_code); diff --git a/mcp/docs/features/async-task-bridge.md b/mcp/docs/features/async-task-bridge.md index cb2a3a05..bae43be8 100644 --- a/mcp/docs/features/async-task-bridge.md +++ b/mcp/docs/features/async-task-bridge.md @@ -225,20 +225,20 @@ This asymmetry is structural, not behavioral: when porting modules between langu ## Contract: AsyncTaskBridge.handle_preview -> Handler for the `__apcore_module_preview` meta-tool introduced in 0.15.0. Renders a non-executing preview of a module's input schema, description, and metadata so agents can decide whether to invoke before paying the cost of an actual call. +> Handler for the `__apcore_module_preview` meta-tool introduced in 0.15.0. Runs Core preflight for the intended module arguments and caller context. ### Inputs - module_id: str, required, validates[non-empty string, not starting with `__apcore_`], reject_with=error tuple - arguments: dict[str, Any] | None, optional — preserved as-is in the preview envelope when null (distinguishing "no arguments supplied" from "empty object supplied") -- version_hint: str | None, optional — forwarded to descriptor lookup +- On Python, the request's `_meta.apcore.version` selects a version as for the planned tool call. The configured version default applies when this metadata is omitted. ### Errors -- Returns `(content, is_error=True, None)` with `{"error": "PREVIEW_UNAVAILABLE", "module_id": ...}` — when descriptor cannot be resolved OR module does not support preview +- Returns a `PREVIEW_UNAVAILABLE` JSON error when the validation handler is missing or Python cannot preview the selected tool version - Returns `(content, is_error=True, None)` with `{"error": "MODULE_NOT_FOUND", "module_id": ...}` — when registry has no descriptor for module_id - Returns error tuple — when module_id is empty or starts with reserved `__apcore_` prefix ### Returns -- On success: tuple `(list[dict], bool, str|None)` — content contains `{"module_id": str, "input_schema": dict, "description": str, "annotations": dict, "arguments": dict | None}`; `arguments` field reflects the input verbatim (null preserved as null, not coerced to empty object) +- On success, text content contains JSON with `valid`, `requires_approval`, `predicted_changes`, and `checks`. - On failure: returns error tuple (never raises) ### Properties diff --git a/mcp/docs/features/mcp-server-factory.md b/mcp/docs/features/mcp-server-factory.md index cde2ce64..56baeb07 100644 --- a/mcp/docs/features/mcp-server-factory.md +++ b/mcp/docs/features/mcp-server-factory.md @@ -334,6 +334,14 @@ extension in `initialize` when its module preview tool is available. Clients can call `previewTool` with the target `module_id`, the intended `arguments`, and the same authenticated session as the planned call. Read `requires_approval` on a successful preflight to show the server's current assessment. The server still enforces current policy during execution. +When a TypeScript tool is published under an alias, its `tools/list` entry includes +`_meta.apcore.moduleId` for use as the preview's `module_id`. + +On Python, send the same `_meta.apcore.version` as the planned call if it has an explicit +version hint. For caller-visible modules, preview uses the same configured default. An +incompatible published contract or a hint for a module outside the caller's discovery scope +returns `PREVIEW_UNAVAILABLE`. Preview results retain their JSON format even when tool execution +uses a custom output formatter. The capability depends on the preview tool and its Core validation handler. It applies to servers with or without management resources, and conveys no information about the loaded ACL or the diff --git a/mcp/python/src/apcore_mcp/server/async_task_bridge.py b/mcp/python/src/apcore_mcp/server/async_task_bridge.py index b08241c1..d35b37ac 100644 --- a/mcp/python/src/apcore_mcp/server/async_task_bridge.py +++ b/mcp/python/src/apcore_mcp/server/async_task_bridge.py @@ -622,7 +622,8 @@ async def _handle_preview_tool( # internally drives an event loop via _run_async_in_sync. import asyncio as _asyncio - result = await _asyncio.to_thread(executor.validate, module_id, raw_args, context) + options = {"version_hint": extra["version_hint"]} if extra.get("_mcp_wire_version") is True else {} + result = await _asyncio.to_thread(executor.validate, module_id, raw_args, context, **options) return self._text_response(_preflight_to_dict(result)) # ── Helpers ───────────────────────────────────────────────────────── diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 039ef7d3..912268dc 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -31,7 +31,12 @@ from apcore_mcp.auth.middleware import _REQUEST_IDENTITY_KEY, auth_identity_var from apcore_mcp.server.approval_bridge import ApprovalBridge, _approval_response_log, _protect_sdk_approval_logs from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge -from apcore_mcp.server.router import ExecutionRouter, _descriptor_version_hint, _matches_registered_version +from apcore_mcp.server.router import ( + ExecutionRouter, + _descriptor_version_hint, + _matches_registered_version, + _request_version_hint, +) from apcore_mcp.server.transport import _protocol_source_var, _scoped_sse_request, transport_session_var logger = logging.getLogger(__name__) @@ -598,6 +603,7 @@ def register_handlers( regular_tool_ids = {id(tool) for tool in tools} captured_sources = discovery_sources or {} caller_aware = isinstance(router, ExecutionRouter) and router.supports_capability_discovery + async_enabled = async_bridge is not None and descriptor_lookup is not None def visible_tool(tool: mcp_types.Tool, identity: Identity | None) -> mcp_types.Tool | None: if not caller_aware or id(tool) not in regular_tool_ids: @@ -612,6 +618,39 @@ def visible_tool(tool: mcp_types.Tool, identity: Identity | None) -> mcp_types.T return None return live_tool if live_tool.name == tool.name else None + def published_tool(name: str) -> mcp_types.Tool | None: + return next((tool for tool in reversed(combined_tools) if tool.name == name), None) + + def bind_preview_version(module_id: str, extra: dict[str, Any], identity: Identity | None) -> bool: + if not isinstance(router, ExecutionRouter): + return True + published = published_tool(module_id) + if published is not None and id(published) in regular_tool_ids: + live_tool = visible_tool(published, identity) + if live_tool is not None: + return self._bind_requested_version( + router, live_tool, extra, async_enabled=async_enabled, + ) is None + + # An undiscoverable target must not disclose whether a hinted + # version exists. Preserve the unhinted Core preflight response. + if caller_aware and router.callable_descriptor(module_id, identity, tool_default=True) is None: + return _request_version_hint(extra) is None + + # A visible canonical ID may be missing from the published list + # due to a server-side prefix or tag filter. + try: + selection = router._select_wire_version(module_id, extra) + except ModuleError: + return False + if selection is not None: + selected, _, can_pin = selection + if not can_pin: + return False + extra["version_hint"] = selected.version + extra["_mcp_wire_version"] = True + return True + @server.list_tools() async def handle_list_tools() -> list[mcp_types.Tool]: identity = _request_identity() @@ -659,7 +698,7 @@ async def send_notification(notification: dict[str, Any]) -> None: extra["send_notification"] = send_notification extra["progress_token"] = progress_token - published = next((tool for tool in reversed(combined_tools) if tool.name == name), None) + published = published_tool(name) regular_tool = published is not None and id(published) in regular_tool_ids if published is not None and caller_aware: live_tool = visible_tool(published, identity) @@ -675,7 +714,7 @@ async def send_notification(notification: dict[str, Any]) -> None: router, published, extra, - async_enabled=async_bridge is not None and descriptor_lookup is not None, + async_enabled=async_enabled, ) if error is not None: return _build_call_result([mcp_types.TextContent(type="text", text=error)], True, None) @@ -714,6 +753,19 @@ async def send_notification(notification: dict[str, Any]) -> None: pending_approval = None # Meta-tool route: handled entirely by the async bridge. if async_bridge is not None and async_meta_tool: + module_id = arguments.get("module_id") if arguments else None + if ( + name == "__apcore_module_preview" + and isinstance(module_id, str) + and module_id + and not module_id.startswith(RESERVED_PREFIX) + and not bind_preview_version(module_id, extra, identity) + ): + error = json.dumps({ + "error": "PREVIEW_UNAVAILABLE", + "message": "The requested module version cannot be previewed.", + }) + return _build_call_result([mcp_types.TextContent(type="text", text=error)], True, None) content, is_error, _trace_id = await async_bridge.handle_meta_tool( name, arguments or {}, diff --git a/mcp/python/tests/server/test_versioned_tool_wire.py b/mcp/python/tests/server/test_versioned_tool_wire.py index 8107f2ca..ed42ed85 100644 --- a/mcp/python/tests/server/test_versioned_tool_wire.py +++ b/mcp/python/tests/server/test_versioned_tool_wire.py @@ -8,7 +8,7 @@ import anyio import pytest -from apcore import Executor, Registry +from apcore import ACL, ACLRule, Executor, Registry from mcp import ClientSession, types from apcore_mcp import APCoreMCP @@ -38,7 +38,7 @@ async def execute(self, inputs, context) -> dict[str, int]: @asynccontextmanager -async def connected_client(registry: Registry, **options) -> AsyncIterator[ClientSession]: +async def connected_client(registry: Registry | Executor, **options) -> AsyncIterator[ClientSession]: server, _, _, init, _ = APCoreMCP(registry, **options)._build_server_components() send_client, read_server = anyio.create_memory_object_stream(10) send_server, read_client = anyio.create_memory_object_stream(10) @@ -138,6 +138,86 @@ async def test_configured_default_uses_its_advertised_contract() -> None: assert (older.calls, current.calls) == (0, 0) +async def test_preview_follows_the_approval_contract_of_the_selected_tool_version() -> None: + registry = Registry() + older = Report("count", 1) + older.annotations = {"requires_approval": True} + current = Report("count", 2) + current.annotations = {"requires_approval": False} + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, current, version="2.0.0", metadata={"version_hint": "^1.0"}) + preview_args = {"module_id": _MODULE, "arguments": {}} + + async with connected_client(registry) as session: + published = next(tool for tool in (await session.list_tools()).tools if tool.name == _MODULE) + assert published.meta["requiresApproval"] is True + for meta in (None, {"apcore": {"version": "^1.0"}}): + preview = await session.call_tool("__apcore_module_preview", preview_args, meta=meta) + assert not preview.isError + result = json.loads(preview.content[0].text) + assert result["valid"] is True + assert result["requires_approval"] is True + called = await session.call_tool(_MODULE, {}, meta=meta) + assert called.isError + assert "approval" in called.content[0].text.lower() + + newer_hint = {"apcore": {"version": "^2.0"}} + preview = await session.call_tool("__apcore_module_preview", preview_args, meta=newer_hint) + called = await session.call_tool(_MODULE, {}, meta=newer_hint) + assert preview.isError + assert json.loads(preview.content[0].text)["error"] == "PREVIEW_UNAVAILABLE" + assert called.isError + assert "does not match the advertised tool contract" in called.content[0].text + + assert (older.calls, current.calls) == (0, 0) + + +async def test_denied_preview_does_not_disclose_which_versions_are_registered() -> None: + registry = Registry() + registry.register(_MODULE, Report("count", 1), version="1.0.0") + registry.register(_MODULE, Report("count", 2), version="2.0.0") + executor = Executor( + registry=registry, + acl=ACL( + [ACLRule(callers=["*"], targets=[_MODULE], effect="deny")], + default_effect="allow", + ), + ) + + async with connected_client(executor) as session: + assert all(tool.name != _MODULE for tool in (await session.list_tools()).tools) + available = await session.call_tool( + "__apcore_module_preview", {"module_id": _MODULE}, meta={"apcore": {"version": "^1.0"}}, + ) + unavailable = await session.call_tool( + "__apcore_module_preview", {"module_id": _MODULE}, meta={"apcore": {"version": "^3.0"}}, + ) + unhinted = await session.call_tool("__apcore_module_preview", {"module_id": _MODULE}) + + assert available.isError is unavailable.isError is True + assert available.content == unavailable.content + assert json.loads(available.content[0].text)["error"] == "PREVIEW_UNAVAILABLE" + assert not unhinted.isError + assert json.loads(unhinted.content[0].text)["valid"] is False + + +async def test_visible_canonical_preview_uses_version_even_when_omitted_by_prefix() -> None: + registry = Registry() + older = Report("count", 1) + older.annotations = {"requires_approval": True} + registry.register(_MODULE, older, version="1.0.0") + registry.register(_MODULE, Report("count", 2), version="2.0.0") + + async with connected_client(registry, prefix="different.") as session: + assert all(tool.name != _MODULE for tool in (await session.list_tools()).tools) + preview = await session.call_tool( + "__apcore_module_preview", {"module_id": _MODULE}, meta={"apcore": {"version": "^1.0"}}, + ) + + assert not preview.isError + assert json.loads(preview.content[0].text)["requires_approval"] is True + + async def test_background_hint_reports_unavailable_before_submission() -> None: registry = Registry() report = Report("count", 2) diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index 7bb25701..88a34ad8 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -644,23 +644,30 @@ export class MCPServerFactory { private _visibleTools( tools: readonly Tool[], - resolve: (moduleId: string, versionHint?: string) => ModuleDescriptor | null, + resolve?: (moduleId: string, versionHint?: string) => ModuleDescriptor | null, ): Tool[] { const visible: Tool[] = []; for (const tool of tools) { const source = this._toolSources.get(tool); - if (!source && tool.name.startsWith(APCORE_META_TOOL_PREFIX)) { - visible.push(tool); - continue; + const moduleId = source?.moduleId ?? tool.name; + let listed = tool; + if (resolve && (source || !tool.name.startsWith(APCORE_META_TOOL_PREFIX))) { + const descriptor = resolve(moduleId, source?.versionHint); + if (descriptor === null) continue; + try { + // Keep the registered MCP name while projecting the live definition. + listed = { ...this.buildTool(descriptor), name: tool.name }; + } catch { + // A replacement may no longer have an MCP-compatible schema. + continue; + } } - const descriptor = resolve(source?.moduleId ?? tool.name, source?.versionHint); - if (descriptor === null) continue; - try { - // Keep the registered MCP name while projecting the live definition. - visible.push({ ...this.buildTool(descriptor), name: tool.name }); - } catch { - // A replacement may no longer have an MCP-compatible schema. + if (moduleId !== listed.name) { + // Describe the exact canonical target used by the aliased tools/call + // after the caller-specific visibility check above. + listed = { ...listed, _meta: { ...listed._meta, apcore: { moduleId } } }; } + visible.push(listed); } return visible; } @@ -698,7 +705,7 @@ export class MCPServerFactory { // Handle tools/list requests server.setRequestHandler(ListToolsRequestSchema, async (_request, extra) => { const resolve = router.discoveryResolver?.(); - const visibleTools = resolve ? this._visibleTools(allTools, resolve) : allTools; + const visibleTools = this._visibleTools(allTools, resolve); const listedTools = supportsStructuredOutput(server, extra) ? visibleTools : visibleTools.map(tool => { const { outputSchema: _outputSchema, ...legacyTool } = tool; return legacyTool; diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index 06f8228d..6c3a8c68 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -24,7 +24,7 @@ import type { ElicitResult } from "../helpers.js"; import { getCurrentIdentity } from "../auth/storage.js"; import type { Identity } from "../auth/types.js"; import { parseTraceparent } from "./trace-context.js"; -import type { AsyncTaskBridge } from "./async-task-bridge.js"; +import { META_TOOL_NAMES, type AsyncTaskBridge } from "./async-task-bridge.js"; /** Maximum recursion depth for deep merge to prevent stack overflow. */ const DEEP_MERGE_MAX_DEPTH = 32; @@ -614,7 +614,12 @@ export class ExecutionRouter { extra?.sessionId, ); const content: TextContentDict[] = [ - { type: "text", text: await this._formatResult(metaResult) }, + { + type: "text", + text: toolName === META_TOOL_NAMES.PREVIEW + ? JSON.stringify(metaResult) + : await this._formatResult(metaResult), + }, ]; return [content, false, effectiveTraceId]; } catch (err: unknown) { diff --git a/mcp/typescript/tests/acl-approval-gating-e2e.test.ts b/mcp/typescript/tests/acl-approval-gating-e2e.test.ts index 1b881453..47bff256 100644 --- a/mcp/typescript/tests/acl-approval-gating-e2e.test.ts +++ b/mcp/typescript/tests/acl-approval-gating-e2e.test.ts @@ -31,6 +31,7 @@ import { ExecutionRouter } from "../src/server/router.js"; import { MCPServerFactory } from "../src/server/factory.js"; const MODULE_ID = "files.delete"; +const TOOL_ALIAS = "delete-file"; /** A module that asks for no approval on its own account. */ class DeleteModule { @@ -76,11 +77,12 @@ class RecordingApprovalHandler { } /** A real executor whose only approval source is an argument-scoped ACL rule. */ -async function buildExecutor() { +async function buildExecutor(alias?: string) { const apcore = await import("apcore-js"); const registry = new apcore.Registry(); - registry.register(MODULE_ID, new DeleteModule() as never); + await registry.register(MODULE_ID, new DeleteModule() as never, undefined, + alias ? { display: { mcp: { alias } } } : undefined); const acl = new apcore.ACL( [ @@ -143,9 +145,12 @@ describe("ACL-sourced approval gating over a real tools/call", () => { }); it.each([true, false])("advertises approval preflight when available (async tasks: %s)", async (enabled) => { - const { executor, handler, registry } = await buildExecutor(); + const { executor, handler, registry } = await buildExecutor(TOOL_ALIAS); const bridge = enabled ? await createAsyncTaskBridge(executor, { enabled: true }) : null; - const router = new ExecutionRouter(executor as never, { asyncTaskBridge: bridge ?? undefined }); + const router = new ExecutionRouter(executor as never, { + asyncTaskBridge: bridge ?? undefined, + outputFormatter: () => '{"formatted":true}', + }); const factory = new MCPServerFactory(); const server = factory.createServer("test", "1.0.0", { health: true, usage: false, manifest: false, control: false, @@ -162,23 +167,29 @@ describe("ACL-sourced approval gating over a real tools/call", () => { expect(extensions?.["com.aiperceivable/management"]).toBeDefined(); const preflight = extensions?.["com.aiperceivable/approval-preflight"]; const { tools } = await client.listTools(); - expect(tools.find(tool => tool.name === MODULE_ID)?._meta?.requiresApproval).not.toBe(true); + const tool = tools.find(candidate => candidate.name === TOOL_ALIAS); + expect(tool?._meta?.requiresApproval).not.toBe(true); + expect(tool?._meta?.apcore).toEqual({ moduleId: MODULE_ID }); + const { moduleId } = tool!._meta!.apcore as { moduleId: string }; expect(tools.some(tool => tool.name === "__apcore_module_preview")).toBe(enabled); if (enabled) { expect(preflight).toEqual({ toolListApproval: "static", previewTool: "__apcore_module_preview" }); for (const [args, expected] of [[{ path: "/tmp/x", recursive: true }, true], [{ path: "/tmp/x" }, false]] as const) { const result = await client.callTool({ name: preflight!.previewTool as string, - arguments: { module_id: MODULE_ID, arguments: args }, + arguments: { module_id: moduleId, arguments: args }, }); expect(result.isError).not.toBe(true); const content = result.content as { text: string }[]; expect(JSON.parse(content[0].text).requires_approval).toBe(expected); + expect(result.structuredContent).toMatchObject({ valid: true, requires_approval: expected }); } } else { expect(preflight).toBeUndefined(); } expect(handler.requests).toEqual([]); + const called = await client.callTool({ name: TOOL_ALIAS, arguments: { path: "/tmp/x" } }); + expect(called.structuredContent).toEqual({ formatted: true }); } finally { await client.close(); await server.close();