RagGovern 0.1.0__py3-none-any.whl
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.
- raggovern-0.1.0.dist-info/METADATA +96 -0
- raggovern-0.1.0.dist-info/RECORD +23 -0
- raggovern-0.1.0.dist-info/WHEEL +4 -0
- raggovern-0.1.0.dist-info/entry_points.txt +2 -0
- raggovern-0.1.0.dist-info/licenses/LICENSE +21 -0
- ragguard/__init__.py +8 -0
- ragguard/__main__.py +4 -0
- ragguard/adapters.py +30 -0
- ragguard/analysis.py +395 -0
- ragguard/catalog.py +113 -0
- ragguard/cli.py +196 -0
- ragguard/config.py +172 -0
- ragguard/core.py +139 -0
- ragguard/discovery.py +263 -0
- ragguard/evidence.py +59 -0
- ragguard/exceptions.py +2 -0
- ragguard/findings.py +29 -0
- ragguard/logging.py +16 -0
- ragguard/metadata.py +153 -0
- ragguard/models.py +177 -0
- ragguard/py.typed +1 -0
- ragguard/rules.py +431 -0
- ragguard/schemas/ragguard-v1.json +342 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: RagGovern
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local, evidence-backed static assessment for RAG projects
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: pydantic<3,>=2.9
|
|
11
|
+
Requires-Dist: pyyaml<7,>=6
|
|
12
|
+
Requires-Dist: rich<16,>=13
|
|
13
|
+
Requires-Dist: typer<1,>=0.16
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
16
|
+
Requires-Dist: hatchling>=1.25; extra == 'dev'
|
|
17
|
+
Requires-Dist: mypy>=1.13; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
19
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
20
|
+
Requires-Dist: types-pyyaml; extra == 'dev'
|
|
21
|
+
Provides-Extra: langchain
|
|
22
|
+
Requires-Dist: faiss-cpu; extra == 'langchain'
|
|
23
|
+
Requires-Dist: langchain-community; extra == 'langchain'
|
|
24
|
+
Requires-Dist: langchain-openai; extra == 'langchain'
|
|
25
|
+
Requires-Dist: langchain-text-splitters; extra == 'langchain'
|
|
26
|
+
Provides-Extra: llamaindex
|
|
27
|
+
Requires-Dist: llama-index-core; extra == 'llamaindex'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# RagGovern
|
|
31
|
+
|
|
32
|
+
RagGovern inventories RAG projects and checks their static configuration locally. It parses source as data and attaches source evidence to every finding. Install the release with `python -m pip install RagGovern`. The Python import and console command are both `ragguard`.
|
|
33
|
+
|
|
34
|
+
Python 3.11+ is supported. Development targets Python 3.12. Run the following commands from this repository in an activated virtual environment.
|
|
35
|
+
|
|
36
|
+
```console
|
|
37
|
+
python -m pip install -e ".[dev]"
|
|
38
|
+
ragguard init
|
|
39
|
+
ragguard config validate
|
|
40
|
+
ragguard scan examples/langchain
|
|
41
|
+
ragguard inspect examples/llamaindex --format mermaid
|
|
42
|
+
ragguard rules --format json
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
For an example with a threshold violation, run `ragguard scan examples/custom --format json`. The logging call that receives retrieved context produces a high-severity RG009 finding and exit code 1. Its evidence includes the relative file, source lines and logging function. The report omits the logged content.
|
|
46
|
+
|
|
47
|
+
## Python SDK
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
from ragguard import RAGGuard
|
|
52
|
+
|
|
53
|
+
guard = RAGGuard.from_config(Path("ragguard.yaml"), profile="ci")
|
|
54
|
+
snapshot = guard.inspect("examples/langchain")
|
|
55
|
+
print(snapshot.architecture.mermaid())
|
|
56
|
+
|
|
57
|
+
run = guard.scan("examples/custom")
|
|
58
|
+
for result in run.results:
|
|
59
|
+
for finding in result.findings:
|
|
60
|
+
print(finding.rule_id, finding.evidence.file, finding.evidence.line, finding.remediation)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`RAGGuard.init(path)` creates a policy. `RAGGuard.validate_config(path)` returns the effective typed settings. `guard.rules()` returns the catalog. JSON output is available from the CLI and through Pydantic's `model_dump_json()`.
|
|
64
|
+
|
|
65
|
+
## Working with results
|
|
66
|
+
|
|
67
|
+
Inspection covers Python sources, manifests, structured configuration, documentation and Dockerfile inventory. Recognized RAG roles range from document loading to citation formatting. Directed edges record observed call inputs and receivers. Confidence and diagnostics describe the limits of each assessment. A clean process exit can include unassessed rules.
|
|
68
|
+
|
|
69
|
+
| Command exit | Meaning |
|
|
70
|
+
|---|---|
|
|
71
|
+
| 0 | Command succeeded, below the configured finding threshold |
|
|
72
|
+
| 1 | A finding reached the severity threshold |
|
|
73
|
+
| 2 | Invalid policy, argument or path |
|
|
74
|
+
| 3 | Internal execution or rule error |
|
|
75
|
+
|
|
76
|
+
Use `--output new-report.json` to create a scan report. A plain scan writes to stdout. The static scanner needs no provider credentials or framework installations.
|
|
77
|
+
|
|
78
|
+
## Development and packaging
|
|
79
|
+
|
|
80
|
+
```console
|
|
81
|
+
python -m pytest
|
|
82
|
+
python -m ruff check .
|
|
83
|
+
python -m ruff format --check .
|
|
84
|
+
python -m mypy src
|
|
85
|
+
python -m build
|
|
86
|
+
python benchmarks/scan.py examples 5
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The wheel and source archive are written to `dist/`. The source tree includes three small framework examples and fixtures for incomplete or sensitive input. CI covers Windows, Linux and macOS.
|
|
90
|
+
|
|
91
|
+
- [Architecture, SDK extension points and Stage 2 handoff](docs/architecture.md)
|
|
92
|
+
- [Rule catalog and remediation guidance](docs/rules.md)
|
|
93
|
+
- [Configuration, precedence and coverage semantics](docs/configuration.md)
|
|
94
|
+
- [Threat model and static analysis limitations](docs/trust-model.md)
|
|
95
|
+
- [Implementation decisions](docs/decisions.md)
|
|
96
|
+
- [MIT license](LICENSE)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
ragguard/__init__.py,sha256=1ufNIp5WD9RKNWdKfJdCRWjomfZ_eYnau5j_4Z5gdGw,182
|
|
2
|
+
ragguard/__main__.py,sha256=Qd-f8z2Q2vpiEP2x6PBFsJrpACWDVxFKQk820MhFmHo,59
|
|
3
|
+
ragguard/adapters.py,sha256=6tbNm2KsuRW4_-ZK7VfZq65w_I27IWEAanWIy_oZbRo,838
|
|
4
|
+
ragguard/analysis.py,sha256=y5XFlQ7Fr4rdH6pH9peVznhUPZOBdUFrHoY7pFG4CEM,15808
|
|
5
|
+
ragguard/catalog.py,sha256=o4hItj0T1RaIaGhgXtR78emYT7-miANLGDo9JBl6PW8,4832
|
|
6
|
+
ragguard/cli.py,sha256=x6qt6q2O0J76_XRblO5nPLI2MnhGTJMiqdma6VpU_z0,6498
|
|
7
|
+
ragguard/config.py,sha256=PpJm2xubLJn4kiucPlEr0zq9q2qcHPWnpegGATtxvuA,6163
|
|
8
|
+
ragguard/core.py,sha256=IHfh2-73Vm0ogvKDGpL2kczoHXfhLyv-HAc9rw8XJ_Q,5308
|
|
9
|
+
ragguard/discovery.py,sha256=jngJmrAi8PfbIPbQI-0aZWI68pRhkjH6Cjcof02gGlU,10077
|
|
10
|
+
ragguard/evidence.py,sha256=j_f0v1SmiwRLVOA-ni7Rocg9vV55ZSYxy6Au5pdCB4k,1726
|
|
11
|
+
ragguard/exceptions.py,sha256=bHsWkGisNR3P-1zEBeM8a9NMWt4dV-5xo8z97XB_8tw,103
|
|
12
|
+
ragguard/findings.py,sha256=R5j_JJSC-a_UBlRZIohnqjbk4j-fJoVoEecKzaxyvgY,823
|
|
13
|
+
ragguard/logging.py,sha256=gc_jxYnbPYdp8OV10crTD6iOILd_5Xpzw25HviJ_h3A,467
|
|
14
|
+
ragguard/metadata.py,sha256=rPX1ItWg0J85oc7_mRIZyBkOHKDKDsujjQvLhO1K8xo,6444
|
|
15
|
+
ragguard/models.py,sha256=_FQ6sLmE8xF0QnvEBGZOpo4s3zkShAFYokKIRjWQ1CE,3985
|
|
16
|
+
ragguard/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
17
|
+
ragguard/rules.py,sha256=przAvVhs5C69BYeib8iwvL8jGYeOV0czP2PjyM8oE5U,15799
|
|
18
|
+
ragguard/schemas/ragguard-v1.json,sha256=F2v3zkWD4d4l6lhG3R_bLQ9mXtyS5_qNFHe-I_9pe-w,7404
|
|
19
|
+
raggovern-0.1.0.dist-info/METADATA,sha256=VwhWgETS1ZDuPH81alNgqDwvHI5l-D-pD1o-VfPaMnE,4191
|
|
20
|
+
raggovern-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
21
|
+
raggovern-0.1.0.dist-info/entry_points.txt,sha256=DRg1WMkk-xS09uNqgs52_5j9w4Bfj7LZlWh1qdPT-8k,46
|
|
22
|
+
raggovern-0.1.0.dist-info/licenses/LICENSE,sha256=5pK908Od5sPW3Jk24Yz08-Cofn6Up3a52v8qP2lpI-0,1079
|
|
23
|
+
raggovern-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RAG-GUARD contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
ragguard/__init__.py
ADDED
ragguard/__main__.py
ADDED
ragguard/adapters.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Trusted, explicitly injected extension interfaces. No automatic plugin loading."""
|
|
2
|
+
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
from .config import RuleOverride, Settings
|
|
6
|
+
from .models import AssessmentRun, RuleInfo, RuleResult, Snapshot
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Scanner(Protocol):
|
|
10
|
+
def discover(self, settings: Settings) -> Snapshot: ...
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Rule(Protocol):
|
|
14
|
+
@property
|
|
15
|
+
def info(self) -> RuleInfo: ...
|
|
16
|
+
def evaluate(self, snapshot: Snapshot, override: RuleOverride) -> RuleResult: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RuntimeAdapter(Protocol):
|
|
20
|
+
def snapshot(self) -> Snapshot:
|
|
21
|
+
"""Return evidence collected with the application owner's consent."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AssessmentEngine(Protocol):
|
|
26
|
+
def assess(self, snapshot: Snapshot, settings: Settings) -> AssessmentRun: ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ReportExporter(Protocol):
|
|
30
|
+
def render(self, run: AssessmentRun) -> str: ...
|
ragguard/analysis.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""File-local, scope-aware AST analysis. Never evaluate a target expression."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import io
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import tokenize
|
|
8
|
+
import warnings
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from collections.abc import Iterator
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
|
|
13
|
+
from .catalog import PROPERTIES, SYMBOLS, technologies
|
|
14
|
+
from .evidence import credential_field, digest, evidence, identifier, model_name
|
|
15
|
+
from .models import Evidence, Kind, Observation, RAGComponent, Relationship, Technology
|
|
16
|
+
|
|
17
|
+
Scalar = str | int | float | bool | None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parse_python(data: bytes, max_nodes: int) -> ast.Module:
|
|
21
|
+
"""Bound individual expressions before CPython constructs a recursive AST."""
|
|
22
|
+
encoding, _ = tokenize.detect_encoding(io.BytesIO(data).readline)
|
|
23
|
+
if encoding.lower().replace("_", "-") not in {
|
|
24
|
+
"utf-8",
|
|
25
|
+
"utf-8-sig",
|
|
26
|
+
"latin-1",
|
|
27
|
+
"iso-8859-1",
|
|
28
|
+
"ascii",
|
|
29
|
+
"cp1252",
|
|
30
|
+
}:
|
|
31
|
+
raise ValueError("Unsupported source encoding")
|
|
32
|
+
source = data.decode(encoding)
|
|
33
|
+
statement_tokens = 0
|
|
34
|
+
for count, token in enumerate(tokenize.generate_tokens(io.StringIO(source).readline)):
|
|
35
|
+
statement_tokens = 0 if token.type == tokenize.NEWLINE else statement_tokens + 1
|
|
36
|
+
if statement_tokens > 1000 or count > 8 * max_nodes:
|
|
37
|
+
raise ValueError("Python token limit reached")
|
|
38
|
+
with warnings.catch_warnings():
|
|
39
|
+
warnings.simplefilter("ignore", SyntaxWarning)
|
|
40
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
41
|
+
tree = ast.parse(source)
|
|
42
|
+
if sum(1 for _ in ast.walk(tree)) > max_nodes:
|
|
43
|
+
raise ValueError("AST limit reached")
|
|
44
|
+
return tree
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def safe_value(key: str, value: object) -> tuple[bool, Scalar]:
|
|
48
|
+
if value is None:
|
|
49
|
+
return True, None
|
|
50
|
+
if key in {"model", "embedding_model"} and isinstance(value, str):
|
|
51
|
+
return True, model_name(value)
|
|
52
|
+
if type(value) in (float, int) and isinstance(value, (int, float)):
|
|
53
|
+
if abs(value) <= 10**18 and math.isfinite(value):
|
|
54
|
+
return True, value
|
|
55
|
+
return False, None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def env_name(value: object) -> str | None:
|
|
59
|
+
if isinstance(value, str) and re.fullmatch("[A-Za-z_][A-Za-z_0-9]{0,127}", value):
|
|
60
|
+
return identifier(value)
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class SourceAnalyzer(ast.NodeVisitor):
|
|
65
|
+
def __init__(self, file: str) -> None:
|
|
66
|
+
self.file = file
|
|
67
|
+
self.components: list[RAGComponent] = []
|
|
68
|
+
self.edges: list[Relationship] = []
|
|
69
|
+
self.tech: list[Technology] = []
|
|
70
|
+
self.env: set[str] = set()
|
|
71
|
+
self.observations: list[Observation] = []
|
|
72
|
+
self.secret_references: list[Evidence] = []
|
|
73
|
+
self.alias: dict[str, str] = {}
|
|
74
|
+
self.constants: dict[str, ast.expr] = {}
|
|
75
|
+
self.bindings: dict[str, str] = {}
|
|
76
|
+
self.produced: dict[ast.AST, str] = {}
|
|
77
|
+
self.scope = "<module>"
|
|
78
|
+
self.guard = 0
|
|
79
|
+
self.counts: Counter[tuple[str, str]] = Counter()
|
|
80
|
+
|
|
81
|
+
def anchor(self, name: str) -> str:
|
|
82
|
+
key = (self.scope, name)
|
|
83
|
+
self.counts[key] += 1
|
|
84
|
+
return "n" + digest(self.file, self.scope, name, str(self.counts[key]))[:24]
|
|
85
|
+
|
|
86
|
+
def symbol(self, expr: ast.AST) -> str:
|
|
87
|
+
if isinstance(expr, ast.Name):
|
|
88
|
+
return self.alias.get(expr.id, expr.id)
|
|
89
|
+
if isinstance(expr, ast.Attribute):
|
|
90
|
+
return self.symbol(expr.value) + "." + expr.attr
|
|
91
|
+
return ""
|
|
92
|
+
|
|
93
|
+
def record_import(self, name: str, line: int) -> None:
|
|
94
|
+
for tech in technologies(name):
|
|
95
|
+
self.tech.append(
|
|
96
|
+
Technology(
|
|
97
|
+
name=tech,
|
|
98
|
+
detection="confirmed",
|
|
99
|
+
confidence="high",
|
|
100
|
+
evidence=evidence(self.file, "import " + identifier(name), line),
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def visit_Import(self, node: ast.Import) -> None:
|
|
105
|
+
for item in node.names:
|
|
106
|
+
root = item.name.split(".")[0]
|
|
107
|
+
self.alias[item.asname or root] = item.name if item.asname else root
|
|
108
|
+
self.record_import(item.name, node.lineno)
|
|
109
|
+
|
|
110
|
+
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
|
|
111
|
+
if node.module and not node.level:
|
|
112
|
+
for item in node.names:
|
|
113
|
+
name = node.module + "." + item.name
|
|
114
|
+
self.alias[item.asname or item.name] = name
|
|
115
|
+
self.record_import(name, node.lineno)
|
|
116
|
+
|
|
117
|
+
@contextmanager
|
|
118
|
+
def nested(self, name: str) -> Iterator[None]:
|
|
119
|
+
saved = self.scope, self.alias, self.bindings, self.constants, self.guard
|
|
120
|
+
self.scope = self.scope + "." + identifier(name)
|
|
121
|
+
self.alias, self.bindings, self.constants = (
|
|
122
|
+
self.alias.copy(),
|
|
123
|
+
self.bindings.copy(),
|
|
124
|
+
self.constants.copy(),
|
|
125
|
+
)
|
|
126
|
+
self.guard = 0
|
|
127
|
+
try:
|
|
128
|
+
yield
|
|
129
|
+
finally:
|
|
130
|
+
self.scope, self.alias, self.bindings, self.constants, self.guard = saved
|
|
131
|
+
|
|
132
|
+
def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
133
|
+
with self.nested(node.name):
|
|
134
|
+
for arg in ast.walk(node.args):
|
|
135
|
+
if isinstance(arg, ast.arg):
|
|
136
|
+
self.bind(arg.arg, None)
|
|
137
|
+
for stmt in node.body:
|
|
138
|
+
self.visit(stmt)
|
|
139
|
+
|
|
140
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
141
|
+
|
|
142
|
+
def visit_If(self, node: ast.If) -> None:
|
|
143
|
+
# Both paths are possible. A post-branch binding needs agreement.
|
|
144
|
+
self.visit(node.test)
|
|
145
|
+
before = self.alias.copy(), self.bindings.copy(), self.constants.copy()
|
|
146
|
+
for stmt in node.body:
|
|
147
|
+
self.visit(stmt)
|
|
148
|
+
taken = self.alias, self.bindings, self.constants
|
|
149
|
+
self.alias, self.bindings, self.constants = before
|
|
150
|
+
for stmt in node.orelse:
|
|
151
|
+
self.visit(stmt)
|
|
152
|
+
self.alias = {k: v for k, v in self.alias.items() if taken[0].get(k) == v}
|
|
153
|
+
self.bindings = {k: v for k, v in self.bindings.items() if taken[1].get(k) == v}
|
|
154
|
+
self.constants = {k: v for k, v in self.constants.items() if taken[2].get(k) is v}
|
|
155
|
+
|
|
156
|
+
def visit_ClassDef(self, node: ast.ClassDef) -> None:
|
|
157
|
+
with self.nested(node.name):
|
|
158
|
+
self.generic_visit(node)
|
|
159
|
+
|
|
160
|
+
def visit_Try(self, node: ast.Try | ast.TryStar) -> None:
|
|
161
|
+
self.guard += bool(node.handlers)
|
|
162
|
+
for stmt in node.body:
|
|
163
|
+
self.visit(stmt)
|
|
164
|
+
self.guard -= bool(node.handlers)
|
|
165
|
+
for child in [*node.handlers, *node.orelse, *node.finalbody]:
|
|
166
|
+
self.visit(child)
|
|
167
|
+
|
|
168
|
+
visit_TryStar = visit_Try
|
|
169
|
+
|
|
170
|
+
def resolve(self, expr: ast.expr) -> ast.expr:
|
|
171
|
+
if isinstance(expr, ast.Name) and credential_field(expr.id):
|
|
172
|
+
return expr
|
|
173
|
+
return self.constants.get(expr.id, expr) if isinstance(expr, ast.Name) else expr
|
|
174
|
+
|
|
175
|
+
def bind(self, target: str, value: ast.expr | None) -> None:
|
|
176
|
+
origin = self.producer(value)
|
|
177
|
+
literal = self.resolve(value) if value else None
|
|
178
|
+
alias = self.symbol(value) if isinstance(value, (ast.Attribute, ast.Name)) else ""
|
|
179
|
+
self.alias.pop(target, None)
|
|
180
|
+
self.constants.pop(target, None)
|
|
181
|
+
self.bindings.pop(target, None)
|
|
182
|
+
if origin:
|
|
183
|
+
self.bindings[target] = origin
|
|
184
|
+
if isinstance(literal, (ast.Constant, ast.Dict)):
|
|
185
|
+
self.constants[target] = literal
|
|
186
|
+
if alias:
|
|
187
|
+
self.alias[target] = alias
|
|
188
|
+
|
|
189
|
+
def visit_Assign(self, node: ast.Assign) -> None:
|
|
190
|
+
self.visit(node.value)
|
|
191
|
+
for target in node.targets:
|
|
192
|
+
if isinstance(target, ast.Name):
|
|
193
|
+
self.record_credential(target.id, node)
|
|
194
|
+
self.bind(target.id, node.value)
|
|
195
|
+
|
|
196
|
+
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
|
|
197
|
+
if node.value:
|
|
198
|
+
self.visit(node.value)
|
|
199
|
+
if isinstance(node.target, ast.Name):
|
|
200
|
+
self.record_credential(node.target.id, node)
|
|
201
|
+
self.bind(node.target.id, node.value)
|
|
202
|
+
|
|
203
|
+
def record_credential(self, name: str, node: ast.expr | ast.stmt | ast.keyword) -> None:
|
|
204
|
+
if field := credential_field(name):
|
|
205
|
+
self.secret_references.append(
|
|
206
|
+
evidence(self.file, "Credential field: " + field, node.lineno, node.end_lineno)
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
def visit_keyword(self, node: ast.keyword) -> None:
|
|
210
|
+
if node.arg:
|
|
211
|
+
self.record_credential(node.arg, node)
|
|
212
|
+
self.generic_visit(node)
|
|
213
|
+
|
|
214
|
+
def producer(self, expr: ast.AST | None) -> str | None:
|
|
215
|
+
if isinstance(expr, ast.Name):
|
|
216
|
+
return self.bindings.get(expr.id)
|
|
217
|
+
return self.produced.get(expr) if expr else None
|
|
218
|
+
|
|
219
|
+
def environment_ref(self, node: ast.AST) -> None:
|
|
220
|
+
if isinstance(node, ast.Constant) and (name := env_name(node.value)):
|
|
221
|
+
self.env.add(name)
|
|
222
|
+
|
|
223
|
+
def visit_Subscript(self, node: ast.Subscript) -> None:
|
|
224
|
+
if self.symbol(node.value) == "os.environ":
|
|
225
|
+
self.environment_ref(node.slice)
|
|
226
|
+
self.generic_visit(node)
|
|
227
|
+
|
|
228
|
+
def pairs(self, key: str | None, value: ast.expr) -> Iterator[tuple[str, ast.expr]]:
|
|
229
|
+
expr = self.resolve(value)
|
|
230
|
+
if key in {None, "search_kwargs", "model_kwargs", "generation_kwargs"} and isinstance(
|
|
231
|
+
expr, ast.Dict
|
|
232
|
+
):
|
|
233
|
+
for k, v in zip(expr.keys, expr.values, strict=True):
|
|
234
|
+
if isinstance(k, ast.Constant) and isinstance(k.value, str):
|
|
235
|
+
yield k.value, self.resolve(v)
|
|
236
|
+
elif key:
|
|
237
|
+
yield key, expr
|
|
238
|
+
|
|
239
|
+
def inputs(self, expr: ast.expr) -> Iterator[str]:
|
|
240
|
+
if origin := self.producer(expr):
|
|
241
|
+
yield origin
|
|
242
|
+
elif isinstance(expr, (ast.List, ast.Tuple, ast.Set)):
|
|
243
|
+
for child in expr.elts:
|
|
244
|
+
yield from self.inputs(child)
|
|
245
|
+
elif isinstance(expr, ast.Dict):
|
|
246
|
+
for child in expr.values:
|
|
247
|
+
yield from self.inputs(child)
|
|
248
|
+
|
|
249
|
+
def visit_Call(self, node: ast.Call) -> None:
|
|
250
|
+
self.generic_visit(node)
|
|
251
|
+
name = self.symbol(node.func)
|
|
252
|
+
short = name.rsplit(".", 1)[-1]
|
|
253
|
+
if name in {"os.environ.get", "os.getenv"} and node.args:
|
|
254
|
+
self.environment_ref(node.args[0])
|
|
255
|
+
ev = evidence(self.file, "call " + identifier(name), node.lineno, node.end_lineno)
|
|
256
|
+
if name in {
|
|
257
|
+
"yaml.load",
|
|
258
|
+
"yaml.unsafe_load",
|
|
259
|
+
"yaml.full_load",
|
|
260
|
+
"yaml.safe_load",
|
|
261
|
+
"yaml.load_all",
|
|
262
|
+
"yaml.safe_load_all",
|
|
263
|
+
"yaml.unsafe_load_all",
|
|
264
|
+
}:
|
|
265
|
+
loader = next((kw.value for kw in node.keywords if kw.arg == "Loader"), None)
|
|
266
|
+
if loader is None and len(node.args) > 1:
|
|
267
|
+
loader = node.args[1]
|
|
268
|
+
known = self.symbol(loader) if loader else ""
|
|
269
|
+
safe = (
|
|
270
|
+
"safe_load" in short
|
|
271
|
+
and "unsafe" not in short
|
|
272
|
+
or known in {"yaml.SafeLoader", "yaml.CSafeLoader"}
|
|
273
|
+
)
|
|
274
|
+
unsafe = "unsafe_load" in short or known in {
|
|
275
|
+
"yaml.Loader",
|
|
276
|
+
"yaml.UnsafeLoader",
|
|
277
|
+
"yaml.CLoader",
|
|
278
|
+
"yaml.CUnsafeLoader",
|
|
279
|
+
}
|
|
280
|
+
self.observations.append(
|
|
281
|
+
Observation(
|
|
282
|
+
kind="yaml_load",
|
|
283
|
+
state="safe" if safe else "unsafe" if unsafe else "unknown",
|
|
284
|
+
evidence=ev,
|
|
285
|
+
anchor=self.anchor(name),
|
|
286
|
+
)
|
|
287
|
+
)
|
|
288
|
+
if short in {"debug", "info", "warning", "error", "exception", "critical"} and any(
|
|
289
|
+
p in {"log", "logging", "logger"} for p in name.lower().split(".")[:-1]
|
|
290
|
+
):
|
|
291
|
+
symbols = [
|
|
292
|
+
n.id if isinstance(n, ast.Name) else n.attr
|
|
293
|
+
for n in ast.walk(node)
|
|
294
|
+
if isinstance(n, (ast.Name, ast.Attribute))
|
|
295
|
+
]
|
|
296
|
+
sensitive = any(
|
|
297
|
+
re.search("secret|password|api_key|token|prompt|document|context", s, re.I)
|
|
298
|
+
for s in symbols
|
|
299
|
+
)
|
|
300
|
+
sensitive |= any(
|
|
301
|
+
isinstance(n, ast.Constant)
|
|
302
|
+
and isinstance(n.value, str)
|
|
303
|
+
and identifier(n.value) != n.value[:160]
|
|
304
|
+
for n in ast.walk(node)
|
|
305
|
+
)
|
|
306
|
+
self.observations.append(
|
|
307
|
+
Observation(
|
|
308
|
+
kind="logging",
|
|
309
|
+
state="unsafe" if sensitive else "unknown",
|
|
310
|
+
evidence=ev,
|
|
311
|
+
anchor=self.anchor(name),
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
kind: Kind | None = SYMBOLS.get(short.lower())
|
|
315
|
+
if short in {
|
|
316
|
+
"from_documents",
|
|
317
|
+
"from_texts",
|
|
318
|
+
"from_template",
|
|
319
|
+
"from_messages",
|
|
320
|
+
"from_defaults",
|
|
321
|
+
} and isinstance(node.func, ast.Attribute):
|
|
322
|
+
kind = SYMBOLS.get(self.symbol(node.func.value).split(".")[-1].lower())
|
|
323
|
+
if name.endswith(
|
|
324
|
+
(
|
|
325
|
+
".chat.completions.create",
|
|
326
|
+
".messages.create",
|
|
327
|
+
".models.generate_content",
|
|
328
|
+
".generate_content",
|
|
329
|
+
)
|
|
330
|
+
):
|
|
331
|
+
kind = "generation"
|
|
332
|
+
if name.endswith(".embeddings.create"):
|
|
333
|
+
kind = "embedding"
|
|
334
|
+
known_technology = technologies(name)
|
|
335
|
+
if not kind and not known_technology:
|
|
336
|
+
return
|
|
337
|
+
status_kind: Kind = kind or "unknown"
|
|
338
|
+
component_id = self.anchor(name)
|
|
339
|
+
self.produced[node] = component_id
|
|
340
|
+
configured: set[str] = set()
|
|
341
|
+
properties: dict[str, Scalar] = {}
|
|
342
|
+
for kw in node.keywords:
|
|
343
|
+
if kw.arg is None or kw.arg in {"search_kwargs", "model_kwargs", "generation_kwargs"}:
|
|
344
|
+
options = self.resolve(kw.value)
|
|
345
|
+
if not isinstance(options, ast.Dict) or any(
|
|
346
|
+
not isinstance(k, ast.Constant) for k in options.keys
|
|
347
|
+
):
|
|
348
|
+
configured.add("dynamic_options")
|
|
349
|
+
for key, expr in self.pairs(kw.arg, kw.value):
|
|
350
|
+
if key in PROPERTIES:
|
|
351
|
+
prop = PROPERTIES[key]
|
|
352
|
+
configured.add(prop)
|
|
353
|
+
if isinstance(expr, ast.Constant):
|
|
354
|
+
found, val = safe_value(prop, expr.value)
|
|
355
|
+
if found:
|
|
356
|
+
properties[prop] = val
|
|
357
|
+
elif (
|
|
358
|
+
isinstance(expr, ast.UnaryOp)
|
|
359
|
+
and isinstance(expr.op, ast.USub)
|
|
360
|
+
and isinstance(expr.operand, ast.Constant)
|
|
361
|
+
and isinstance(expr.operand.value, (int, float))
|
|
362
|
+
and not isinstance(expr.operand.value, bool)
|
|
363
|
+
):
|
|
364
|
+
found, val = safe_value(prop, -expr.operand.value)
|
|
365
|
+
if found:
|
|
366
|
+
properties[prop] = val
|
|
367
|
+
self.components.append(
|
|
368
|
+
RAGComponent(
|
|
369
|
+
id=component_id,
|
|
370
|
+
name=identifier(name),
|
|
371
|
+
kind=status_kind,
|
|
372
|
+
scope=self.scope,
|
|
373
|
+
detection="unknown"
|
|
374
|
+
if not kind
|
|
375
|
+
else "confirmed"
|
|
376
|
+
if known_technology
|
|
377
|
+
else "inferred",
|
|
378
|
+
confidence="low" if not kind else "high" if known_technology else "medium",
|
|
379
|
+
evidence=ev,
|
|
380
|
+
configured=sorted(configured),
|
|
381
|
+
properties=properties,
|
|
382
|
+
guarded=bool(self.guard),
|
|
383
|
+
)
|
|
384
|
+
)
|
|
385
|
+
for arg in [*node.args, *(kw.value for kw in node.keywords)]:
|
|
386
|
+
for source in self.inputs(arg):
|
|
387
|
+
self.edges.append(
|
|
388
|
+
Relationship(
|
|
389
|
+
source=source, target=component_id, relation="argument", evidence=ev
|
|
390
|
+
)
|
|
391
|
+
)
|
|
392
|
+
if isinstance(node.func, ast.Attribute) and (receiver := self.producer(node.func.value)):
|
|
393
|
+
self.edges.append(
|
|
394
|
+
Relationship(source=receiver, target=component_id, relation="receiver", evidence=ev)
|
|
395
|
+
)
|