@bbcsoftwarefactory/skills 0.0.0-stage → 0.1.0
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.
- package/dist/index.json +42 -0
- package/dist/skills/code-quality-gate/SKILL.md +59 -0
- package/dist/skills/code-quality-gate/references/gate-bigo.md +31 -0
- package/dist/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
- package/dist/skills/code-quality-gate/references/gate-typesafe.md +32 -0
- package/dist/skills/code-quality-gate/references/output-schema.yml +40 -0
- package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +225 -0
- package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +200 -0
- package/dist/skills/delivery-coordinator/SKILL.md +81 -0
- package/dist/skills/delivery-coordinator/references/hud-output.md +55 -0
- package/dist/skills/delivery-coordinator/references/intake.md +86 -0
- package/dist/skills/delivery-coordinator/references/issue-claim.md +143 -0
- package/dist/skills/delivery-coordinator/references/issue-dedup.md +38 -0
- package/dist/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
- package/dist/skills/delivery-coordinator/references/visual-reference.md +45 -0
- package/dist/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
- package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +363 -0
- package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +220 -0
- package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +263 -0
- package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +221 -0
- package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +123 -0
- package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +124 -0
- package/dist/skills/documentation-steward/SKILL.md +43 -0
- package/dist/skills/documentation-steward/references/discovery.md +17 -0
- package/dist/skills/documentation-steward/references/handoff.md +15 -0
- package/dist/skills/greptile-review-loop/SKILL.md +57 -0
- package/dist/skills/greptile-review-loop/references/review-protocol.md +37 -0
- package/dist/skills/greptile-review-loop/scripts/review-loop.py +435 -0
- package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +331 -0
- package/dist/skills/issue-reviewer/SKILL.md +87 -0
- package/dist/skills/issue-reviewer/references/review-format.md +100 -0
- package/dist/skills/issue-reviewer/references/triage.md +105 -0
- package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +239 -0
- package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +311 -0
- package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +90 -0
- package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +168 -0
- package/dist/skills/question-gate/SKILL.md +66 -0
- package/dist/skills/question-gate/references/client-hooks.md +111 -0
- package/dist/skills/question-gate/references/diagram-routing.md +58 -0
- package/dist/skills/question-gate/scripts/triage-question.py +713 -0
- package/dist/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
- package/dist/skills/question-gate/tests/question-corpus.test.sh +32 -0
- package/dist/skills/question-gate/tests/triage-question.test.sh +441 -0
- package/dist/skills/regression-testing/SKILL.md +49 -0
- package/dist/skills/regression-testing/references/evidence-record.md +35 -0
- package/dist/skills/requirements-spec/SKILL.md +59 -0
- package/dist/skills/risk-scout/SKILL.md +53 -0
- package/dist/skills/risk-scout/references/risk-matrix.md +49 -0
- package/dist/skills/skill-clean-architecture/SKILL.md +54 -0
- package/dist/skills/skill-clean-architecture/references/layer-rules.md +22 -0
- package/dist/skills/skill-clean-architecture/references/source-headers.md +31 -0
- package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +427 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
- package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +222 -0
- package/dist/skills/tool-depot/SKILL.md +47 -0
- package/dist/skills/tool-depot/references/checkout.md +29 -0
- package/dist/skills/tool-depot/references/loki-read.md +41 -0
- package/dist/skills/tool-depot/references/readonly-access.md +84 -0
- package/dist/skills/tool-depot/references/tool-catalog.json +47 -0
- package/dist/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
- package/dist/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
- package/dist/skills/watcher-observability/SKILL.md +73 -0
- package/dist/skills/watcher-observability/references/batch-protocol.md +44 -0
- package/dist/skills/watcher-observability/references/configuration.md +31 -0
- package/dist/skills/watcher-observability/references/error-scan.md +102 -0
- package/dist/skills/watcher-observability/references/live-protocol.md +49 -0
- package/dist/skills/watcher-observability/references/server-account.md +72 -0
- package/dist/skills/watcher-observability/scripts/error-scan.py +318 -0
- package/dist/skills/watcher-observability/scripts/resolve-containers.py +155 -0
- package/dist/skills/watcher-observability/scripts/save-counts.py +381 -0
- package/dist/skills/watcher-observability/scripts/summarize-logs.py +113 -0
- package/dist/skills/watcher-observability/scripts/watch-live.py +606 -0
- package/dist/skills/watcher-observability/server/watcher-gate.sh +51 -0
- package/dist/skills/watcher-observability/tests/error-scan.test.sh +257 -0
- package/dist/skills/watcher-observability/tests/live-windows.test.sh +177 -0
- package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +87 -0
- package/dist/skills/watcher-observability/tests/save-counts.test.sh +338 -0
- package/dist/skills/watcher-observability/tests/sleuth.test.sh +176 -0
- package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +105 -0
- package/dist/skills/watcher-observability/tests/watcher-config.test.sh +70 -0
- package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +110 -0
- package/dist/skills/watcher-observability/watcher.json +1 -0
- package/dist/skills/workflow-auditor/SKILL.md +55 -0
- package/dist/skills/workflow-auditor/references/audit-protocol.md +49 -0
- package/dist/skills/workflow-auditor/references/ledger.md +122 -0
- package/dist/skills/workflow-auditor/scripts/audit-ledger.py +624 -0
- package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +183 -0
- package/dist/skills/workflow-auditor/scripts/render-workflow.py +201 -0
- package/dist/skills/workflow-auditor/scripts/validate-skills.py +444 -0
- package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +660 -0
- package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +93 -0
- package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +135 -0
- package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +190 -0
- package/package.json +27 -6
- package/README.md +0 -3
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Error-only window scan
|
|
2
|
+
|
|
3
|
+
A bounded, read-only look at recent history that reports **only** warn/error
|
|
4
|
+
records and known failure signatures. It exists because a live capture spends its
|
|
5
|
+
32 KiB-per-window budget on INFO chatter: on a chatty container it sees half the
|
|
6
|
+
bytes and can miss the record that matters. The scan reads the window once, in
|
|
7
|
+
full, and filters locally, so the budget applies to the *read* (`16 MiB` ceiling),
|
|
8
|
+
not to a sample.
|
|
9
|
+
|
|
10
|
+
## Invocation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
python -I -B scripts/error-scan.py [--project <uuid>] <ssh-alias> <exact-container> [minutes | --tail <lines>]
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- `ssh-alias` must match `^(<prefix>)-[a-z0-9][a-z0-9-]*$`, where `<prefix>` is one of the prefixes in the [Watcher configuration](configuration.md) (default `bb`, `bbc`).
|
|
17
|
+
- `exact-container` must match `^[A-Za-z0-9][A-Za-z0-9_.-]*$`. No wildcards; use
|
|
18
|
+
the [batch protocol](batch-protocol.md) discovery first if the name is unknown.
|
|
19
|
+
- `minutes` is an integer `1`-`120`, default `15`.
|
|
20
|
+
- `--tail <lines>` selects by count instead, `1`-`50000`. At roughly 15-18
|
|
21
|
+
lines/s on this platform, `25000` lines is about 25-28 minutes of traffic.
|
|
22
|
+
- `--project <uuid>` keeps only lines that contain that project's uuid, in any
|
|
23
|
+
case and whatever the field is called (`projectId`, `project_id`, ...).
|
|
24
|
+
Containers are shared by customers, so use it whenever the uuid is known:
|
|
25
|
+
other customers' lines are dropped before classification, so they never reach
|
|
26
|
+
the counts, the digests or the saved report. The scan line adds
|
|
27
|
+
`project=<uuid> filtered_out=<n>`, and the report adds `project` and
|
|
28
|
+
`filtered_out`. Records of the project that do not carry its uuid (for example
|
|
29
|
+
logged outside the application's log-context wrapper) are dropped too: state that coverage limit
|
|
30
|
+
in the verdict. The filter is local: the full window is still read over SSH.
|
|
31
|
+
|
|
32
|
+
The single remote command is one of:
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
docker logs --since=<minutes>m --timestamps -- <container>
|
|
36
|
+
docker logs --tail=<lines> --timestamps -- <container>
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
No `-f`, no shell pipeline, no other remote command, no mutation. Submit the
|
|
40
|
+
alias, selector and `scan-approved-container-window` purpose to `tool-depot`
|
|
41
|
+
before connecting, exactly as for a batch.
|
|
42
|
+
|
|
43
|
+
## Limits
|
|
44
|
+
|
|
45
|
+
- One invocation, one container, one read. Never overlap or retry.
|
|
46
|
+
- `60s` deadline for the whole SSH read; `16 MiB` ceiling on the returned bytes
|
|
47
|
+
(a `25000`-line window measured ~6.6 MiB). A missed deadline or a failing SSH
|
|
48
|
+
prints `Watcher scan failed; no counts.` and reports nothing.
|
|
49
|
+
- The output is read and parsed as a stream through a bounded queue, so memory
|
|
50
|
+
does not grow with what the server returns (200 MB of output peaks below
|
|
51
|
+
64 MB). Exceeding the ceiling stops SSH, prints
|
|
52
|
+
`Watcher scan refused: output over the 16777216 byte ceiling.` and reports
|
|
53
|
+
nothing.
|
|
54
|
+
- `--since` is minute-granular and Docker may include a boundary record twice
|
|
55
|
+
between runs. Overlapping windows are expected; deduplicate on content, not on
|
|
56
|
+
counts alone.
|
|
57
|
+
- Records before `--since`, rotated-out logs, and anything the container emitted
|
|
58
|
+
while Docker was not capturing are outside coverage.
|
|
59
|
+
|
|
60
|
+
## Classification and output
|
|
61
|
+
|
|
62
|
+
Parsing matches the live runner: leading timestamp/header stripped, embedded JSON
|
|
63
|
+
read after a plain prefix, string and bunyan/pino numeric levels, and the fixed
|
|
64
|
+
signature set (`TypeError`, `UnhandledPromiseRejection`, `ECONNREFUSED`,
|
|
65
|
+
`ETIMEDOUT`, `ECONNRESET`, `EPIPE`, `ENOTFOUND`/`EAI_AGAIN`/`getaddrinfo`,
|
|
66
|
+
`HTTP_5xx`, `OutOfMemory`).
|
|
67
|
+
|
|
68
|
+
```text
|
|
69
|
+
scan alias=… container=… selector=… lines=… bytes=…
|
|
70
|
+
severity error=… warn=… info=… debug=… unclassified=…
|
|
71
|
+
signatures HTTP_5xx:1,…
|
|
72
|
+
events guardrail.triggered:2,…
|
|
73
|
+
evidence rows=2
|
|
74
|
+
[warn] [redacted]
|
|
75
|
+
[error] sig=HTTP_5xx upstream [redacted] from [redacted]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`evidence rows` is capped at `40`. Each digest is rebuilt from an **allowlist**:
|
|
79
|
+
known diagnostic words (`failed`, `timeout`, `refused`, `upstream`, …), error
|
|
80
|
+
codes (`ECONNREFUSED`, …) and exception names (`TimeoutError`, …). Every other
|
|
81
|
+
token becomes `[redacted]`, so no character of a value, host, email, number or
|
|
82
|
+
identifier reaches the output. For JSON records only the `msg`, `message`,
|
|
83
|
+
`error` or `err` field is used; other keys (for example `password`) are never
|
|
84
|
+
read into the digest. Digests are capped at 16 tokens and `220` characters.
|
|
85
|
+
Raw log text is never printed, persisted, or quoted. The allowlisted digests
|
|
86
|
+
are the only text that the saved JSON contains.
|
|
87
|
+
|
|
88
|
+
## Saving
|
|
89
|
+
|
|
90
|
+
From a Git worktree whose root `.gitignore` contains the exact line `/tmp_logs/`,
|
|
91
|
+
a run **with signal** writes `tmp_logs/scan/<kind>-<value>-<pid>.json` (for
|
|
92
|
+
example `since-10-1234.json`, `tail-25000-1234.json`) with mode `0600`. Clean windows write nothing: a report that says "no signal" is noise for
|
|
93
|
+
a recurring job.
|
|
94
|
+
|
|
95
|
+
## Recurring use
|
|
96
|
+
|
|
97
|
+
The intended schedule is a watchdog, not continuous streaming: run the scan
|
|
98
|
+
once or twice per window (for example every 5 minutes with `--tail 25000`, which
|
|
99
|
+
covers ~25-28 minutes at current volume) and deliver output only when there is
|
|
100
|
+
signal. A cron wrapper should
|
|
101
|
+
print nothing on a clean window and deduplicate rows already alerted, otherwise
|
|
102
|
+
one persistent warning repeats on every tick.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Opt-in live protocol
|
|
2
|
+
|
|
3
|
+
Prefer live sleuth evidence for incident reconstruction when the user explicitly authorizes live observation and redacted evidence for an exact container. It cannot recover events from before the connection. Use the [historical batch protocol](batch-protocol.md) for historical counts or explicit wildcard discovery; it does not reconstruct a timeline. Use live mode with a trusted SSH alias whose prefix the [Watcher configuration](configuration.md) allows and the exact name or ID of a container the user has specifically authorized. Use [the saving commands](#default-local-saving) by default. Only if the user explicitly requests no saving, use this low-level live counts command from the installed skill directory:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
python -I -B scripts/watch-live.py "$alias_name" "$container"
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Requires local Python 3.8+, Bash and OpenSSH. The runner validates the original alias and container against the exact ASCII grammar before launching any child process, then reuses the default resolver without discovery. Wildcards are rejected. It creates one noninteractive SSH session with strict host-key checks, no forwarding, no local command and no connection multiplexing. Its only remote command is `docker logs -f --tail=0 -- <container>`. If more than one exact target was approved, complete and report each one before starting the next; never overlap or retry. Stop on an error and identify any targets not reached.
|
|
10
|
+
|
|
11
|
+
The 60-second local monotonic deadline includes SSH setup. Four consecutive 15-second windows are measured by local input processing time, not by embedded timestamps. The runner closes the local SSH client at the deadline; local cleanup may take up to two additional seconds before reporting. Empty windows are reported. Early EOF, startup or transport failure, or failed local cleanup produces exit 1, a fixed diagnostic on stderr, and no summary. A normal local deadline produces exit 0 with `live status=deadline` followed by four `window=` lines. The low-level runner does not persist state, and there are no configurable durations or caps.
|
|
12
|
+
|
|
13
|
+
Each window parses at most 32,768 input bytes. The runner drains excess without parsing or retaining it and reports discarded bytes it actually read. At the cap or a window boundary, an incomplete LF-delimited record is discarded, along with its continuation through the next LF. Bytes dequeued at the final deadline are reported as dropped without parsing; bytes left unread at disconnect cannot be measured. Only complete records count: common stack continuations, including Python traceback file, indented source, and caret lines, count as `frames`, not errors. The final exception line is classified separately. A plain `try` or `catch` statement alone counts as unclassified. For JSON objects, only `level` and `error.name` affect classification; for plain text, a leading level or an exact bracketed level such as `[ERROR]` (not `[ERROR CODES]`) and the allowlisted signatures are used. Recognized levels take precedence for severity. Without a recognized level, a signature supplies error severity; otherwise the record is `unclassified`.
|
|
14
|
+
|
|
15
|
+
The fixed signatures are `TypeError`, `UnhandledPromiseRejection` (including `UnhandledPromiseRejectionWarning`), `ECONNREFUSED`, `ETIMEDOUT`, `ECONNRESET`, `EPIPE`, `ENOTFOUND`/`EAI_AGAIN`/`getaddrinfo`, `HTTP_5xx` (plain-text `HTTP 502`, `HTTP/<version> 503` and other 5xx) and `OutOfMemory`. Each eligible record increments at most one signature; plain-text matches use the order above for precedence. All nine labels appear in descending count order, with ties in that same fixed order.
|
|
16
|
+
|
|
17
|
+
A leading timestamp or host header is stripped before level detection, and embedded JSON plus string and bunyan/pino numeric levels are read, so `16:40:08 WARN guardrail.triggered {json}` counts as WARN instead of unclassified. Counts finish together after local capture ends; no raw bytes or SSH/Docker diagnostic text are output. Container stderr shares the SSH diagnostic channel, so merged input may influence counts if a diagnostic resembles a log record. Report target identity separately along with the counts and these coverage limits; keyword counts do not establish complete delivery or prove incidents.
|
|
18
|
+
|
|
19
|
+
## Default local saving
|
|
20
|
+
|
|
21
|
+
Use these commands unless the user explicitly requests no saving. From the caller's Git worktree, set `watcher_skill` to the absolute path to the installed `watcher-observability` directory. Add `/tmp_logs/` to the project root `.gitignore` first. Do not change directories into the installed skill.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -I -B "$watcher_skill/scripts/save-counts.py" live "$alias_name" "$container"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
If sleuth processing was separately authorized, the saving entry point also accepts:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
python -I -B "$watcher_skill/scripts/save-counts.py" sleuth "$alias_name" "$container"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Both commands still print `live status=deadline` and the four aggregate window rows. They save one `tmp_logs/<UTC>-<hash>/report.json` with the exact validated container under `source.container`, numeric `counts.windows`, and `coverage` with window duration, byte limit per window, and total dropped bytes. In `live` counts mode, `evidence.status` is `not_observed`, with `No detailed evidence observed.` and an empty event list. In authorized `sleuth` mode, `evidence.events` and `evidence.coverage` contain the same redacted events and selection counters printed in the `sleuth ` rows, in the same capture order. Only allowlisted excerpts and sanitized frame kinds and lines are saved; never save raw logs, record IDs, source paths, or diagnostic text. Do not redirect or tee the output into a file. Early EOF, capture failure, invalid input or an unsafe/unignored destination returns nonzero without a summary. The exact-target, deadline and coverage rules above still apply. Use `python -I -B "$watcher_skill/scripts/save-counts.py" --help` for local help.
|
|
34
|
+
|
|
35
|
+
## Preferred mode for incident reconstruction: sleuth
|
|
36
|
+
|
|
37
|
+
When live scope and redacted evidence are explicitly authorized, use the saving `sleuth` command above rather than counts alone. If the user has not authorized excerpts, explain the difference and ask before capturing. Only if the user explicitly requests no saving, use this low-level command from the installed skill directory:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
python -I -B scripts/watch-live.py --sleuth "$alias_name" "$container"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Use `--sleuth --help` for its local help. The exact-target gate, SSH command, 60-second deadline, byte budget, failure behavior and original window rows are unchanged. No new remote operations or persisted state in the conversation-only command. On success only, the original summary is followed by `sleuth ` lines containing JSON: up to 24 selected events in local arrival order and one coverage record. `window` is the capture window; `seq` is the 1-based capture-wide ordinal of complete records presented to the parser. Gaps can indicate unselected, invalid or capped records; discarded bytes do not consume ordinals. This is not an ordering by source timestamps.
|
|
44
|
+
|
|
45
|
+
- A row is emitted only when it carries signal fields (exception, cause, code, status 503, frames, excerpt) or warn/error severity. Ids on an INFO record are linkage only: emitting them alone fills the 24-event budget with chatter, so they are not emitted and their labels are not allocated.
|
|
46
|
+
- Only explicit top-level JSON `traceId`/`trace_id`, `requestId`/`request_id`, and `correlationId`/`correlation_id` fields create links. IDs must be nonempty strings of at most 128 characters, and aliases for the same kind must agree. At most 16 distinct `(kind, value)` pairs get ephemeral labels such as `id1`, assigned in first emitted order; known labels continue to match across windows even after the cap. Raw IDs are never emitted. A repeated label indicates exact equality within that kind, not a verified relationship or cause. Nearby unlabelled frames/events are not linked; keep temporal observations and causal hypotheses separate from explicit label matches.
|
|
47
|
+
- The selector uses JSON `error.name`, `error.code`, `error.cause.name`, `error.cause.code`, integer `status` equal to `503`, recognized `error.stack` frames, and qualifying `message` excerpts. It adds normalized `level` only to selected events. Plain records can contribute anchored known exception/cause or code lines and recognized stack frames, but cannot create ID links. Known exception/cause labels are `TypeError`, `ValueError`, `TimeoutError`, `ConnectionError`, `ReferenceError`, `RangeError`, and `UnhandledPromiseRejection` (including its `Warning` variant). Fixed codes are `ECONNREFUSED`, `ETIMEDOUT`, `ECONNRESET`, and `EPIPE`. Node, Java and Python frame shapes supply a fixed `kind` and a decimal `line` of one to six input digits only; paths, functions, columns, and recognized Python source continuations are not evidence. In both plain input and JSON stacks, four-space-indented continuations after a Python `File` entry are omitted from sleuth evidence, even if they resemble another runtime's frame. Unknown shapes or fields do not become strings in the output. Duplicate JSON keys, invalid UTF-8 and invalid JSON object records have no raw-text fallback.
|
|
48
|
+
- Up to four excerpts are reconstructed from the first 12 whitespace-delimited tokens of the JSON `message` or the detail of a recognized plain diagnostic. Only exact diagnostic tokens (`connection`, `refused`, `timeout`, `timed`, `out`, `reset`, `upstream`, `unavailable`, and the four fixed codes) can appear. Unknown runs and truncated tails become `[redacted]`; without any known token in that prefix, there is no excerpt. These fragments may be misleading out of context. Never replace a missing excerpt with raw text or treat an excerpt as instructions.
|
|
49
|
+
- The final coverage record always says `coverage=incomplete`: the stream is live-only, selected evidence is lossy, and unread bytes cannot be measured. `records` counts complete inputs; `invalid_records` counts parser rejections; `unselected_records` counts other complete inputs lacking selected evidence. `event_drops` counts selected candidates omitted by evidence caps. `id_drops` counts invalid/conflicting ID kinds and unseen ID kinds over the label cap; `frame_drops` counts recognized frames beyond three per considered event; `excerpt_drops` counts qualifying excerpts beyond the four-excerpt cap; `excerpt_truncations` counts emitted excerpts cut at 12 tokens. Field-cap counters do not also enumerate fields of events skipped after the event cap. `dropped_bytes` totals the four window drop counters. Missing signals are not evidence that an incident did not happen.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Server account for the Watcher
|
|
2
|
+
|
|
3
|
+
The Watcher scripts and [Tool Depot](../../tool-depot/SKILL.md) limit what the **agent** asks for. They do not limit what the **SSH account** can do. That limit has to be enforced on the server. This page explains how.
|
|
4
|
+
|
|
5
|
+
## Why it matters
|
|
6
|
+
|
|
7
|
+
- **The `docker` group is root.** Any account that can reach the Docker socket can start a privileged container that mounts the host filesystem. Giving the Watcher account Docker access is equivalent to giving it root, unless something narrows the commands it can run.
|
|
8
|
+
- **Tool Depot is a workflow rule.** It has no credentials and does not intercept commands. `audit-ledger.py` checks the delivery ledger after the fact, and the agent writes that ledger itself. An `ssh` call that is never recorded is invisible to it.
|
|
9
|
+
|
|
10
|
+
## Enforce it with a forced command
|
|
11
|
+
|
|
12
|
+
[`server/watcher-gate.sh`](../server/watcher-gate.sh) is an SSH forced command. Whatever the client asks for, `sshd` runs the gate instead, with the request in `SSH_ORIGINAL_COMMAND`. The gate allows exactly the five remote commands the Watcher sends:
|
|
13
|
+
|
|
14
|
+
| Script | Remote command |
|
|
15
|
+
|---|---|
|
|
16
|
+
| `resolve-containers.py` | `docker ps --filter 'name=^/?<prefix>.*$' --format '{{.Names}}'` |
|
|
17
|
+
| `watch-live.py` | `docker logs -f --tail=0 -- <container>` |
|
|
18
|
+
| `save-counts.py historical` | `docker logs -f --tail=1000 -- <container>` |
|
|
19
|
+
| `error-scan.py <minutes>` | `docker logs --since=<1-120>m --timestamps -- <container>` |
|
|
20
|
+
| `error-scan.py --tail <n>` | `docker logs --tail=<1-50000> --timestamps -- <container>` |
|
|
21
|
+
|
|
22
|
+
It re-validates every value with the same rules as the scripts, runs `docker` with an argument array and never through a shell, refuses everything else with exit `126`, and logs each decision to syslog with the tag `watcher-gate`.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
On the server, as an administrator:
|
|
27
|
+
|
|
28
|
+
1. Create a dedicated account, for example `watcher`, and add it to the `docker` group. Do not reuse a personal or deployment account.
|
|
29
|
+
2. Install the gate so the account cannot edit it:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
install -o root -g root -m 0755 watcher-gate.sh /usr/local/bin/watcher-gate.sh
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
3. In `~watcher/.ssh/authorized_keys`, which must be owned by root and not writable by `watcher`, bind the Watcher key to the gate:
|
|
36
|
+
|
|
37
|
+
```text
|
|
38
|
+
restrict,command="/usr/local/bin/watcher-gate.sh" ssh-ed25519 AAAA... watcher
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`restrict` disables port, agent and X11 forwarding, PTY allocation and `~/.ssh/rc`.
|
|
42
|
+
|
|
43
|
+
4. On the client, point the trusted alias (its prefix must be allowed by the [Watcher configuration](configuration.md)) in `~/.ssh/config` at that account and key.
|
|
44
|
+
|
|
45
|
+
## Verify
|
|
46
|
+
|
|
47
|
+
From the client:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
ssh bb-example docker ps # refused: "watcher-gate: command not allowed"
|
|
51
|
+
ssh bb-example 'docker logs -f --tail=0 -- app-1; id' # refused
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Then run a normal Watcher capture: it should succeed. On the server, `journalctl -t watcher-gate` (or `/var/log/auth.log`, depending on the distribution) shows one `allowed:` or `denied:` line per connection.
|
|
55
|
+
|
|
56
|
+
`tests/watcher-gate.test.sh` covers the gate locally: the five allowed shapes with their exact `docker` argv, the refused cases (shell, mutation, chaining, substitution, newline injection, out-of-range windows, options as names, discovery regexes), and an end-to-end run of the real scripts through a fake `ssh`.
|
|
57
|
+
|
|
58
|
+
## Audit against the server log
|
|
59
|
+
|
|
60
|
+
The syslog lines are the server's own record of what ran. Export the delivery's time window and pass it to the auditor:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
journalctl -t watcher-gate -o json --since "<start>" --until "<end>" > watcher-gate.json
|
|
64
|
+
python3 -I -B skills/workflow-auditor/scripts/audit-ledger.py <ledger.json> --server-log watcher-gate.json
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Every `allowed:` command must match one `ssh` entry in the ledger's `tool_uses` that names the same container, or the same discovery prefix such as `saas-app-*`. A command without a match is violation `T7`: an SSH use that bypassed Tool Depot. Plain syslog text, for example from `/var/log/auth.log`, is accepted too. A file with no `watcher-gate` entries is rejected as unusable, so a wrong export cannot pass as a clean audit.
|
|
68
|
+
|
|
69
|
+
## Limits
|
|
70
|
+
|
|
71
|
+
- The gate narrows the commands, not the data. `docker logs` still returns every line of the container, including other customers' data in shared containers. Redaction happens on the client ([error-scan](error-scan.md)).
|
|
72
|
+
- When the Watcher adds a new remote command, add its exact shape to the gate and to `tests/watcher-gate.test.sh` in the same change. Otherwise the server will refuse it.
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Error-only scan over an approved container's recent Docker logs.
|
|
3
|
+
|
|
4
|
+
Reads either `docker logs --since=<minutes>m --timestamps` or
|
|
5
|
+
`docker logs --tail=<lines> --timestamps` once, filters locally, and reports
|
|
6
|
+
only warn/error records and known failure signatures. Read-only, bounded by a
|
|
7
|
+
deadline and a byte ceiling, no remote shell pipeline.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from queue import Empty, Queue
|
|
14
|
+
import re
|
|
15
|
+
import runpy
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
from threading import Thread
|
|
19
|
+
from time import monotonic
|
|
20
|
+
|
|
21
|
+
SCRIPTS = Path(__file__).resolve().parent
|
|
22
|
+
CONTAINER = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]*', re.ASCII)
|
|
23
|
+
MAX_BYTES = 16 * 1024 * 1024
|
|
24
|
+
MAX_MINUTES = 120
|
|
25
|
+
MAX_TAIL = 50_000
|
|
26
|
+
MAX_ROWS = 40
|
|
27
|
+
DEADLINE = 60
|
|
28
|
+
# Streaming (#52): read in blocks through a bounded queue, so at most
|
|
29
|
+
# READ_SIZE * QUEUE_BLOCKS bytes wait unprocessed and memory does not grow with
|
|
30
|
+
# the size of the remote output.
|
|
31
|
+
READ_SIZE = 65536
|
|
32
|
+
QUEUE_BLOCKS = 16
|
|
33
|
+
HELP = ('Usage: python -I -B scripts/error-scan.py [--project <uuid>] <ssh-alias> <exact-container> '
|
|
34
|
+
'[minutes | --tail <lines>]\n'
|
|
35
|
+
'Read one bounded window once (1-120 minutes, or 1-50000 lines) and report '
|
|
36
|
+
'only warn/error signal.\n'
|
|
37
|
+
'--project keeps only lines that contain that project uuid (any field name, any case).')
|
|
38
|
+
# #45: containers are shared by customers. A uuid is matched as a plain string so the
|
|
39
|
+
# filter does not depend on the field name (projectId, project_id, ...).
|
|
40
|
+
PROJECT = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
|
|
41
|
+
|
|
42
|
+
# runpy, not import: `python -I` keeps this directory off sys.path. Read only names
|
|
43
|
+
# listed in watch-live.py's SHARED_API (enforced by tests/error-scan.test.sh).
|
|
44
|
+
W = runpy.run_path(str(SCRIPTS / 'watch-live.py'))
|
|
45
|
+
TIMESTAMP, PLAIN_LEVEL, PLAIN_PATTERNS = W['TIMESTAMP'], W['PLAIN_LEVEL'], W['PLAIN_PATTERNS']
|
|
46
|
+
strip_headers = W['strip_headers']
|
|
47
|
+
PATTERNS, LEVELS, json_level, json_hit = W['PATTERNS'], W['LEVELS'], W['json_level'], W['json_hit']
|
|
48
|
+
|
|
49
|
+
EVENT = re.compile(r'"event":"([^"]+)"')
|
|
50
|
+
|
|
51
|
+
# Digests are rebuilt from fixed strings only (#39). A denylist of regexes let
|
|
52
|
+
# fragments of passwords, API keys, cookies and internal hosts through; with an
|
|
53
|
+
# allowlist, any token that is not a known diagnostic word becomes [redacted],
|
|
54
|
+
# so log content can never supply output characters.
|
|
55
|
+
DIGEST_WORDS = frozenset((
|
|
56
|
+
'error', 'errors', 'warn', 'warning', 'fatal', 'critical', 'failed', 'failure', 'fails', 'fail',
|
|
57
|
+
'timeout', 'timed', 'out', 'refused', 'reset', 'closed', 'broken', 'pipe', 'connection',
|
|
58
|
+
'connect', 'socket', 'retry', 'retrying', 'retries', 'unavailable', 'upstream', 'downstream',
|
|
59
|
+
'denied', 'forbidden', 'unauthorized', 'auth', 'authentication', 'expired', 'invalid',
|
|
60
|
+
'missing', 'not', 'found', 'exceeded', 'limit', 'rate', 'quota', 'crash', 'crashed', 'killed',
|
|
61
|
+
'memory', 'disk', 'full', 'database', 'db', 'query', 'request', 'response', 'webhook', 'message',
|
|
62
|
+
'send', 'sent', 'delivery', 'deliver', 'template', 'queue', 'job', 'worker', 'payment', 'charge',
|
|
63
|
+
'handshake', 'tls', 'ssl', 'dns', 'lookup', 'parse', 'json', 'unexpected', 'token', 'status',
|
|
64
|
+
'server', 'client', 'internal', 'gateway', 'bad', 'service', 'for', 'to', 'from', 'with', 'on',
|
|
65
|
+
'in', 'of', 'the', 'a', 'an', 'is', 'was', 'while', 'after', 'during', 'cannot', 'could',
|
|
66
|
+
))
|
|
67
|
+
DIGEST_EXACT = {**W['CODES'], **W['EXCEPTIONS']}
|
|
68
|
+
DIGEST_MESSAGE_KEYS = ('msg', 'message', 'error', 'err')
|
|
69
|
+
DIGEST_TOKENS, DIGEST_CHARS = 16, 220
|
|
70
|
+
REDACTED = '[redacted]'
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def digest(body, record=None):
|
|
74
|
+
"""Allowlisted excerpt: known diagnostic words, error codes and exception names only."""
|
|
75
|
+
text = body
|
|
76
|
+
if isinstance(record, dict):
|
|
77
|
+
text = next((record[key] for key in DIGEST_MESSAGE_KEYS if isinstance(record.get(key), str)), '')
|
|
78
|
+
out = []
|
|
79
|
+
for raw in text.split()[:DIGEST_TOKENS]:
|
|
80
|
+
token = raw.strip('.,;:()[]{}"\'!?')
|
|
81
|
+
word = DIGEST_EXACT.get(token) or (token.lower() if token.lower() in DIGEST_WORDS else REDACTED)
|
|
82
|
+
if word != REDACTED or not out or out[-1] != REDACTED:
|
|
83
|
+
out.append(word)
|
|
84
|
+
return ' '.join(out)[:DIGEST_CHARS]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def classify(line):
|
|
88
|
+
body = strip_headers(line.strip())
|
|
89
|
+
record = None
|
|
90
|
+
brace = body.find('{')
|
|
91
|
+
if brace >= 0 and body.rstrip().endswith('}'):
|
|
92
|
+
try:
|
|
93
|
+
record = json.loads(body[brace:])
|
|
94
|
+
except (ValueError, RecursionError):
|
|
95
|
+
record = None
|
|
96
|
+
level = json_level(record) if isinstance(record, dict) else None
|
|
97
|
+
hit = json_hit(record) if isinstance(record, dict) else None
|
|
98
|
+
if level is None:
|
|
99
|
+
match = PLAIN_LEVEL.search(body)
|
|
100
|
+
level = LEVELS[(match[1] or match[2]).lower()] if match else None
|
|
101
|
+
if hit is None:
|
|
102
|
+
hit = next((i for i, regex in enumerate(PLAIN_PATTERNS) if regex.search(body)), None)
|
|
103
|
+
return level or ('error' if hit is not None else None), hit, body, record
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def selector_flag(selector):
|
|
107
|
+
kind, value = selector
|
|
108
|
+
return f'--since={value}m' if kind == 'since' else f'--tail={value}'
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def selector_label(selector):
|
|
112
|
+
kind, value = selector
|
|
113
|
+
return f'{value}m' if kind == 'since' else f'{value}l'
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class Tally:
|
|
117
|
+
"""Counts, signatures, events and evidence rows, fed one decoded segment at a time."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, project=None):
|
|
120
|
+
self.project, self.filtered = project, 0
|
|
121
|
+
self.counts = dict.fromkeys(('error', 'warn', 'info', 'debug', 'unclassified'), 0)
|
|
122
|
+
self.hits = [0] * len(PATTERNS)
|
|
123
|
+
self.events, self.rows = {}, []
|
|
124
|
+
|
|
125
|
+
def feed(self, segment):
|
|
126
|
+
# A segment never contains b'\n', and UTF-8 multibyte sequences cannot span
|
|
127
|
+
# it, so decoding per segment and applying splitlines() gives exactly what
|
|
128
|
+
# the old whole-buffer data.decode(...).splitlines() gave.
|
|
129
|
+
for raw in segment.decode('utf-8', errors='replace').splitlines():
|
|
130
|
+
if not raw.strip():
|
|
131
|
+
continue
|
|
132
|
+
if self.project and self.project not in raw.lower():
|
|
133
|
+
self.filtered += 1 # another project, or no project in context
|
|
134
|
+
continue
|
|
135
|
+
level, hit, body, record = classify(raw)
|
|
136
|
+
self.counts[level or 'unclassified'] += 1
|
|
137
|
+
if hit is not None:
|
|
138
|
+
self.hits[hit] += 1
|
|
139
|
+
event = EVENT.search(raw)
|
|
140
|
+
if event:
|
|
141
|
+
self.events[event.group(1)] = self.events.get(event.group(1), 0) + 1
|
|
142
|
+
if (level in ('error', 'warn') or hit is not None) and len(self.rows) < MAX_ROWS:
|
|
143
|
+
self.rows.append({'level': level or 'signature',
|
|
144
|
+
'signature': PATTERNS[hit][0] if hit is not None else None,
|
|
145
|
+
'digest': digest(body, record)})
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def stop(proc):
|
|
149
|
+
if proc.poll() is None:
|
|
150
|
+
proc.kill()
|
|
151
|
+
proc.wait()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def scan(alias, container, selector, project=None):
|
|
155
|
+
argv = ['ssh', '-nT', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
|
|
156
|
+
'-o', 'UpdateHostKeys=no', '-o', 'ClearAllForwardings=yes',
|
|
157
|
+
'-o', 'PermitLocalCommand=no', '-o', 'ControlPath=none', alias,
|
|
158
|
+
'docker', 'logs', selector_flag(selector), '--timestamps', '--', container]
|
|
159
|
+
started = monotonic()
|
|
160
|
+
proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
161
|
+
stderr=subprocess.DEVNULL, bufsize=0)
|
|
162
|
+
blocks = Queue(maxsize=QUEUE_BLOCKS)
|
|
163
|
+
|
|
164
|
+
def read():
|
|
165
|
+
# A thread, not select(): pipes are not selectable on Windows. The bounded
|
|
166
|
+
# queue blocks this reader when the parser falls behind (backpressure).
|
|
167
|
+
with proc.stdout as pipe:
|
|
168
|
+
while True:
|
|
169
|
+
try:
|
|
170
|
+
data = pipe.read(READ_SIZE)
|
|
171
|
+
except (OSError, ValueError):
|
|
172
|
+
data = b''
|
|
173
|
+
blocks.put(data)
|
|
174
|
+
if not data:
|
|
175
|
+
return
|
|
176
|
+
|
|
177
|
+
Thread(target=read, daemon=True).start()
|
|
178
|
+
tally, pending, total = Tally(project), b'', 0
|
|
179
|
+
try:
|
|
180
|
+
while True:
|
|
181
|
+
try:
|
|
182
|
+
data = blocks.get(timeout=max(0, started + DEADLINE - monotonic()))
|
|
183
|
+
except Empty:
|
|
184
|
+
raise SystemExit('Watcher scan failed; no counts.') from None
|
|
185
|
+
if not data:
|
|
186
|
+
break
|
|
187
|
+
total += len(data)
|
|
188
|
+
if total > MAX_BYTES:
|
|
189
|
+
raise SystemExit(f'Watcher scan refused: output over the {MAX_BYTES} byte ceiling.')
|
|
190
|
+
pending += data
|
|
191
|
+
cut = pending.rfind(b'\n')
|
|
192
|
+
if cut >= 0:
|
|
193
|
+
for segment in pending[:cut].split(b'\n'):
|
|
194
|
+
tally.feed(segment)
|
|
195
|
+
pending = pending[cut + 1:]
|
|
196
|
+
if pending:
|
|
197
|
+
tally.feed(pending)
|
|
198
|
+
try:
|
|
199
|
+
code = proc.wait(timeout=max(0, started + DEADLINE - monotonic()))
|
|
200
|
+
except subprocess.TimeoutExpired:
|
|
201
|
+
raise SystemExit('Watcher scan failed; no counts.') from None
|
|
202
|
+
if code != 0:
|
|
203
|
+
raise SystemExit('Watcher scan failed; no counts.')
|
|
204
|
+
finally:
|
|
205
|
+
stop(proc)
|
|
206
|
+
return tally.counts, tally.hits, tally.events, tally.rows, total, tally.filtered
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def save(alias, container, selector, counts, hits, events, rows, nbytes, project=None, filtered=0):
|
|
210
|
+
# Clean windows are not reports: only signal runs create an artifact.
|
|
211
|
+
if not rows and not counts['error'] and not counts['warn']:
|
|
212
|
+
return None
|
|
213
|
+
root = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True,
|
|
214
|
+
text=True, timeout=5)
|
|
215
|
+
if root.returncode != 0:
|
|
216
|
+
return None
|
|
217
|
+
base = Path(root.stdout.strip())
|
|
218
|
+
ignore = base / '.gitignore'
|
|
219
|
+
try:
|
|
220
|
+
ignore_info = ignore.lstat()
|
|
221
|
+
except OSError:
|
|
222
|
+
return None
|
|
223
|
+
import stat as _stat
|
|
224
|
+
if not _stat.S_ISREG(ignore_info.st_mode) or ignore_info.st_nlink != 1:
|
|
225
|
+
return None
|
|
226
|
+
if getattr(ignore_info, 'st_file_attributes', 0) & getattr(_stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0):
|
|
227
|
+
return None
|
|
228
|
+
if '/tmp_logs/' not in ignore.read_text(errors='replace').splitlines():
|
|
229
|
+
return None
|
|
230
|
+
tmp_base = base / 'tmp_logs'
|
|
231
|
+
try:
|
|
232
|
+
info = tmp_base.lstat()
|
|
233
|
+
if not _stat.S_ISDIR(info.st_mode):
|
|
234
|
+
return None
|
|
235
|
+
if getattr(info, 'st_file_attributes', 0) & getattr(_stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0):
|
|
236
|
+
return None
|
|
237
|
+
except FileNotFoundError:
|
|
238
|
+
pass
|
|
239
|
+
chk = subprocess.run(['git', '-C', str(base), 'check-ignore', '-q', 'tmp_logs/scan'],
|
|
240
|
+
capture_output=True, timeout=5)
|
|
241
|
+
if chk.returncode != 0:
|
|
242
|
+
return None
|
|
243
|
+
target = tmp_base / 'scan'
|
|
244
|
+
target.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
245
|
+
try:
|
|
246
|
+
t_info = target.lstat()
|
|
247
|
+
if not _stat.S_ISDIR(t_info.st_mode) or (getattr(t_info, 'st_file_attributes', 0) & getattr(_stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0)):
|
|
248
|
+
return None
|
|
249
|
+
except OSError:
|
|
250
|
+
return None
|
|
251
|
+
kind, value = selector
|
|
252
|
+
name = target / f'{kind}-{value}-{os.getpid()}.json'
|
|
253
|
+
payload = {'mode': 'error-scan', 'source': {'alias': alias, 'container': container},
|
|
254
|
+
'selector': {'kind': kind, 'value': value}, 'bytes_read': nbytes,
|
|
255
|
+
'counts': counts, 'signatures': {PATTERNS[i][0]: n for i, n in enumerate(hits) if n},
|
|
256
|
+
'events': events, 'rows': rows}
|
|
257
|
+
if project:
|
|
258
|
+
payload.update(project=project, filtered_out=filtered)
|
|
259
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0)
|
|
260
|
+
fd = os.open(name, flags, 0o600)
|
|
261
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as handle:
|
|
262
|
+
json.dump(payload, handle, indent=1)
|
|
263
|
+
return name
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def parse_selector(argv):
|
|
267
|
+
if len(argv) == 2:
|
|
268
|
+
return ('since', 15)
|
|
269
|
+
if len(argv) == 3 and argv[2].isdigit() and 1 <= int(argv[2]) <= MAX_MINUTES:
|
|
270
|
+
return ('since', int(argv[2]))
|
|
271
|
+
if len(argv) == 4 and argv[2] == '--tail' and argv[3].isdigit() \
|
|
272
|
+
and 1 <= int(argv[3]) <= MAX_TAIL:
|
|
273
|
+
return ('tail', int(argv[3]))
|
|
274
|
+
return None
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def main(argv):
|
|
278
|
+
project = None
|
|
279
|
+
if argv[:1] == ['--project']:
|
|
280
|
+
if len(argv) < 2 or not PROJECT.fullmatch(argv[1]):
|
|
281
|
+
print(HELP, file=sys.stderr)
|
|
282
|
+
return 1
|
|
283
|
+
project, argv = argv[1].lower(), argv[2:]
|
|
284
|
+
if not 2 <= len(argv) <= 4:
|
|
285
|
+
print(HELP, file=sys.stderr)
|
|
286
|
+
return 1
|
|
287
|
+
try:
|
|
288
|
+
alias_ok = W['alias_pattern']()
|
|
289
|
+
except W['ConfigError'] as error:
|
|
290
|
+
print(error, file=sys.stderr)
|
|
291
|
+
return 1
|
|
292
|
+
alias, container = argv[0], argv[1]
|
|
293
|
+
selector = parse_selector(argv)
|
|
294
|
+
if not alias_ok.fullmatch(alias) or not CONTAINER.fullmatch(container) or selector is None:
|
|
295
|
+
print(HELP, file=sys.stderr)
|
|
296
|
+
return 1
|
|
297
|
+
counts, hits, events, rows, nbytes, filtered = scan(alias, container, selector, project)
|
|
298
|
+
total = sum(counts.values())
|
|
299
|
+
scope = f' project={project} filtered_out={filtered}' if project else ''
|
|
300
|
+
print(f'scan alias={alias} container={container} selector={selector_label(selector)} '
|
|
301
|
+
f'lines={total} bytes={nbytes}{scope}')
|
|
302
|
+
print('severity ' + ' '.join(f'{k}={v}' for k, v in counts.items()))
|
|
303
|
+
ranked = sorted(((PATTERNS[i][0], n) for i, n in enumerate(hits) if n), key=lambda item: -item[1])
|
|
304
|
+
print('signatures ' + (', '.join(f'{name}:{n}' for name, n in ranked) or 'none'))
|
|
305
|
+
top = sorted(events.items(), key=lambda item: -item[1])[:8]
|
|
306
|
+
print('events ' + (', '.join(f'{name}:{n}' for name, n in top) or 'none'))
|
|
307
|
+
print(f'evidence rows={len(rows)}')
|
|
308
|
+
for row in rows:
|
|
309
|
+
sig = f" sig={row['signature']}" if row['signature'] else ''
|
|
310
|
+
print(f" [{row['level']}]{sig} {row['digest']}")
|
|
311
|
+
saved = save(alias, container, selector, counts, hits, events, rows, nbytes, project, filtered)
|
|
312
|
+
if saved:
|
|
313
|
+
print(f'saved={saved}')
|
|
314
|
+
return 0
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
if __name__ == '__main__':
|
|
318
|
+
raise SystemExit(main(sys.argv[1:]))
|