guardtrellis 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.
- guardtrellis/__init__.py +31 -0
- guardtrellis/guard.py +276 -0
- guardtrellis/json_check.py +170 -0
- guardtrellis/models.py +149 -0
- guardtrellis/py.typed +0 -0
- guardtrellis/scanners.py +162 -0
- guardtrellis/tools.py +87 -0
- guardtrellis-0.1.0.dist-info/METADATA +222 -0
- guardtrellis-0.1.0.dist-info/RECORD +11 -0
- guardtrellis-0.1.0.dist-info/WHEEL +4 -0
- guardtrellis-0.1.0.dist-info/licenses/LICENSE +202 -0
guardtrellis/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""GuardTrellis: explicit, local boundaries around model and tool calls."""
|
|
2
|
+
|
|
3
|
+
from .guard import Guard, Scanner
|
|
4
|
+
from .json_check import JSONScanner
|
|
5
|
+
from .models import Action, Check, Edit, Finding, Rejected, Result, RunResult, Stage, Trace
|
|
6
|
+
from .scanners import InvisibleScanner, LiteralScanner, PIIScanner, SecretScanner
|
|
7
|
+
from .tools import ToolGuard, ToolResult
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Action",
|
|
13
|
+
"Check",
|
|
14
|
+
"Edit",
|
|
15
|
+
"Finding",
|
|
16
|
+
"Guard",
|
|
17
|
+
"InvisibleScanner",
|
|
18
|
+
"JSONScanner",
|
|
19
|
+
"LiteralScanner",
|
|
20
|
+
"PIIScanner",
|
|
21
|
+
"Rejected",
|
|
22
|
+
"Result",
|
|
23
|
+
"RunResult",
|
|
24
|
+
"Scanner",
|
|
25
|
+
"SecretScanner",
|
|
26
|
+
"Stage",
|
|
27
|
+
"ToolGuard",
|
|
28
|
+
"ToolResult",
|
|
29
|
+
"Trace",
|
|
30
|
+
"__version__",
|
|
31
|
+
]
|
guardtrellis/guard.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Ordered checks and provider-independent, complete-response callback integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextvars
|
|
7
|
+
import inspect
|
|
8
|
+
import math
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
11
|
+
from dataclasses import replace
|
|
12
|
+
from functools import partial
|
|
13
|
+
from typing import Protocol, TypeVar, cast
|
|
14
|
+
|
|
15
|
+
from .models import Action, Check, Finding, Result, RunResult, Stage, Trace, combine_actions
|
|
16
|
+
|
|
17
|
+
T = TypeVar("T")
|
|
18
|
+
_IDENTIFIER = re.compile(r"[a-zA-Z][a-zA-Z0-9_]{0,63}\Z")
|
|
19
|
+
MAX_FINDINGS = 256
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Scanner(Protocol):
|
|
23
|
+
"""Custom scanners are trusted code; never put content in names or finding codes."""
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def name(self) -> str: ...
|
|
27
|
+
|
|
28
|
+
def scan(self, text: str, *, stage: Stage) -> Check | Awaitable[Check]: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _consume_task(task: asyncio.Task[T]) -> None:
|
|
32
|
+
if not task.cancelled():
|
|
33
|
+
task.exception()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _discard_worker_result(future: asyncio.Future[T | Awaitable[T]]) -> None:
|
|
37
|
+
if future.cancelled() or future.exception() is not None:
|
|
38
|
+
return
|
|
39
|
+
value = future.result()
|
|
40
|
+
if inspect.iscoroutine(value):
|
|
41
|
+
value.close()
|
|
42
|
+
elif isinstance(value, asyncio.Future):
|
|
43
|
+
value.cancel()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def _invoke(function: Callable[[], T | Awaitable[T]]) -> T:
|
|
47
|
+
if inspect.iscoroutinefunction(function):
|
|
48
|
+
return await cast(Awaitable[T], function())
|
|
49
|
+
# Copy context like to_thread, but retain the future to dispose of late awaitables.
|
|
50
|
+
# Cancelling a thread's await cannot stop that thread from returning a coroutine.
|
|
51
|
+
worker = asyncio.get_running_loop().run_in_executor(
|
|
52
|
+
None, contextvars.copy_context().run, function
|
|
53
|
+
)
|
|
54
|
+
try:
|
|
55
|
+
value = await asyncio.shield(worker)
|
|
56
|
+
except asyncio.CancelledError:
|
|
57
|
+
worker.add_done_callback(_discard_worker_result)
|
|
58
|
+
raise
|
|
59
|
+
if inspect.isawaitable(value):
|
|
60
|
+
return await value
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def _bounded(function: Callable[[], T | Awaitable[T]], wait_seconds: float) -> T:
|
|
65
|
+
task = asyncio.create_task(_invoke(function))
|
|
66
|
+
try:
|
|
67
|
+
# wait_for/timeout can accept late results if user code suppresses cancellation.
|
|
68
|
+
done, _ = await asyncio.wait({task}, timeout=wait_seconds)
|
|
69
|
+
if not done:
|
|
70
|
+
raise TimeoutError
|
|
71
|
+
return task.result()
|
|
72
|
+
finally:
|
|
73
|
+
if not task.done():
|
|
74
|
+
task.cancel()
|
|
75
|
+
task.add_done_callback(_consume_task)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _sync_value(value: T | Awaitable[T]) -> T:
|
|
79
|
+
if inspect.isawaitable(value):
|
|
80
|
+
if inspect.iscoroutine(value):
|
|
81
|
+
value.close()
|
|
82
|
+
raise TypeError("Use the asynchronous entry point for awaitable work")
|
|
83
|
+
return value
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _error(stage: Stage, code: str) -> Result:
|
|
87
|
+
return Result(Action.ERROR, stage, None, (Finding(code, scanner="guard"),))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _Pipeline:
|
|
91
|
+
def __init__(self, text: str, stage: Stage, max_chars: int):
|
|
92
|
+
self.text = text
|
|
93
|
+
self.stage = stage
|
|
94
|
+
self.max_chars = max_chars
|
|
95
|
+
self.action = Action.ALLOW
|
|
96
|
+
self.revision = 0
|
|
97
|
+
self.findings: list[Finding] = []
|
|
98
|
+
self.trace: list[Trace] = []
|
|
99
|
+
|
|
100
|
+
def apply(self, check: Check, name: str, index: int) -> None:
|
|
101
|
+
# Validate a custom scanner's entire response before changing state.
|
|
102
|
+
if not isinstance(check, Check) or not isinstance(check.action, Action):
|
|
103
|
+
raise ValueError("Invalid scanner decision")
|
|
104
|
+
if len(check.findings) > MAX_FINDINGS or len(check.edits) > MAX_FINDINGS:
|
|
105
|
+
raise ValueError("Scanner result limit exceeded")
|
|
106
|
+
if check.action == Action.ALLOW and (check.findings or check.edits):
|
|
107
|
+
raise ValueError("Allow cannot contain findings or edits")
|
|
108
|
+
if check.action != Action.ALLOW and not check.findings:
|
|
109
|
+
raise ValueError("Non-allow decisions require a reason")
|
|
110
|
+
if bool(check.edits) != (check.action == Action.REDACT):
|
|
111
|
+
raise ValueError("Only redact decisions may contain edits")
|
|
112
|
+
for finding in check.findings:
|
|
113
|
+
if not isinstance(finding, Finding) or not _IDENTIFIER.fullmatch(finding.code):
|
|
114
|
+
raise ValueError("Invalid finding")
|
|
115
|
+
if finding.start is None and finding.end is None:
|
|
116
|
+
continue
|
|
117
|
+
if (
|
|
118
|
+
type(finding.start) is not int
|
|
119
|
+
or type(finding.end) is not int
|
|
120
|
+
or not 0 <= finding.start < finding.end <= len(self.text)
|
|
121
|
+
):
|
|
122
|
+
raise ValueError("Invalid finding span")
|
|
123
|
+
previous = 0
|
|
124
|
+
for edit in sorted(check.edits, key=lambda item: item.start):
|
|
125
|
+
if (
|
|
126
|
+
type(edit.start) is not int
|
|
127
|
+
or type(edit.end) is not int
|
|
128
|
+
or not previous <= edit.start < edit.end <= len(self.text)
|
|
129
|
+
or not isinstance(edit.replacement, str)
|
|
130
|
+
):
|
|
131
|
+
raise ValueError("Invalid edit")
|
|
132
|
+
previous = edit.end
|
|
133
|
+
updated = self.text
|
|
134
|
+
for edit in sorted(check.edits, key=lambda item: item.start, reverse=True):
|
|
135
|
+
updated = updated[: edit.start] + edit.replacement + updated[edit.end :]
|
|
136
|
+
if len(updated) > self.max_chars:
|
|
137
|
+
raise ValueError("Transformed text exceeds limit")
|
|
138
|
+
before = self.revision
|
|
139
|
+
if check.action == Action.REDACT:
|
|
140
|
+
self.revision += 1
|
|
141
|
+
self.findings.extend(
|
|
142
|
+
replace(item, scanner=name, scanner_index=index, revision=before)
|
|
143
|
+
for item in check.findings
|
|
144
|
+
)
|
|
145
|
+
self.trace.append(Trace(name, index, check.action, before, self.revision))
|
|
146
|
+
self.text = updated
|
|
147
|
+
self.action = combine_actions(self.action, check.action)
|
|
148
|
+
|
|
149
|
+
def fail(self, name: str, index: int, code: str) -> None:
|
|
150
|
+
self.apply(Check(Action.ERROR, (Finding(code),)), name, index)
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def stopped(self) -> bool:
|
|
154
|
+
return self.action in (Action.BLOCK, Action.ERROR)
|
|
155
|
+
|
|
156
|
+
def result(self) -> Result:
|
|
157
|
+
return Result(
|
|
158
|
+
self.action,
|
|
159
|
+
self.stage,
|
|
160
|
+
None if self.stopped else self.text,
|
|
161
|
+
tuple(self.findings),
|
|
162
|
+
tuple(self.trace),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class Guard:
|
|
167
|
+
"""Explicit, ordered stage policies. An unconfigured stage allows bounded text.
|
|
168
|
+
|
|
169
|
+
Async timeout is per scanner/callback, not for the complete run. Cancellation
|
|
170
|
+
cannot terminate a worker thread or preempt an event-loop-blocking coroutine.
|
|
171
|
+
Synchronous entry points have no execution deadline.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def __init__(
|
|
175
|
+
self,
|
|
176
|
+
*,
|
|
177
|
+
input_scanners: Sequence[Scanner] = (),
|
|
178
|
+
output_scanners: Sequence[Scanner] = (),
|
|
179
|
+
retrieval_scanners: Sequence[Scanner] = (),
|
|
180
|
+
tool_scanners: Sequence[Scanner] = (),
|
|
181
|
+
max_chars: int = 100_000,
|
|
182
|
+
timeout_seconds: float = 5.0,
|
|
183
|
+
):
|
|
184
|
+
if type(max_chars) is not int or max_chars < 1:
|
|
185
|
+
raise ValueError("max_chars must be a positive integer")
|
|
186
|
+
if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
|
|
187
|
+
raise ValueError("timeout_seconds must be positive and finite")
|
|
188
|
+
self.max_chars = max_chars
|
|
189
|
+
self.timeout_seconds = timeout_seconds
|
|
190
|
+
self._scanners = {
|
|
191
|
+
Stage.INPUT: tuple(input_scanners),
|
|
192
|
+
Stage.OUTPUT: tuple(output_scanners),
|
|
193
|
+
Stage.RETRIEVAL: tuple(retrieval_scanners),
|
|
194
|
+
Stage.TOOL: tuple(tool_scanners),
|
|
195
|
+
}
|
|
196
|
+
for scanners in self._scanners.values():
|
|
197
|
+
for scanner in scanners:
|
|
198
|
+
if not _IDENTIFIER.fullmatch(scanner.name) or not callable(scanner.scan):
|
|
199
|
+
raise ValueError("Scanners require a static identifier name and scan method")
|
|
200
|
+
|
|
201
|
+
def _prepare(self, text: str, stage: Stage) -> _Pipeline | Result:
|
|
202
|
+
if not isinstance(stage, Stage):
|
|
203
|
+
raise ValueError("stage must be a Stage enum")
|
|
204
|
+
if not isinstance(text, str):
|
|
205
|
+
return _error(stage, "invalid_text_type")
|
|
206
|
+
if len(text) > self.max_chars:
|
|
207
|
+
return _error(stage, "text_limit_exceeded")
|
|
208
|
+
return _Pipeline(text, stage, self.max_chars)
|
|
209
|
+
|
|
210
|
+
def scan(self, text: str, *, stage: Stage = Stage.INPUT) -> Result:
|
|
211
|
+
pipeline = self._prepare(text, stage)
|
|
212
|
+
if isinstance(pipeline, Result):
|
|
213
|
+
return pipeline
|
|
214
|
+
for index, scanner in enumerate(self._scanners[stage]):
|
|
215
|
+
try:
|
|
216
|
+
check = _sync_value(scanner.scan(pipeline.text, stage=stage))
|
|
217
|
+
pipeline.apply(check, scanner.name, index)
|
|
218
|
+
except Exception:
|
|
219
|
+
pipeline.fail(scanner.name, index, "scanner_error")
|
|
220
|
+
if pipeline.stopped:
|
|
221
|
+
break
|
|
222
|
+
return pipeline.result()
|
|
223
|
+
|
|
224
|
+
async def ascan(self, text: str, *, stage: Stage = Stage.INPUT) -> Result:
|
|
225
|
+
pipeline = self._prepare(text, stage)
|
|
226
|
+
if isinstance(pipeline, Result):
|
|
227
|
+
return pipeline
|
|
228
|
+
for index, scanner in enumerate(self._scanners[stage]):
|
|
229
|
+
try:
|
|
230
|
+
check = await _bounded(
|
|
231
|
+
partial(scanner.scan, pipeline.text, stage=stage), self.timeout_seconds
|
|
232
|
+
)
|
|
233
|
+
pipeline.apply(check, scanner.name, index)
|
|
234
|
+
except TimeoutError:
|
|
235
|
+
pipeline.fail(scanner.name, index, "scanner_timeout")
|
|
236
|
+
except Exception:
|
|
237
|
+
pipeline.fail(scanner.name, index, "scanner_error")
|
|
238
|
+
if pipeline.stopped:
|
|
239
|
+
break
|
|
240
|
+
return pipeline.result()
|
|
241
|
+
|
|
242
|
+
def run(self, text: str, model: Callable[[str], str]) -> RunResult:
|
|
243
|
+
checked_input = self.scan(text, stage=Stage.INPUT)
|
|
244
|
+
if not checked_input.accepted:
|
|
245
|
+
return RunResult(checked_input.action, checked_input, None)
|
|
246
|
+
try:
|
|
247
|
+
output = _sync_value(model(checked_input.require_text()))
|
|
248
|
+
except Exception:
|
|
249
|
+
checked_output = _error(Stage.OUTPUT, "callback_error")
|
|
250
|
+
else:
|
|
251
|
+
checked_output = self.scan(output, stage=Stage.OUTPUT)
|
|
252
|
+
return RunResult(
|
|
253
|
+
combine_actions(checked_input.action, checked_output.action),
|
|
254
|
+
checked_input,
|
|
255
|
+
checked_output,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
async def arun(self, text: str, model: Callable[[str], str | Awaitable[str]]) -> RunResult:
|
|
259
|
+
checked_input = await self.ascan(text, stage=Stage.INPUT)
|
|
260
|
+
if not checked_input.accepted:
|
|
261
|
+
return RunResult(checked_input.action, checked_input, None)
|
|
262
|
+
try:
|
|
263
|
+
output = await _bounded(
|
|
264
|
+
lambda: model(checked_input.require_text()), self.timeout_seconds
|
|
265
|
+
)
|
|
266
|
+
except TimeoutError:
|
|
267
|
+
checked_output = _error(Stage.OUTPUT, "callback_timeout")
|
|
268
|
+
except Exception:
|
|
269
|
+
checked_output = _error(Stage.OUTPUT, "callback_error")
|
|
270
|
+
else:
|
|
271
|
+
checked_output = await self.ascan(output, stage=Stage.OUTPUT)
|
|
272
|
+
return RunResult(
|
|
273
|
+
combine_actions(checked_input.action, checked_output.action),
|
|
274
|
+
checked_input,
|
|
275
|
+
checked_output,
|
|
276
|
+
)
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Strict JSON and local Draft 2020-12 validation with bounded structural depth."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from jsonschema import Draft202012Validator
|
|
10
|
+
from jsonschema.exceptions import SchemaError
|
|
11
|
+
from referencing import Registry, Resource
|
|
12
|
+
from referencing.exceptions import Unresolvable
|
|
13
|
+
from referencing.jsonschema import DRAFT202012
|
|
14
|
+
|
|
15
|
+
from .models import Action, Check, Finding, Stage
|
|
16
|
+
|
|
17
|
+
Schema = dict[str, Any] | bool
|
|
18
|
+
_DIALECT = "https://json-schema.org/draft/2020-12/schema"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _JSONProblem(ValueError):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _constant(_: str) -> Any:
|
|
26
|
+
raise _JSONProblem("json_non_finite")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _float(value: str) -> float:
|
|
30
|
+
number = float(value)
|
|
31
|
+
if not math.isfinite(number):
|
|
32
|
+
raise _JSONProblem("json_non_finite")
|
|
33
|
+
return number
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
37
|
+
result: dict[str, Any] = {}
|
|
38
|
+
for key, value in pairs:
|
|
39
|
+
if key in result:
|
|
40
|
+
raise _JSONProblem("json_duplicate_key")
|
|
41
|
+
result[key] = value
|
|
42
|
+
return result
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _check_depth(text: str, limit: int) -> None:
|
|
46
|
+
depth = 0
|
|
47
|
+
in_string = False
|
|
48
|
+
escaped = False
|
|
49
|
+
for char in text:
|
|
50
|
+
if in_string:
|
|
51
|
+
if escaped:
|
|
52
|
+
escaped = False
|
|
53
|
+
elif char == "\\":
|
|
54
|
+
escaped = True
|
|
55
|
+
elif char == '"':
|
|
56
|
+
in_string = False
|
|
57
|
+
elif char == '"':
|
|
58
|
+
in_string = True
|
|
59
|
+
elif char in "[{":
|
|
60
|
+
depth += 1
|
|
61
|
+
if depth > limit:
|
|
62
|
+
raise _JSONProblem("json_too_deep")
|
|
63
|
+
elif char in "]}":
|
|
64
|
+
depth -= 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def strict_loads(text: str, *, max_depth: int = 32) -> Any:
|
|
68
|
+
_check_depth(text, max_depth)
|
|
69
|
+
try:
|
|
70
|
+
return json.loads(
|
|
71
|
+
text, object_pairs_hook=_object, parse_constant=_constant, parse_float=_float
|
|
72
|
+
)
|
|
73
|
+
except _JSONProblem:
|
|
74
|
+
raise
|
|
75
|
+
except (ValueError, RecursionError):
|
|
76
|
+
raise _JSONProblem("json_invalid") from None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _check_schema_policy(schema: Schema) -> None:
|
|
80
|
+
"""Check schema positions AND referenced extension data, without inspecting const data.
|
|
81
|
+
|
|
82
|
+
JSON pointers can turn arbitrary extension fields into active schemas. Following
|
|
83
|
+
them prevents hiding a regex/remote reference outside normal schema positions.
|
|
84
|
+
"""
|
|
85
|
+
root = DRAFT202012.create_resource(schema)
|
|
86
|
+
registry = Registry().with_resource("urn:guardtrellis:root", root)
|
|
87
|
+
resolver = registry.resolver("urn:guardtrellis:root").in_subresource(root)
|
|
88
|
+
pending: list[tuple[Resource[Any], Any]] = [(root, resolver)]
|
|
89
|
+
visited: set[int] = set()
|
|
90
|
+
while pending:
|
|
91
|
+
resource, current_resolver = pending.pop()
|
|
92
|
+
node = resource.contents
|
|
93
|
+
if id(node) in visited or isinstance(node, bool):
|
|
94
|
+
continue
|
|
95
|
+
visited.add(id(node))
|
|
96
|
+
Draft202012Validator.check_schema(node)
|
|
97
|
+
if node.get("$schema", _DIALECT).rstrip("#") != _DIALECT:
|
|
98
|
+
raise ValueError
|
|
99
|
+
if "pattern" in node or "patternProperties" in node:
|
|
100
|
+
raise ValueError
|
|
101
|
+
for keyword in ("$ref", "$dynamicRef"):
|
|
102
|
+
if keyword not in node:
|
|
103
|
+
continue
|
|
104
|
+
if not node[keyword].startswith("#"):
|
|
105
|
+
raise ValueError
|
|
106
|
+
try:
|
|
107
|
+
resolved = current_resolver.lookup(node[keyword])
|
|
108
|
+
except Unresolvable:
|
|
109
|
+
# A missing target is an explicit runtime ERROR if the branch is used.
|
|
110
|
+
continue
|
|
111
|
+
pending.append((DRAFT202012.create_resource(resolved.contents), resolved.resolver))
|
|
112
|
+
for child in resource.subresources():
|
|
113
|
+
pending.append((child, current_resolver.in_subresource(child)))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class JSONScanner:
|
|
117
|
+
"""Validate JSON and an optional, trusted Draft 2020-12 schema.
|
|
118
|
+
|
|
119
|
+
References must be document-local fragments. Regex schema keywords are
|
|
120
|
+
rejected to avoid exposing Python's backtracking regex engine to instances.
|
|
121
|
+
Formats remain annotations, per JSON Schema's default behavior.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
name = "json"
|
|
125
|
+
|
|
126
|
+
def __init__(
|
|
127
|
+
self,
|
|
128
|
+
schema: Schema | None = None,
|
|
129
|
+
*,
|
|
130
|
+
max_depth: int = 32,
|
|
131
|
+
require_object: bool = False,
|
|
132
|
+
):
|
|
133
|
+
if type(max_depth) is not int or not 1 <= max_depth <= 64:
|
|
134
|
+
raise ValueError("max_depth must be an integer from 1 to 64")
|
|
135
|
+
self.max_depth = max_depth
|
|
136
|
+
self.require_object = require_object
|
|
137
|
+
self._validator: Draft202012Validator | None = None
|
|
138
|
+
if schema is not None:
|
|
139
|
+
try:
|
|
140
|
+
# Snapshot config so mutation of the caller's schema cannot change a policy.
|
|
141
|
+
if not isinstance(schema, (dict, bool)):
|
|
142
|
+
raise ValueError
|
|
143
|
+
serialized = json.dumps(schema, allow_nan=False)
|
|
144
|
+
if len(serialized) > 100_000:
|
|
145
|
+
raise ValueError
|
|
146
|
+
copied = strict_loads(serialized, max_depth=64)
|
|
147
|
+
Draft202012Validator.check_schema(copied)
|
|
148
|
+
_check_schema_policy(copied)
|
|
149
|
+
# Supplying a Registry explicitly prevents legacy automatic URL retrieval.
|
|
150
|
+
self._validator = Draft202012Validator(copied, registry=Registry())
|
|
151
|
+
except (ValueError, TypeError, RecursionError, SchemaError):
|
|
152
|
+
raise ValueError(
|
|
153
|
+
"Schema must be bounded Draft 2020-12 with local references "
|
|
154
|
+
"and no regex keywords"
|
|
155
|
+
) from None
|
|
156
|
+
|
|
157
|
+
def scan(self, text: str, *, stage: Stage) -> Check:
|
|
158
|
+
try:
|
|
159
|
+
instance = strict_loads(text, max_depth=self.max_depth)
|
|
160
|
+
except _JSONProblem as problem:
|
|
161
|
+
return Check(Action.BLOCK, (Finding(str(problem)),))
|
|
162
|
+
if self.require_object and not isinstance(instance, dict):
|
|
163
|
+
return Check(Action.BLOCK, (Finding("json_object_required"),))
|
|
164
|
+
if self._validator is not None:
|
|
165
|
+
# Consume one error only; do not retain ValidationError (it holds the instance).
|
|
166
|
+
# Resolution/runtime errors propagate into Guard's explicit ERROR result.
|
|
167
|
+
error = next(self._validator.iter_errors(instance), None)
|
|
168
|
+
if error is not None:
|
|
169
|
+
return Check(Action.BLOCK, (Finding("json_schema_mismatch"),))
|
|
170
|
+
return Check()
|
guardtrellis/models.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Public, payload-safe result types. Explicit serialization may still expose text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import StrEnum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Action(StrEnum):
|
|
11
|
+
ALLOW = "allow"
|
|
12
|
+
WARN = "warn"
|
|
13
|
+
REDACT = "redact"
|
|
14
|
+
BLOCK = "block"
|
|
15
|
+
ERROR = "error"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Stage(StrEnum):
|
|
19
|
+
INPUT = "input"
|
|
20
|
+
OUTPUT = "output"
|
|
21
|
+
RETRIEVAL = "retrieval"
|
|
22
|
+
TOOL = "tool"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Finding:
|
|
27
|
+
"""Offsets are half-open Python character indices in the indicated text revision.
|
|
28
|
+
|
|
29
|
+
Codes and scanner names must be static metadata, never matched text.
|
|
30
|
+
The orchestrator supplies revision, scanner, and scanner_index.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
code: str
|
|
34
|
+
start: int | None = None
|
|
35
|
+
end: int | None = None
|
|
36
|
+
scanner: str = ""
|
|
37
|
+
scanner_index: int = -1
|
|
38
|
+
revision: int = 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Edit:
|
|
43
|
+
"""A replacement in the current scanner's input, never a rehydration map."""
|
|
44
|
+
|
|
45
|
+
start: int
|
|
46
|
+
end: int
|
|
47
|
+
replacement: str = field(default="[REDACTED]", repr=False)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Check:
|
|
52
|
+
"""A scanner decision; REDACT requires non-overlapping edits and findings."""
|
|
53
|
+
|
|
54
|
+
action: Action = Action.ALLOW
|
|
55
|
+
findings: tuple[Finding, ...] = ()
|
|
56
|
+
edits: tuple[Edit, ...] = field(default=(), repr=False)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Trace:
|
|
61
|
+
scanner: str
|
|
62
|
+
scanner_index: int
|
|
63
|
+
action: Action
|
|
64
|
+
revision_before: int
|
|
65
|
+
revision_after: int
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Rejected(RuntimeError):
|
|
69
|
+
"""Raised by require_text when a result has no deliverable content."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class Result:
|
|
74
|
+
action: Action
|
|
75
|
+
stage: Stage
|
|
76
|
+
text: str | None = field(repr=False)
|
|
77
|
+
findings: tuple[Finding, ...] = ()
|
|
78
|
+
trace: tuple[Trace, ...] = ()
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def accepted(self) -> bool:
|
|
82
|
+
return self.action in (Action.ALLOW, Action.WARN, Action.REDACT)
|
|
83
|
+
|
|
84
|
+
def require_text(self) -> str:
|
|
85
|
+
if not self.accepted or self.text is None:
|
|
86
|
+
raise Rejected(f"GuardTrellis rejected content: {self.action.value}")
|
|
87
|
+
return self.text
|
|
88
|
+
|
|
89
|
+
def diagnostics(self) -> dict[str, Any]:
|
|
90
|
+
"""The supported metadata-only logging interface (unlike dataclasses.asdict)."""
|
|
91
|
+
return {
|
|
92
|
+
"action": self.action.value,
|
|
93
|
+
"stage": self.stage.value,
|
|
94
|
+
"findings": [
|
|
95
|
+
{
|
|
96
|
+
"code": item.code,
|
|
97
|
+
"start": item.start,
|
|
98
|
+
"end": item.end,
|
|
99
|
+
"scanner": item.scanner,
|
|
100
|
+
"scanner_index": item.scanner_index,
|
|
101
|
+
"revision": item.revision,
|
|
102
|
+
}
|
|
103
|
+
for item in self.findings
|
|
104
|
+
],
|
|
105
|
+
"trace": [
|
|
106
|
+
{
|
|
107
|
+
"scanner": item.scanner,
|
|
108
|
+
"scanner_index": item.scanner_index,
|
|
109
|
+
"action": item.action.value,
|
|
110
|
+
"revision_before": item.revision_before,
|
|
111
|
+
"revision_after": item.revision_after,
|
|
112
|
+
}
|
|
113
|
+
for item in self.trace
|
|
114
|
+
],
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class RunResult:
|
|
120
|
+
action: Action
|
|
121
|
+
input_result: Result
|
|
122
|
+
output_result: Result | None
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def text(self) -> str | None:
|
|
126
|
+
if self.output_result is None:
|
|
127
|
+
return None
|
|
128
|
+
return self.output_result.text
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def accepted(self) -> bool:
|
|
132
|
+
return self.output_result is not None and self.output_result.accepted
|
|
133
|
+
|
|
134
|
+
def require_text(self) -> str:
|
|
135
|
+
if not self.accepted or self.text is None:
|
|
136
|
+
raise Rejected(f"GuardTrellis rejected call: {self.action.value}")
|
|
137
|
+
return self.text
|
|
138
|
+
|
|
139
|
+
def diagnostics(self) -> dict[str, Any]:
|
|
140
|
+
return {
|
|
141
|
+
"action": self.action.value,
|
|
142
|
+
"input": self.input_result.diagnostics(),
|
|
143
|
+
"output": self.output_result.diagnostics() if self.output_result else None,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def combine_actions(*actions: Action) -> Action:
|
|
148
|
+
priority = (Action.ALLOW, Action.WARN, Action.REDACT, Action.BLOCK, Action.ERROR)
|
|
149
|
+
return max(actions, key=priority.index)
|
guardtrellis/py.typed
ADDED
|
File without changes
|
guardtrellis/scanners.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Small, deterministic format detectors. These are not semantic safety classifiers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from collections.abc import Iterable, Sequence
|
|
8
|
+
|
|
9
|
+
from .guard import MAX_FINDINGS
|
|
10
|
+
from .models import Action, Check, Edit, Finding, Stage
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _validate_action(action: Action) -> None:
|
|
14
|
+
if not isinstance(action, Action) or action not in (Action.WARN, Action.REDACT, Action.BLOCK):
|
|
15
|
+
raise ValueError("Detector action must be WARN, REDACT, or BLOCK")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _decision(findings: Iterable[Finding], action: Action, replacement: str) -> Check:
|
|
19
|
+
collected = []
|
|
20
|
+
for finding in findings:
|
|
21
|
+
collected.append(finding)
|
|
22
|
+
if len(collected) > MAX_FINDINGS:
|
|
23
|
+
return Check(Action.ERROR, (Finding("finding_limit_exceeded"),))
|
|
24
|
+
if not collected:
|
|
25
|
+
return Check()
|
|
26
|
+
ordered = tuple(sorted(collected, key=lambda item: (item.start or 0, item.end or 0, item.code)))
|
|
27
|
+
edits: list[Edit] = []
|
|
28
|
+
if action == Action.REDACT:
|
|
29
|
+
for item in ordered:
|
|
30
|
+
assert item.start is not None and item.end is not None
|
|
31
|
+
if edits and item.start < edits[-1].end:
|
|
32
|
+
previous = edits.pop()
|
|
33
|
+
edits.append(Edit(previous.start, max(previous.end, item.end), replacement))
|
|
34
|
+
else:
|
|
35
|
+
edits.append(Edit(item.start, item.end, replacement))
|
|
36
|
+
return Check(action, ordered, tuple(edits))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PIIScanner:
|
|
40
|
+
"""ASCII email, contiguous international +phone (8-15 digits), US SSN shapes.
|
|
41
|
+
|
|
42
|
+
This does not identify people, validate issuance, or cover all PII formats.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
name = "pii"
|
|
46
|
+
_patterns = {
|
|
47
|
+
"email": re.compile(
|
|
48
|
+
r"(?<![\w.!#$%&'*+/=?^`{|}~@-])"
|
|
49
|
+
r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]"
|
|
50
|
+
r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{0,63}"
|
|
51
|
+
r"@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.){1,8}"
|
|
52
|
+
r"[A-Za-z]{2,63}(?![\w@-])"
|
|
53
|
+
),
|
|
54
|
+
"phone": re.compile(r"(?<![\w+])\+[1-9][0-9]{7,14}(?!\w)"),
|
|
55
|
+
"ssn": re.compile(
|
|
56
|
+
r"(?<!\w)(?!000|666|9[0-9]{2})[0-9]{3}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}(?!\w)"
|
|
57
|
+
),
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
*,
|
|
63
|
+
formats: Sequence[str] = ("email", "phone", "ssn"),
|
|
64
|
+
action: Action = Action.REDACT,
|
|
65
|
+
):
|
|
66
|
+
_validate_action(action)
|
|
67
|
+
if not formats or any(name not in self._patterns for name in formats):
|
|
68
|
+
raise ValueError("Unsupported or empty PII format selection")
|
|
69
|
+
self._formats = tuple(dict.fromkeys(formats))
|
|
70
|
+
self.action = action
|
|
71
|
+
|
|
72
|
+
def scan(self, text: str, *, stage: Stage) -> Check:
|
|
73
|
+
findings = (
|
|
74
|
+
Finding(f"pii_{name}", match.start(), match.end())
|
|
75
|
+
for name in self._formats
|
|
76
|
+
for match in self._patterns[name].finditer(text)
|
|
77
|
+
)
|
|
78
|
+
return _decision(findings, self.action, "[PII]")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class SecretScanner:
|
|
82
|
+
"""Selected token signatures and private-key envelopes, not credential verification."""
|
|
83
|
+
|
|
84
|
+
name = "secrets"
|
|
85
|
+
_patterns = {
|
|
86
|
+
"github_classic": re.compile(r"(?<!\w)gh[pousr]_[A-Za-z0-9]{36}(?!\w)"),
|
|
87
|
+
"github_fine_grained": re.compile(r"(?<!\w)github_pat_[A-Za-z0-9_]{82}(?!\w)"),
|
|
88
|
+
"aws_access_key_id": re.compile(r"(?<!\w)(?:AKIA|ASIA)[A-Z0-9]{16}(?!\w)"),
|
|
89
|
+
}
|
|
90
|
+
_pem = re.compile(r"-----BEGIN ((?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY)-----")
|
|
91
|
+
|
|
92
|
+
def __init__(self, *, action: Action = Action.BLOCK):
|
|
93
|
+
_validate_action(action)
|
|
94
|
+
self.action = action
|
|
95
|
+
|
|
96
|
+
def _find(self, text: str) -> Iterable[Finding]:
|
|
97
|
+
for name, pattern in self._patterns.items():
|
|
98
|
+
for match in pattern.finditer(text):
|
|
99
|
+
yield Finding(f"secret_{name}", match.start(), match.end())
|
|
100
|
+
for match in self._pem.finditer(text):
|
|
101
|
+
footer = f"-----END {match.group(1)}-----"
|
|
102
|
+
end = text.find(footer, match.end())
|
|
103
|
+
# An incomplete envelope is conservatively covered through end of input.
|
|
104
|
+
yield Finding(
|
|
105
|
+
"secret_private_key", match.start(), len(text) if end < 0 else end + len(footer)
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def scan(self, text: str, *, stage: Stage) -> Check:
|
|
109
|
+
return _decision(self._find(text), self.action, "[SECRET]")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class InvisibleScanner:
|
|
113
|
+
"""Flag Unicode Cc/Cf except tab, CR, and LF; warning is the non-destructive default."""
|
|
114
|
+
|
|
115
|
+
name = "invisible"
|
|
116
|
+
|
|
117
|
+
def __init__(self, *, action: Action = Action.WARN):
|
|
118
|
+
_validate_action(action)
|
|
119
|
+
self.action = action
|
|
120
|
+
|
|
121
|
+
def scan(self, text: str, *, stage: Stage) -> Check:
|
|
122
|
+
findings = (
|
|
123
|
+
Finding("invisible_control", index, index + 1)
|
|
124
|
+
for index, char in enumerate(text)
|
|
125
|
+
if char not in "\t\r\n" and unicodedata.category(char) in ("Cc", "Cf")
|
|
126
|
+
)
|
|
127
|
+
return _decision(findings, self.action, "")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class LiteralScanner:
|
|
131
|
+
"""Substring policies with exact or ASCII-insensitive matching; no arbitrary regex."""
|
|
132
|
+
|
|
133
|
+
name = "literal"
|
|
134
|
+
_lower = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
|
|
135
|
+
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
literals: Sequence[str],
|
|
139
|
+
*,
|
|
140
|
+
action: Action = Action.BLOCK,
|
|
141
|
+
case_sensitive: bool = True,
|
|
142
|
+
):
|
|
143
|
+
_validate_action(action)
|
|
144
|
+
if isinstance(literals, str) or not 1 <= len(literals) <= 128:
|
|
145
|
+
raise ValueError("Supply between 1 and 128 literal strings")
|
|
146
|
+
if any(not isinstance(item, str) or not 1 <= len(item) <= 1024 for item in literals):
|
|
147
|
+
raise ValueError("Each literal must contain between 1 and 1024 characters")
|
|
148
|
+
self._literals = tuple(dict.fromkeys(literals))
|
|
149
|
+
self.action = action
|
|
150
|
+
self.case_sensitive = case_sensitive
|
|
151
|
+
|
|
152
|
+
def _find(self, text: str) -> Iterable[Finding]:
|
|
153
|
+
haystack = text if self.case_sensitive else text.translate(self._lower)
|
|
154
|
+
for literal in self._literals:
|
|
155
|
+
needle = literal if self.case_sensitive else literal.translate(self._lower)
|
|
156
|
+
start = haystack.find(needle)
|
|
157
|
+
while start >= 0:
|
|
158
|
+
yield Finding("literal_match", start, start + len(literal))
|
|
159
|
+
start = haystack.find(needle, start + 1)
|
|
160
|
+
|
|
161
|
+
def scan(self, text: str, *, stage: Stage) -> Check:
|
|
162
|
+
return _decision(self._find(text), self.action, "[REDACTED]")
|
guardtrellis/tools.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Tool validation returns data, and never dispatches or authorizes execution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .guard import Guard, Scanner
|
|
10
|
+
from .json_check import JSONScanner, Schema, strict_loads
|
|
11
|
+
from .models import Action, Finding, Rejected, Result, Stage
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class ToolResult:
|
|
16
|
+
validation: Result
|
|
17
|
+
name: str | None = field(default=None, repr=False)
|
|
18
|
+
arguments: dict[str, Any] | None = field(default=None, repr=False)
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def action(self) -> Action:
|
|
22
|
+
return self.validation.action
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def accepted(self) -> bool:
|
|
26
|
+
return self.validation.accepted
|
|
27
|
+
|
|
28
|
+
def require_call(self) -> tuple[str, dict[str, Any]]:
|
|
29
|
+
if not self.accepted or self.name is None or self.arguments is None:
|
|
30
|
+
raise Rejected(f"GuardTrellis rejected tool call: {self.action.value}")
|
|
31
|
+
return self.name, self.arguments
|
|
32
|
+
|
|
33
|
+
def diagnostics(self) -> dict[str, Any]:
|
|
34
|
+
return self.validation.diagnostics()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ToolGuard:
|
|
38
|
+
"""Exact name allowlist with a separate argument schema for each tool.
|
|
39
|
+
|
|
40
|
+
Arguments must arrive as JSON text, enabling duplicate-key detection. A
|
|
41
|
+
syntax check precedes text policies, and the schema is checked after edits.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
tools: Mapping[str, Schema],
|
|
47
|
+
*,
|
|
48
|
+
argument_scanners: Sequence[Scanner] = (),
|
|
49
|
+
max_chars: int = 100_000,
|
|
50
|
+
timeout_seconds: float = 5.0,
|
|
51
|
+
max_depth: int = 32,
|
|
52
|
+
):
|
|
53
|
+
if any(not isinstance(name, str) or not 1 <= len(name) <= 128 for name in tools):
|
|
54
|
+
raise ValueError("Tool names must have between 1 and 128 characters")
|
|
55
|
+
self._guards = {
|
|
56
|
+
name: Guard(
|
|
57
|
+
tool_scanners=(
|
|
58
|
+
JSONScanner(max_depth=max_depth, require_object=True),
|
|
59
|
+
*argument_scanners,
|
|
60
|
+
JSONScanner(schema, max_depth=max_depth, require_object=True),
|
|
61
|
+
),
|
|
62
|
+
max_chars=max_chars,
|
|
63
|
+
timeout_seconds=timeout_seconds,
|
|
64
|
+
)
|
|
65
|
+
for name, schema in tools.items()
|
|
66
|
+
}
|
|
67
|
+
self._max_depth = max_depth
|
|
68
|
+
|
|
69
|
+
def _unknown(self) -> ToolResult:
|
|
70
|
+
return ToolResult(Result(Action.BLOCK, Stage.TOOL, None, (Finding("tool_not_allowed"),)))
|
|
71
|
+
|
|
72
|
+
def _result(self, name: str, validation: Result) -> ToolResult:
|
|
73
|
+
if not validation.accepted:
|
|
74
|
+
return ToolResult(validation)
|
|
75
|
+
return ToolResult(
|
|
76
|
+
validation, name, strict_loads(validation.require_text(), max_depth=self._max_depth)
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def validate(self, name: str, arguments_json: str) -> ToolResult:
|
|
80
|
+
if not isinstance(name, str) or name not in self._guards:
|
|
81
|
+
return self._unknown()
|
|
82
|
+
return self._result(name, self._guards[name].scan(arguments_json, stage=Stage.TOOL))
|
|
83
|
+
|
|
84
|
+
async def avalidate(self, name: str, arguments_json: str) -> ToolResult:
|
|
85
|
+
if not isinstance(name, str) or name not in self._guards:
|
|
86
|
+
return self._unknown()
|
|
87
|
+
return self._result(name, await self._guards[name].ascan(arguments_json, stage=Stage.TOOL))
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: guardtrellis
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Provider-independent local checks for model inputs, outputs, retrieval, and tool calls
|
|
5
|
+
Project-URL: Source, https://github.com/sahilmathur254/guardtrellis
|
|
6
|
+
Project-URL: Issues, https://github.com/sahilmathur254/guardtrellis/issues
|
|
7
|
+
Project-URL: Documentation, https://github.com/sahilmathur254/guardtrellis/blob/main/docs/api.md
|
|
8
|
+
Project-URL: Changelog, https://github.com/sahilmathur254/guardtrellis/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Roadmap, https://github.com/users/sahilmathur254/projects/3
|
|
10
|
+
Author: Sahil Mathur
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: <3.15,>=3.11
|
|
21
|
+
Requires-Dist: jsonschema<5,>=4.23
|
|
22
|
+
Requires-Dist: referencing<0.38,>=0.35
|
|
23
|
+
Provides-Extra: fastapi
|
|
24
|
+
Requires-Dist: fastapi<1,>=0.115; extra == 'fastapi'
|
|
25
|
+
Requires-Dist: httpx<1,>=0.27; extra == 'fastapi'
|
|
26
|
+
Requires-Dist: uvicorn<1,>=0.30; extra == 'fastapi'
|
|
27
|
+
Provides-Extra: gemini
|
|
28
|
+
Requires-Dist: google-genai<3,>=2.25; extra == 'gemini'
|
|
29
|
+
Requires-Dist: httpx<1,>=0.28.1; extra == 'gemini'
|
|
30
|
+
Provides-Extra: langgraph
|
|
31
|
+
Requires-Dist: langgraph<2,>=1; extra == 'langgraph'
|
|
32
|
+
Requires-Dist: langsmith<1,>=0.3; extra == 'langgraph'
|
|
33
|
+
Provides-Extra: openai
|
|
34
|
+
Requires-Dist: httpx2<3,>=2.12; extra == 'openai'
|
|
35
|
+
Requires-Dist: openai<4,>=3; extra == 'openai'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# GuardTrellis
|
|
39
|
+
|
|
40
|
+
A small Python SDK for local checks around model inputs, complete outputs, retrieved text,
|
|
41
|
+
and proposed tool calls. Policies are explicit, composable, and independent of model providers.
|
|
42
|
+
|
|
43
|
+
The documented public API is supported across `0.1.x` under the
|
|
44
|
+
[compatibility policy](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/compatibility.md).
|
|
45
|
+
Supported Python: 3.11–3.14. Apache-2.0 licensed.
|
|
46
|
+
|
|
47
|
+
<!-- guardtrellis-release:start -->
|
|
48
|
+
**Version: `0.1.0`.** See [PyPI](https://pypi.org/project/guardtrellis/0.1.0/)
|
|
49
|
+
for availability and [release notes](https://github.com/sahilmathur254/guardtrellis/releases).
|
|
50
|
+
A source checkout may describe a candidate that has not been published yet.
|
|
51
|
+
|
|
52
|
+
Install this version in an activated virtual environment:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
python -m pip install 'guardtrellis==0.1.0'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
An explicit version opts into a prerelease when applicable. Optional integrations:
|
|
59
|
+
`'guardtrellis[fastapi]==0.1.0'`,
|
|
60
|
+
`'guardtrellis[langgraph]==0.1.0'`,
|
|
61
|
+
`'guardtrellis[openai]==0.1.0'`,
|
|
62
|
+
`'guardtrellis[gemini]==0.1.0'`.
|
|
63
|
+
<!-- guardtrellis-release:end -->
|
|
64
|
+
|
|
65
|
+
## Included capabilities
|
|
66
|
+
|
|
67
|
+
- A [retrieval and tool-call recipe](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/retrieval_tools.md)
|
|
68
|
+
that carries checked text and validated arguments through both boundaries using core dependencies.
|
|
69
|
+
- A separate [40-case Unicode and PII development set](https://github.com/sahilmathur254/guardtrellis/blob/main/evaluation/challenges/README.md)
|
|
70
|
+
with synthetic provenance, multilingual context, benign cases, and retained misses and false positives.
|
|
71
|
+
The original 72-case smoke corpus and its historical results remain available.
|
|
72
|
+
- OpenAI SDK 3 compatibility for the optional OpenAI and Azure examples, using HTTPX2.
|
|
73
|
+
See the [migration notes](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/openai.md#sdk-3-compatibility)
|
|
74
|
+
for custom clients and certificate trust changes.
|
|
75
|
+
|
|
76
|
+
Synthetic results measure the recorded cases and do not establish broader detection accuracy.
|
|
77
|
+
|
|
78
|
+
## Quickstart
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from guardtrellis import Guard, PIIScanner, SecretScanner
|
|
82
|
+
|
|
83
|
+
guard = Guard(
|
|
84
|
+
input_scanners=[SecretScanner(), PIIScanner()],
|
|
85
|
+
output_scanners=[SecretScanner(), PIIScanner()],
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# Deterministic local demonstration, not a real model integration.
|
|
89
|
+
result = guard.run("Contact casey@example.org", lambda text: f"Received: {text}")
|
|
90
|
+
print(result.require_text()) # Received: Contact [PII]
|
|
91
|
+
print(result.diagnostics()) # Metadata only; no matched strings or prompt text.
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`run` calls your callback only after accepted input checks, then checks the **complete**
|
|
95
|
+
returned string before exposing it. Use `await guard.arun(text, callback)` for async work;
|
|
96
|
+
both sync and async callbacks work there. Provider SDKs are not required by the core.
|
|
97
|
+
|
|
98
|
+
| Check | Default | Scope |
|
|
99
|
+
| --- | --- | --- |
|
|
100
|
+
| `PIIScanner` | redact | ASCII email, contiguous international phone, US SSN shapes |
|
|
101
|
+
| `SecretScanner` | block | Selected GitHub tokens, AWS access-key IDs, PEM private keys |
|
|
102
|
+
| `InvisibleScanner` | warn | Unicode control/format characters except tab and newlines |
|
|
103
|
+
| `LiteralScanner([...])` | block | Configured literal substrings; optional ASCII case folding |
|
|
104
|
+
| `JSONScanner(schema)` | block invalid data | Strict JSON and constrained Draft 2020-12 schemas |
|
|
105
|
+
| `ToolGuard({name: schema})` | block invalid calls | Exact tool names and object argument schemas |
|
|
106
|
+
|
|
107
|
+
No scanners are installed implicitly: `Guard()` permits bounded text. Choose policies for each
|
|
108
|
+
boundary. Heuristic matches are signals, not probabilities or comprehensive protection.
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from guardtrellis import Action, Guard, JSONScanner, LiteralScanner, Stage, ToolGuard
|
|
112
|
+
|
|
113
|
+
guard = Guard(
|
|
114
|
+
retrieval_scanners=[LiteralScanner(["confidential"], action=Action.BLOCK)],
|
|
115
|
+
output_scanners=[JSONScanner({"type": "object", "required": ["answer"]})],
|
|
116
|
+
)
|
|
117
|
+
retrieval = guard.scan("A public reference", stage=Stage.RETRIEVAL)
|
|
118
|
+
# In async code: await guard.ascan("A public reference", stage=Stage.RETRIEVAL)
|
|
119
|
+
|
|
120
|
+
tools = ToolGuard(
|
|
121
|
+
{
|
|
122
|
+
"search": {
|
|
123
|
+
"type": "object",
|
|
124
|
+
"properties": {"query": {"type": "string", "maxLength": 200}},
|
|
125
|
+
"required": ["query"],
|
|
126
|
+
"additionalProperties": False,
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
call = tools.validate("search", '{"query":"public documentation"}')
|
|
131
|
+
name, arguments = call.require_call()
|
|
132
|
+
# Your application must still enforce identity, permissions, and execution limits.
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`ALLOW`, `WARN`, and `REDACT` expose `result.text`; `BLOCK` and `ERROR` expose `None`.
|
|
136
|
+
`require_text()` / `require_call()` raise a payload-free `Rejected` exception on rejection.
|
|
137
|
+
WARN deliberately permits delivery. Scanner/callback exceptions are errors, never successful
|
|
138
|
+
checks. The first block/error stops its stage. Input rejection prevents the callback entirely.
|
|
139
|
+
|
|
140
|
+
Stages have separate scanner lists: `input_scanners`, `output_scanners`, `retrieval_scanners`,
|
|
141
|
+
and `tool_scanners`. Use `scan(text, stage=Stage.INPUT/OUTPUT/RETRIEVAL/TOOL)` or `ascan`;
|
|
142
|
+
the default stage is `Stage.INPUT`. Retrieval/tool checks must be invoked explicitly;
|
|
143
|
+
`run` does not discover or intercept these operations. `ToolGuard` adds name/schema validation.
|
|
144
|
+
|
|
145
|
+
Scanners run in configuration order. Each sees the text produced by preceding redactions.
|
|
146
|
+
Findings record half-open character offsets, scanner index, and the **input revision** they
|
|
147
|
+
refer to; every redacting scanner increments the revision. Offsets from different revisions
|
|
148
|
+
must not be applied to the original string. No originals or rehydration maps are retained.
|
|
149
|
+
|
|
150
|
+
Defaults: 100,000 characters per stage, 256 findings per scanner, JSON nesting at most 32,
|
|
151
|
+
and a 5-second **per-operation async wait**. Synchronous calls have no execution deadline.
|
|
152
|
+
Async cancellation cannot terminate a running thread or preempt a coroutine that blocks
|
|
153
|
+
the event loop. Timed-out work may continue and have side effects. Use process isolation
|
|
154
|
+
and application concurrency limits when execution must be forcibly bounded.
|
|
155
|
+
|
|
156
|
+
## Examples and development
|
|
157
|
+
|
|
158
|
+
Clone the source to run the examples or contribute:
|
|
159
|
+
|
|
160
|
+
```sh
|
|
161
|
+
git clone https://github.com/sahilmathur254/guardtrellis.git
|
|
162
|
+
cd guardtrellis
|
|
163
|
+
uv sync --all-extras --group dev
|
|
164
|
+
uv run python examples/plain_callable.py
|
|
165
|
+
uv run python examples/retrieval_tools.py # Checked retrieval through a proposed tool call
|
|
166
|
+
uv run python examples/fastapi_app.py # Local TestClient demo, no server needed
|
|
167
|
+
uv run python examples/langgraph_app.py # Local graph, no provider credentials
|
|
168
|
+
uv run python examples/openai_app.py # Real SDK, in-memory HTTP mock by default
|
|
169
|
+
uv run python examples/azure_openai_app.py # Azure SDK, in-memory HTTP mock by default
|
|
170
|
+
uv run python examples/gemini_app.py # Gemini SDK, in-memory HTTP mock by default
|
|
171
|
+
uv run pytest
|
|
172
|
+
uv run ruff check .
|
|
173
|
+
uv run ruff format --check .
|
|
174
|
+
uv run mypy
|
|
175
|
+
uv run python evaluation/run.py --report-dir /tmp/guardtrellis-eval
|
|
176
|
+
uv build
|
|
177
|
+
uv run python scripts/smoke_dist.py
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
The [retrieval/tool-call recipe](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/retrieval_tools.md)
|
|
181
|
+
uses only core dependencies and shows checked data crossing both boundaries, rejected callbacks,
|
|
182
|
+
and host authorization.
|
|
183
|
+
|
|
184
|
+
FastAPI and LangGraph are optional extras (`.[fastapi]`, `.[langgraph]`). LangGraph input
|
|
185
|
+
checks run **before** text enters graph state. The example also checks model output before
|
|
186
|
+
returning it to graph state. Instrumentation around callbacks may still capture raw data.
|
|
187
|
+
|
|
188
|
+
The optional provider examples (`.[openai]`) use direct OpenAI Responses or Azure OpenAI
|
|
189
|
+
Chat Completions through guarded callbacks. Their default modes and ordinary tests make
|
|
190
|
+
no provider calls. See the [OpenAI guide](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/openai.md)
|
|
191
|
+
and [Azure guide](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/azure_openai.md)
|
|
192
|
+
for setup, privacy/failure boundaries, and separately approved one-request live smokes.
|
|
193
|
+
The `openai` extra now requires `openai>=3,<4` and `httpx2>=2.12,<3`; custom clients
|
|
194
|
+
must follow the SDK 3 migration notes above. Live verification of both paths is pending.
|
|
195
|
+
|
|
196
|
+
The separate [Gemini example](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/gemini.md)
|
|
197
|
+
uses the optional `.[gemini]` extra and also defaults to mocked HTTP. Its one-request live smoke can use an approved Gemini Free Tier
|
|
198
|
+
project with the documented model and limits. A maintainer-approved live smoke passed on
|
|
199
|
+
2026-09-26; the guide records the exact source, versions, token counts, and evidence limits.
|
|
200
|
+
|
|
201
|
+
See [API details](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/api.md),
|
|
202
|
+
[limitations and trust boundaries](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/limitations.md),
|
|
203
|
+
[evaluation methodology](https://github.com/sahilmathur254/guardtrellis/blob/main/evaluation/README.md),
|
|
204
|
+
[measured smoke results](https://github.com/sahilmathur254/guardtrellis/blob/main/evaluation/REPORT.md),
|
|
205
|
+
[Unicode and PII challenges](https://github.com/sahilmathur254/guardtrellis/blob/main/evaluation/challenges/README.md),
|
|
206
|
+
[resource measurements and host controls](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/resource_limits.md),
|
|
207
|
+
and [contribution guidance](https://github.com/sahilmathur254/guardtrellis/blob/main/CONTRIBUTING.md).
|
|
208
|
+
These checks do not provide comprehensive
|
|
209
|
+
prompt-injection prevention, factual verification, regulatory compliance, or a tool sandbox.
|
|
210
|
+
|
|
211
|
+
## Roadmap and contributions
|
|
212
|
+
|
|
213
|
+
Use the public [GitHub Project](https://github.com/users/sahilmathur254/projects/3) to find
|
|
214
|
+
ready work and track progress. The [roadmap](https://github.com/sahilmathur254/guardtrellis/blob/main/ROADMAP.md) explains the release milestones,
|
|
215
|
+
dependencies, and longer-term proposals. Start with a
|
|
216
|
+
[good first issue](https://github.com/sahilmathur254/guardtrellis/labels/good%20first%20issue)
|
|
217
|
+
or a [help wanted issue](https://github.com/sahilmathur254/guardtrellis/labels/help%20wanted),
|
|
218
|
+
then follow the [contributor workflow](https://github.com/sahilmathur254/guardtrellis/blob/main/CONTRIBUTING.md).
|
|
219
|
+
|
|
220
|
+
See the [changelog](https://github.com/sahilmathur254/guardtrellis/blob/main/CHANGELOG.md)
|
|
221
|
+
for version-specific behavior and the [release guide](https://github.com/sahilmathur254/guardtrellis/blob/main/docs/releasing.md)
|
|
222
|
+
for packaging checks, TestPyPI rehearsal, and maintainer-approved publication.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
guardtrellis/__init__.py,sha256=YpcsC0mWBXKuF_CO3xmNb_wdK5VBRcKec0nvJzDjgDE,713
|
|
2
|
+
guardtrellis/guard.py,sha256=yJO_AcWD9hIK0rU73DmCvrEwvXnP724T3fbqh0pqlcI,10925
|
|
3
|
+
guardtrellis/json_check.py,sha256=FOiNiUfgJ7jrbvQ_6W6Lqsy4WopI7yCa1jdxAbHOi4Q,6269
|
|
4
|
+
guardtrellis/models.py,sha256=gGBXVnx_fzLA19VSmrBBcpQhRbc7Hfkxt9XwLp5i9xo,4129
|
|
5
|
+
guardtrellis/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
guardtrellis/scanners.py,sha256=aqqhn4ptKhlJx5kDbZ-nmnRkPBdKIYV7VgGhztaHYjY,6299
|
|
7
|
+
guardtrellis/tools.py,sha256=SEEcglZ5WLtP_3oE-dihZcyOomAk8opihkb-1eI27vU,3224
|
|
8
|
+
guardtrellis-0.1.0.dist-info/METADATA,sha256=wb-nH-U52TkhhfgaQ2G5HUybT7zzZEk-IRRMmda9jOw,12028
|
|
9
|
+
guardtrellis-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
10
|
+
guardtrellis-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
guardtrellis-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|