|
| 1 | +"""Raw REST passthrough: `cycode platform api <METHOD> <PATH>`. |
| 2 | +
|
| 3 | +Lets scripts call any Cycode REST endpoint without handling credentials themselves. |
| 4 | +The CLI resolves credentials (client id/secret or OIDC, from flags, environment |
| 5 | +variables, or `cycode auth`), mints and refreshes the access token, and prints the |
| 6 | +response body. Tokens and secrets are never printed. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import re |
| 11 | +import sys |
| 12 | +from typing import TYPE_CHECKING, Any, Optional, Union |
| 13 | + |
| 14 | +import click |
| 15 | + |
| 16 | +from cycode.logger import get_logger |
| 17 | + |
| 18 | +if TYPE_CHECKING: |
| 19 | + from requests import Response |
| 20 | + |
| 21 | +logger = get_logger('Raw API Command') |
| 22 | + |
| 23 | +_SUPPORTED_METHODS = ('get', 'post', 'put') |
| 24 | +_METHODS_WITH_BODY = ('post', 'put') |
| 25 | +# Allowlist: a versioned API path such as `v4/projects` or `api/v4/auth/api-token`. |
| 26 | +# Anything else (full URLs, protocol-relative paths, paths with whitespace) is rejected. |
| 27 | +_API_PATH_RE = re.compile(r'^(api/)?v4/\S+$') |
| 28 | + |
| 29 | +_HELP = """[BETA] Send a raw authenticated request to the Cycode API. |
| 30 | +
|
| 31 | +METHOD is one of get, post, put. PATH is an API path such as `v4/projects` |
| 32 | +(a leading slash is optional). |
| 33 | +
|
| 34 | +Credentials come from the CLI: `cycode auth`, the CYCODE_CLIENT_ID/CYCODE_CLIENT_SECRET |
| 35 | +(or CYCODE_ID_TOKEN) environment variables, or the global `--client-id`/`--client-secret`/ |
| 36 | +`--id-token` options. Your credentials and access token are never printed. |
| 37 | +
|
| 38 | +\b |
| 39 | +Examples: |
| 40 | + cycode platform api get v4/projects -q page-size=5 |
| 41 | + cycode platform api get v4/violations -q severity=High -q severity=Critical |
| 42 | + cycode platform api post v4/sbom/import -d @body.json |
| 43 | + cat body.json | cycode platform api put v4/some/resource -d - |
| 44 | +""" |
| 45 | + |
| 46 | + |
| 47 | +def _validate_path(path: str) -> str: |
| 48 | + """Validate that PATH is a versioned API path, so credentials only reach the configured Cycode host.""" |
| 49 | + url_path = path.lstrip('/') |
| 50 | + if not _API_PATH_RE.match(url_path): |
| 51 | + raise click.ClickException(f'PATH must be a versioned API path such as `v4/projects`, not `{path}`.') |
| 52 | + |
| 53 | + return url_path |
| 54 | + |
| 55 | + |
| 56 | +def _parse_query(query: tuple[str, ...]) -> dict[str, Union[str, list[str]]]: |
| 57 | + """Parse repeatable `key=value` pairs. Repeated keys collapse into a list.""" |
| 58 | + params: dict[str, Union[str, list[str]]] = {} |
| 59 | + for item in query: |
| 60 | + key, sep, value = item.partition('=') |
| 61 | + if not sep or not key: |
| 62 | + raise click.ClickException(f'Invalid query parameter "{item}". Expected format: key=value') |
| 63 | + |
| 64 | + if key in params: |
| 65 | + existing = params[key] |
| 66 | + if isinstance(existing, list): |
| 67 | + existing.append(value) |
| 68 | + else: |
| 69 | + params[key] = [existing, value] |
| 70 | + else: |
| 71 | + params[key] = value |
| 72 | + |
| 73 | + return params |
| 74 | + |
| 75 | + |
| 76 | +def _parse_headers(header: tuple[str, ...]) -> dict[str, str]: |
| 77 | + """Parse repeatable `Key: Value` pairs.""" |
| 78 | + headers: dict[str, str] = {} |
| 79 | + for item in header: |
| 80 | + key, sep, value = item.partition(':') |
| 81 | + key = key.strip() |
| 82 | + if not sep or not key: |
| 83 | + raise click.ClickException(f'Invalid header "{item}". Expected format: "Key: Value"') |
| 84 | + |
| 85 | + if key.lower() == 'authorization': |
| 86 | + raise click.ClickException('The Authorization header is managed by the CLI and cannot be overridden.') |
| 87 | + |
| 88 | + headers[key] = value.strip() |
| 89 | + |
| 90 | + return headers |
| 91 | + |
| 92 | + |
| 93 | +def _read_body(data: str) -> Any: |
| 94 | + """Read the request body from an inline JSON string, `@file`, or `-` (stdin).""" |
| 95 | + if data == '-': |
| 96 | + raw = sys.stdin.read() |
| 97 | + source = 'stdin' |
| 98 | + elif data.startswith('@'): |
| 99 | + file_path = data[1:] |
| 100 | + try: |
| 101 | + with open(file_path, encoding='utf-8') as f: |
| 102 | + raw = f.read() |
| 103 | + except OSError as e: |
| 104 | + raise click.ClickException(f'Could not read request body file "{file_path}": {e}') from e |
| 105 | + source = file_path |
| 106 | + else: |
| 107 | + raw = data |
| 108 | + source = 'the --data value' |
| 109 | + |
| 110 | + try: |
| 111 | + return json.loads(raw) |
| 112 | + except json.JSONDecodeError as e: |
| 113 | + raise click.ClickException(f'Could not parse JSON from {source}: {e}') from e |
| 114 | + |
| 115 | + |
| 116 | +def _echo_response_body(response: 'Response') -> None: |
| 117 | + try: |
| 118 | + click.echo(json.dumps(response.json(), indent=2)) |
| 119 | + except ValueError: |
| 120 | + # Not a JSON body (empty response, plain text, file download, etc.) |
| 121 | + click.echo(response.text) |
| 122 | + |
| 123 | + |
| 124 | +def _callback( |
| 125 | + method: str, |
| 126 | + path: str, |
| 127 | + query: tuple[str, ...], |
| 128 | + header: tuple[str, ...], |
| 129 | + data: Optional[str], |
| 130 | + timeout: Optional[int], |
| 131 | +) -> None: |
| 132 | + from cycode.cli.exceptions.custom_exceptions import RequestHttpError |
| 133 | + from cycode.cli.utils.get_api_client import get_raw_api_client |
| 134 | + |
| 135 | + method = method.lower() |
| 136 | + url_path = _validate_path(path) |
| 137 | + params = _parse_query(query) |
| 138 | + headers = _parse_headers(header) |
| 139 | + |
| 140 | + body = None |
| 141 | + if data is not None: |
| 142 | + if method not in _METHODS_WITH_BODY: |
| 143 | + raise click.ClickException(f'--data is not supported for the {method} method.') |
| 144 | + body = _read_body(data) |
| 145 | + |
| 146 | + ctx = click.get_current_context() |
| 147 | + client = get_raw_api_client(ctx.find_root()) |
| 148 | + |
| 149 | + kwargs: dict[str, Any] = {'headers': headers or None, 'params': params or None} |
| 150 | + if timeout is not None: |
| 151 | + kwargs['timeout'] = timeout |
| 152 | + |
| 153 | + logger.debug('Sending raw API request, %s', {'method': method, 'path': url_path}) |
| 154 | + |
| 155 | + try: |
| 156 | + if method == 'get': |
| 157 | + response = client.get(url_path, **kwargs) |
| 158 | + elif method == 'post': |
| 159 | + response = client.post(url_path, body=body, **kwargs) |
| 160 | + else: |
| 161 | + response = client.put(url_path, body=body, **kwargs) |
| 162 | + except RequestHttpError as e: |
| 163 | + click.echo(f'HTTP {e.status_code}: {e.error_message}', err=True) |
| 164 | + raise click.exceptions.Exit(1) from e |
| 165 | + except Exception as e: |
| 166 | + click.echo(f'Error: {e}', err=True) |
| 167 | + raise click.exceptions.Exit(1) from e |
| 168 | + |
| 169 | + _echo_response_body(response) |
| 170 | + |
| 171 | + |
| 172 | +def build_raw_api_command() -> click.Command: |
| 173 | + """Build the `cycode platform api` raw request command.""" |
| 174 | + return click.Command( |
| 175 | + name='api', |
| 176 | + callback=_callback, |
| 177 | + help=_HELP, |
| 178 | + short_help='[BETA] Send a raw authenticated request to the Cycode API.', |
| 179 | + params=[ |
| 180 | + click.Argument(['method'], type=click.Choice(_SUPPORTED_METHODS, case_sensitive=False), required=True), |
| 181 | + click.Argument(['path'], type=click.STRING, required=True), |
| 182 | + click.Option( |
| 183 | + ['-q', '--query'], |
| 184 | + multiple=True, |
| 185 | + metavar='KEY=VALUE', |
| 186 | + help='Query parameter. Repeatable; repeating a key sends multiple values.', |
| 187 | + ), |
| 188 | + click.Option( |
| 189 | + ['-H', '--header'], |
| 190 | + multiple=True, |
| 191 | + metavar='"KEY: VALUE"', |
| 192 | + help='Additional request header. Repeatable. Authorization is managed by the CLI.', |
| 193 | + ), |
| 194 | + click.Option( |
| 195 | + ['-d', '--data'], |
| 196 | + metavar='JSON', |
| 197 | + help='JSON request body for post/put. Use @file to read a file, or - to read stdin.', |
| 198 | + ), |
| 199 | + click.Option( |
| 200 | + ['--timeout'], |
| 201 | + type=click.INT, |
| 202 | + help='Request timeout in seconds. Defaults to the CLI request timeout.', |
| 203 | + ), |
| 204 | + ], |
| 205 | + ) |
0 commit comments