nti-scanner 0.1.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.
Files changed (54) hide show
  1. nti_scanner-0.1.0/LICENSE +201 -0
  2. nti_scanner-0.1.0/PKG-INFO +60 -0
  3. nti_scanner-0.1.0/README.md +36 -0
  4. nti_scanner-0.1.0/nti_scanner/__init__.py +2 -0
  5. nti_scanner-0.1.0/nti_scanner/analysis/__init__.py +1 -0
  6. nti_scanner-0.1.0/nti_scanner/analysis/behavior_graph.py +31 -0
  7. nti_scanner-0.1.0/nti_scanner/ast_analysis/__init__.py +1 -0
  8. nti_scanner-0.1.0/nti_scanner/ast_analysis/callgraph.py +15 -0
  9. nti_scanner-0.1.0/nti_scanner/ast_analysis/parser.py +20 -0
  10. nti_scanner-0.1.0/nti_scanner/ast_analysis/taint.py +42 -0
  11. nti_scanner-0.1.0/nti_scanner/cli.py +85 -0
  12. nti_scanner-0.1.0/nti_scanner/cwe/__init__.py +1 -0
  13. nti_scanner-0.1.0/nti_scanner/cwe/mapping.py +10 -0
  14. nti_scanner-0.1.0/nti_scanner/framework/__init__.py +1 -0
  15. nti_scanner-0.1.0/nti_scanner/framework/detector.py +39 -0
  16. nti_scanner-0.1.0/nti_scanner/report/__init__.py +1 -0
  17. nti_scanner-0.1.0/nti_scanner/report/html.py +10 -0
  18. nti_scanner-0.1.0/nti_scanner/report/json_report.py +6 -0
  19. nti_scanner-0.1.0/nti_scanner/report/sarif.py +29 -0
  20. nti_scanner-0.1.0/nti_scanner/report/terminal.py +41 -0
  21. nti_scanner-0.1.0/nti_scanner/rules/__init__.py +1 -0
  22. nti_scanner-0.1.0/nti_scanner/rules/base.py +42 -0
  23. nti_scanner-0.1.0/nti_scanner/rules/nti/__init__.py +1 -0
  24. nti_scanner-0.1.0/nti_scanner/rules/nti/audit.py +31 -0
  25. nti_scanner-0.1.0/nti_scanner/rules/nti/capability_diff.py +38 -0
  26. nti_scanner-0.1.0/nti_scanner/rules/nti/consensus.py +29 -0
  27. nti_scanner-0.1.0/nti_scanner/rules/nti/governance.py +32 -0
  28. nti_scanner-0.1.0/nti_scanner/rules/nti/identity.py +33 -0
  29. nti_scanner-0.1.0/nti_scanner/rules/nti/persistence.py +25 -0
  30. nti_scanner-0.1.0/nti_scanner/rules/nti/trust_boundary.py +36 -0
  31. nti_scanner-0.1.0/nti_scanner/rules/registry.py +31 -0
  32. nti_scanner-0.1.0/nti_scanner/rules/security/__init__.py +1 -0
  33. nti_scanner-0.1.0/nti_scanner/rules/security/a2a_rules.py +21 -0
  34. nti_scanner-0.1.0/nti_scanner/rules/security/capability_escalation.py +29 -0
  35. nti_scanner-0.1.0/nti_scanner/rules/security/command_injection.py +38 -0
  36. nti_scanner-0.1.0/nti_scanner/rules/security/llm_trust.py +35 -0
  37. nti_scanner-0.1.0/nti_scanner/rules/security/mcp_rules.py +21 -0
  38. nti_scanner-0.1.0/nti_scanner/rules/security/path_traversal.py +28 -0
  39. nti_scanner-0.1.0/nti_scanner/rules/security/pqc_readiness.py +24 -0
  40. nti_scanner-0.1.0/nti_scanner/rules/security/prompt_injection.py +24 -0
  41. nti_scanner-0.1.0/nti_scanner/rules/security/secret_leak.py +22 -0
  42. nti_scanner-0.1.0/nti_scanner/rules/security/sql_injection.py +27 -0
  43. nti_scanner-0.1.0/nti_scanner/rules/security/ssrf.py +31 -0
  44. nti_scanner-0.1.0/nti_scanner/rules/security/unsafe_deserialization.py +29 -0
  45. nti_scanner-0.1.0/nti_scanner/scanner.py +78 -0
  46. nti_scanner-0.1.0/nti_scanner.egg-info/PKG-INFO +60 -0
  47. nti_scanner-0.1.0/nti_scanner.egg-info/SOURCES.txt +52 -0
  48. nti_scanner-0.1.0/nti_scanner.egg-info/dependency_links.txt +1 -0
  49. nti_scanner-0.1.0/nti_scanner.egg-info/entry_points.txt +2 -0
  50. nti_scanner-0.1.0/nti_scanner.egg-info/requires.txt +2 -0
  51. nti_scanner-0.1.0/nti_scanner.egg-info/top_level.txt +1 -0
  52. nti_scanner-0.1.0/pyproject.toml +30 -0
  53. nti_scanner-0.1.0/setup.cfg +4 -0
  54. nti_scanner-0.1.0/tests/test_scanner.py +71 -0
