Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion cli/conformance/fixtures/structured_flags.json
Original file line number Diff line number Diff line change
Expand Up @@ -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" } },
Expand All @@ -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\"]"],
Expand Down
1 change: 1 addition & 0 deletions cli/docs/features/builtin-group.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>` | `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

Expand Down
12 changes: 11 additions & 1 deletion cli/docs/features/core-dispatcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`.
Expand Down
22 changes: 22 additions & 0 deletions cli/docs/features/schema-parser.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 33 additions & 4 deletions cli/docs/features/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)

---

Expand Down Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions cli/python/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
20 changes: 20 additions & 0 deletions cli/python/src/apcore_cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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",
)
Expand Down
1 change: 1 addition & 0 deletions cli/python/src/apcore_cli/builtin_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class ApcliConfig(TypedDict, total=False):
# the canonical set from 13 to 15.
"acl",
"openapi",
"login",
}
)

Expand Down
49 changes: 36 additions & 13 deletions cli/python/src/apcore_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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,
)
)
Expand Down Expand Up @@ -1156,6 +1174,7 @@ async def _do_stream() -> None:
"input",
"yes",
"large_input",
"max_input_bytes",
"format",
"fields",
"sandbox",
Expand All @@ -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

Expand Down Expand Up @@ -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}
Expand All @@ -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

Expand Down
9 changes: 2 additions & 7 deletions cli/python/src/apcore_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 9 additions & 1 deletion cli/python/src/apcore_cli/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading