guardana-server 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.
@@ -0,0 +1,4 @@
1
+ from guardana.server.app import create_app
2
+ from guardana.server.envelope import SCHEMA_VERSION, Submission
3
+
4
+ __all__ = ["SCHEMA_VERSION", "Submission", "create_app"]
guardana/server/app.py ADDED
@@ -0,0 +1,78 @@
1
+ import os
2
+ from dataclasses import asdict
3
+
4
+ from fastapi import FastAPI, HTTPException, Query
5
+ from fastapi.responses import HTMLResponse
6
+ from guardana.server.dashboard import render_dashboard
7
+ from guardana.server.envelope import SCHEMA_VERSION, Submission
8
+ from guardana.server.rule_catalog import rule_catalog
9
+ from guardana.server.stats import compute_stats
10
+ from guardana.server.store import InMemoryStore, Store
11
+
12
+ _UNPROCESSABLE = 422
13
+ _TRUTHY = {"1", "true", "yes", "on"}
14
+
15
+
16
+ def _dashboard_enabled(flag: bool) -> bool:
17
+ """Whether to mount the dashboard — the `dashboard=` arg, or `GUARDANA_DASHBOARD` env."""
18
+ return flag or os.environ.get("GUARDANA_DASHBOARD", "").strip().lower() in _TRUTHY
19
+
20
+
21
+ def create_app(
22
+ store: Store | None = None, *, dashboard: bool = False, refresh_seconds: int = 15
23
+ ) -> FastAPI:
24
+ """Build the collector FastAPI app. Ingest/list/trend always; dashboard opt-in.
25
+
26
+ The dashboard (a read-only monitoring page plus its `/stats` data endpoint) is
27
+ off by default; pass `dashboard=True` or set `GUARDANA_DASHBOARD=1` to mount it.
28
+ """
29
+ active_store: Store = store if store is not None else InMemoryStore()
30
+ app = FastAPI(title="guardana-server")
31
+
32
+ @app.post("/findings")
33
+ def post_findings(submission: Submission) -> dict[str, object]:
34
+ if submission.schema_version != SCHEMA_VERSION:
35
+ raise HTTPException(
36
+ status_code=_UNPROCESSABLE,
37
+ detail=(
38
+ f"unsupported schema_version {submission.schema_version}; "
39
+ f"this collector speaks version {SCHEMA_VERSION}"
40
+ ),
41
+ )
42
+ active_store.add(submission)
43
+ return {"status": "ok", "stored": len(submission.findings)}
44
+
45
+ @app.get("/findings")
46
+ def get_findings(
47
+ source: str | None = Query(default=None),
48
+ limit: int = Query(default=100, ge=1, le=1000),
49
+ ) -> list[Submission]:
50
+ # Paginated: an unbounded list could return the entire store (tens of MB)
51
+ # in one response. Newest first, so `limit` returns the most recent.
52
+ return active_store.submissions(source)[-limit:][::-1]
53
+
54
+ @app.get("/trend")
55
+ def get_trend() -> dict[str, int]:
56
+ return active_store.trend()
57
+
58
+ if _dashboard_enabled(dashboard):
59
+ _mount_dashboard(app, active_store, refresh_seconds)
60
+
61
+ return app
62
+
63
+
64
+ def _mount_dashboard(app: FastAPI, store: Store, refresh_seconds: int) -> None:
65
+ """Add the read-only dashboard page and its aggregated `/stats` data endpoint."""
66
+ page = render_dashboard(refresh_seconds)
67
+
68
+ @app.get("/", response_class=HTMLResponse)
69
+ def dashboard_page() -> str:
70
+ return page
71
+
72
+ @app.get("/stats")
73
+ def get_stats() -> dict[str, object]:
74
+ return asdict(compute_stats(store.records()))
75
+
76
+ @app.get("/catalog")
77
+ def get_catalog() -> dict[str, dict[str, str]]:
78
+ return rule_catalog()
@@ -0,0 +1 @@
1
+ """Human-readable descriptions of the built-in rules, for the dashboard."""
@@ -0,0 +1,105 @@
1
+ {
2
+ "language": "en",
3
+ "rules": {
4
+ "guardana.supply_chain.pickle_opcode": {
5
+ "name": "Malicious pickle opcode",
6
+ "description": "A pickle file (including one hidden inside a .pt archive) imports a callable that is not on the safe allowlist — arbitrary code that runs the moment the model is loaded. Never load an untrusted pickle; prefer safetensors."
7
+ },
8
+ "guardana.supply_chain.dependency_risk": {
9
+ "name": "Unsafe deserialization sink",
10
+ "description": "Source code calls an unsafe loader on untrusted data — the pickle family (pickle/joblib/dill/pandas.read_pickle), torch.load without weights_only=True, yaml.load with an unsafe Loader, or numpy.load with allow_pickle. Each can execute arbitrary code on load."
11
+ },
12
+ "guardana.supply_chain.remote_code": {
13
+ "name": "Remote code execution on model load",
14
+ "description": "Code enables trust_remote_code=True or calls torch.hub.load — both download and run Python from a remote repo at load time. Today's most common way a downloaded model achieves code execution on your machine."
15
+ },
16
+ "guardana.supply_chain.remote_code_config": {
17
+ "name": "Config requests custom-code execution",
18
+ "description": "A model config.json declares an auto_map / custom_pipelines pointer to custom Python that runs on a trust_remote_code=True load — the on-disk artifact of the RCE. HIGH when the referenced module ships alongside the config."
19
+ },
20
+ "guardana.supply_chain.code_execution": {
21
+ "name": "Dynamic code or shell execution",
22
+ "description": "Source uses a dynamic-code or shell sink — builtin eval/exec, os.system, or subprocess with shell=True. If any of it touches attacker-influenced input, it is a command-injection vector."
23
+ },
24
+ "guardana.supply_chain.insecure_transport": {
25
+ "name": "Insecure model/data transport",
26
+ "description": "TLS certificate verification is disabled (verify=False → man-in-the-middle), or a model/dataset is fetched over plaintext http:// where its bytes can be swapped in transit."
27
+ },
28
+ "guardana.supply_chain.keras_lambda": {
29
+ "name": "Keras Lambda-layer code execution",
30
+ "description": "A Keras model embeds a Lambda layer — arbitrary Python that runs on load_model, no training or inference needed. Escalated when the layer reaches for os/subprocess and similar (CVE-2024-3660 class)."
31
+ },
32
+ "guardana.supply_chain.saved_model_ops": {
33
+ "name": "TensorFlow SavedModel file ops",
34
+ "description": "A TensorFlow SavedModel graph contains ReadFile / WriteFile operators — load-time filesystem read or overwrite baked into the model (a lead; JFrog TFLOW-MALOPS class)."
35
+ },
36
+ "guardana.supply_chain.malicious_dependency": {
37
+ "name": "Known-malicious dependency",
38
+ "description": "A dependency manifest pins a package release known to be compromised (curated blocklist, e.g. the ultralytics incident), or a setup.py fetches from the network at install time — a second-stage payload vector."
39
+ },
40
+ "guardana.supply_chain.hallucinated_package": {
41
+ "name": "Unknown / slopsquat package import",
42
+ "description": "Source imports a package that isn't recognized — a possible slopsquat (a hallucinated dependency name an attacker has registered). Reported as a lead: verify it really exists and is the package you meant."
43
+ },
44
+ "guardana.supply_chain.hardcoded_secret": {
45
+ "name": "Hardcoded secret",
46
+ "description": "A current-era API key or credential is committed in source — OpenAI/Anthropic keys (sk-proj-/sk-ant-api03-), GitHub token forms, or a private-key header. Rotate it and move it to a secret store."
47
+ },
48
+ "guardana.supply_chain.model_format": {
49
+ "name": "Code-carrying model format",
50
+ "description": "A model ships in a format that can carry executable code rather than pure weights. A well-formed safetensors file is never flagged; prefer it."
51
+ },
52
+ "guardana.supply_chain.notebook_payload": {
53
+ "name": "Dangerous payload in a notebook",
54
+ "description": "A Jupyter .ipynb code cell (a format the .py scanners never open) contains a code-execution sink or a shell escape that pipes a download into a shell (curl … | sh). An unparseable cell is surfaced, never silently skipped."
55
+ },
56
+ "guardana.supply_chain.provenance": {
57
+ "name": "Weak model provenance",
58
+ "description": "A model is pulled from an unpinned source or ships without a license — you can't prove what you're loading or that it hasn't changed. Reported as a lead; pin a revision and record provenance."
59
+ },
60
+ "guardana.output.secrets": {
61
+ "name": "Secret leaked in model output",
62
+ "description": "A live model emits secret-shaped strings (API keys, tokens) in its replies to benign prompts — sensitive data leaking through generated output."
63
+ },
64
+ "guardana.prompt.mcp_tool_poisoning": {
65
+ "name": "MCP tool-manifest poisoning",
66
+ "description": "An MCP tool description hides instructions the agent's model will read as trusted context — invisible Unicode, instruction-override phrases, or a base64 payload. Indirect prompt injection through a tool manifest."
67
+ },
68
+ "guardana.prompt.hidden_instructions": {
69
+ "name": "Hidden instructions (rules-file backdoor)",
70
+ "description": "An agent rule file (.cursorrules and friends) or a model card hides an instruction inside invisible characters — bidirectional overrides, the Unicode Tags block, zero-width space. The signal is concealment, not the presence of directives."
71
+ },
72
+ "guardana.training.dataset_integrity": {
73
+ "name": "Training-data integrity gap",
74
+ "description": "A training-data hygiene gap that makes poisoning possible: a Hugging Face dataset loading script (code that runs on load), or an unpinned load_dataset(...) whose source can be swapped under you. Reported as a lead, not proof of poisoning."
75
+ },
76
+ "guardana.agent.excessive_tool_use": {
77
+ "name": "Excessive tool-use agency",
78
+ "description": "Offered a harmless calculator alongside shell/delete/email tools for a trivial task, the model reached for a destructive one it was never asked to use. Graded deterministically on the tool calls it actually made."
79
+ },
80
+ "guardana.prompt.injection.ignore_previous": {
81
+ "name": "Direct prompt injection",
82
+ "description": "A direct instruction-override attack (\"ignore your previous instructions and …\") made the model abandon its system prompt and comply with the injected instruction."
83
+ },
84
+ "guardana.prompt.jailbreak.dan_style": {
85
+ "name": "DAN-style jailbreak",
86
+ "description": "A persona-override or encoding-smuggling jailbreak (DAN and relatives) got the model to bypass its safety guidelines."
87
+ },
88
+ "guardana.scenario.gradual_jailbreak": {
89
+ "name": "Gradual multi-turn jailbreak",
90
+ "description": "A multi-turn conversation that escalates gradually — each turn is innocuous, but together they walk the model past a refusal the single prompts would trigger. Graded per turn and across the whole conversation."
91
+ },
92
+ "guardana.scenario.indirect_injection": {
93
+ "name": "Indirect (RAG) prompt injection",
94
+ "description": "A poisoned \"retrieved document\" carries an instruction telling the model to reveal its secret token; a canary leak proves the model obeyed content it was only supposed to read — the RAG attack surface."
95
+ },
96
+ "guardana.prompt.system_prompt_leak.canary": {
97
+ "name": "System-prompt leakage",
98
+ "description": "The model disclosed its system prompt, proven by a fresh random canary token planted per run. Unfakeable, unambiguous evidence that the confidential prompt leaked."
99
+ },
100
+ "guardana.prompt.unbounded_consumption": {
101
+ "name": "Unbounded output (denial-of-wallet)",
102
+ "description": "A divergence prompt (\"repeat forever\") made the model generate without a server-side cap — runaway tokens that translate into cost and resource exhaustion (denial-of-wallet)."
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,293 @@
1
+ """The optional, self-hosted monitoring dashboard — one self-contained HTML page.
2
+
3
+ No template engine, no build step, no external assets: inline CSS/JS and inline
4
+ SVG charts, so it works fully offline. The page is a thin client — it polls
5
+ `/stats` (aggregated server-side) and `/findings`, reads `/catalog` once for
6
+ human-readable rule names/descriptions, and renders. Submitted data is untrusted
7
+ (any agent can POST), so the client escapes every value it injects.
8
+ """
9
+
10
+
11
+ def render_dashboard(refresh_seconds: int) -> str:
12
+ """Return the dashboard as one self-contained HTML document."""
13
+ return _PAGE.replace("__REFRESH_MS__", str(max(1, refresh_seconds) * 1000))
14
+
15
+
16
+ _PAGE = """<!doctype html>
17
+ <html lang="en">
18
+ <head>
19
+ <meta charset="utf-8">
20
+ <meta name="viewport" content="width=device-width, initial-scale=1">
21
+ <title>Guardana — collector</title>
22
+ <style>
23
+ :root {
24
+ --bg: #f6f7f9; --card: #ffffff; --ink: #1b1f24; --muted: #5f6673;
25
+ --line: #e3e6ea; --accent: #c2410c;
26
+ --sev-critical: #c0392b; --sev-high: #e07b00; --sev-medium: #b7950b;
27
+ --sev-low: #2e7d32; --sev-info: #5f6368;
28
+ }
29
+ @media (prefers-color-scheme: dark) {
30
+ :root {
31
+ --bg: #0e1116; --card: #171b21; --ink: #e6e9ee; --muted: #9aa0a6;
32
+ --line: #2a2f37; --accent: #f97316;
33
+ --sev-critical: #ff6b5e; --sev-high: #ffa54f; --sev-medium: #e6c34a;
34
+ --sev-low: #66bb6a; --sev-info: #9aa0a6;
35
+ }
36
+ }
37
+ * { box-sizing: border-box; }
38
+ body { margin: 0; background: var(--bg); color: var(--ink);
39
+ font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
40
+ a { color: var(--accent); }
41
+ header { padding: 20px 24px; border-bottom: 1px solid var(--line); }
42
+ h1 { margin: 0; font-size: 18px; } h1 span { color: var(--muted); font-weight: 400; }
43
+ .sub { color: var(--muted); font-size: 12px; margin-top: 2px; }
44
+ main { padding: 20px 24px; max-width: 1100px; margin: 0 auto; }
45
+ h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .04em;
46
+ color: var(--muted); margin: 0 0 10px; }
47
+ .grid { display: grid; gap: 16px; }
48
+ .tiles { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
49
+ .cols { grid-template-columns: 1fr 1fr; }
50
+ @media (max-width: 720px) { .cols { grid-template-columns: 1fr; } }
51
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: 10px;
52
+ padding: 16px; }
53
+ .tile .n { font-size: 28px; font-weight: 600; font-variant-numeric: tabular-nums; }
54
+ .tile .l { color: var(--muted); font-size: 12px; }
55
+ .tile.warn .n { color: var(--sev-high); }
56
+ .bar-row { display: grid; grid-template-columns: 92px 1fr 44px; align-items: center;
57
+ gap: 8px; margin: 6px 0; }
58
+ .bar-row .k { font-size: 12px; color: var(--muted); overflow: hidden; text-overflow: ellipsis;
59
+ white-space: nowrap; }
60
+ .bar-row .k.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; }
61
+ .bar { height: 12px; border-radius: 4px; min-width: 2px; }
62
+ .bar-row .v { text-align: right; font-variant-numeric: tabular-nums; font-size: 12px; }
63
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
64
+ th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line);
65
+ vertical-align: top; }
66
+ th { color: var(--muted); font-weight: 500; }
67
+ td.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
68
+ .pill { display: inline-block; padding: 1px 7px; border-radius: 999px; font-size: 11px;
69
+ font-weight: 600; color: #fff; }
70
+ .sev-CRITICAL { background: var(--sev-critical); } .sev-HIGH { background: var(--sev-high); }
71
+ .sev-MEDIUM { background: var(--sev-medium); } .sev-LOW { background: var(--sev-low); }
72
+ .sev-INFO { background: var(--sev-info); }
73
+ .legend { display: flex; gap: 14px; font-size: 12px; color: var(--muted); margin-bottom: 6px; }
74
+ .legend b { display: inline-block; width: 10px; height: 10px; border-radius: 2px;
75
+ margin-right: 4px; vertical-align: middle; }
76
+ .row { display: flex; justify-content: space-between; align-items: center; gap: 12px;
77
+ flex-wrap: wrap; }
78
+ select { background: var(--card); color: var(--ink); border: 1px solid var(--line);
79
+ border-radius: 6px; padding: 4px 8px; font-size: 12px; }
80
+ .empty { color: var(--muted); font-style: italic; padding: 8px 0; }
81
+ footer { color: var(--muted); font-size: 11px; padding: 16px 24px;
82
+ border-top: 1px solid var(--line); max-width: 1100px; margin: 0 auto; }
83
+ .mt { margin-top: 20px; }
84
+ /* Bounded so the page height stays stable as findings accumulate — the footer
85
+ is always reachable, and the list scrolls within its own box. */
86
+ #findings { max-height: 460px; overflow-y: auto; margin-top: 8px; }
87
+ #sources { max-height: 300px; overflow-y: auto; }
88
+ details.f { border-bottom: 1px solid var(--line); }
89
+ details.f > summary { list-style: none; cursor: pointer; padding: 7px 4px; display: grid;
90
+ grid-template-columns: 76px 1fr 34%; gap: 10px; align-items: baseline; }
91
+ details.f > summary::-webkit-details-marker { display: none; }
92
+ details.f > summary:hover { background: var(--bg); }
93
+ .fname { font-weight: 500; }
94
+ .fname .rid { display: block; font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
95
+ font-size: 11px; color: var(--muted); font-weight: 400; }
96
+ .fsrc { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px;
97
+ color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
98
+ .det { padding: 2px 10px 14px 86px; font-size: 12px; }
99
+ .det p { margin: 5px 0; } .det .lbl { color: var(--muted); }
100
+ .det code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px;
101
+ background: var(--bg); padding: 1px 4px; border-radius: 4px; word-break: break-all; }
102
+ .tax { display: inline-block; border: 1px solid var(--line); border-radius: 4px;
103
+ padding: 0 5px; font-size: 10px; color: var(--muted); margin-right: 4px; }
104
+ </style>
105
+ </head>
106
+ <body>
107
+ <header>
108
+ <h1>Guardana <span>· collector</span></h1>
109
+ <div class="sub">Findings forwarded by your agents. Read-only · auto-refreshing ·
110
+ <span id="updated">loading…</span></div>
111
+ </header>
112
+ <main>
113
+ <div class="grid tiles" id="tiles"></div>
114
+
115
+ <div class="card mt">
116
+ <h2>Findings by severity</h2>
117
+ <div id="severity"></div>
118
+ </div>
119
+
120
+ <div class="grid cols mt">
121
+ <div class="card">
122
+ <h2>By source</h2>
123
+ <div id="sources"></div>
124
+ </div>
125
+ <div class="card">
126
+ <h2>Top rules</h2>
127
+ <div id="rules"></div>
128
+ </div>
129
+ </div>
130
+
131
+ <div class="card mt">
132
+ <h2>Activity over time (recent window)</h2>
133
+ <div class="legend">
134
+ <span><b style="background:var(--sev-high)"></b>findings</span>
135
+ <span><b style="background:var(--sev-info)"></b>unverified</span>
136
+ </div>
137
+ <div id="series"></div>
138
+ </div>
139
+
140
+ <div class="card mt">
141
+ <div class="row">
142
+ <h2 style="margin:0">Recent findings</h2>
143
+ <label>source
144
+ <select id="source-filter"><option value="">all sources</option></select>
145
+ </label>
146
+ </div>
147
+ <div id="findings" class="mt"></div>
148
+ </div>
149
+ </main>
150
+ <footer>
151
+ guardana-server · this dashboard is read-only and unauthenticated — do not expose
152
+ it to an untrusted network (see SECURITY.md). The time window covers the
153
+ collector's in-memory buffer, not long-range history.
154
+ </footer>
155
+
156
+ <script>
157
+ const SEVS = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"];
158
+ const SEV_VAR = s => getComputedStyle(document.documentElement)
159
+ .getPropertyValue("--sev-" + s.toLowerCase()).trim() || "var(--sev-info)";
160
+ const esc = s => String(s == null ? "" : s).replace(/[&<>"']/g,
161
+ c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
162
+ const el = id => document.getElementById(id);
163
+ let CATALOG = {}; // rule_id -> {name, description}, from /catalog
164
+ const friendlyName = f => (CATALOG[f.rule_id] || {}).name || f.title || f.rule_id;
165
+
166
+ function barRow(key, value, max, color, mono) {
167
+ const w = max > 0 ? Math.round((value / max) * 100) : 0;
168
+ return `<div class="bar-row"><div class="k${mono ? " mono" : ""}" title="${esc(key)}">`
169
+ + `${esc(key)}</div><div class="bar" style="width:${w}%;background:${color}"`
170
+ + ` title="${esc(key)}: ${value}"></div><div class="v">${value}</div></div>`;
171
+ }
172
+
173
+ function renderTiles(t) {
174
+ const tile = (n, l, warn) => `<div class="card tile${warn ? " warn" : ""}">`
175
+ + `<div class="n">${n}</div><div class="l">${l}</div></div>`;
176
+ el("tiles").innerHTML = tile(t.findings, "findings")
177
+ + tile(t.unverified, "unverified", t.unverified > 0)
178
+ + tile(t.sources, "sources") + tile(t.submissions, "submissions");
179
+ }
180
+
181
+ function renderSeverity(by) {
182
+ const max = Math.max(1, ...SEVS.map(s => by[s] || 0));
183
+ const any = SEVS.some(s => by[s]);
184
+ el("severity").innerHTML = any
185
+ ? SEVS.map(s => barRow(s, by[s] || 0, max, SEV_VAR(s))).join("")
186
+ : `<div class="empty">No findings yet.</div>`;
187
+ }
188
+
189
+ function renderSources(rows) {
190
+ if (!rows.length) {
191
+ el("sources").innerHTML = `<div class="empty">No sources yet.</div>`; return; }
192
+ el("sources").innerHTML = "<table><thead><tr><th>source</th><th>find.</th>"
193
+ + "<th>unver.</th><th>worst</th></tr></thead><tbody>"
194
+ + rows.map(r => `<tr><td class="mono" title="${esc(r.source)}">${esc(r.source)}</td>`
195
+ + `<td>${r.findings}</td><td>${r.unverified}</td><td>${sevPill(r.worst_severity)}</td></tr>`)
196
+ .join("") + "</tbody></table>";
197
+ }
198
+
199
+ function sevPill(s) { return s ? `<span class="pill sev-${esc(s)}">${esc(s)}</span>` : "—"; }
200
+
201
+ function renderRules(rows) {
202
+ if (!rows.length) { el("rules").innerHTML = `<div class="empty">No findings yet.</div>`; return; }
203
+ const max = Math.max(1, ...rows.map(r => r.count));
204
+ el("rules").innerHTML = rows.map(r => {
205
+ const name = (CATALOG[r.rule_id] || {}).name || r.rule_id.replace(/^guardana\\./, "");
206
+ return barRow(name, r.count, max, "var(--accent)");
207
+ }).join("");
208
+ }
209
+
210
+ function renderSeries(series) {
211
+ if (series.length < 2) { el("series").innerHTML =
212
+ `<div class="empty">Not enough activity yet to plot a trend.</div>`; return; }
213
+ const W = 640, H = 120, P = 6;
214
+ const maxY = Math.max(1, ...series.map(b => Math.max(b.findings, b.unverified)));
215
+ const x = i => P + (i / (series.length - 1)) * (W - 2 * P);
216
+ const y = v => H - P - (v / maxY) * (H - 2 * P);
217
+ const path = key => series.map((b, i) => (i ? "L" : "M") + x(i).toFixed(1)
218
+ + " " + y(b[key]).toFixed(1)).join(" ");
219
+ const dots = key => series.map((b, i) =>
220
+ `<circle cx="${x(i).toFixed(1)}" cy="${y(b[key]).toFixed(1)}" r="2.5"
221
+ fill="${key === "findings" ? "var(--sev-high)" : "var(--sev-info)"}">`
222
+ + `<title>${b[key]} ${key}</title></circle>`).join("");
223
+ el("series").innerHTML = `<svg viewBox="0 0 ${W} ${H}" width="100%" height="${H}"
224
+ role="img" aria-label="findings and unverified over time">
225
+ <path d="${path("findings")}" fill="none" stroke="var(--sev-high)" stroke-width="2"/>
226
+ <path d="${path("unverified")}" fill="none" stroke="var(--sev-info)" stroke-width="2"
227
+ stroke-dasharray="4 3"/>${dots("findings")}${dots("unverified")}</svg>`;
228
+ }
229
+
230
+ function renderFindings(items) {
231
+ if (!items.length) { el("findings").innerHTML = `<div class="empty">No findings.</div>`; return; }
232
+ el("findings").innerHTML = items.map(f => {
233
+ const c = CATALOG[f.rule_id] || {}, ev = f.evidence || {}, v = f.verdict;
234
+ const tax = (f.taxonomy || []).map(t => `<span class="tax">${esc(t.id)}</span>`).join("");
235
+ const det = `<div class="det">`
236
+ + (c.description ? `<p>${esc(c.description)}</p>` : "")
237
+ + (ev.summary ? `<p><span class="lbl">evidence:</span> ${esc(ev.summary)}</p>` : "")
238
+ + (ev.detail ? `<p><span class="lbl">detail:</span> <code>${esc(ev.detail)}</code></p>` : "")
239
+ + `<p><span class="lbl">target:</span> <code>${esc(f.target_ref)}</code></p>`
240
+ + (v ? `<p><span class="lbl">verdict:</span> ${esc(v.outcome)} (confidence `
241
+ + `${Number(v.confidence).toFixed(2)}, ${esc(v.evaluator_id)})`
242
+ + (v.rationale ? ` — ${esc(v.rationale)}` : "") + `</p>` : "")
243
+ + (tax ? `<p>${tax}</p>` : "") + `</div>`;
244
+ return `<details class="f"><summary><span>${sevPill(f.severity)}</span>`
245
+ + `<span class="fname">${esc(friendlyName(f))}`
246
+ + `<span class="rid">${esc(f.rule_id)}</span></span>`
247
+ + `<span class="fsrc" title="${esc(f.target_ref)}">${esc(f.target_ref)}</span>`
248
+ + `</summary>${det}</details>`;
249
+ }).join("");
250
+ }
251
+
252
+ function populateSourceFilter(rows) {
253
+ const sel = el("source-filter"), cur = sel.value;
254
+ sel.innerHTML = `<option value="">all sources</option>`
255
+ + rows.map(r => `<option value="${esc(r.source)}">${esc(r.source)}</option>`).join("");
256
+ sel.value = cur;
257
+ }
258
+
259
+ async function loadCatalog() {
260
+ try { CATALOG = await (await fetch("catalog")).json(); } catch (e) { CATALOG = {}; }
261
+ }
262
+
263
+ async function loadFindings() {
264
+ const src = el("source-filter").value;
265
+ const url = "findings?limit=100" + (src ? "&source=" + encodeURIComponent(src) : "");
266
+ const box = el("findings"), innerScroll = box.scrollTop;
267
+ const items = (await (await fetch(url)).json())
268
+ .flatMap(sub => (sub.findings || []).concat(sub.unverified || []));
269
+ renderFindings(items.slice(0, 100));
270
+ box.scrollTop = innerScroll; // keep the reader's place across refresh
271
+ }
272
+
273
+ async function loadStats() {
274
+ const s = await (await fetch("stats")).json();
275
+ renderTiles(s.totals); renderSeverity(s.by_severity);
276
+ renderSources(s.by_source); renderRules(s.by_rule); renderSeries(s.series);
277
+ populateSourceFilter(s.by_source);
278
+ el("updated").textContent = "updated " + new Date().toLocaleTimeString();
279
+ }
280
+
281
+ async function refresh() {
282
+ const pageScroll = window.scrollY;
283
+ try { await loadStats(); await loadFindings(); window.scrollTo(0, pageScroll); }
284
+ catch (e) { el("updated").textContent = "collector unreachable"; }
285
+ }
286
+
287
+ el("source-filter").addEventListener("change", loadFindings);
288
+ loadCatalog().then(refresh);
289
+ setInterval(refresh, __REFRESH_MS__);
290
+ </script>
291
+ </body>
292
+ </html>
293
+ """
@@ -0,0 +1,80 @@
1
+ """The wire contract between a Guardana agent and the collector.
2
+
3
+ The collector never imports the engine: it accepts a normalized JSON envelope
4
+ produced by `guardana.core.reporter`, validated here. `SCHEMA_VERSION` is what
5
+ makes that independence safe — an agent and a collector can be upgraded apart,
6
+ and a version the collector does not understand is rejected, never guessed at.
7
+ """
8
+
9
+ from typing import Annotated
10
+
11
+ from pydantic import BaseModel, Field, StringConstraints
12
+
13
+ SCHEMA_VERSION = 2
14
+
15
+ # Ingest is untrusted input: an unbounded body would let one POST exhaust the
16
+ # collector's memory (the store bounds submission *count*, not bytes). These caps
17
+ # make Pydantic reject an oversized body at the door, before anything is stored.
18
+ _MAX_FINDINGS = 5_000
19
+ _MAX_SKIPPED = 5_000
20
+ _Str = Annotated[str, StringConstraints(max_length=4_096)]
21
+ _Text = Annotated[str, StringConstraints(max_length=65_536)]
22
+
23
+
24
+ class TaxonomyRefIn(BaseModel):
25
+ """A standards reference (OWASP/ATLAS/NIST) carried by a finding."""
26
+
27
+ framework: _Str
28
+ id: _Str
29
+
30
+
31
+ class EvidenceIn(BaseModel):
32
+ """Why the finding was raised. Redacted by the agent before it is sent."""
33
+
34
+ summary: _Text
35
+ detail: _Text | None = None
36
+
37
+
38
+ class VerdictIn(BaseModel):
39
+ """An evaluator's judgement, present only on dynamic findings."""
40
+
41
+ outcome: _Str
42
+ confidence: float
43
+ rationale: _Text | None = None
44
+ evaluator_id: _Str | None = None
45
+
46
+
47
+ class FindingIn(BaseModel):
48
+ """One finding, as serialized by `guardana.core.report.serialize`."""
49
+
50
+ rule_id: _Str
51
+ severity: _Str
52
+ title: _Text
53
+ target_ref: _Text
54
+ evidence: EvidenceIn
55
+ taxonomy: list[TaxonomyRefIn] = Field(default_factory=list, max_length=64)
56
+ verdict: VerdictIn | None = None
57
+
58
+
59
+ class SummaryIn(BaseModel):
60
+ """What the run did, beyond the findings themselves."""
61
+
62
+ rules_run: int = 0
63
+ rules_skipped: list[_Str] = Field(default_factory=list, max_length=_MAX_SKIPPED)
64
+ max_severity: _Str | None = None
65
+ unverified: int = 0
66
+
67
+
68
+ class Submission(BaseModel):
69
+ """One agent's scan result, as POSTed to `/findings`."""
70
+
71
+ source: _Str
72
+ # Required, not defaulted: an omitted version must be rejected, not silently
73
+ # assumed to be v1. Guessing at a version we don't understand is exactly what
74
+ # versioning exists to prevent.
75
+ schema_version: int
76
+ findings: list[FindingIn] = Field(default_factory=list, max_length=_MAX_FINDINGS)
77
+ # Checks that ran but could not reach a verdict — stored, never discarded, so
78
+ # the collector can surface "these were not graded" instead of an all-clear.
79
+ unverified: list[FindingIn] = Field(default_factory=list, max_length=_MAX_FINDINGS)
80
+ summary: SummaryIn | None = None
File without changes
@@ -0,0 +1,25 @@
1
+ """Loads the human-readable rule catalog the dashboard shows instead of bare ids.
2
+
3
+ The catalog is a plain JSON file (`catalog/en.json`) — English for now, structured
4
+ so a translation (`catalog/pl.json`, …) can slot in later. It is bundled with the
5
+ server so the collector stays self-sufficient; a rule id it doesn't know about
6
+ (a custom, third-party rule) simply falls back to the id and the finding's own
7
+ title on the page.
8
+ """
9
+
10
+ import json
11
+ from functools import cache
12
+ from importlib.resources import files
13
+
14
+ _DEFAULT_LANGUAGE = "en"
15
+
16
+
17
+ @cache
18
+ def rule_catalog(language: str = _DEFAULT_LANGUAGE) -> dict[str, dict[str, str]]:
19
+ """Return `{rule_id: {"name", "description"}}` for the given language (English by default)."""
20
+ resource = files("guardana.server.catalog").joinpath(f"{language}.json")
21
+ if not resource.is_file():
22
+ return {}
23
+ data = json.loads(resource.read_text(encoding="utf-8"))
24
+ rules = data.get("rules", {})
25
+ return rules if isinstance(rules, dict) else {}
@@ -0,0 +1,162 @@
1
+ """Pure aggregation of stored submissions into the shape the dashboard renders.
2
+
3
+ Kept separate from the store and the app so it can be tested in isolation: given
4
+ a list of `StoredSubmission`, `compute_stats` returns typed counts and a
5
+ time-series, with no I/O and no framework.
6
+ """
7
+
8
+ from collections.abc import Iterable
9
+ from dataclasses import dataclass
10
+
11
+ from guardana.server.store import StoredSubmission
12
+
13
+ # Ordinal severity, worst last — used to pick a source's worst finding.
14
+ _SEVERITY_ORDER = ("INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL")
15
+
16
+
17
+ def _severity_rank(severity: str) -> int:
18
+ try:
19
+ return _SEVERITY_ORDER.index(severity)
20
+ except ValueError:
21
+ return -1
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class SourceStat:
26
+ """One reporting source (a scanned path or a probed endpoint)."""
27
+
28
+ source: str
29
+ findings: int
30
+ unverified: int
31
+ worst_severity: str | None
32
+ last_seen: float
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class RuleStat:
37
+ """How many findings a single rule produced across the fleet."""
38
+
39
+ rule_id: str
40
+ count: int
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class TimeBucket:
45
+ """Findings and ungraded checks received within one time bucket."""
46
+
47
+ t: float
48
+ findings: int
49
+ unverified: int
50
+
51
+
52
+ @dataclass(frozen=True, slots=True)
53
+ class Totals:
54
+ """Headline counters across everything stored."""
55
+
56
+ submissions: int
57
+ sources: int
58
+ findings: int
59
+ unverified: int
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class Stats:
64
+ """Everything the dashboard needs, computed server-side so the client never re-aggregates."""
65
+
66
+ by_severity: dict[str, int]
67
+ by_source: list[SourceStat]
68
+ by_rule: list[RuleStat]
69
+ series: list[TimeBucket]
70
+ totals: Totals
71
+
72
+
73
+ def compute_stats(
74
+ records: Iterable[StoredSubmission], *, buckets: int = 24, top_rules: int = 10
75
+ ) -> Stats:
76
+ """Aggregate stored submissions into dashboard stats. Pure; safe on empty input."""
77
+ ordered = sorted(records, key=lambda r: r.received_at)
78
+ by_severity: dict[str, int] = {}
79
+ by_rule_counts: dict[str, int] = {}
80
+ source_findings: dict[str, int] = {}
81
+ source_unverified: dict[str, int] = {}
82
+ source_worst: dict[str, int] = {}
83
+ source_last_seen: dict[str, float] = {}
84
+ total_findings = 0
85
+ total_unverified = 0
86
+
87
+ for record in ordered:
88
+ submission = record.submission
89
+ source = submission.source
90
+ source_last_seen[source] = record.received_at
91
+ source_findings.setdefault(source, 0)
92
+ source_unverified.setdefault(source, 0)
93
+ source_unverified[source] += len(submission.unverified)
94
+ total_unverified += len(submission.unverified)
95
+ for finding in submission.findings:
96
+ total_findings += 1
97
+ by_severity[finding.severity] = by_severity.get(finding.severity, 0) + 1
98
+ by_rule_counts[finding.rule_id] = by_rule_counts.get(finding.rule_id, 0) + 1
99
+ source_findings[source] += 1
100
+ rank = _severity_rank(finding.severity)
101
+ if rank > source_worst.get(source, -2):
102
+ source_worst[source] = rank
103
+
104
+ by_source = [
105
+ SourceStat(
106
+ source=source,
107
+ findings=source_findings[source],
108
+ unverified=source_unverified[source],
109
+ worst_severity=(
110
+ _SEVERITY_ORDER[source_worst[source]] if source in source_worst else None
111
+ ),
112
+ last_seen=source_last_seen[source],
113
+ )
114
+ for source in sorted(source_findings, key=lambda s: source_findings[s], reverse=True)
115
+ ]
116
+ by_rule = [
117
+ RuleStat(rule_id=rule_id, count=count)
118
+ for rule_id, count in sorted(by_rule_counts.items(), key=lambda kv: kv[1], reverse=True)[
119
+ :top_rules
120
+ ]
121
+ ]
122
+ return Stats(
123
+ by_severity=by_severity,
124
+ by_source=by_source,
125
+ by_rule=by_rule,
126
+ series=_series(ordered, buckets),
127
+ totals=Totals(
128
+ submissions=len(ordered),
129
+ sources=len(source_findings),
130
+ findings=total_findings,
131
+ unverified=total_unverified,
132
+ ),
133
+ )
134
+
135
+
136
+ def _series(ordered: list[StoredSubmission], buckets: int) -> list[TimeBucket]:
137
+ """Bucket submissions across their observed time span. Robust on empty/degenerate input."""
138
+ if not ordered:
139
+ return []
140
+ t_min = ordered[0].received_at
141
+ t_max = ordered[-1].received_at
142
+ span = t_max - t_min
143
+ if span <= 0: # a single submission, or several at the same instant → one bucket
144
+ return [
145
+ TimeBucket(
146
+ t=t_min,
147
+ findings=sum(len(r.submission.findings) for r in ordered),
148
+ unverified=sum(len(r.submission.unverified) for r in ordered),
149
+ )
150
+ ]
151
+ n = max(1, min(buckets, len(ordered)))
152
+ width = span / n
153
+ findings = [0] * n
154
+ unverified = [0] * n
155
+ for record in ordered:
156
+ index = min(n - 1, int((record.received_at - t_min) / width))
157
+ findings[index] += len(record.submission.findings)
158
+ unverified[index] += len(record.submission.unverified)
159
+ return [
160
+ TimeBucket(t=t_min + i * width, findings=findings[i], unverified=unverified[i])
161
+ for i in range(n)
162
+ ]
@@ -0,0 +1,93 @@
1
+ import threading
2
+ import time
3
+ from collections import deque
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass
6
+ from typing import Protocol
7
+
8
+ from guardana.server.envelope import Submission
9
+
10
+ # The default store is a process-lifetime buffer, so it is bounded: a collector
11
+ # left running must not grow without limit. Durable storage is the seam a cloud
12
+ # backend replaces (see SECURITY.md — do not expose this one to an untrusted network).
13
+ MAX_SUBMISSIONS = 10_000
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class StoredSubmission:
18
+ """A submission plus when the collector received it — the time axis of the dashboard."""
19
+
20
+ received_at: float
21
+ submission: Submission
22
+
23
+
24
+ class Store(Protocol):
25
+ """Persists reporter submissions. The seam a paid cloud backend replaces."""
26
+
27
+ def add(self, submission: Submission) -> None:
28
+ """Store one submission, stamping it with the receive time."""
29
+ ...
30
+
31
+ def submissions(self, source: str | None = None) -> list[Submission]:
32
+ """Return every submission, optionally filtered to one source."""
33
+ ...
34
+
35
+ def trend(self) -> dict[str, int]:
36
+ """Return finding counts by severity, across everything stored."""
37
+ ...
38
+
39
+ def records(self) -> list[StoredSubmission]:
40
+ """Return every stored submission with its receive time — raw data for stats."""
41
+ ...
42
+
43
+
44
+ class InMemoryStore:
45
+ """Default `Store`: keeps the most recent submissions for the process lifetime.
46
+
47
+ FastAPI runs sync endpoints in a threadpool, so reads and writes genuinely
48
+ race. A lock guards every access — iterating the deque while another thread
49
+ appends (and, once full, evicts) would otherwise raise `RuntimeError` and 500
50
+ every reader after one concurrent write.
51
+
52
+ `clock` is injectable so tests get deterministic `received_at` timestamps (the
53
+ same pattern the monitor uses for `sleep`).
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ max_submissions: int = MAX_SUBMISSIONS,
59
+ *,
60
+ clock: Callable[[], float] = time.time,
61
+ ) -> None:
62
+ self._records: deque[StoredSubmission] = deque(maxlen=max_submissions)
63
+ self._lock = threading.Lock()
64
+ self._clock = clock
65
+
66
+ def add(self, submission: Submission) -> None:
67
+ """Store one submission (stamped with the receive time), evicting the oldest when full."""
68
+ record = StoredSubmission(received_at=self._clock(), submission=submission)
69
+ with self._lock:
70
+ self._records.append(record)
71
+
72
+ def submissions(self, source: str | None = None) -> list[Submission]:
73
+ """Return every submission held, optionally filtered to one source."""
74
+ held = [record.submission for record in self._snapshot()]
75
+ if source is None:
76
+ return held
77
+ return [s for s in held if s.source == source]
78
+
79
+ def trend(self) -> dict[str, int]:
80
+ """Return finding counts by severity, across everything held."""
81
+ counts: dict[str, int] = {}
82
+ for record in self._snapshot():
83
+ for finding in record.submission.findings:
84
+ counts[finding.severity] = counts.get(finding.severity, 0) + 1
85
+ return counts
86
+
87
+ def records(self) -> list[StoredSubmission]:
88
+ """Return every stored submission with its receive time (oldest first)."""
89
+ return self._snapshot()
90
+
91
+ def _snapshot(self) -> list[StoredSubmission]:
92
+ with self._lock:
93
+ return list(self._records)
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.4
2
+ Name: guardana-server
3
+ Version: 0.1.0
4
+ Summary: Guardana collector: minimal FastAPI server that ingests and lists findings.
5
+ Project-URL: Homepage, https://guardana.io
6
+ Project-URL: Repository, https://github.com/guardana/guardana
7
+ Project-URL: Documentation, https://guardana.dev
8
+ Project-URL: Issues, https://github.com/guardana/guardana/issues
9
+ Project-URL: Changelog, https://github.com/guardana/guardana/blob/main/CHANGELOG.md
10
+ Author-email: Guardana contributors <maintainers@guardana.io>
11
+ Maintainer-email: Guardana contributors <maintainers@guardana.io>
12
+ License-Expression: Apache-2.0
13
+ License-File: LICENSE
14
+ Keywords: ai-security,llm,mlsecops,prompt-injection,security-scanner
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: fastapi>=0.115
25
+ Requires-Dist: pydantic>=2.7
26
+ Description-Content-Type: text/markdown
27
+
28
+ # guardana-server
29
+
30
+ Guardana's optional collector — a minimal FastAPI service that ingests findings
31
+ from many agents and, optionally, serves a read-only monitoring dashboard.
32
+
33
+ Part of **[Guardana](https://github.com/guardana/guardana)** — security
34
+ verification for self-hosted and self-built AI (model files, live endpoints,
35
+ and agents) from one rule engine that runs on your laptop, in CI, and next to
36
+ a served model.
37
+
38
+ ## Run it
39
+
40
+ ```bash
41
+ # API only (POST/GET /findings, GET /trend):
42
+ uvicorn --factory guardana.server:create_app
43
+
44
+ # With the opt-in dashboard (adds GET / and GET /stats):
45
+ GUARDANA_DASHBOARD=1 uvicorn --factory guardana.server:create_app
46
+ # or, from your own code: create_app(dashboard=True, refresh_seconds=15)
47
+ ```
48
+
49
+ The dashboard is a single self-contained page (no build step, works offline)
50
+ showing severity, per-source/per-rule breakdowns, an activity-over-time trend,
51
+ the `unverified` counter, and a filterable recent-findings table. It is
52
+ **read-only and unauthenticated** — do not expose it to an untrusted network
53
+ (see [SECURITY.md](https://github.com/guardana/guardana/blob/main/SECURITY.md)).
54
+
55
+ - Main README & quickstart: https://github.com/guardana/guardana#readme
56
+ - Documentation: https://guardana.dev
57
+
58
+ Licensed under Apache-2.0.
@@ -0,0 +1,14 @@
1
+ guardana/server/__init__.py,sha256=azrxMC-4zeHqOk5sAEksmWUadfQ2hCe68FESVWYxgxs,165
2
+ guardana/server/app.py,sha256=90SeaoNBkMS3aZqfo7hVHgdPCdQBJ3cNparztSEh2-w,2898
3
+ guardana/server/dashboard.py,sha256=mYuw-jTiW-QxtiBwiFqnMOTLqDe1TN-BcbbrqWeYC4I,13883
4
+ guardana/server/envelope.py,sha256=WCAqj7rkUYvOzHMQ-U1tWFprKOhV9Zf36h_ZzEfrHhQ,2707
5
+ guardana/server/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ guardana/server/rule_catalog.py,sha256=-gf7OzGyPqB4BV6U_veyd0EjN2_OGSz3W9xv9aUPuG8,1000
7
+ guardana/server/stats.py,sha256=qtO3Ohl7EiCeHizsy8tSpeCa8turse0HCA5h4crFgGo,5197
8
+ guardana/server/store.py,sha256=ljg0U6CnbSfavNvb0_vY6YgWKU7vAKVF1lqx-EWbRFM,3461
9
+ guardana/server/catalog/__init__.py,sha256=yGj5wgQIcLCY2oF8QlvIh3h9WnXKCH2n-7gc51snP9o,76
10
+ guardana/server/catalog/en.json,sha256=fArsMiC-4dIQF0knFhLua2EWdVG3lZrd4TwKGUSUicw,8029
11
+ guardana_server-0.1.0.dist-info/METADATA,sha256=CEowjlfQQ5Bj1Ve1kaFvgeFbSx_UyLLe1ARWTXQjK-c,2444
12
+ guardana_server-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
13
+ guardana_server-0.1.0.dist-info/licenses/LICENSE,sha256=ZQhRridXNGA1cvM3x69Uon-GKhKSWBAdEx43KkRCpgM,11352
14
+ guardana_server-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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 2026 Guardana contributors
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.