cerbia-cli 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cerbia_cli-0.2.0/LICENSE +73 -0
- cerbia_cli-0.2.0/NOTICE +13 -0
- cerbia_cli-0.2.0/PKG-INFO +39 -0
- cerbia_cli-0.2.0/README.md +10 -0
- cerbia_cli-0.2.0/pyproject.toml +48 -0
- cerbia_cli-0.2.0/src/cerbia/cli/__init__.py +27 -0
- cerbia_cli-0.2.0/src/cerbia/cli/__main__.py +4 -0
- cerbia_cli-0.2.0/src/cerbia/cli/config.py +54 -0
- cerbia_cli-0.2.0/src/cerbia/cli/logging.py +54 -0
- cerbia_cli-0.2.0/src/cerbia/cli/py.typed +0 -0
- cerbia_cli-0.2.0/src/cerbia/cli/scan/__init__.py +3 -0
- cerbia_cli-0.2.0/src/cerbia/cli/scan/_command.py +124 -0
- cerbia_cli-0.2.0/src/cerbia/cli/scan/_data.py +23 -0
- cerbia_cli-0.2.0/src/cerbia/cli/scan/_ui.py +85 -0
- cerbia_cli-0.2.0/src/cerbia/cli/validate/__init__.py +3 -0
- cerbia_cli-0.2.0/src/cerbia/cli/validate/_command.py +50 -0
- cerbia_cli-0.2.0/src/cerbia/cli/validate/_ui.py +38 -0
cerbia_cli-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
cerbia_cli-0.2.0/NOTICE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.)
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cerbia-cli
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: CerbIA Command-line interface
|
|
5
|
+
Author: Sergio Bugallo Enjamio, Mario Escobedo Del Rio
|
|
6
|
+
Author-email: Sergio Bugallo Enjamio <sergiobe@inditex.com>, Mario Escobedo Del Rio <marioer@inditex.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: NOTICE
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Information Technology
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Software Development
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Dist: cerbia-core==0.2.0
|
|
23
|
+
Requires-Dist: typer~=0.27
|
|
24
|
+
Requires-Python: >=3.12
|
|
25
|
+
Project-URL: Homepage, https://github.com/InditexTech/cerbia
|
|
26
|
+
Project-URL: Repository, https://github.com/InditexTech/cerbia
|
|
27
|
+
Project-URL: Issues, https://github.com/InditexTech/cerbia/issues
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# cerbia-cli
|
|
31
|
+
|
|
32
|
+
The package that provides the `cerbia` executable.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install cerbia-cli
|
|
36
|
+
cerbia validate config.yaml
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Run `cerbia scan --config config.yaml --text "Text to scan"` to scan inline input. Read the [full package reference](https://inditextech.github.io/cerbia/latest/cerbia-cli/).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# cerbia-cli
|
|
2
|
+
|
|
3
|
+
The package that provides the `cerbia` executable.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install cerbia-cli
|
|
7
|
+
cerbia validate config.yaml
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Run `cerbia scan --config config.yaml --text "Text to scan"` to scan inline input. Read the [full package reference](https://inditextech.github.io/cerbia/latest/cerbia-cli/).
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "cerbia-cli"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "CerbIA Command-line interface"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "Sergio Bugallo Enjamio", email = "sergiobe@inditex.com" },
|
|
11
|
+
{ name = "Mario Escobedo Del Rio", email = "marioer@inditex.com" },
|
|
12
|
+
]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"Intended Audience :: Information Technology",
|
|
16
|
+
"Programming Language :: Python",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Topic :: Software Development",
|
|
22
|
+
"Topic :: Software Development :: Libraries",
|
|
23
|
+
"Topic :: Software Development :: Libraries :: Application Frameworks",
|
|
24
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"cerbia-core==0.2.0",
|
|
29
|
+
"typer~=0.27",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.scripts]
|
|
33
|
+
cerbia = "cerbia.cli:app"
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/InditexTech/cerbia"
|
|
37
|
+
Repository = "https://github.com/InditexTech/cerbia"
|
|
38
|
+
Issues = "https://github.com/InditexTech/cerbia/issues"
|
|
39
|
+
|
|
40
|
+
[build-system]
|
|
41
|
+
requires = ["uv_build>=0.11.31,<0.12"]
|
|
42
|
+
build-backend = "uv_build"
|
|
43
|
+
|
|
44
|
+
[tool.uv.build-backend]
|
|
45
|
+
module-name = "cerbia.cli"
|
|
46
|
+
|
|
47
|
+
[tool.uv.sources]
|
|
48
|
+
cerbia-core = { workspace = true }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""CerbIA CLI package."""
|
|
2
|
+
|
|
3
|
+
import typer
|
|
4
|
+
|
|
5
|
+
from .scan import scan_command
|
|
6
|
+
from .validate import validate_command
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _build_app() -> typer.Typer:
|
|
10
|
+
"""Build the CerbIA CLI application.
|
|
11
|
+
|
|
12
|
+
Returns:
|
|
13
|
+
typer.Typer: The CerbIA CLI application.
|
|
14
|
+
"""
|
|
15
|
+
app = typer.Typer(
|
|
16
|
+
name="cerbia",
|
|
17
|
+
help="LLM security scanning — language-agnostic guardrails for AI agents.",
|
|
18
|
+
no_args_is_help=True,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
app.add_typer(scan_command)
|
|
22
|
+
app.add_typer(validate_command)
|
|
23
|
+
|
|
24
|
+
return app
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
app = _build_app()
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import typer
|
|
5
|
+
import yaml
|
|
6
|
+
from cerbia.core.config import CerbIAConfig
|
|
7
|
+
from cerbia.core.exceptions import CerbIAConfigError, CerbIAError
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from yaml.error import YAMLError
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_config_from_yaml(path: Path, output_console: Console) -> CerbIAConfig:
|
|
15
|
+
"""Load and validate configuration from a YAML file.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
path (Path): Filesystem path to the config YAML file.
|
|
19
|
+
output_console (Console): Rich console for outputting warnings and errors.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
CerbIAConfig: Validated configuration instance.
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
cerbia.core.exceptions.CerbIAConfigError: If the file does not contain a YAML mapping.
|
|
26
|
+
"""
|
|
27
|
+
try:
|
|
28
|
+
logger.debug("Loading configuration")
|
|
29
|
+
with open(path, encoding="utf-8") as f:
|
|
30
|
+
raw = yaml.safe_load(f)
|
|
31
|
+
|
|
32
|
+
if not isinstance(raw, dict):
|
|
33
|
+
raise CerbIAConfigError(f"Expected YAML mapping, got {type(raw).__name__}")
|
|
34
|
+
|
|
35
|
+
config = CerbIAConfig.model_validate(raw)
|
|
36
|
+
logger.debug("Configuration loaded")
|
|
37
|
+
|
|
38
|
+
return config
|
|
39
|
+
|
|
40
|
+
except FileNotFoundError as exc:
|
|
41
|
+
output_console.print(f"[red]Error:[/red] config file not found: {path}")
|
|
42
|
+
raise typer.Exit(code=2) from exc
|
|
43
|
+
except IsADirectoryError as exc:
|
|
44
|
+
output_console.print(f"[red]Error:[/red] config path is a directory: {path}")
|
|
45
|
+
raise typer.Exit(code=2) from exc
|
|
46
|
+
except PermissionError as exc:
|
|
47
|
+
output_console.print(f"[red]Error:[/red] permission denied reading config file: {path}")
|
|
48
|
+
raise typer.Exit(code=2) from exc
|
|
49
|
+
except YAMLError as exc:
|
|
50
|
+
output_console.print(f"[red]Error:[/red] invalid YAML in config file: {path}")
|
|
51
|
+
raise typer.Exit(code=2) from exc
|
|
52
|
+
except CerbIAError as exc:
|
|
53
|
+
output_console.print(f"[red]Error:[/red] invalid configuration in file: {path}")
|
|
54
|
+
raise typer.Exit(code=2) from exc
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Final
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
|
|
8
|
+
_LOG_LEVELS: Final = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
|
|
9
|
+
_LOG_FORMAT: Final = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def configure_logging(log_level: str | None, log_file: Path | None, output_console: Console) -> Path | None:
|
|
13
|
+
"""Configure application logging from CLI overrides.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
log_level (str | None): Optional explicit log-level override from the CLI.
|
|
17
|
+
log_file (Path | None): Optional explicit log-file path from the CLI.
|
|
18
|
+
output_console (Console): Rich console for outputting warnings and errors.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
Path | None: The effective log file path, if any.
|
|
22
|
+
|
|
23
|
+
Raises:
|
|
24
|
+
typer.Exit: Raised with exit code ``2`` when the effective log level is invalid.
|
|
25
|
+
"""
|
|
26
|
+
effective_level = (log_level or "INFO").upper()
|
|
27
|
+
|
|
28
|
+
if effective_level not in _LOG_LEVELS:
|
|
29
|
+
output_console.print(f"[red]Error:[/red] invalid log level. Choose from {', '.join(_LOG_LEVELS)}.")
|
|
30
|
+
raise typer.Exit(code=2)
|
|
31
|
+
|
|
32
|
+
is_default_configuration = log_level is None and log_file is None
|
|
33
|
+
if is_default_configuration and logging.getLogger().handlers:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
handlers: list[logging.Handler] = []
|
|
37
|
+
if log_file is not None:
|
|
38
|
+
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
if log_file.exists():
|
|
40
|
+
output_console.print("[yellow]Warning:[/yellow] overwriting existing log file.")
|
|
41
|
+
|
|
42
|
+
handlers.append(logging.FileHandler(log_file, mode="w"))
|
|
43
|
+
|
|
44
|
+
else:
|
|
45
|
+
handlers.append(logging.StreamHandler())
|
|
46
|
+
|
|
47
|
+
logging.basicConfig(
|
|
48
|
+
level=effective_level,
|
|
49
|
+
format=_LOG_FORMAT,
|
|
50
|
+
handlers=handlers,
|
|
51
|
+
force=not is_default_configuration,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return log_file
|
|
File without changes
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Annotated
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from cerbia.core.config import LoaderConfig
|
|
7
|
+
from cerbia.core.exceptions import CerbIAError
|
|
8
|
+
from cerbia.core.models.results import ScanResult
|
|
9
|
+
from cerbia.core.runner import Runner
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.progress import Progress, SpinnerColumn, TextColumn
|
|
12
|
+
|
|
13
|
+
from ..config import load_config_from_yaml
|
|
14
|
+
from ..logging import configure_logging
|
|
15
|
+
from ._data import write_json_result
|
|
16
|
+
from ._ui import render_scan_result
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
app = typer.Typer(no_args_is_help=True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@app.command()
|
|
24
|
+
def scan(
|
|
25
|
+
config: Annotated[Path, typer.Option("--config", "-c", help="Path to a single YAML configuration file.")],
|
|
26
|
+
text: Annotated[
|
|
27
|
+
list[str] | None, typer.Option("--text", "-t", help="Text to scan; repeatable (file mode only).")
|
|
28
|
+
] = None,
|
|
29
|
+
file: Annotated[
|
|
30
|
+
list[Path] | None, typer.Option("--file", "-f", help="File to scan; repeatable (file mode only).")
|
|
31
|
+
] = None,
|
|
32
|
+
output_path: Annotated[Path | None, typer.Option("--output", "-o", help="Write JSON results to this file.")] = None,
|
|
33
|
+
log_level: Annotated[
|
|
34
|
+
str | None, typer.Option("--log-level", help="Log level (DEBUG/INFO/WARNING/ERROR/CRITICAL).")
|
|
35
|
+
] = None,
|
|
36
|
+
log_file: Annotated[
|
|
37
|
+
Path | None, typer.Option("--log-file", help="Write logs to this file instead of stderr.")
|
|
38
|
+
] = None,
|
|
39
|
+
threshold: Annotated[
|
|
40
|
+
float | None,
|
|
41
|
+
typer.Option("--threshold", help="Ensemble score threshold for BLOCK verdict (overrides config)."),
|
|
42
|
+
] = None,
|
|
43
|
+
unsafe_only: Annotated[
|
|
44
|
+
bool,
|
|
45
|
+
typer.Option(
|
|
46
|
+
"--unsafe-only",
|
|
47
|
+
help=(
|
|
48
|
+
"Report only entries where is_safe == False. Filters console output and entry_results in JSON; "
|
|
49
|
+
"does not change scan execution or exit codes."
|
|
50
|
+
),
|
|
51
|
+
),
|
|
52
|
+
] = False,
|
|
53
|
+
) -> None:
|
|
54
|
+
"""Run security gates against input text or config-file entries.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
typer.Exit: Always raised to terminate the command with the appropriate
|
|
58
|
+
exit code after validation or execution.
|
|
59
|
+
"""
|
|
60
|
+
err_console = Console(stderr=True)
|
|
61
|
+
|
|
62
|
+
err_console.print("[bold]CerbIA CLI Scan[/bold]")
|
|
63
|
+
|
|
64
|
+
with Progress(
|
|
65
|
+
SpinnerColumn(),
|
|
66
|
+
TextColumn("{task.description}"),
|
|
67
|
+
console=err_console,
|
|
68
|
+
transient=True,
|
|
69
|
+
) as progress:
|
|
70
|
+
err_console.print("[bold]Running scan...[/bold]")
|
|
71
|
+
task_id = progress.add_task("Parsing configuration...", total=None)
|
|
72
|
+
text = text or []
|
|
73
|
+
file = file or []
|
|
74
|
+
|
|
75
|
+
if output_path is not None and output_path.suffix != ".json":
|
|
76
|
+
err_console.print("[red]Error:[/red] --output path must have a .json extension.")
|
|
77
|
+
raise typer.Exit(code=2)
|
|
78
|
+
|
|
79
|
+
cfg = load_config_from_yaml(config, err_console)
|
|
80
|
+
configure_logging(log_level, log_file, err_console)
|
|
81
|
+
|
|
82
|
+
loaders: list[LoaderConfig] = []
|
|
83
|
+
if text:
|
|
84
|
+
loaders.append(LoaderConfig(loader="cerbia.core.loaders.text.TextLoader", init_args={"texts": text}))
|
|
85
|
+
|
|
86
|
+
if file:
|
|
87
|
+
loaders.append(
|
|
88
|
+
LoaderConfig(
|
|
89
|
+
loader="cerbia.core.loaders.file.FileLoader", init_args={"paths": [str(path) for path in file]}
|
|
90
|
+
)
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
if loaders:
|
|
94
|
+
if cfg.loaders:
|
|
95
|
+
logger.warning("CLI input overrides the loaders configured in the config file")
|
|
96
|
+
|
|
97
|
+
cfg.loaders = loaders
|
|
98
|
+
|
|
99
|
+
if threshold is not None:
|
|
100
|
+
cfg.threshold = threshold
|
|
101
|
+
|
|
102
|
+
if not cfg.loaders:
|
|
103
|
+
err_console.print("[red]Error:[/red] provide --text, --file, or configure loaders in your config.")
|
|
104
|
+
raise typer.Exit(code=2)
|
|
105
|
+
|
|
106
|
+
progress.update(task_id, description="Preparing components...")
|
|
107
|
+
try:
|
|
108
|
+
runner = Runner(cfg)
|
|
109
|
+
|
|
110
|
+
progress.update(task_id, description="Scanning...")
|
|
111
|
+
results = runner.scan()
|
|
112
|
+
except (CerbIAError, TypeError) as exc:
|
|
113
|
+
err_console.print("[red]Error:[/red] scan failed: " + str(exc))
|
|
114
|
+
raise typer.Exit(code=2) from exc
|
|
115
|
+
|
|
116
|
+
if unsafe_only:
|
|
117
|
+
results = ScanResult(entry_results=[entry for entry in results.entry_results if not entry.is_safe])
|
|
118
|
+
|
|
119
|
+
render_scan_result(results, unsafe_only, err_console)
|
|
120
|
+
|
|
121
|
+
if output_path is not None:
|
|
122
|
+
write_json_result(results, output_path)
|
|
123
|
+
|
|
124
|
+
raise typer.Exit(code=0 if results.is_safe else 1)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from cerbia.core.models.results import ScanResult
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def write_json_result(result: ScanResult, output_path: Path) -> None:
|
|
10
|
+
"""Write the result to a JSON file, creating parent directories if necessary.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
result (ScanResult): The scan result to write.
|
|
14
|
+
output_path (Path): The path to the output JSON file.
|
|
15
|
+
"""
|
|
16
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
17
|
+
|
|
18
|
+
if output_path.exists():
|
|
19
|
+
logger.warning("Overwriting existing output file %s", output_path)
|
|
20
|
+
|
|
21
|
+
output_path.write_text(result.model_dump_json(indent=2, ensure_ascii=False))
|
|
22
|
+
|
|
23
|
+
logger.debug("JSON results written to %s", output_path)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
from cerbia.core.models.results import EntryResult, ScanResult
|
|
4
|
+
from rich.console import Console
|
|
5
|
+
from rich.markup import escape
|
|
6
|
+
from rich.panel import Panel
|
|
7
|
+
from rich.table import Table
|
|
8
|
+
from rich.text import Text
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def render_scan_result(results: ScanResult, unsafe_only: bool, output_console: Console) -> None:
|
|
12
|
+
"""Render selected scan results with the established Rich panels.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
results (ScanResult): The scan result to render.
|
|
16
|
+
unsafe_only (bool): Whether to filter the output to only show unsafe entries.
|
|
17
|
+
output_console (Console): Rich console for output.
|
|
18
|
+
"""
|
|
19
|
+
if unsafe_only and not results.entry_results:
|
|
20
|
+
output_console.print(_build_no_unsafe_panel())
|
|
21
|
+
return
|
|
22
|
+
|
|
23
|
+
for entry_result in results.entry_results:
|
|
24
|
+
entry_label = escape(entry_result.entry.field_path or entry_result.entry.source)
|
|
25
|
+
panel = _build_gate_panel(entry_result, unsafe_only=unsafe_only)
|
|
26
|
+
show_source_label = unsafe_only or len(results.entry_results) > 1
|
|
27
|
+
|
|
28
|
+
if show_source_label:
|
|
29
|
+
output_console.print(
|
|
30
|
+
f"\n[bold white]{escape(entry_result.entry.source)}[/bold white]:[white]{entry_label}[/white]"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
output_console.print(panel)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _build_no_unsafe_panel() -> Panel:
|
|
37
|
+
return Panel(
|
|
38
|
+
Text(""),
|
|
39
|
+
title=Text("✓ No unsafe entries found", style="bold green"),
|
|
40
|
+
border_style="green",
|
|
41
|
+
padding=(0, 1),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _build_gate_panel(entry_result: EntryResult, unsafe_only: bool) -> Panel:
|
|
46
|
+
is_safe = entry_result.is_safe
|
|
47
|
+
border = "green" if is_safe else "red"
|
|
48
|
+
status = Text("✓ SAFE", style="bold green") if is_safe else Text("✗ UNSAFE", style="bold red")
|
|
49
|
+
|
|
50
|
+
table = Table(show_header=True, expand=True, show_edge=False, pad_edge=False)
|
|
51
|
+
table.add_column("Scanner", style="cyan", no_wrap=True, ratio=2)
|
|
52
|
+
table.add_column("", justify="center", width=3)
|
|
53
|
+
table.add_column("Rationale", ratio=5)
|
|
54
|
+
|
|
55
|
+
for finding in entry_result.findings:
|
|
56
|
+
is_safe_finding = math.isclose(finding.risk_score, 0.0, abs_tol=1e-9)
|
|
57
|
+
if unsafe_only and is_safe_finding:
|
|
58
|
+
continue
|
|
59
|
+
|
|
60
|
+
marker = Text("✓", style="green") if is_safe_finding else Text("✗", style="red")
|
|
61
|
+
rationale = finding.rationale
|
|
62
|
+
|
|
63
|
+
if finding.matches:
|
|
64
|
+
spans = ", ".join(f"{match.start}:{match.end}" for match in finding.matches)
|
|
65
|
+
rationale = f"{rationale} [dim](matches: {spans})[/dim]"
|
|
66
|
+
|
|
67
|
+
table.add_row(finding.scanner_name, marker, rationale)
|
|
68
|
+
|
|
69
|
+
if not unsafe_only:
|
|
70
|
+
for skipped in entry_result.skipped_scanners:
|
|
71
|
+
table.add_row(
|
|
72
|
+
Text(skipped.scanner_name, style="dim"),
|
|
73
|
+
Text("⊘", style="dim"),
|
|
74
|
+
Text(skipped.reason, style="dim"),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
subtitle = f"score={entry_result.aggregated_score:.2f} · {entry_result.rationale}"
|
|
78
|
+
return Panel(
|
|
79
|
+
table,
|
|
80
|
+
title=status,
|
|
81
|
+
subtitle=f"[dim]{subtitle}[/dim]",
|
|
82
|
+
subtitle_align="left",
|
|
83
|
+
border_style=border,
|
|
84
|
+
padding=(0, 1),
|
|
85
|
+
)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Annotated
|
|
3
|
+
|
|
4
|
+
import typer
|
|
5
|
+
from cerbia.core.exceptions import CerbIAError
|
|
6
|
+
from cerbia.core.runner import Runner
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
|
|
9
|
+
from ..config import load_config_from_yaml
|
|
10
|
+
from ..logging import configure_logging
|
|
11
|
+
from ._ui import render_validation_summary
|
|
12
|
+
|
|
13
|
+
app = typer.Typer(no_args_is_help=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def validate(
|
|
18
|
+
config: Annotated[Path, typer.Argument(help="Path to a single YAML configuration file.")],
|
|
19
|
+
log_level: Annotated[
|
|
20
|
+
str | None, typer.Option("--log-level", help="Log level (DEBUG/INFO/WARNING/ERROR/CRITICAL).")
|
|
21
|
+
] = None,
|
|
22
|
+
log_file: Annotated[
|
|
23
|
+
Path | None, typer.Option("--log-file", help="Write logs to this file instead of stderr.")
|
|
24
|
+
] = None,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Validate a single YAML configuration file and report gate structure.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
typer.Exit: Raised with a non-zero code when the configuration path is invalid or the configuration fails
|
|
30
|
+
validation.
|
|
31
|
+
"""
|
|
32
|
+
err_console = Console(stderr=True)
|
|
33
|
+
|
|
34
|
+
if not config.exists():
|
|
35
|
+
err_console.print("[red]Error:[/red] configuration file not found.")
|
|
36
|
+
raise typer.Exit(code=2)
|
|
37
|
+
|
|
38
|
+
cfg = load_config_from_yaml(config, err_console)
|
|
39
|
+
configure_logging(log_level, log_file, err_console)
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
runner = Runner(cfg)
|
|
43
|
+
render_validation_summary(cfg, runner, err_console)
|
|
44
|
+
|
|
45
|
+
except CerbIAError as exc:
|
|
46
|
+
err_console.print("[red bold]✗ Invalid config[/red bold]")
|
|
47
|
+
raise typer.Exit(code=1) from exc
|
|
48
|
+
except TypeError as exc:
|
|
49
|
+
err_console.print("[red bold]✗ Config validation failed.[/red bold]")
|
|
50
|
+
raise typer.Exit(code=2) from exc
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from cerbia.core.config import CerbIAConfig
|
|
2
|
+
from cerbia.core.runner import Runner
|
|
3
|
+
from rich.console import Console
|
|
4
|
+
from rich.panel import Panel
|
|
5
|
+
from rich.table import Table
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def render_validation_summary(config: CerbIAConfig, runner: Runner, output_console: Console) -> None:
|
|
9
|
+
"""Render the established validation table and status panel.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
config (CerbIAConfig): Validated configuration instance.
|
|
13
|
+
runner (Runner): Runner instance initialized with the configuration.
|
|
14
|
+
output_console (Console): Rich console for output.
|
|
15
|
+
"""
|
|
16
|
+
table = Table(show_header=True, expand=True, border_style="green")
|
|
17
|
+
table.add_column("Gate", style="bold cyan", no_wrap=True)
|
|
18
|
+
table.add_column("Scanners", ratio=3)
|
|
19
|
+
table.add_column("#", justify="right", style="dim")
|
|
20
|
+
|
|
21
|
+
scanner_names = [type(scanner).__name__ for scanner in runner.gate.scanners]
|
|
22
|
+
table.add_row(
|
|
23
|
+
runner.gate.name,
|
|
24
|
+
", ".join(scanner_names),
|
|
25
|
+
str(len(scanner_names)),
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
loader_status = "[green]yes[/green]" if config.loaders else "[yellow]no[/yellow]"
|
|
29
|
+
|
|
30
|
+
output_console.print(
|
|
31
|
+
Panel(
|
|
32
|
+
table,
|
|
33
|
+
title="[bold green]✓ Config valid[/bold green]",
|
|
34
|
+
subtitle=f"1 gate(s) · loaders={loader_status}",
|
|
35
|
+
border_style="green",
|
|
36
|
+
padding=(0, 1),
|
|
37
|
+
)
|
|
38
|
+
)
|