@@ -0,0 +1,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: nti-scanner
3
+ Version: 0.1.0
4
+ Summary: Professional NTI-1 compliance and AI agent security scanner with AST analysis, taint tracking, CWE mapping, MCP/A2A rules, and SARIF output.
5
+ Author-email: Abisheak <abisheakp197@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://abisheakp197.github.io/Neutral-Trust-Infrastructure/
8
+ Project-URL: Repository, https://github.com/abisheakp197/nti-scanner
9
+ Project-URL: Issues, https://github.com/abisheakp197/nti-scanner/issues
10
+ Keywords: ai-agents,security-scanner,sast,static-analysis,nti,nti-1,compliance,post-quantum-cryptography,pqc,ai-security,sarif,cwe,mcp,a2a
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Topic :: Security
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: click>=8.1.0
22
+ Requires-Dist: rich>=13.0.0
23
+ Dynamic: license-file
24
+
25
+ # nti-scanner
26
+
27
+
28
+ Professional SAST tool for AI agent security. AST-based analysis, taint tracking, CWE mapping, and SARIF output.
29
+
30
+
31
+ ## Features
32
+ - AST-based analysis
33
+ - Taint tracking
34
+ - 19 rules (NTI-1 + OWASP AI security)
35
+ - CWE mapping
36
+ - SARIF output for GitHub Security tab
37
+ - Framework detection (LangChain, CrewAI, AutoGen, OpenAI, Anthropic)
38
+ - MCP + A2A rules (first in the world)
39
+ - PQC readiness check
40
+ - Capability diff
41
+ - Behavior graph export
42
+
43
+
44
+ ## Install
45
+ pip install nti-scanner
46
+
47
+
48
+ ## Usage
49
+ nti-scanner scan ./my-agent-project
50
+ nti-scanner scan ./my-project --format sarif --output report.sarif
51
+ nti-scanner scan . --min-score 80
52
+
53
+
54
+ ## License
55
+ Apache License 2.0. See LICENSE.
56
+
57
+
58
+ ## Links
59
+ - NTI-1 Spec: https://abisheakp197.github.io/nti-spec/
60
+ - Core SDK: https://pypi.org/project/ube-foundation/
@@ -0,0 +1,36 @@
1
+ # nti-scanner
2
+
3
+
4
+ Professional SAST tool for AI agent security. AST-based analysis, taint tracking, CWE mapping, and SARIF output.
5
+
6
+
7
+ ## Features
8
+ - AST-based analysis
9
+ - Taint tracking
10
+ - 19 rules (NTI-1 + OWASP AI security)
11
+ - CWE mapping
12
+ - SARIF output for GitHub Security tab
13
+ - Framework detection (LangChain, CrewAI, AutoGen, OpenAI, Anthropic)
14
+ - MCP + A2A rules (first in the world)
15
+ - PQC readiness check
16
+ - Capability diff
17
+ - Behavior graph export
18
+
19
+
20
+ ## Install
21
+ pip install nti-scanner
22
+
23
+
24
+ ## Usage
25
+ nti-scanner scan ./my-agent-project
26
+ nti-scanner scan ./my-project --format sarif --output report.sarif
27
+ nti-scanner scan . --min-score 80
28
+
29
+
30
+ ## License
31
+ Apache License 2.0. See LICENSE.
32
+
33
+
34
+ ## Links
35
+ - NTI-1 Spec: https://abisheakp197.github.io/nti-spec/
36
+ - Core SDK: https://pypi.org/project/ube-foundation/
@@ -0,0 +1,2 @@
1
+ """nti-scanner: Professional NTI-1 compliance and AI agent security scanner."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1 @@
1
+ """Advanced NTI-specific analysis."""
@@ -0,0 +1,31 @@
1
+ """Build an agent behavior graph from AST."""
2
+ import ast
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Dict, List
6
+
7
+
8
+ def build_behavior_graph(trees: Dict) -> dict:
9
+ nodes = []
10
+ edges = []
11
+ for f, tree in trees.items():
12
+ for node in ast.walk(tree):
13
+ if isinstance(node, ast.Call):
14
+ name = _name(node.func)
15
+ if name in {"Agent", "AgentExecutor", "Crew"}:
16
+ nodes.append({"id": f"{f}:{node.lineno}", "type": "agent", "name": name, "file": str(f)})
17
+ elif name in {"execute_transfer", "delete_account", "read_account", "transfer"}:
18
+ nodes.append({"id": f"{f}:{node.lineno}", "type": "action", "name": name, "file": str(f)})
19
+ elif name in {"os.system", "subprocess.run", "eval", "exec", "open"}:
20
+ nodes.append({"id": f"{f}:{node.lineno}", "type": "sink", "name": name, "file": str(f)})
21
+ return {"nodes": nodes, "edges": edges}
22
+
23
+
24
+ def _name(node):
25
+ if isinstance(node, ast.Name): return node.id
26
+ if isinstance(node, ast.Attribute): return node.attr
27
+ return ""
28
+
29
+
30
+ def render_graph_json(graph: dict) -> str:
31
+ return json.dumps(graph, indent=2)
@@ -0,0 +1 @@
1
+ """AST-based analysis utilities."""
@@ -0,0 +1,15 @@
1
+ """Build a call graph from Python AST."""
2
+ import ast
3
+ from typing import Dict, Set
4
+
5
+
6
+ def build_call_graph(tree: ast.AST) -> Dict[str, Set[str]]:
7
+ graph: Dict[str, Set[str]] = {}
8
+ for node in ast.walk(tree):
9
+ if isinstance(node, ast.FunctionDef):
10
+ calls = set()
11
+ for sub in ast.walk(node):
12
+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name):
13
+ calls.add(sub.func.id)
14
+ graph[node.name] = calls
15
+ return graph
@@ -0,0 +1,20 @@
1
+ """Safe AST parser."""
2
+ import ast
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+
7
+ def parse_python_file(path: Path) -> Optional[ast.AST]:
8
+ try:
9
+ source = path.read_text(encoding="utf-8", errors="ignore")
10
+ return ast.parse(source, filename=str(path))
11
+ except (SyntaxError, ValueError):
12
+ return None
13
+
14
+
15
+ def get_source_segment(path: Path, node: ast.AST) -> str:
16
+ try:
17
+ source = path.read_text(encoding="utf-8", errors="ignore")
18
+ return ast.get_source_segment(source, node) or ""
19
+ except Exception:
20
+ return ""
@@ -0,0 +1,42 @@
1
+ """Lightweight taint tracking."""
2
+ import ast
3
+ from typing import Set
4
+
5
+
6
+ USER_INPUT_SOURCES = {"input", "request.form", "request.json", "request.args", "sys.stdin.read", "sys.argv"}
7
+ UNSAFE_SINKS = {"eval", "exec", "os.system", "subprocess.run", "subprocess.Popen", "subprocess.call", "pickle.loads", "yaml.load", "os.popen"}
8
+
9
+
10
+ def find_tainted_calls(tree: ast.AST) -> list:
11
+ findings = []
12
+ tainted_names: Set[str] = set()
13
+ for node in ast.walk(tree):
14
+ if isinstance(node, ast.Assign):
15
+ if _is_user_input(node.value):
16
+ for target in node.targets:
17
+ if isinstance(target, ast.Name):
18
+ tainted_names.add(target.id)
19
+ if isinstance(node, ast.Call):
20
+ func_name = _get_call_name(node)
21
+ if func_name in UNSAFE_SINKS:
22
+ for arg in node.args:
23
+ if isinstance(arg, ast.Name) and arg.id in tainted_names:
24
+ findings.append({"line": node.lineno, "col": node.col_offset, "sink": func_name, "source": arg.id})
25
+ return findings
26
+
27
+
28
+ def _is_user_input(node: ast.AST) -> bool:
29
+ if isinstance(node, ast.Call):
30
+ return _get_call_name(node) in USER_INPUT_SOURCES
31
+ return False
32
+
33
+
34
+ def _get_call_name(node: ast.Call) -> str:
35
+ parts = []
36
+ cur = node.func
37
+ while isinstance(cur, ast.Attribute):
38
+ parts.append(cur.attr)
39
+ cur = cur.value
40
+ if isinstance(cur, ast.Name):
41
+ parts.append(cur.id)
42
+ return ".".join(reversed(parts))
@@ -0,0 +1,85 @@
1
+ """Command-line interface."""
2
+ import sys
3
+ from pathlib import Path
4
+ import click
5
+ from rich.console import Console
6
+ from nti_scanner.scanner import scan_directory
7
+ from nti_scanner.report.terminal import render_terminal
8
+ from nti_scanner.report.json_report import render_json
9
+ from nti_scanner.report.sarif import render_sarif
10
+ from nti_scanner.report.html import render_html
11
+ console = Console()
12
+
13
+
14
+ @click.group()
15
+ @click.version_option()
16
+ def main():
17
+ """nti-scanner: NTI-1 compliance and AI agent security scanner."""
18
+ pass
19
+
20
+
21
+ @main.command()
22
+ @click.argument("path", type=click.Path(exists=True, file_okay=False))
23
+ @click.option("--format", "fmt", type=click.Choice(["terminal", "json", "sarif", "html"]), default="terminal")
24
+ @click.option("--output", "-o", type=click.Path(), default=None)
25
+ @click.option("--min-score", default=0)
26
+ @click.option("--severity", type=click.Choice(["critical", "high", "medium", "low", "info"]), default="info")
27
+ @click.option("--exclude", multiple=True)
28
+ def scan(path, fmt, output, min_score, severity, exclude):
29
+ """Scan a directory for NTI-1 compliance and AI agent security issues."""
30
+ if fmt == "terminal":
31
+ console.print(f"[bold cyan]nti-scanner v{__import__('nti_scanner').__version__}[/bold cyan]")
32
+ console.print(f"Scanning [bold]{path}[/bold]...\n")
33
+ result = scan_directory(Path(path).resolve(), min_severity=severity, excludes=list(exclude))
34
+ if fmt == "terminal":
35
+ render_terminal(result, console)
36
+ elif fmt == "json":
37
+ content = render_json(result)
38
+ if output: Path(output).write_text(content)
39
+ else: console.print_json(content)
40
+ elif fmt == "sarif":
41
+ content = render_sarif(result)
42
+ if output: Path(output).write_text(content)
43
+ else: print(content)
44
+ elif fmt == "html":
45
+ content = render_html(result)
46
+ if output: Path(output).write_text(content)
47
+ else: print(content)
48
+ if min_score and result.nti1_score < min_score:
49
+ sys.exit(1)
50
+
51
+
52
+ @main.command()
53
+ def rules():
54
+ """List all available rules."""
55
+ from rich.table import Table
56
+ from nti_scanner.rules.registry import RULES
57
+ table = Table(title="Available Rules")
58
+ table.add_column("ID", style="cyan")
59
+ table.add_column("Category")
60
+ table.add_column("Severity")
61
+ table.add_column("Description")
62
+ for r in RULES:
63
+ table.add_row(r.meta.id, r.meta.category, r.meta.severity, r.meta.description[:60])
64
+ console.print(table)
65
+
66
+
67
+ @main.command()
68
+ @click.argument("path", type=click.Path(exists=True, file_okay=False))
69
+ @click.option("--output", "-o", type=click.Path(), required=True)
70
+ def graph(path, output):
71
+ """Build and export the agent behavior graph."""
72
+ from pathlib import Path
73
+ from nti_scanner.ast_analysis.parser import parse_python_file
74
+ from nti_scanner.analysis.behavior_graph import build_behavior_graph, render_graph_json
75
+ trees = {}
76
+ for f in Path(path).rglob("*.py"):
77
+ t = parse_python_file(f)
78
+ if t: trees[f] = t
79
+ graph_data = build_behavior_graph(trees)
80
+ Path(output).write_text(render_graph_json(graph_data))
81
+ console.print(f"[green]Graph written to {output}[/green]")
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
@@ -0,0 +1 @@
1
+ """CWE metadata."""
@@ -0,0 +1,10 @@
1
+ """CWE metadata lookup."""
2
+ CWE_NAMES = {"CWE-22": "Path Traversal", "CWE-78": "OS Command Injection", "CWE-89": "SQL Injection",
3
+ "CWE-269": "Privilege Management", "CWE-287": "Authentication", "CWE-353": "Missing Integrity",
4
+ "CWE-502": "Unsafe Deserialization", "CWE-778": "Insufficient Logging", "CWE-798": "Hardcoded Credentials",
5
+ "CWE-862": "Missing Authorization", "CWE-918": "SSRF", "CWE-1336": "Template Injection",
6
+ "CWE-1426": "AI Output Validation"}
7
+
8
+
9
+ def cwe_url(cwe: str) -> str:
10
+ return f"https://cwe.mitre.org/data/definitions/{cwe.replace('CWE-', '')}.html"
@@ -0,0 +1 @@
1
+ """Framework detection."""
@@ -0,0 +1,39 @@
1
+ """Detect which AI frameworks a codebase uses."""
2
+ import ast
3
+ from typing import Dict, List
4
+
5
+
6
+ FRAMEWORK_SIGNATURES = {
7
+ "langchain": {"langchain", "langchain_core", "langchain_openai", "ChatOpenAI", "AgentExecutor"},
8
+ "crewai": {"crewai", "Crew", "Agent", "Task"},
9
+ "autogen": {"autogen", "ConversableAgent", "AssistantAgent"},
10
+ "openai": {"openai", "OpenAI", "ChatCompletion"},
11
+ "anthropic": {"anthropic", "Anthropic"},
12
+ }
13
+
14
+
15
+ def detect_frameworks(trees: Dict) -> List[str]:
16
+ detected = set()
17
+ for tree in trees.values():
18
+ for node in ast.walk(tree):
19
+ if isinstance(node, ast.Import):
20
+ for n in node.names: _match(n.name, detected)
21
+ elif isinstance(node, ast.ImportFrom):
22
+ if node.module: _match(node.module, detected)
23
+ elif isinstance(node, ast.Call):
24
+ name = _name(node.func)
25
+ if name: _match(name, detected)
26
+ return sorted(detected)
27
+
28
+
29
+ def _match(name: str, detected: set):
30
+ for fw, sigs in FRAMEWORK_SIGNATURES.items():
31
+ for sig in sigs:
32
+ if sig.lower() in name.lower():
33
+ detected.add(fw); return
34
+
35
+
36
+ def _name(node):
37
+ if isinstance(node, ast.Name): return node.id
38
+ if isinstance(node, ast.Attribute): return node.attr
39
+ return ""
@@ -0,0 +1 @@
1
+ """Report renderers."""
@@ -0,0 +1,10 @@
1
+ """HTML report."""
2
+ from html import escape
3
+
4
+
5
+ def render_html(result) -> str:
6
+ findings_html = ""
7
+ for f in result.findings:
8
+ findings_html += f'<div class="finding {f.severity}"><div><strong>{f.severity.upper()}</strong> - {f.rule_id}</div><div>{escape(f.message)}</div><div>{escape(f.file)}:{f.line}</div></div>'
9
+ pillars_html = "".join(f'<div><span>{p}</span><span>{s}/100</span></div>' for p, s in result.pillar_scores.items())
10
+ return f'<!DOCTYPE html><html><head><meta charset="utf-8"><title>nti-scanner</title></head><body><h1>NTI-1 Report</h1><div>{result.nti1_score}/100</div><p>{result.files_scanned} files - {len(result.findings)} findings</p><h2>Pillars</h2>{pillars_html}<h2>Findings</h2>{findings_html}</body></html>'
@@ -0,0 +1,6 @@
1
+ """JSON report."""
2
+ import json
3
+
4
+
5
+ def render_json(result) -> str:
6
+ return json.dumps(result.to_dict(), indent=2)
@@ -0,0 +1,29 @@
1
+ """SARIF 2.1.0 reporter for GitHub Security integration."""
2
+ import json
3
+ from nti_scanner.rules.registry import RULES
4
+
5
+
6
+ SEVERITY_TO_LEVEL = {"critical": "error", "high": "error", "medium": "warning", "low": "note", "info": "note"}
7
+
8
+
9
+ def render_sarif(result) -> str:
10
+ rules_meta = []
11
+ for r in RULES:
12
+ rules_meta.append({"id": r.meta.id, "name": r.meta.id,
13
+ "shortDescription": {"text": r.meta.description},
14
+ "helpUri": f"https://cwe.mitre.org/data/definitions/{r.meta.cwe.replace('CWE-','')}.html" if r.meta.cwe else "",
15
+ "properties": {"category": r.meta.category, "confidence": r.meta.confidence}})
16
+ sarif_results = []
17
+ for f in result.findings:
18
+ sarif_results.append({"ruleId": f.rule_id, "level": SEVERITY_TO_LEVEL.get(f.severity, "warning"),
19
+ "message": {"text": f.message},
20
+ "locations": [{"physicalLocation": {"artifactLocation": {"uri": f.file},
21
+ "region": {"startLine": max(1, f.line), "startColumn": max(1, f.column)}}}],
22
+ "properties": {"cwe": f.cwe, "confidence": f.confidence}})
23
+ sarif = {"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
24
+ "version": "2.1.0",
25
+ "runs": [{"tool": {"driver": {"name": "nti-scanner",
26
+ "informationUri": "https://github.com/abisheakp197/nti-scanner",
27
+ "version": "0.1.0", "rules": rules_meta}},
28
+ "results": sarif_results}]}
29
+ return json.dumps(sarif, indent=2)
@@ -0,0 +1,41 @@
1
+ """Rich terminal renderer."""
2
+ from rich.console import Console
3
+ from rich.table import Table
4
+ from rich.panel import Panel
5
+
6
+
7
+ SEVERITY_COLORS = {"critical": "bold red", "high": "red", "medium": "yellow", "low": "dim", "info": "blue"}
8
+
9
+
10
+ def render_terminal(result, console: Console):
11
+ score = result.nti1_score
12
+ if score >= 90: color, grade = "green", "A"
13
+ elif score >= 75: color, grade = "cyan", "B"
14
+ elif score >= 50: color, grade = "yellow", "C"
15
+ elif score >= 25: color, grade = "orange3", "D"
16
+ else: color, grade = "red", "F"
17
+ console.print(Panel.fit(f"[bold {color}]NTI-1 Score: {score}/100 (Grade {grade})[/bold {color}]\n"
18
+ f"Files scanned: {result.files_scanned} | Lines: {result.lines_scanned} | Findings: {len(result.findings)}\n"
19
+ f"Frameworks detected: {', '.join(result.frameworks) or 'none'}", title="nti-scanner"))
20
+ if result.pillar_scores:
21
+ table = Table(title="Pillar Breakdown")
22
+ table.add_column("Pillar", style="cyan")
23
+ table.add_column("Score", justify="right")
24
+ for p, s in result.pillar_scores.items():
25
+ color = "green" if s >= 80 else "yellow" if s >= 50 else "red"
26
+ table.add_row(p, f"[{color}]{s}/100[/]")
27
+ console.print(table)
28
+ if result.findings:
29
+ t = Table(title=f"Findings ({len(result.findings)})")
30
+ t.add_column("Severity")
31
+ t.add_column("Rule")
32
+ t.add_column("CWE")
33
+ t.add_column("Message")
34
+ t.add_column("File:Line")
35
+ for f in result.findings[:30]:
36
+ t.add_row(f"[{SEVERITY_COLORS.get(f.severity, 'white')}]{f.severity.upper()}[/]",
37
+ f.rule_id, f.cwe or "-", f.message[:70], f"{f.file.split('/')[-1]}:{f.line}")
38
+ console.print(t)
39
+ console.print()
40
+ console.print("[bold]Fix your score:[/bold] pip install ube-foundation")
41
+ console.print("[dim]Spec: https://abisheakp197.github.io/nti-spec/[/dim]")