Compare commits
174
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d19b3d478f | ||
|
|
0cd6e4f856 | ||
|
|
acf767360f | ||
|
|
9ad5b2fc34 | ||
|
|
8596cd057b | ||
|
|
42b0fdb718 | ||
|
|
452354a8e3 | ||
|
|
5fb37bfbaf | ||
|
|
cdd8c292db | ||
|
|
9cdad90e3a | ||
|
|
da1a21ee47 | ||
|
|
1fdc13aa73 | ||
|
|
374b320ba4 | ||
|
|
4dbb39b8ee | ||
|
|
26de69b6e2 | ||
|
|
f3d5a8161d | ||
|
|
ffaae2b459 | ||
|
|
8b8dec0754 | ||
|
|
cd6d8b5119 | ||
|
|
a303a0d7f5 | ||
|
|
f711e6babb | ||
|
|
00fb35096d | ||
|
|
d33ce4d64c | ||
|
|
61ad96bc1a | ||
|
|
98505ed7b4 | ||
|
|
a961501b6d | ||
|
|
0a54751b7e | ||
|
|
313237f167 | ||
|
|
de1a5c2893 | ||
|
|
e93368fa84 | ||
|
|
067a257b6a | ||
|
|
07b754090a | ||
|
|
5d3b3e96bb | ||
|
|
3742fc63fe | ||
|
|
48121aec0d | ||
|
|
2618fb9e45 | ||
|
|
a747e4c1bb | ||
|
|
51eed69fe4 | ||
|
|
8caedd11d5 | ||
|
|
3b5fe0c116 | ||
|
|
a2575233b7 | ||
|
|
8236789781 | ||
|
|
e217ed509a | ||
|
|
02967629ff | ||
|
|
a8c0482e76 | ||
|
|
b3b2ff1f07 | ||
|
|
248afd2253 | ||
|
|
fd5c788569 | ||
|
|
106d796d95 | ||
|
|
7919051688 | ||
|
|
61a9887ebb | ||
|
|
aece5c381f | ||
|
|
163a57237c | ||
|
|
5b21e03726 | ||
|
|
2104da912d | ||
|
|
2ccf33e1f5 | ||
|
|
1c710dfe94 | ||
|
|
4d21b7a32e | ||
|
|
c1d6f97096 | ||
|
|
95ceee421f | ||
|
|
bae67494e2 | ||
|
|
da84a9a800 | ||
|
|
f2b966d5d4 | ||
|
|
32e1a97877 | ||
|
|
8310bc3616 | ||
|
|
c751035374 | ||
|
|
347347b835 | ||
|
|
ff6d7155cd | ||
|
|
1b817866a4 | ||
|
|
037d47b592 | ||
|
|
5820de1d85 | ||
|
|
a2f5d83662 | ||
|
|
0b34782b8e | ||
|
|
cff6e7c425 | ||
|
|
56134e832a | ||
|
|
cb943d1328 | ||
|
|
3318c89629 | ||
|
|
9fa085a53e | ||
|
|
7c57bac03c | ||
|
|
f99633cabd | ||
|
|
755c8b6f0f | ||
|
|
888dbc32ef | ||
|
|
4c39dd3fb0 | ||
|
|
2b41fb14c7 | ||
|
|
307170b128 | ||
|
|
a734815a63 | ||
|
|
41e28adbf9 | ||
|
|
731478411a | ||
|
|
00ff5e7ddf | ||
|
|
8fcb49f2c7 | ||
|
|
5277097032 | ||
|
|
0b0bab61bb | ||
|
|
2fb3271558 | ||
|
|
07dfb95b6b | ||
|
|
7df665a457 | ||
|
|
e43c502bcb | ||
|
|
77ad99d8a7 | ||
|
|
46d3ca5622 | ||
|
|
80af0acbd4 | ||
|
|
aa641cba2f | ||
|
|
9c72539401 | ||
|
|
b062237168 | ||
|
|
53a0e4b2ab | ||
|
|
838a94f265 | ||
|
|
eac9e9da83 | ||
|
|
2358dcc453 | ||
|
|
43c6fda4ae | ||
|
|
47381dc8e9 | ||
|
|
53997ad861 | ||
|
|
05e9af02db | ||
|
|
b8cde77d12 | ||
|
|
38b65e97d6 | ||
|
|
f3fd655ada | ||
|
|
bff85094ec | ||
|
|
d68c46e359 | ||
|
|
2eb96855c7 | ||
|
|
9297d60a33 | ||
|
|
067ad0939c | ||
|
|
9c57d6d2ce | ||
|
|
2ec1836e8c | ||
|
|
bc2f56ef8f | ||
|
|
5e6bbd47a1 | ||
|
|
ec9de0e039 | ||
|
|
a74fa24996 | ||
|
|
36fbcb1d63 | ||
|
|
afc40fd3ca | ||
|
|
6a6c69e803 | ||
|
|
2cb1afad4f | ||
|
|
88dcd8ecaa | ||
|
|
8957161317 | ||
|
|
da17047b38 | ||
|
|
90378229ae | ||
|
|
f13a15f9db | ||
|
|
10f0d15407 | ||
|
|
0992679100 | ||
|
|
dfecc637b5 | ||
|
|
a672941cc7 | ||
|
|
f29d85eeb2 | ||
|
|
d32fa041cf | ||
|
|
bf41e43315 | ||
|
|
9b94c7747e | ||
|
|
10c44dd1f0 | ||
|
|
68674a3c6f | ||
|
|
da6e80a90c | ||
|
|
f60cca7f59 | ||
|
|
d0e502f622 | ||
|
|
81cc69196a | ||
|
|
1b233dfd83 | ||
|
|
3ccf8b50cb | ||
|
|
fca5b57455 | ||
|
|
cd95792196 | ||
|
|
20fb47b457 | ||
|
|
4c66e67661 | ||
|
|
3c7e1de96c | ||
|
|
0341e114a9 | ||
|
|
313c49eb4e | ||
|
|
27e9ef2046 | ||
|
|
a30ab9cc95 | ||
|
|
bb00651bce | ||
|
|
437da860d4 | ||
|
|
e55b68868d | ||
|
|
95e7c0f314 | ||
|
|
d7616fd9a9 | ||
|
|
ff234af701 | ||
|
|
152705a999 | ||
|
|
3f19efb7e3 | ||
|
|
9f47dcaefa | ||
|
|
9f5f99ae65 | ||
|
|
2645082183 | ||
|
|
96090f7c10 | ||
|
|
96c90efbde | ||
|
|
4197efe482 | ||
|
|
8b621a62d6 | ||
|
|
1e869e1a14 |
@@ -23,6 +23,12 @@ jobs:
|
||||
- name: Run production inventory placeholder guard self-test
|
||||
run: bash scripts/check_production_inventory_placeholders.sh --self-test
|
||||
|
||||
- name: Run private-config guard
|
||||
run: bash scripts/check_private_config_guard.sh
|
||||
|
||||
- name: Run portal contract sync guard
|
||||
run: node scripts/check_portal_contract_sync.mjs
|
||||
|
||||
rust-runtime-guard:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
name: rust-binary-build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- 'rust-toolchain.toml'
|
||||
- 'adk-rust/**'
|
||||
- 'scripts/package_rust_release_binaries.py'
|
||||
- '.github/workflows/rust-binary-build.yml'
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-linux-x86_64:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install 1.94.0 --profile minimal --component rustfmt --component clippy
|
||||
rustup override set 1.94.0
|
||||
rustup show active-toolchain
|
||||
cargo +1.94.0 --version
|
||||
rustc +1.94.0 --version
|
||||
|
||||
- name: Build release binaries
|
||||
run: cargo +1.94.0 build --manifest-path adk-rust/Cargo.toml --workspace --release
|
||||
|
||||
- name: Package release binaries
|
||||
run: |
|
||||
python3 scripts/package_rust_release_binaries.py \
|
||||
--release-dir adk-rust/target/release \
|
||||
--out-dir dist/awatch-rus-linux-x86_64 \
|
||||
--archive dist/awatch-rus-linux-x86_64-release-binaries.tar.gz \
|
||||
--target linux-x86_64 \
|
||||
--commit "${GITHUB_SHA}" \
|
||||
--ref "${GITHUB_REF}" \
|
||||
--run-id "${GITHUB_RUN_ID}"
|
||||
|
||||
- name: Upload release binaries artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: awatch-rus-linux_x86_64-release-binaries
|
||||
path: |
|
||||
dist/awatch-rus-linux_x86_64-release-binaries.tar.gz
|
||||
dist/awatch-rus-linux_x86_64-release-binaries.tar.gz.sha256
|
||||
dist/awatch-rus-linux_x86_64/BINARIES.txt
|
||||
dist/awatch-rus-linux_x86_64/SHA256SUMS.txt
|
||||
dist/awatch-rus-linux_x86_64/BUILD_MANIFEST.json
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
- name: Publish GitHub Release assets
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
generate_release_notes: true
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
dist/awatch-rus-linux_x86_64-release-binaries.tar.gz
|
||||
dist/awatch-rus-linux_x86_64-release-binaries.tar.gz.sha256
|
||||
dist/awatch-rus-linux_x86_64/BINARIES.txt
|
||||
dist/awatch-rus-linux_x86_64/SHA256SUMS.txt
|
||||
dist/awatch-rus-linux_x86_64/BUILD_MANIFEST.json
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Rust clippy diagnostic
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- codex/rust-professionalization
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
detmir-portal-clippy-diagnostic:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust 1.85 with rustfmt and clippy
|
||||
run: |
|
||||
rustup toolchain install 1.85.0 --profile minimal --component rustfmt --component clippy
|
||||
rustup default 1.85.0
|
||||
|
||||
- name: Capture detmir-portal clippy output
|
||||
working-directory: adk-rust
|
||||
run: |
|
||||
set +e
|
||||
cargo clippy -p detmir-portal --all-targets -- -D warnings > ../detmir-portal-clippy.log 2>&1
|
||||
status=$?
|
||||
echo "clippy_exit_status=${status}" > ../detmir-portal-clippy-status.txt
|
||||
tail -n 240 ../detmir-portal-clippy.log
|
||||
exit ${status}
|
||||
|
||||
- name: Upload detmir-portal clippy log
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: detmir-portal-clippy-log
|
||||
path: |
|
||||
detmir-portal-clippy.log
|
||||
detmir-portal-clippy-status.txt
|
||||
@@ -0,0 +1,73 @@
|
||||
name: Rust professionalization check
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'rust-toolchain.toml'
|
||||
- 'adk-rust/crates/detmir-core/**'
|
||||
- 'adk-rust/crates/detmir-portal/**'
|
||||
- 'scripts/check_private_config_guard.sh'
|
||||
- 'scripts/check_portal_contract_sync.mjs'
|
||||
- '.github/workflows/rust-professionalization-check.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
rust-check:
|
||||
name: changed Rust crates smoke
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install 1.94.0 --profile minimal --component rustfmt --component clippy
|
||||
rustup override set 1.94.0
|
||||
rustup show active-toolchain
|
||||
cargo +1.94.0 --version
|
||||
rustc +1.94.0 --version
|
||||
|
||||
- name: Cargo fmt check
|
||||
working-directory: adk-rust
|
||||
run: cargo +1.94.0 fmt --all -- --check
|
||||
|
||||
- name: Test detmir-core
|
||||
working-directory: adk-rust
|
||||
run: cargo +1.94.0 test -p detmir-core
|
||||
|
||||
- name: Test detmir-portal
|
||||
working-directory: adk-rust
|
||||
run: cargo +1.94.0 test -p detmir-portal
|
||||
|
||||
- name: Clippy detmir-core
|
||||
working-directory: adk-rust
|
||||
run: cargo +1.94.0 clippy -p detmir-core --all-targets -- -D warnings
|
||||
|
||||
- name: Clippy detmir-portal with captured log
|
||||
working-directory: adk-rust
|
||||
run: |
|
||||
set +e
|
||||
cargo +1.94.0 clippy -p detmir-portal --all-targets -- -D warnings > ../detmir-portal-clippy.log 2>&1
|
||||
status=$?
|
||||
echo "clippy_exit_status=${status}" > ../detmir-portal-clippy-status.txt
|
||||
tail -n 80 ../detmir-portal-clippy.log
|
||||
exit ${status}
|
||||
|
||||
- name: Upload detmir-portal clippy log
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: detmir-portal-clippy-log
|
||||
path: |
|
||||
detmir-portal-clippy.log
|
||||
detmir-portal-clippy-status.txt
|
||||
|
||||
- name: Private config guard
|
||||
run: bash scripts/check_private_config_guard.sh
|
||||
|
||||
- name: Portal contract sync
|
||||
run: node scripts/check_portal_contract_sync.mjs
|
||||
@@ -0,0 +1,35 @@
|
||||
name: rust-workspace
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
rust-workspace:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install 1.94.0 --profile minimal --component rustfmt --component clippy
|
||||
rustup override set 1.94.0
|
||||
rustup show active-toolchain
|
||||
cargo +1.94.0 --version
|
||||
rustc +1.94.0 --version
|
||||
|
||||
- name: Format
|
||||
run: cargo +1.94.0 fmt --manifest-path adk-rust/Cargo.toml --all -- --check
|
||||
|
||||
- name: Test
|
||||
run: cargo +1.94.0 test --manifest-path adk-rust/Cargo.toml --workspace
|
||||
|
||||
- name: Clippy
|
||||
run: cargo +1.94.0 clippy --manifest-path adk-rust/Cargo.toml --workspace --all-targets -- -D warnings
|
||||
|
||||
- name: Release build
|
||||
run: cargo +1.94.0 build --manifest-path adk-rust/Cargo.toml --workspace --release
|
||||
+9
-2
@@ -1,7 +1,11 @@
|
||||
# Local secrets
|
||||
/secrets/
|
||||
/private-config/*.env
|
||||
/private-config/*.local
|
||||
/private-config/*
|
||||
!/private-config/
|
||||
!/private-config/README.md
|
||||
!/private-config/.gitkeep
|
||||
!/private-config/*.example
|
||||
!/private-config/*.template
|
||||
/ansible/inventory.ini
|
||||
/codex_history.txt
|
||||
|
||||
@@ -12,9 +16,12 @@
|
||||
windows/*.report.json
|
||||
.rollout-logs/
|
||||
output/
|
||||
artifacts/browser-smoke/
|
||||
dist/
|
||||
.ai/
|
||||
.autonomous/
|
||||
.ops/
|
||||
.playwright-cli/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
|
||||
@@ -1,52 +1,246 @@
|
||||
AGENTS for OpenCode
|
||||
# AGENTS.md
|
||||
|
||||
Keep this file minimal and high-signal: only include facts an agent would otherwise miss.
|
||||
Operational rules for OpenCode/Codex agents in AWatch-rus.
|
||||
|
||||
1) Repo purpose (one line)
|
||||
- This repository bundles an ActivityWatch Server deployment, RU WebUI patch, Windows collectors (PowerShell), and Rust operational utilities for aggregation, monitoring, health checks, SLO, DLP helpers, and DetMir automation. Python is retained only for explicit exceptions: Telegram bot runtime, pfSense tooling, OCR/content-analysis, 1C AI/ETL, and detmir-mcp.
|
||||
## Defaults
|
||||
|
||||
2) Highest-value entrypoints & commands
|
||||
- Read README.md and docs/preparation.md first (they are the authoritative onboarding flow).
|
||||
- Create a Proxmox CT: `proxmox/create-ct.sh [ /path/to/deploy.secrets.env ]` (reads secrets/deploy.secrets.env).
|
||||
- Push server artifacts to an existing CT: `proxmox/push-aw-artifacts.sh [ /path/to/deploy.secrets.env ]`.
|
||||
- Install AW server on the CT (runs inside CT): `aw-server/install_aw_server.sh` (requires `/etc/activitywatch/aw-server.env`).
|
||||
- Apply RU WebUI patch (must run on the CT and after webui is present): `aw-server/apply_webui_ru_patch.sh`.
|
||||
- Run the Windows ensemble deploy from a Windows admin host: `windows/deploy-ensemble.ps1` (see its parameters; it calls `deploy-domain-users.ps1`).
|
||||
- Quick DLP aggregation (local): `adk-rust/target/release/dlp-aggregator`.
|
||||
- Rust is the primary runtime: use `adk-rust/`, build with `cargo build --release -p <crate>`, test with `cargo test -p <crate>`.
|
||||
- Root scripts (`check-aw-data.sh`, `check-aw-full.sh`, `scripts/prod_rollout.sh`, install-kit helpers) are Rust-first wrappers with legacy fallback.
|
||||
- Python is allowed only in `aw-server/dlp-content-analysis/`, `clickhouse-1c/ai/`, `clickhouse-1c/etl/`, `detmir-mcp/main.py`, `grafana-1c/`, `pfsense/`, `proxmox/tsj_guardian_bot.py`.
|
||||
- Never add real secrets from `secrets/`, private `.env`, or host credentials.
|
||||
- When auditing private/ignored files, report only path, secret type, and remediation. Never copy secret values into docs, logs, markdown, terminal summaries, commits, or handoff reports.
|
||||
|
||||
3) Exact env/secrets behavior agents often miss
|
||||
- Secrets live in `secrets/deploy.secrets.env` (actual file is intentionally local-only). Many scripts default to that path if no arg provided. Never add real secrets to commits. Use `.example` files as templates.
|
||||
- The CT bootstrap workflow expects `/etc/activitywatch/aw-server.env` on the CT (pushed by push-aw-artifacts when AW_SERVER_* variables are set). `install_aw_server.sh` sources that exact path.
|
||||
## Required Checks
|
||||
|
||||
4) CI / quality checks the repo enforces
|
||||
- GitHub CI runs shellcheck for `*.sh` and PSScriptAnalyzer for PowerShell in `windows/*.ps1` (see .github/workflows/ci.yml).
|
||||
- Local quality gate: `scripts/quality-gate.sh` performs bash `-n`, (optional) shellcheck, pwsh parse checks, and ansible syntax checks. Run this before PRs.
|
||||
- General: `scripts/quality-gate.sh`.
|
||||
- Rust: targeted `cargo test -p <crate>`.
|
||||
- Windows: parse PowerShell; CI also runs PSScriptAnalyzer on `windows/*.ps1`, `.psm1`, `.psd1`.
|
||||
- Ansible: affected `ansible-playbook --syntax-check ...`.
|
||||
|
||||
5) File locations and toolchain quirks
|
||||
- AW server binary is installed under `/opt/activitywatch/releases` and symlinked from `/opt/activitywatch/bin/aw-server-rust` by `install_aw_server.sh`.
|
||||
- RU WebUI patching expects JS assets in `$AW_SERVER_WEBUI_DIR` (default `/opt/activitywatch/webui-ru`). The patch script writes `js/ru-patch-v5.js` and edits `index.html` in-place (it makes backups with .bak timestamps).
|
||||
- `proxmox/create-ct.sh` and `proxmox/push-aw-artifacts.sh` source the same deploy.secrets.env and require many CT_* / AW_SERVER_* variables; missing vars cause immediate exit.
|
||||
## Map
|
||||
|
||||
6) Monorepo boundaries / responsibilities
|
||||
- aw-server/: server install & systemd unit + RU webui patching.
|
||||
- proxmox/: create CT and push artifacts scripts (requires Proxmox `pct` CLI and CT preconditions).
|
||||
- windows/: PowerShell collectors and deployment automation (Target: Windows admin hosts; validated via `validate-deployment.ps1`).
|
||||
- grafana-1c/, pfsense/: monitoring stacks and pollers (separate deploys, not part of aw-server install).
|
||||
- scripts/: small utilities and `quality-gate.sh` used by contributors.
|
||||
- `adk-rust/`: operational crates.
|
||||
- `aw-server/`: server install, env examples, RU WebUI patch, systemd.
|
||||
- `windows/`: RDP deployment, collectors, recovery, validation.
|
||||
- `ansible/`: deployment playbooks.
|
||||
- `proxmox/`: CT/gateway/bot automation.
|
||||
- `clickhouse-1c/`, `grafana-1c/`, `pfsense/`: integration stacks.
|
||||
- `grafana/`: flat version-controlled dashboard JSON; use Ansible to import/check it.
|
||||
|
||||
7) Common gotchas
|
||||
- Do NOT commit secrets (secrets/ are local-only; PRs must not contain real secrets).
|
||||
- Many scripts assume they run on the target CT or on a Linux admin host with `pct` available. Don't try to run them on macOS without adapting dependencies.
|
||||
- `aw-server/install_aw_server.sh` expects network access to download the AW release URL provided by AW_SERVER_DOWNLOAD_URL.
|
||||
- `aw-server/apply_webui_ru_patch.sh` must run after AW webui files are present; it will fail if required bootstrap files under `<CT_BOOTSTRAP_DIR>` are missing.
|
||||
- When pushing AW_SERVER env via `push-aw-artifacts.sh` the script will only write `/etc/activitywatch/aw-server.env` if all AW_SERVER_* variables are set; otherwise it warns and skips.
|
||||
## Entrypoints
|
||||
|
||||
8) PR / commit checklist for agents
|
||||
- Run `scripts/quality-gate.sh` locally (or ensure CI covers changed files).
|
||||
- Ensure no secrets (.env with real values) are staged.
|
||||
- If changing PowerShell, ensure PSScriptAnalyzer rules pass (CI enforces this).
|
||||
Use `proxmox/create-ct.sh`, `proxmox/push-aw-artifacts.sh`, `aw-server/install_aw_server.sh`, `aw-server/apply_webui_ru_patch.sh`, `windows/deploy-ensemble.ps1`, and docs in `docs/preparation.md`, `docs/deployment.md`, `docs/runbook.md`, `docs/operations.md`.
|
||||
|
||||
9) Where to find more instructions (preserve these files)
|
||||
- README.md, docs/preparation.md, docs/deployment.md, docs/runbook.md, docs/operations.md, docs/codebase-onboarding.md — read these when doing infra or deployment work.
|
||||
## Incident Handling
|
||||
|
||||
If you need me to add step-by-step repros or automate one of the tasks above (create CT, push artifacts, run install on CT), say which one and I will implement the helper or run the checked commands.
|
||||
OpenCode must handle AWatch-rus incidents as evidence-based operational triage,
|
||||
not as guesswork from one red dashboard card.
|
||||
|
||||
### Assessment Basis
|
||||
|
||||
Assess every incident from these signals, in this order:
|
||||
|
||||
- **User impact:** portal/report/dashboard unavailable, stale, slow, or wrong;
|
||||
which role is affected: executive, manager, security, forensics, admin.
|
||||
- **Data freshness:** ActivityWatch bucket `metadata.end`, collector heartbeats,
|
||||
Windows scheduled task recency, queue depth, and upload/send failure counters.
|
||||
- **Service health:** systemd failed units, active timers, bounded HTTP checks,
|
||||
`/health` or `/api/health` responses, container health where relevant.
|
||||
- **Pipeline layer:** identify the first broken layer in the chain
|
||||
`Windows/RDP collectors -> ActivityWatch buckets -> Rust services -> exporters
|
||||
-> Grafana/Portal -> ClickHouse/1C where configured`.
|
||||
- **Risk/evidence:** DLP endpoint signals, incident candidates, evidence
|
||||
artifacts, UEBA/risk narrative inputs, coverage gaps, and security
|
||||
correlation indicators.
|
||||
- **Blast radius:** one user/session/collector, one host, one service, one
|
||||
dashboard, or the full contour.
|
||||
- **Recoverability:** known rollback, stale-cache availability, safe restart
|
||||
boundary, and whether a human approval is required.
|
||||
|
||||
Risk Narrative is only decision support. It can raise priority and explain
|
||||
why a manual check is needed, but it does not prove a policy violation, DLP
|
||||
incident, or SIEM finding by itself.
|
||||
|
||||
### Severity
|
||||
|
||||
Use this practical severity model:
|
||||
|
||||
- `P0`: data loss risk, auth/security boundary broken, raw private service
|
||||
exposed, production report chain unavailable with no stale fallback, or
|
||||
repeated collector process storms/memory pressure.
|
||||
- `P1`: executive/security workflows degraded, fresh data missing for a critical
|
||||
host, DLP evidence sync broken, ClickHouse/1C ingest stopped, or portal health
|
||||
degraded with user-visible effect.
|
||||
- `P2`: one collector stale, one dashboard/panel wrong, delayed timer, bad label
|
||||
normalization, missing noncritical evidence, or recoverable stale report.
|
||||
- `P3`: documentation drift, cosmetic UI issue, non-production demo fixture,
|
||||
or a warning with fresh data still confirmed.
|
||||
|
||||
Escalate severity when the same symptom repeats after recovery, when coverage
|
||||
is unknown, or when evidence contradicts dashboard status.
|
||||
|
||||
### Mechanisms To Use
|
||||
|
||||
Start with the repo wrappers before ad hoc probing:
|
||||
|
||||
```bash
|
||||
cd /mnt/usb_hdd2/Projects/ActivityWatch-Russian
|
||||
./check-aw-data.sh
|
||||
./check-aw-full.sh
|
||||
```
|
||||
|
||||
Then narrow by layer:
|
||||
|
||||
- ActivityWatch API: `/api/0/info`, `/api/0/buckets`, bucket metadata and recent
|
||||
events with explicit `no_proxy` and short `curl --max-time`.
|
||||
- Worktime: `aw-worktime-api` `/health`, `/reports/worktime/today`,
|
||||
`/reports/worktime/management?allow_stale=1`, prewarm logs, stale-cache
|
||||
fields, `AW_WORKTIME_EVENTS_LIMIT`, and `aw_query_timeout_count`.
|
||||
- Windows/RDP: `validate-deployment.ps1`, exact `ActivityWatch Launch [...]`
|
||||
scheduled tasks, `ActivityWatch Recovery`, collector guard state, session
|
||||
collectors, local queue depth, and send failure counters.
|
||||
- DLP: `aw-dlp-policy-engine`, `aw-dlp-case-management`, `dlp-health-check`,
|
||||
`aw-dlp-endpoint-signals_<HOST>`, evidence artifact sync, policy audit, and
|
||||
case/compliance services.
|
||||
- Portal/Gateway/Grafana: `/portal/api/health`, `/api/reports`, gateway
|
||||
`/healthz`, protected `/d/...` Grafana routes, role gates, and browser smoke
|
||||
scripts.
|
||||
- ClickHouse/1C: only for file-1C/analytics incidents. Do not blame ClickHouse
|
||||
for worktime report failures unless the affected path explicitly uses it.
|
||||
|
||||
Use existing guards and bounded mechanisms before broad restarts:
|
||||
|
||||
- stale-cache and fail-closed worktime behavior;
|
||||
- `aw-worktime-autoheal`, `aw-worktime-prewarm`, `aw-worktime-ui-bridge`,
|
||||
`aw-rus-healthd` timers;
|
||||
- Windows collector guard and exact localized scheduled tasks;
|
||||
- DLP evidence sync and health timers;
|
||||
- targeted service restart only after evidence identifies the layer.
|
||||
|
||||
### DLP Rule Update System
|
||||
|
||||
Do not describe AWatch-rus DLP rules as manual local JSON entry, and do not
|
||||
collapse all DLP updates into one mechanism. There are two related but separate
|
||||
contours:
|
||||
|
||||
1. policy lifecycle and endpoint synchronization through the DLP Policy Engine;
|
||||
2. automatic IOC/signature replenishment from the open-source Hayabusa/Sigma
|
||||
ruleset.
|
||||
|
||||
The centralized policy update contour is:
|
||||
|
||||
- Server service: `aw-dlp-policy-engine.service`, Rust binary
|
||||
`/usr/local/bin/aw-dlp-policy-engine-rust`, default API port `5601`.
|
||||
- Storage: SQLite DB from `AW_DLP_POLICY_ENGINE_DB_PATH`, with policy records,
|
||||
policy versions, active policy pointer, rollback versions, and `policy_audit`.
|
||||
- API contract:
|
||||
- `GET /healthz`;
|
||||
- CRUD: `/api/0/dlp/policies`;
|
||||
- active bundle: `GET /api/0/dlp/policies/active`;
|
||||
- active version/checksum: `GET /api/0/dlp/policies/active/version`;
|
||||
- approval lifecycle:
|
||||
`draft -> pending_approval -> approved -> deployed`;
|
||||
- workflow calls:
|
||||
`POST /submit`, `POST /approve`, `POST /draft`, `POST /activate`;
|
||||
- rollback: `POST /api/0/dlp/policies/rollback`;
|
||||
- audit:
|
||||
`GET /api/0/dlp/policies/audit?limit=N` and
|
||||
`GET /api/0/dlp/policies/{id}/audit?limit=N`;
|
||||
- endpoint sync:
|
||||
`POST /api/0/dlp/policies/agents/{agent_id}/heartbeat` and
|
||||
`GET /api/0/dlp/policies/agents/{agent_id}/desired`.
|
||||
- Windows side is configured for server-driven policy mode:
|
||||
`aw_windows_policy_mode: "server"`,
|
||||
`aw_windows_policy_engine_enabled: true`,
|
||||
`aw_windows_policy_refresh_seconds: 300`, and policy engine host/port from
|
||||
Ansible group vars.
|
||||
- Agents report their current policy version/checksum by heartbeat. The server
|
||||
compares it with the active deployed policy and returns `desired` with
|
||||
`refreshNow=true` when the endpoint must update.
|
||||
- `dlp-admin-cli` is the operator CLI for read-side checks such as
|
||||
`policies list`, `policies active`, incident/case listing, and combined DLP
|
||||
health checks. It is not a replacement for the lifecycle API when changing
|
||||
policy state.
|
||||
|
||||
Automatic IOC/signature replenishment:
|
||||
|
||||
- Name it precisely as `DLP IOC Enrichment from Hayabusa/Sigma` or
|
||||
`Hayabusa Sigma IOC refresh pipeline`.
|
||||
- Source rules come from the open-source GitHub ruleset
|
||||
`Yamato-Security/hayabusa-rules`, configured by
|
||||
`aw_dlp_ioc_rules_zip_url`.
|
||||
- Deployment is controlled by `ansible/deploy_aw_server.yml` when
|
||||
`aw_dlp_ioc_enabled=true`.
|
||||
- The refresh wrapper `/usr/local/bin/aw-dlp-ioc-refresh.sh` downloads the
|
||||
latest `hayabusa-rules` ZIP, unpacks Sigma YAML rules, and runs the Rust
|
||||
extractor `/usr/local/bin/aw-extract-ioc-from-sigma`.
|
||||
- The Rust extractor is built from
|
||||
`adk-rust/crates/extract-ioc-from-sigma`; local/manual builds use
|
||||
`scripts/build_dlp_ioc_from_hayabusa.sh`.
|
||||
- Extracted IOC-like values include process image suffixes, command-line
|
||||
substrings, original filenames, and SHA256 hashes. They are de-duplicated and
|
||||
emitted as `ioc_blacklist.json`, `ioc_blacklist.csv`, and
|
||||
`ioc_blacklist.sql`.
|
||||
- Production artifacts live under `/opt/activitywatch/dlp-ioc/output` and are
|
||||
served by `aw-worktime-api` on `/dlp-ioc/ioc_blacklist.json`,
|
||||
`/dlp-ioc/ioc_blacklist.csv`, and `/dlp-ioc/ioc_blacklist.sql`.
|
||||
- Windows DLP policy can consume this feed through the `ioc.source` field with
|
||||
format `hayabusa_sigma_v1`; endpoint health/heartbeat should expose loaded
|
||||
IOC state such as `iocRulesLoaded`.
|
||||
- Runtime automation is `aw-dlp-ioc-refresh.service` plus
|
||||
`aw-dlp-ioc-refresh.timer` with interval `aw_dlp_ioc_refresh_interval`
|
||||
(default `6h`). Health/diagnostics should check this timer before assuming
|
||||
signatures are static or manually maintained.
|
||||
- This Hayabusa/Sigma IOC pipeline enriches the DLP rule base automatically; it
|
||||
is not the same thing as hand-editing endpoint JSON and is also distinct from
|
||||
the server-side Hayabusa EVTX forensics runner.
|
||||
|
||||
Operational meaning:
|
||||
|
||||
1. To update rules, create or update a policy draft through the policy engine.
|
||||
2. Submit it for approval, approve it, then activate/deploy it. Activation is
|
||||
allowed only from `approved`.
|
||||
3. For policy changes, verify `active/version`, audit entries, Windows agent
|
||||
heartbeat/desired, and downstream DLP signals after endpoints refresh.
|
||||
4. For automatic signature replenishment, verify
|
||||
`aw-dlp-ioc-refresh.timer`, the last `aw-dlp-ioc-refresh.service` run,
|
||||
non-empty `ioc_blacklist.json/csv/sql`, Worktime API `/dlp-ioc/...`
|
||||
exports, and Windows IOC load counters.
|
||||
5. If a policy causes noise or misses, use policy rollback through the API; do
|
||||
not hand-edit endpoint policy files as the normal rollback path.
|
||||
|
||||
Manual edits of `C:\Program Files\AWatch-rus\windows\dlp-policy.example.json`
|
||||
or `C:\ProgramData\AWatch-rus\dlp-policy.json` are diagnostic or emergency
|
||||
fallback only. If such an edit is unavoidable, document it as configuration
|
||||
drift and bring the rule back into the central policy engine.
|
||||
|
||||
### Response Workflow
|
||||
|
||||
1. Capture current state first: command, timestamp, host, service, and exact
|
||||
failing endpoint. Do not restart before collecting evidence unless the
|
||||
system is in active resource exhaustion.
|
||||
2. Find the first broken layer. If buckets are stale, fix collectors before
|
||||
Grafana. If `aw-worktime-api` is degraded, fix/report that before portal.
|
||||
3. Separate real outage from presentation drift: dashboards can be stale or
|
||||
mislabeled while buckets and services are healthy.
|
||||
4. Apply the narrowest safe recovery: restart a collector/task/service, reduce
|
||||
unsafe limits, clear process storms, or restore a known-good binary/config.
|
||||
Back up config/binaries before replacement.
|
||||
5. Verify with the same failing check plus one upstream and one downstream
|
||||
check. For collector incidents, require bucket freshness and guard/healthd
|
||||
consistency, not just one green command.
|
||||
6. Record closure evidence: root cause, affected layer, action taken, commands
|
||||
run, post-check results, remaining risk, and rollback path.
|
||||
|
||||
### Safety Rules
|
||||
|
||||
- Old snapshots, memory, dashboards, and handoff notes are hints; live runtime
|
||||
evidence wins.
|
||||
- Never expose passwords, tokens, private host credentials, private URLs, raw
|
||||
security events, or customer identifiers in incident writeups.
|
||||
- Do not run broad deploys, full restarts, or `cargo build --workspace` during
|
||||
incident triage unless the scope demands it and rollback is clear.
|
||||
- Do not treat `status=ok` as sufficient when freshness, queue depth, or
|
||||
coverage evidence says otherwise.
|
||||
- For owner-facing reports, publish only protected gateway/Grafana routes, not
|
||||
raw `:5600`, `:5610`, `:8720`, or ClickHouse endpoints.
|
||||
|
||||
+6
-6
@@ -38,7 +38,7 @@
|
||||
|
||||
## release-readiness-v0.1 - 2026-06-03
|
||||
|
||||
Назначение этапа: довести DetMir/AWatch-rus до проверяемого release-readiness
|
||||
Назначение этапа: довести AWatch-rus до проверяемого release-readiness
|
||||
пакета для пилота, экспертной оценки и последующей публикации релиза без
|
||||
раскрытия приватного коммерческого контура.
|
||||
|
||||
@@ -64,15 +64,15 @@
|
||||
- `cargo test --manifest-path adk-rust/Cargo.toml -p detmir-readiness -p detmir-portal`.
|
||||
- `cargo clippy --manifest-path adk-rust/Cargo.toml -p detmir-readiness -p detmir-portal --all-targets -- -D warnings`.
|
||||
- `node --check adk-rust/crates/detmir-portal/src/static/app.js`.
|
||||
- Ansible syntax-check для AW server и DetMir portal deploy playbooks.
|
||||
- Runtime deployment на проектные сервисы DetMir без изменения pfSense или
|
||||
- Ansible syntax-check для AW server и AWatch-rus portal deploy playbooks.
|
||||
- Runtime deployment на проектные сервисы AWatch-rus без изменения pfSense или
|
||||
Proxmox platform layer.
|
||||
|
||||
## v1.0.1-public-review - 2026-06-03
|
||||
|
||||
Назначение релиза: публичный пакет для экспертной оценки DetMir/AWatch-rus и
|
||||
Назначение релиза: публичный пакет для экспертной оценки AWatch-rus и
|
||||
подготовки к реестровой проверке. Релиз не меняет работающий коммерческий
|
||||
runtime DetMir; изменения относятся к source/release package, документации,
|
||||
runtime AWatch-rus; изменения относятся к source/release package, документации,
|
||||
обезличиванию и проверяемости поставки.
|
||||
|
||||
### Добавлено
|
||||
@@ -120,7 +120,7 @@ runtime DetMir; изменения относятся к source/release package,
|
||||
### Известные ограничения
|
||||
|
||||
- `v1.0.1-public-review` является source/review release. Коммерческий runtime
|
||||
DetMir продолжает использовать private runtime config вне Git.
|
||||
AWatch-rus продолжает использовать private runtime config вне Git.
|
||||
- Python остается для Telegram runtime, OCR/content-analysis, 1C/AI/ETL и MCP
|
||||
helpers. Это отражено в registry docs как допустимое исключение.
|
||||
- pfSense/infrastructure runtime не менялся в рамках этого релиза.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Описание программного продукта DetMir / AWatch-rus
|
||||
# Описание программного продукта AWatch-rus
|
||||
|
||||
`DetMir` на базе `AWatch-rus` - программный комплекс операционного контроля,
|
||||
`AWatch-rus` - программный комплекс операционного контроля,
|
||||
технического аудита, оценки трудоотдачи сотрудников и мониторинга
|
||||
ИТ-инфраструктуры.
|
||||
|
||||
@@ -13,12 +13,12 @@
|
||||
|
||||
## Коммерческие модули
|
||||
|
||||
- `DetMir Workforce` - ежедневный управленческий слой: активность,
|
||||
- `AWatch-rus Workforce` - ежедневный управленческий слой: активность,
|
||||
активное время, простои, RDP/1C/рабочие приложения, загрузка сотрудников и
|
||||
отчеты для руководителя.
|
||||
- `DetMir Security` - прикладной слой ИБ: DLP-сигналы, evidence metadata,
|
||||
- `AWatch-rus Security` - прикладной слой ИБ: DLP-сигналы, evidence metadata,
|
||||
доступные скриншоты, review/case queue и audit действий оператора.
|
||||
- `DetMir Forensics` - расследовательский слой: цепочки событий,
|
||||
- `AWatch-rus Forensics` - расследовательский слой: цепочки событий,
|
||||
Hayabusa/offline-разбор, кейсы и материалы для внутреннего расследования.
|
||||
|
||||
## Основные функции
|
||||
|
||||
@@ -1,36 +1,107 @@
|
||||
# AWatch-rus
|
||||
|
||||
AWatch-rus / DetMir - программный комплекс операционного контроля,
|
||||
AWatch-rus - программный комплекс операционного контроля,
|
||||
технического аудита, оценки трудоотдачи сотрудников и мониторинга
|
||||
корпоративной ИТ-инфраструктуры на базе ActivityWatch, Rust-сервисов
|
||||
автоматизации, Grafana/Prometheus-витрин и модулей расследования инцидентов.
|
||||
|
||||
Проект не позиционируется как сертифицированная DLP/SIEM/EDR/XDR/СЗИ. DLP,
|
||||
evidence и Hayabusa используются как прикладные модули внутри платформы
|
||||
операционного контроля и технического аудита.
|
||||
Проект не позиционируется как сертифицированная DLP/SIEM/EDR/XDR/СЗИ,хотя DLP,evidence и Hayabusa используются в проекте.
|
||||
|
||||
## Назначение
|
||||
|
||||
- DetMir Workforce: активность сотрудников, загрузка, RDP/1C/рабочие
|
||||
- AWatch-rus Workforce: активность сотрудников, загрузка, RDP/1C/рабочие
|
||||
приложения и управленческие отчеты для владельца бизнеса.
|
||||
- DetMir Security: DLP-сигналы, evidence, очередь кейсов и audit действий
|
||||
оператора без заявления продукта как сертифицированной СЗИ.
|
||||
- DetMir Forensics: цепочки событий, Hayabusa/offline-разбор и материалы для
|
||||
внутреннего расследования.
|
||||
- AWatch-rus Security: DLP-сигналы, evidence, очередь кейсов и audit действий оператора без заявления продукта как сертифицированной СЗИ.
|
||||
- AWatch-rus Forensics: цепочки событий, Hayabusa/offline-разбор и материалы для внутреннего расследования.
|
||||
- Контроль доступности и свежести данных ActivityWatch.
|
||||
- Учет активного времени, RDP-сессий, окон, приложений и рабочих интервалов.
|
||||
- Витрины Grafana для администратора, оператора ИБ и руководителя.
|
||||
- Учет активного времени, Windows RDP-сессий окон, приложений и рабочих интервалов а также активности пользователей в Linux/Unix системах.
|
||||
- витрины Grafana для администратора, оператора ИБ и руководителя(dashboards).
|
||||
- Автоматизация runbook-проверок, health-check, SLO и безопасного auto-heal.
|
||||
- Сбор evidence по инцидентам и аудит действий оператора.
|
||||
|
||||
## Rust-first runtime
|
||||
|
||||
Основной серверный runtime DetMir переведен на Rust: status/check/auto-heal,
|
||||
Основной серверный runtime AWatch-rus переведен на Rust: status/check/auto-heal,
|
||||
SLO, worktime, DLP server-side helpers, evidence и install-kit tooling.
|
||||
|
||||
Python в репозитории остается для вспомогательных направлений: Telegram bot
|
||||
runtime, OCR/content-analysis, 1C/AI/ETL integration и MCP/dev helpers. Эти
|
||||
части не являются ядром Rust-first runtime.
|
||||
Python, присутствующий в коде репозитория, остается для вспомогательных направлений: Telegram bot
|
||||
runtime(для оперативного оповещения), OCR/content-analysis, 1C/AI/ETL integration и MCP/dev helpers. Эти части не являются ядром Rust-first runtime.
|
||||
|
||||
Портальный слой зафиксирован как Rust server-rendered HTML + HTMX-compatible
|
||||
JSON API, OpenAPI и TypeScript declarations. Dioxus не используется и не
|
||||
рассматривается для Pilot v1.0. React, Tauri и Electron также не входят в
|
||||
текущий основной UI, но возможна их интеграция в проект.
|
||||
|
||||
## Product Evolution
|
||||
|
||||
AWatch-rus является рабочей платформой Workforce + Security + Forensics.
|
||||
Архитектура предусматривает расширение на агентные и agentless-источники
|
||||
данных. Planned/Future элементы ниже не являются реализованной функциональностью
|
||||
и не должны трактоваться как готовые collectors или integrations.
|
||||
|
||||
Implemented:
|
||||
|
||||
- Rust Backend.
|
||||
- Rust Agent.
|
||||
- HTML/HTMX Portal.
|
||||
- Role-based Pilot v1 contracts.
|
||||
- Product architecture page `/portal/architecture`.
|
||||
- Workforce reports.
|
||||
- UEBA v1.
|
||||
- Forensics reporting.
|
||||
- pfSense contract/readiness layer со статусом `contract_only`, без заявления
|
||||
production ingestion.
|
||||
|
||||
Planned:
|
||||
|
||||
- Provider detail expansion under `/portal/architecture`.
|
||||
- PowerShell Provider.
|
||||
- SSH Provider.
|
||||
- Syslog Provider.
|
||||
- 1C Provider как формализация текущего file-based 1C analytics направления.
|
||||
- Russian OS support validation.
|
||||
|
||||
Future:
|
||||
|
||||
- Extended Enterprise connectors.
|
||||
- SCUD/VPN integrations.
|
||||
- React/TypeScript Enterprise UI.
|
||||
- Tauri Desktop Forensics.
|
||||
|
||||
## Pilot v1 demo
|
||||
|
||||
Pilot v1 demo показывает AWatch-rus как рабочую платформу Workforce Analytics +
|
||||
Security Analytics + Forensics для ролей `executive`, `manager`, `security`,
|
||||
`forensics` и `admin`.
|
||||
|
||||
Демо-материалы:
|
||||
|
||||
- [сценарий Pilot v1 demo](docs/PILOT_DEMO_SCENARIO_RU.md);
|
||||
- [сценарий руководителя](docs/demo/DEMO_SCENARIO_EXECUTIVE_RU.md);
|
||||
- [сценарий ИБ](docs/demo/DEMO_SCENARIO_SECURITY_RU.md);
|
||||
- [сценарий расследований](docs/demo/DEMO_SCENARIO_FORENSICS_RU.md);
|
||||
- [demo seed data](docs/fixtures/pilot-v1-demo/demo-seed-data.json);
|
||||
- [demo evidence pack](docs/fixtures/pilot-v1-demo/evidence-pack/);
|
||||
- [пример итогового demo-отчета](docs/DEMO_REPORT_EXAMPLE_RU.md);
|
||||
- [ценность пилота для заказчика](docs/PILOT_VALUE_PROPOSITION_RU.md);
|
||||
- [преддемо-runbook](docs/DEMO_RUNBOOK_RU.md).
|
||||
|
||||
Pilot validation:
|
||||
|
||||
- [чеклист проверки пилота](docs/PILOT_VALIDATION_CHECKLIST_RU.md);
|
||||
- [gap analysis пилота](docs/PILOT_GAP_ANALYSIS_RU.md);
|
||||
- [вопросы для discovery с заказчиком](docs/CUSTOMER_DISCOVERY_QUESTIONS_RU.md);
|
||||
- [критерии успеха пилота](docs/PILOT_SUCCESS_CRITERIA_RU.md);
|
||||
- [конкурентное позиционирование](docs/COMPETITIVE_POSITIONING_RU.md).
|
||||
|
||||
Границы показа:
|
||||
|
||||
- pfSense показывается только как `contract_only/readiness`, без заявления
|
||||
production ingestion или SIEM;
|
||||
- UEBA Score v1 является прозрачной rule-based моделью, без ML/LLM;
|
||||
- demo fixtures не содержат реальных IP-адресов, hostname, логинов, ФИО,
|
||||
подразделений заказчика или событий безопасности;
|
||||
- planned/future providers не являются реализованными collectors.
|
||||
|
||||
## Что видит оператор
|
||||
|
||||
@@ -47,21 +118,155 @@ runtime, OCR/content-analysis, 1C/AI/ETL integration и MCP/dev helpers. Эти
|
||||
- ИБ - заметить DLP-сигналы и подозрительную активность.
|
||||
- Администратору - проверить, что сборщики и сервер работают стабильно.
|
||||
|
||||
## Интерфейс
|
||||
|
||||
Скриншоты ниже подготовлены на демонстрационных данных: без реальных IP-адресов,
|
||||
hostname, логинов, сотрудников, подразделений заказчика и событий безопасности.
|
||||
|
||||
Все демонстрационные скриншоты от 2026-06-06 лежат в
|
||||
[docs/screenshots/](docs/screenshots/):
|
||||
[главный вывод](docs/screenshots/01-executive-overview.png),
|
||||
[карта рисков](docs/screenshots/02-risk-heatmap.png),
|
||||
[безопасность](docs/screenshots/03-security-view.png),
|
||||
[эксплуатация](docs/screenshots/04-operations-view.png),
|
||||
[пакет расследования](docs/screenshots/05-investigation-pack.png),
|
||||
[итоговый отчет](docs/screenshots/06-markdown-report.png),
|
||||
[архитектура продукта](docs/screenshots/07-product-architecture.png).
|
||||
Сводный список и правила публикации: [docs/PORTAL_SCREENSHOTS_RU.md](docs/PORTAL_SCREENSHOTS_RU.md).
|
||||
|
||||
### Главный вывод
|
||||
|
||||

|
||||
|
||||
Руководитель видит главный риск первым, затем сводку по достоверности
|
||||
показателей, полноте данных, кандидатам на проверку и рискам подразделений.
|
||||
|
||||
### Карта рисков подразделений
|
||||
|
||||

|
||||
|
||||
Карта рисков показывает, где одновременно проседают активность, покрытие
|
||||
агентов, доверие к показателям и количество ситуаций для проверки.
|
||||
|
||||
### Представление безопасности
|
||||
|
||||

|
||||
|
||||
ИБ получает очередь кандидатов на проверку, связанные расследования и материалы
|
||||
без просмотра сырых логов и без автоматического принятия решений.
|
||||
|
||||
### Представление эксплуатации
|
||||
|
||||

|
||||
|
||||
Эксплуатация видит полноту данных, качество агентского сбора, ошибки сбора и
|
||||
понятный статус событий безопасности через ClickHouse.
|
||||
|
||||
### Пакет расследования
|
||||
|
||||

|
||||
|
||||
Пакет расследования связывает материалы, историю проверки и итоговый вывод,
|
||||
который ответственный сотрудник может подтвердить вручную.
|
||||
|
||||
### Итоговый отчет
|
||||
|
||||

|
||||
|
||||
Markdown-отчет собирает главный вывод, риски подразделений, материалы
|
||||
расследований и рекомендации в формате, удобном для передачи руководителю.
|
||||
|
||||
### Архитектура продукта
|
||||
|
||||

|
||||
|
||||
Страница `/portal/architecture` показывает текущие компоненты, planned
|
||||
extensions и future-направления без создания новых API или фиктивных
|
||||
collectors.
|
||||
|
||||
## Если дашборд пустой
|
||||
|
||||
Обычно это значит одно из трех: выбран слишком узкий период времени, рабочий компьютер давно не присылал события или временно не обновилась витрина в Grafana. Начните с периода `Last 24 hours`, затем переходите к техническим разделам ниже.
|
||||
|
||||
## Поставка и регистрация
|
||||
|
||||
- [Позиционирование для реестра российского ПО](docs/DETMIR_RUSSIAN_SOFTWARE_REGISTRY_POSITIONING_RU.md)
|
||||
- Enterprise deployment documentation:
|
||||
[deployment guide](docs/ENTERPRISE_DEPLOYMENT_GUIDE_RU.md),
|
||||
[topologies](docs/DEPLOYMENT_TOPOLOGIES_RU.md),
|
||||
[sizing](docs/SIZING_GUIDE_RU.md),
|
||||
[backup and recovery](docs/BACKUP_AND_RECOVERY_RU.md),
|
||||
[operations runbook](docs/OPERATIONS_RUNBOOK_RU.md),
|
||||
[security hardening](docs/SECURITY_HARDENING_RU.md),
|
||||
[acceptance checklist](docs/ENTERPRISE_ACCEPTANCE_CHECKLIST_RU.md).
|
||||
|
||||
- Registry readiness documentation:
|
||||
[product passport](docs/REGISTRY_PRODUCT_PASSPORT_RU.md),
|
||||
[architecture](docs/REGISTRY_ARCHITECTURE_RU.md),
|
||||
[functional scope](docs/REGISTRY_FUNCTIONAL_SCOPE_RU.md),
|
||||
[dependency statement](docs/REGISTRY_DEPENDENCY_STATEMENT_RU.md),
|
||||
[deployment model](docs/REGISTRY_DEPLOYMENT_MODEL_RU.md),
|
||||
[commercial positioning](docs/REGISTRY_COMMERCIAL_POSITIONING_RU.md),
|
||||
[readiness checklist](docs/REGISTRY_READINESS_CHECKLIST_RU.md).
|
||||
|
||||
- [Позиционирование для реестра российского ПО](docs/RUSSIAN_SOFTWARE_REGISTRY_POSITIONING_RU.md)
|
||||
- [Сведения для подачи в реестр](REGISTER_RU_SOFTWARE.md)
|
||||
- [Registry product passport](docs/REGISTRY_PRODUCT_PASSPORT_RU.md)
|
||||
- [Registry architecture](docs/REGISTRY_ARCHITECTURE_RU.md)
|
||||
- [Registry functional scope](docs/REGISTRY_FUNCTIONAL_SCOPE_RU.md)
|
||||
- [Registry dependency statement](docs/REGISTRY_DEPENDENCY_STATEMENT_RU.md)
|
||||
- [Registry deployment model](docs/REGISTRY_DEPLOYMENT_MODEL_RU.md)
|
||||
- [Registry commercial positioning](docs/REGISTRY_COMMERCIAL_POSITIONING_RU.md)
|
||||
- [Registry readiness checklist](docs/REGISTRY_READINESS_CHECKLIST_RU.md)
|
||||
- [Описание продукта](PRODUCT_DESCRIPTION_RU.md)
|
||||
- [Журнал изменений](CHANGELOG_RU.md)
|
||||
- [Установка для эксперта](INSTALL_FOR_EXPERT_RU.md)
|
||||
- [Сценарий экспертной проверки](docs/EXPERT_TEST_SCENARIO_RU.md)
|
||||
- [Release manifest 2026-06](docs/RELEASE_MANIFEST_2026-06.md)
|
||||
- [Эксплуатационный профиль](docs/OPERATIONAL_PROOF_PROFILE_RU.md)
|
||||
- [Коммерческие модули DetMir](docs/DETMIR_COMMERCIAL_MODULES_RU.md)
|
||||
- [Коммерческие модули AWatch-rus](docs/COMMERCIAL_MODULES_RU.md)
|
||||
- [Архитектурный baseline](docs/ARCHITECTURE_BASELINE_RU.md)
|
||||
- [Пакет пилота для заказчика](docs/CUSTOMER_PILOT_PACK_RU.md)
|
||||
- [Enterprise deployment guide](docs/ENTERPRISE_DEPLOYMENT_GUIDE_RU.md)
|
||||
- [Deployment topologies](docs/DEPLOYMENT_TOPOLOGIES_RU.md)
|
||||
- [Sizing guide](docs/SIZING_GUIDE_RU.md)
|
||||
- [Backup and recovery](docs/BACKUP_AND_RECOVERY_RU.md)
|
||||
- [Operations runbook](docs/OPERATIONS_RUNBOOK_RU.md)
|
||||
- [Security hardening](docs/SECURITY_HARDENING_RU.md)
|
||||
- [Enterprise acceptance checklist](docs/ENTERPRISE_ACCEPTANCE_CHECKLIST_RU.md)
|
||||
- [Pilot v1.0](docs/PILOT_V1_RU.md)
|
||||
- [Pilot v1 demo](docs/PILOT_DEMO_SCENARIO_RU.md)
|
||||
- [Demo scenario: руководитель](docs/demo/DEMO_SCENARIO_EXECUTIVE_RU.md)
|
||||
- [Demo scenario: ИБ](docs/demo/DEMO_SCENARIO_SECURITY_RU.md)
|
||||
- [Demo scenario: расследования](docs/demo/DEMO_SCENARIO_FORENSICS_RU.md)
|
||||
- [Demo report example](docs/DEMO_REPORT_EXAMPLE_RU.md)
|
||||
- [Pilot value proposition](docs/PILOT_VALUE_PROPOSITION_RU.md)
|
||||
- [Pilot v1.0 acceptance checklist](docs/PILOT_V1_ACCEPTANCE_CHECKLIST_RU.md)
|
||||
- [Pilot v1.0 evidence](docs/PILOT_V1_EVIDENCE_RU.md)
|
||||
- [Pilot validation checklist](docs/PILOT_VALIDATION_CHECKLIST_RU.md)
|
||||
- [Pilot gap analysis](docs/PILOT_GAP_ANALYSIS_RU.md)
|
||||
- [Customer discovery questions](docs/CUSTOMER_DISCOVERY_QUESTIONS_RU.md)
|
||||
- [Pilot success criteria](docs/PILOT_SUCCESS_CRITERIA_RU.md)
|
||||
- [Competitive positioning](docs/COMPETITIVE_POSITIONING_RU.md)
|
||||
- [Roadmap conformance audit](docs/ROADMAP_CONFORMANCE_AUDIT_RU.md)
|
||||
- [Browser conformance smoke](docs/BROWSER_CONFORMANCE_RU.md)
|
||||
- [Production readiness портала](docs/PRODUCTION_READINESS_RU.md)
|
||||
- [Explainable Workforce KPI](docs/EXPLAINABLE_KPI_RU.md)
|
||||
- [Risk Narrative](docs/RISK_NARRATIVE_RU.md)
|
||||
- [Executive Action Center](docs/EXECUTIVE_ACTION_CENTER_RU.md)
|
||||
- [Rust Agent baseline](docs/RUST_AGENT_BASELINE_RU.md)
|
||||
- [Итог production-расследования 2026-06-07](docs/PRODUCTION_INCIDENT_REPORT_2026-06-07_RU.md)
|
||||
- [Runbook восстановления worktime reports](docs/OPERATIONS_RUNBOOK_WORKTIME_RU.md)
|
||||
- [Позиционирование продукта](docs/PRODUCT_POSITIONING_RU.md)
|
||||
- [Экосистема сборщиков](docs/COLLECTOR_ECOSYSTEM_RU.md)
|
||||
- [Стратегия внедрения](docs/DEPLOYMENT_STRATEGY_RU.md)
|
||||
- [Стратегия платформ](docs/PLATFORM_STRATEGY_RU.md)
|
||||
- [Ролевая модель портала](docs/ROLES_RU.md)
|
||||
- [UEBA Score v1](docs/UEBA_SCORE_RU.md)
|
||||
- [pfSense integration readiness](docs/PFSENSE_INTEGRATION_RU.md)
|
||||
- [Сценарий демонстрации заказчику](docs/CUSTOMER_DEMO_SCENARIO_RU.md)
|
||||
- [Аудит готовности к пилоту](docs/PILOT_READINESS_AUDIT_RU.md)
|
||||
- [Позиционирование для первой встречи](docs/SALES_POSITIONING_RU.md)
|
||||
- [Преддемо-сценарий](docs/DEMO_RUNBOOK_RU.md)
|
||||
- [Сторонние компоненты](THIRD_PARTY_COMPONENTS.md)
|
||||
- [Сторонние лицензии](THIRD_PARTY_LICENSES_RU.md)
|
||||
- [Архитектура](docs/ARCHITECTURE_RU.md)
|
||||
|
||||
+15
-15
@@ -1,7 +1,7 @@
|
||||
# Сведения для подачи в реестр российского ПО
|
||||
|
||||
Статус документа: рабочий пакет для подготовки продукта `DetMir` на базе
|
||||
`AWatch-rus` к экспертной проверке и возможной подаче в реестр российского ПО.
|
||||
Статус документа: рабочий пакет для подготовки продукта `AWatch-rus` к
|
||||
экспертной проверке и возможной подаче в реестр российского ПО.
|
||||
|
||||
Документ намеренно описывает продукт как программный комплекс операционного
|
||||
контроля, технического аудита и управления ИТ-инфраструктурой. Продукт не
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
## 1. Наименование продукта
|
||||
|
||||
Коммерческое/продуктовое наименование:
|
||||
Публичное наименование:
|
||||
|
||||
- `DetMir`.
|
||||
- `AWatch-rus`.
|
||||
|
||||
Техническая база и репозиторий:
|
||||
|
||||
@@ -21,15 +21,16 @@
|
||||
Рекомендуемая формула для документов:
|
||||
|
||||
```text
|
||||
DetMir, программный комплекс на базе AWatch-rus.
|
||||
Программный продукт AWatch-rus.
|
||||
```
|
||||
|
||||
Такое разделение позволяет использовать `DetMir` как продуктовую марку, а
|
||||
`AWatch-rus` как техническое имя репозитория и исходной кодовой базы.
|
||||
Для публичных материалов использовать единую формулу: `Программный продукт
|
||||
AWatch-rus`. Это не создает второго бренда и не отделяет продукт от
|
||||
репозитория.
|
||||
|
||||
## 2. Назначение ПО
|
||||
|
||||
`DetMir` предназначен для централизованного операционного контроля,
|
||||
`AWatch-rus` предназначен для централизованного операционного контроля,
|
||||
технического аудита и мониторинга ИТ-инфраструктуры организации.
|
||||
|
||||
Основные задачи:
|
||||
@@ -86,8 +87,7 @@ DetMir, программный комплекс на базе AWatch-rus.
|
||||
|
||||
## 4. Правообладатель
|
||||
|
||||
Правообладатель: владелец репозитория и программного комплекса `DetMir /
|
||||
AWatch-rus`.
|
||||
Правообладатель: владелец репозитория и программного продукта `AWatch-rus`.
|
||||
|
||||
Перед подачей в реестр рекомендуется подготовить отдельный
|
||||
правообладательский пакет:
|
||||
@@ -101,7 +101,7 @@ AWatch-rus`.
|
||||
|
||||
Собственными компонентами считаются:
|
||||
|
||||
- Rust helpers и runtime-модули DetMir;
|
||||
- Rust helpers и runtime-модули AWatch-rus;
|
||||
- портал оператора;
|
||||
- Ansible deployment automation;
|
||||
- Windows collectors/deployment scripts;
|
||||
@@ -196,16 +196,16 @@ Windows/Linux endpoints
|
||||
ActivityWatch collectors / endpoint helpers
|
||||
|
|
||||
v
|
||||
AW server + DetMir Rust helpers
|
||||
AW server + AWatch-rus Rust helpers
|
||||
|
|
||||
+--> SQLite state/cases/policy/evidence metadata
|
||||
+--> InfluxDB/metrics storage
|
||||
+--> Grafana dashboards
|
||||
+--> DetMir operator portal
|
||||
+--> AWatch-rus operator portal
|
||||
+--> Telegram/operator runtime, если включен
|
||||
```
|
||||
|
||||
Ядро DetMir реализовано как Rust-first runtime:
|
||||
Ядро AWatch-rus реализовано как Rust-first runtime:
|
||||
|
||||
- health/status/check helpers;
|
||||
- worktime exporters/API/bridges;
|
||||
@@ -305,5 +305,5 @@ stale/dead buckets для обязательных источников.
|
||||
- `docs/ARCHITECTURE_RU.md` - архитектура.
|
||||
- `docs/ADMIN_GUIDE_RU.md` - руководство администратора.
|
||||
- `docs/OPERATOR_GUIDE_RU.md` - руководство оператора.
|
||||
- `docs/DETMIR_RUSSIAN_SOFTWARE_REGISTRY_POSITIONING_RU.md` - стратегия
|
||||
- `docs/RUSSIAN_SOFTWARE_REGISTRY_POSITIONING_RU.md` - стратегия
|
||||
позиционирования.
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
5. `Forensic Layer`
|
||||
Отдельный bounded DFIR-путь через `Hayabusa`, который используется для post-incident enrichment, а не как основной real-time detector.
|
||||
|
||||
Подтвержденный runtime для `DetMir`:
|
||||
Подтвержденный runtime для `AWatch-rus`:
|
||||
|
||||
- `<AW_SERVER_HOST>` — основной `AW-rus` server, health, worktime/reporting, DLP server-side services, `Hayabusa` processing.
|
||||
- `<GATEWAY_HOST>` — operator/gateway host, Telegram bot, web gateway, часть `1C` analytics runtime.
|
||||
@@ -335,9 +335,9 @@ Collector и server-side сервисы проектировались так,
|
||||
- status, support and investigation commands;
|
||||
- human-readable operator menu для DLP и forensic path.
|
||||
|
||||
### MCP / PowerShell remote для DetMir
|
||||
### MCP / PowerShell remote для AWatch-rus
|
||||
|
||||
Документ: `docs/DETMIR_POWERSHELL_MCP_REMOTE_RU.md`
|
||||
Документ: `docs/POWERSHELL_MCP_REMOTE_RU.md`
|
||||
|
||||
Реализует:
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# DetMir / AWatch-rus: сторонние компоненты и лицензии
|
||||
# AWatch-rus: сторонние компоненты и лицензии
|
||||
|
||||
Статус документа: рабочий license inventory для подготовки поставки и
|
||||
экспертной проверки. Документ не является юридическим заключением. Перед
|
||||
@@ -7,10 +7,10 @@
|
||||
|
||||
## 1. Собственный код проекта
|
||||
|
||||
Собственные компоненты `DetMir / AWatch-rus`:
|
||||
Собственные компоненты `AWatch-rus`:
|
||||
|
||||
- Rust workspace `adk-rust/`;
|
||||
- DetMir status/check/auto/heal helpers;
|
||||
- AWatch-rus status/check/auto/heal helpers;
|
||||
- worktime exporters/API/bridge/autoheal;
|
||||
- DLP server-side helpers;
|
||||
- evidence API и portal helpers;
|
||||
@@ -35,19 +35,19 @@ Apache License 2.0
|
||||
| Компонент | Роль в продукте | Типовая лицензия upstream | Статус поставки | Комментарий для аудита |
|
||||
|---|---|---|---|---|
|
||||
| ActivityWatch | Базовый сбор и API событий активности | MPL-2.0 | Устанавливается/используется как внешний компонент | Weak copyleft на измененные MPL-файлы; модификации ActivityWatch нужно учитывать отдельно. |
|
||||
| Grafana OSS | Dashboards и визуализация | AGPL-3.0 для современных версий Grafana OSS | Обычно внешний сервис/контейнер, не собственный код DetMir | AGPL требует отдельной проверки модели распространения и сетевого использования. |
|
||||
| Grafana OSS | Dashboards и визуализация | AGPL-3.0 для современных версий Grafana OSS | Обычно внешний сервис/контейнер, не собственный код AWatch-rus | AGPL требует отдельной проверки модели распространения и сетевого использования. |
|
||||
| Prometheus | Monitoring ecosystem, exporters, scrape model | Apache-2.0 | Внешний компонент при включении мониторинга | Совместим с Apache-поставкой при соблюдении notice/license требований. |
|
||||
| InfluxDB / compatible TSDB | Хранилище временных рядов `aw_metrics` | Зависит от версии/дистрибутива | Внешний компонент | Зафиксировать конкретную версию в release notes. |
|
||||
| Hayabusa | Offline/DFIR timeline и enrichment | AGPLv3; rules могут иметь Detection Rule License | Опциональный прикладной модуль расследования | Не позиционировать как ядро продукта; проверить obligations при включении в поставку. |
|
||||
| Ansible | Deployment automation | GPL-3.0-or-later для Ansible core | Инструмент установки | Обычно не линкуется с кодом продукта; входит в toolchain. |
|
||||
| PowerShell | Windows deployment/collectors runtime | MIT для PowerShell Core; Windows PowerShell как компонент ОС | Runtime/tooling | Уточнять окружение заказчика: Windows PowerShell или PowerShell 7. |
|
||||
| SQLite | Local state/warehouse DB | Public domain/blessing style | Embedded/library/runtime | Обычно низкий license risk. |
|
||||
| ClickHouse clients/tooling | 1C/file analytics integration | Зависит от клиента; ClickHouse server Apache-2.0 | Отдельный 1C/business-data слой | Не является обязательным ядром DetMir. |
|
||||
| ClickHouse clients/tooling | 1C/file analytics integration | Зависит от клиента; ClickHouse server Apache-2.0 | Отдельный 1C/business-data слой | Не является обязательным ядром AWatch-rus. |
|
||||
| OpenAI/Pollinations-compatible integrations | AI assistant/integration paths | API terms, не open-source license | Опционально | Не включать ключи/API credentials в поставку. |
|
||||
|
||||
## 3. Rust dependencies
|
||||
|
||||
Rust является основным runtime-слоем DetMir. Точный список зависимостей должен
|
||||
Rust является основным runtime-слоем AWatch-rus. Точный список зависимостей должен
|
||||
фиксироваться по `Cargo.lock` конкретного релиза.
|
||||
|
||||
Ключевые crates, используемые в workspace:
|
||||
@@ -82,7 +82,7 @@ cargo about generate about.hbs > ../docs/licenses-rust.html
|
||||
|
||||
## 4. Python-зависимости
|
||||
|
||||
Python не является основным runtime-ядром DetMir. Он остается для
|
||||
Python не является основным runtime-ядром AWatch-rus. Он остается для
|
||||
согласованных вспомогательных направлений:
|
||||
|
||||
- Telegram bot runtime, если включен в экземпляре;
|
||||
@@ -120,7 +120,7 @@ release profile.
|
||||
|
||||
| Компонент | Роль | License-audit действие |
|
||||
|---|---|---|
|
||||
| Grafana dashboards JSON | Собственные dashboards DetMir | Входят в собственную поставку; проверить отсутствие embedded secrets/URLs. |
|
||||
| Grafana dashboards JSON | Собственные dashboards AWatch-rus | Входят в собственную поставку; проверить отсутствие embedded secrets/URLs. |
|
||||
| ActivityWatch WebUI patches | Собственный overlay/patch слой | Учитывать MPL-2.0 границы ActivityWatch, если изменяются upstream файлы. |
|
||||
| Playwright/browser smoke tooling | Проверки UI | Обычно dev/test dependency; не включать в runtime claim. |
|
||||
| JavaScript snippets | WebUI patching/helper scripts | Проверить зависимости, если добавляются npm packages. |
|
||||
|
||||
Generated
+439
-18
@@ -164,6 +164,26 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "aw-1c-ingest"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"calamine",
|
||||
"chrono",
|
||||
"clap",
|
||||
"csv",
|
||||
"filetime",
|
||||
"fs2",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"sha1",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aw-browser-smoke"
|
||||
version = "0.1.0"
|
||||
@@ -283,12 +303,68 @@ dependencies = [
|
||||
"urlencoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aw-windows-telemetry"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"clap",
|
||||
"csv",
|
||||
"notify",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"url",
|
||||
"windows",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "awatch-agent"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"clap",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"tiny_http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "awatch-agent-rs"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"clap",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.11.1"
|
||||
@@ -310,12 +386,33 @@ version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
|
||||
[[package]]
|
||||
name = "calamine"
|
||||
version = "0.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a3a315226fdc5b1c3e33521073e1712a05944bc0664d665ff1f6ff0396334da"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"codepage",
|
||||
"encoding_rs",
|
||||
"log",
|
||||
"quick-xml",
|
||||
"serde",
|
||||
"zip 0.6.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.63"
|
||||
@@ -385,7 +482,7 @@ dependencies = [
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -434,6 +531,15 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "codepage"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48f68d061bc2828ae826206326e61251aca94c1e4a5305cf52d9138639c918b4"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
@@ -464,6 +570,15 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.21"
|
||||
@@ -480,6 +595,27 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "csv"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
|
||||
dependencies = [
|
||||
"csv-core",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "csv-core"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.4.2"
|
||||
@@ -805,6 +941,15 @@ dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -903,6 +1048,15 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fsevent-sys"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.32"
|
||||
@@ -1212,7 +1366,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1344,6 +1498,26 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"inotify-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify-sys"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.0"
|
||||
@@ -1374,6 +1548,26 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5"
|
||||
dependencies = [
|
||||
"kqueue-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue-sys"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
@@ -1447,6 +1641,18 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.1"
|
||||
@@ -1458,6 +1664,25 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify"
|
||||
version = "6.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d"
|
||||
dependencies = [
|
||||
"bitflags 2.11.1",
|
||||
"crossbeam-channel",
|
||||
"filetime",
|
||||
"fsevent-sys",
|
||||
"inotify",
|
||||
"kqueue",
|
||||
"libc",
|
||||
"log",
|
||||
"mio 0.8.11",
|
||||
"walkdir",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -1567,6 +1792,16 @@ dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.31.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1004a344b30a54e2ee58d66a71b32d2db2feb0a31f9a2d302bf0536f15de2a33"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.9"
|
||||
@@ -1695,7 +1930,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"zip",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1787,7 +2022,7 @@ version = "0.32.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bitflags 2.11.1",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
@@ -1807,7 +2042,7 @@ version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bitflags 2.11.1",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
@@ -1861,6 +2096,15 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
@@ -1935,6 +2179,17 @@ dependencies = [
|
||||
"unsafe-libyaml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -2128,7 +2383,7 @@ checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"mio 1.2.1",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
@@ -2178,7 +2433,7 @@ version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bitflags 2.11.1",
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http",
|
||||
@@ -2348,7 +2603,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"zip",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2374,6 +2629,16 @@ version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||
dependencies = [
|
||||
"same-file",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.1"
|
||||
@@ -2490,7 +2755,7 @@ version = "0.244.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bitflags 2.11.1",
|
||||
"hashbrown 0.15.5",
|
||||
"indexmap",
|
||||
"semver",
|
||||
@@ -2541,23 +2806,66 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f919aee0a93304be7f62e8e5027811bbba96bcb1de84d6618be56e43f8a32a1"
|
||||
dependencies = [
|
||||
"windows-core 0.59.0",
|
||||
"windows-targets 0.53.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "810ce18ed2112484b0d4e15d022e5f598113e220c53e373fb31e67e21670c1ce"
|
||||
dependencies = [
|
||||
"windows-implement 0.59.0",
|
||||
"windows-interface",
|
||||
"windows-result 0.3.4",
|
||||
"windows-strings 0.3.1",
|
||||
"windows-targets 0.53.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
"windows-link 0.2.1",
|
||||
"windows-result 0.4.1",
|
||||
"windows-strings 0.5.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2582,19 +2890,43 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
|
||||
dependencies = [
|
||||
"windows-link 0.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319"
|
||||
dependencies = [
|
||||
"windows-link 0.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2603,7 +2935,16 @@ version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
||||
dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2615,6 +2956,15 @@ dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.60.2"
|
||||
@@ -2630,7 +2980,22 @@ version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm 0.48.5",
|
||||
"windows_aarch64_msvc 0.48.5",
|
||||
"windows_i686_gnu 0.48.5",
|
||||
"windows_i686_msvc 0.48.5",
|
||||
"windows_x86_64_gnu 0.48.5",
|
||||
"windows_x86_64_gnullvm 0.48.5",
|
||||
"windows_x86_64_msvc 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2655,7 +3020,7 @@ version = "0.53.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows-link 0.2.1",
|
||||
"windows_aarch64_gnullvm 0.53.1",
|
||||
"windows_aarch64_msvc 0.53.1",
|
||||
"windows_i686_gnu 0.53.1",
|
||||
@@ -2666,6 +3031,12 @@ dependencies = [
|
||||
"windows_x86_64_msvc 0.53.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
@@ -2678,6 +3049,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -2690,6 +3067,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
@@ -2714,6 +3097,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -2726,6 +3115,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
@@ -2738,6 +3133,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
@@ -2750,6 +3151,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -2826,7 +3233,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"bitflags 2.11.1",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -2863,9 +3270,11 @@ dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"clap",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tiny_http",
|
||||
"url",
|
||||
"urlencoding",
|
||||
@@ -3041,6 +3450,18 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "0.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"crc32fast",
|
||||
"crossbeam-utils",
|
||||
"flate2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "2.4.2"
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/aw-1c-ingest",
|
||||
"crates/aw-windows-telemetry",
|
||||
"crates/awatch-agent",
|
||||
"crates/awatch-agent-rs",
|
||||
"crates/detmir-auto",
|
||||
"crates/detmir-aw-client",
|
||||
"crates/aw-db-health",
|
||||
@@ -66,20 +70,26 @@ publish = false
|
||||
adk-rust = { version = "0.9.1", default-features = false }
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
calamine = "=0.24.0"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
csv = "1"
|
||||
detmir-aw-client = { path = "crates/detmir-aw-client" }
|
||||
detmir-core = { path = "crates/detmir-core" }
|
||||
detmir-state = { path = "crates/detmir-state" }
|
||||
filetime = "0.2"
|
||||
fs2 = "0.4"
|
||||
notify = "6"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
|
||||
regex = "1"
|
||||
rusqlite = "0.32"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_yaml = "0.9"
|
||||
sha1 = "0.10"
|
||||
sha2 = "0.10"
|
||||
tempfile = "3"
|
||||
tiny_http = "0.12"
|
||||
url = "2"
|
||||
urlencoding = "2"
|
||||
windows-sys = "0.59"
|
||||
|
||||
+14
-13
@@ -1,9 +1,9 @@
|
||||
# Runbook: перевод DetMir на Rust / ADK-Rust
|
||||
# Runbook: перевод AWatch-rus на Rust / ADK-Rust
|
||||
|
||||
Дата фиксации: `2026-06-01`
|
||||
|
||||
Цель: постепенно заменить хрупкие Python/shell operational scripts на
|
||||
самодостаточные Rust-бинарники, не ломая текущий production-контур DetMir.
|
||||
самодостаточные Rust-бинарники, не ломая текущий production-контур AWatch-rus.
|
||||
|
||||
Этот runbook является рабочим планом миграции. Если фактический runtime
|
||||
расходится с этим документом, сначала фиксируется baseline, затем обновляется
|
||||
@@ -1543,7 +1543,7 @@ systemctl is-active tsj-guardian-bot tsj-guardian-watchdog gost-tg
|
||||
- production binary доставлен на AW server, но `--apply` не запускался;
|
||||
- production dry-run: `apply=false`, `ok=true`, `missing=0`,
|
||||
`executed=0`, `steps=25`;
|
||||
- final production gates: AW failed units `0`, DetMir status OK with
|
||||
- final production gates: AW failed units `0`, `detmir-status` OK with
|
||||
`service_warnings=0`, `dlp_counts={ok:22,warn:0,fail:0}`,
|
||||
`ok_for_operator=true`;
|
||||
- gates: `cargo fmt --all -- --check`, `cargo test -p
|
||||
@@ -1707,15 +1707,15 @@ systemctl is-active tsj-guardian-bot tsj-guardian-watchdog gost-tg
|
||||
Grafana check `ok=true` with `fail=0`, `detmir-auto --no-heal` rc `0`,
|
||||
portal health `true`, `detmir-status` `OK / ok_for_operator=true`, and
|
||||
failed units `0`.
|
||||
- `docs/DETMIR_THREAT_MODEL_RU.md` added as the current working threat
|
||||
model for DetMir. It records the product as an operational
|
||||
- `docs/THREAT_MODEL_RU.md` added as the current working threat
|
||||
model for AWatch-rus. It records the product as an operational
|
||||
control and technical audit platform, not a certified DLP/SIEM/EDR/XDR
|
||||
or FSTEC SZI. It also records Igor as the declared product owner, lists
|
||||
assets, trust zones, attacker/operator-failure classes, implemented
|
||||
evidence controls, residual risks, and the hardening roadmap.
|
||||
- `docs/DETMIR_RUSSIAN_SOFTWARE_REGISTRY_POSITIONING_RU.md` added as the
|
||||
registry/product positioning note. Current decision: lead with DetMir as
|
||||
an operational control and IT infrastructure management platform, use
|
||||
- `docs/RUSSIAN_SOFTWARE_REGISTRY_POSITIONING_RU.md` added as the
|
||||
registry/product positioning note. Current decision: lead with AWatch-rus
|
||||
as an operational control and IT infrastructure management platform, use
|
||||
`09.10` as the primary Russian software registry class target, keep
|
||||
DLP/security/evidence/Hayabusa as applied modules, and prepare website,
|
||||
operator/admin docs, ownership package, screenshots, and dependency
|
||||
@@ -1724,17 +1724,18 @@ systemctl is-active tsj-guardian-bot tsj-guardian-watchdog gost-tg
|
||||
`docs/ADMIN_GUIDE_RU.md`, `docs/OPERATOR_GUIDE_RU.md`,
|
||||
`docs/INSTALL_RU.md`, `docs/ARCHITECTURE_RU.md`,
|
||||
`docs/OWNERSHIP_RU.md`, `docs/THIRD_PARTY_LICENSES_RU.md`, and
|
||||
`docs/REGISTRY_CHECKLIST_RU.md`. Naming decision fixed across the docs:
|
||||
`DetMir` is the product, `AWatch-rus` is the repository/technical base,
|
||||
and the external formula is `DetMir, программный комплекс на базе
|
||||
AWatch-rus`.
|
||||
`docs/REGISTRY_CHECKLIST_RU.md`. Current naming decision for public
|
||||
materials: `AWatch-rus` is the product and repository name. Legacy
|
||||
`detmir-*` service, crate and environment identifiers remain technical
|
||||
runtime identifiers until a separate compatibility-safe migration is
|
||||
approved.
|
||||
|
||||
Отложить:
|
||||
|
||||
- post-MVP развитие `detmir-portal`: role-aware views, safe check-now action,
|
||||
daily owner report, historical trends, AI summary with strict source
|
||||
citations, action buttons with allowlist and audit log. Детальный план:
|
||||
`docs/DETMIR_PORTAL_GUI_PLAN_RU.md`;
|
||||
`docs/PORTAL_GUI_PLAN_RU.md`;
|
||||
- перенос Telegram bot runtime снят с плана: Python остается постоянным
|
||||
runtime, Rust используется только для backend helpers;
|
||||
- перенос оставшихся install/runtime scripts на Rust;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "aw-1c-ingest"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
calamine.workspace = true
|
||||
chrono.workspace = true
|
||||
clap.workspace = true
|
||||
csv.workspace = true
|
||||
filetime.workspace = true
|
||||
fs2.workspace = true
|
||||
regex.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_yaml.workspace = true
|
||||
sha1.workspace = true
|
||||
tempfile.workspace = true
|
||||
File diff suppressed because it is too large
Load Diff
@@ -71,9 +71,7 @@ fn default_node_path(current: Option<&OsStr>) -> Option<OsString> {
|
||||
if current.is_some_and(|value| !value.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let Some(home) = std::env::var_os("HOME") else {
|
||||
return None;
|
||||
};
|
||||
let home = std::env::var_os("HOME")?;
|
||||
let path = PathBuf::from(home)
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
|
||||
@@ -116,7 +116,7 @@ fn run_proxmox_remote() -> Result<i32> {
|
||||
check_tcp(&mut counts, "nginx http", "127.0.0.1", 80);
|
||||
check_tcp(&mut counts, "nginx https", "127.0.0.1", 443);
|
||||
check_tcp(&mut counts, "proxmox web", "127.0.0.1", 8006);
|
||||
check_tcp(&mut counts, "1C company API", "192.0.2.2", 8710);
|
||||
check_tcp(&mut counts, "1C company API", "10.10.10.2", 8710);
|
||||
check_tcp(&mut counts, "clickhouse native", "127.0.0.1", 9000);
|
||||
check_tcp(&mut counts, "clickhouse http", "127.0.0.1", 8123);
|
||||
if let Ok(out) = command_output("ss", &["-tulpn"]) {
|
||||
@@ -135,29 +135,26 @@ fn run_proxmox_remote() -> Result<i32> {
|
||||
"https://127.0.0.1/healthz",
|
||||
&[200],
|
||||
);
|
||||
check_http_redirect(
|
||||
check_http_code(
|
||||
&mut counts,
|
||||
&no_redirect_http,
|
||||
"go proxmox gui",
|
||||
&http,
|
||||
"go proxmox gui protected",
|
||||
"https://127.0.0.1/go/proxmox-gui",
|
||||
&[301, 302, 307, 308],
|
||||
Some("https://192.0.2.2:8006/"),
|
||||
&[401],
|
||||
);
|
||||
check_http_redirect(
|
||||
check_http_code(
|
||||
&mut counts,
|
||||
&no_redirect_http,
|
||||
"go file1c brief",
|
||||
&http,
|
||||
"go file1c brief protected",
|
||||
"https://127.0.0.1/go/file1c-brief",
|
||||
&[301, 302, 307, 308],
|
||||
Some("http://192.0.2.2:8710/manager/brief"),
|
||||
&[401],
|
||||
);
|
||||
check_http_redirect(
|
||||
check_http_code(
|
||||
&mut counts,
|
||||
&no_redirect_http,
|
||||
"go file1c actions",
|
||||
&http,
|
||||
"go file1c actions protected",
|
||||
"https://127.0.0.1/go/file1c-actions",
|
||||
&[301, 302, 307, 308],
|
||||
Some("http://192.0.2.2:8710/manager/actions"),
|
||||
&[401],
|
||||
);
|
||||
|
||||
section("1C Company API");
|
||||
@@ -165,24 +162,24 @@ fn run_proxmox_remote() -> Result<i32> {
|
||||
&mut counts,
|
||||
&no_redirect_http,
|
||||
"1C root redirect",
|
||||
"http://192.0.2.2:8710/",
|
||||
"http://10.10.10.2:8710/",
|
||||
&[307],
|
||||
);
|
||||
for (name, url) in [
|
||||
("1C /health", "http://192.0.2.2:8710/health"),
|
||||
("1C /api/health", "http://192.0.2.2:8710/api/health"),
|
||||
("1C manager brief", "http://192.0.2.2:8710/manager/brief"),
|
||||
("1C /health", "http://10.10.10.2:8710/health"),
|
||||
("1C /api/health", "http://10.10.10.2:8710/api/health"),
|
||||
("1C manager brief", "http://10.10.10.2:8710/manager/brief"),
|
||||
(
|
||||
"1C manager actions",
|
||||
"http://192.0.2.2:8710/manager/actions",
|
||||
"http://10.10.10.2:8710/manager/actions",
|
||||
),
|
||||
(
|
||||
"1C manager recovery",
|
||||
"http://192.0.2.2:8710/manager/recovery",
|
||||
"http://10.10.10.2:8710/manager/recovery",
|
||||
),
|
||||
(
|
||||
"1C weekly digest",
|
||||
"http://192.0.2.2:8710/manager/digest/weekly",
|
||||
"http://10.10.10.2:8710/manager/digest/weekly",
|
||||
),
|
||||
] {
|
||||
check_http_code(&mut counts, &http, name, url, &[200]);
|
||||
@@ -345,39 +342,6 @@ fn check_http_code(counts: &mut Counts, client: &Client, name: &str, url: &str,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_http_redirect(
|
||||
counts: &mut Counts,
|
||||
client: &Client,
|
||||
name: &str,
|
||||
url: &str,
|
||||
expected: &[u16],
|
||||
expected_location: Option<&str>,
|
||||
) {
|
||||
match client.head(url).send() {
|
||||
Ok(response) => {
|
||||
let code = response.status().as_u16();
|
||||
let location = response
|
||||
.headers()
|
||||
.get(reqwest::header::LOCATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("");
|
||||
let location_ok = expected_location.is_none_or(|expected| location.contains(expected));
|
||||
if expected.contains(&code) && location_ok {
|
||||
counts.pass(format!(
|
||||
"{name} HTTP {code} {}",
|
||||
if location.is_empty() { url } else { location }
|
||||
));
|
||||
} else {
|
||||
counts.fail(format!(
|
||||
"{name} HTTP {code} {}",
|
||||
if location.is_empty() { url } else { location }
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(err) => counts.fail(format!("{name} HTTP error {url}: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_command(counts: &mut Counts, name: &str, cmd: &str, args: &[&str]) {
|
||||
match command_output(cmd, args) {
|
||||
Ok(out) => {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "aw-windows-telemetry"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
chrono.workspace = true
|
||||
clap.workspace = true
|
||||
csv.workspace = true
|
||||
notify.workspace = true
|
||||
reqwest.workspace = true
|
||||
regex.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
tempfile.workspace = true
|
||||
url.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.59", features = ["Win32_Foundation", "Win32_System_Com", "Win32_UI_Accessibility", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_DataExchange", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Memory", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_WindowsAndMessaging"] }
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "awatch-agent-rs"
|
||||
version = "0.3.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
clap.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.59", features = ["Win32_System_RemoteDesktop"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
asm-lowlevel = []
|
||||
legacy-powershell = []
|
||||
@@ -0,0 +1,18 @@
|
||||
server_url = "https://awatch.local/api/telemetry"
|
||||
api_key = "change-me"
|
||||
collect_interval_seconds = 60
|
||||
role = "workstation"
|
||||
|
||||
enable_processes = true
|
||||
enable_network = true
|
||||
enable_security_events = true
|
||||
enable_workforce_activity = true
|
||||
|
||||
spool_dir = "/var/lib/awatch-agent/spool"
|
||||
timeout_seconds = 10
|
||||
retry_attempts = 3
|
||||
|
||||
# Optional ActivityWatch compatibility output.
|
||||
# Enables Rust replacement for the PowerShell worktime-session collector path.
|
||||
aw_api_base = "http://awatch.local:5600/api/0"
|
||||
aw_worktime_enabled = false
|
||||
@@ -0,0 +1,127 @@
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::config::AgentRole;
|
||||
use crate::telemetry::{SecurityEventInfo, SessionInfo};
|
||||
|
||||
pub fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new(program).args(args).output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
pub fn hostname() -> String {
|
||||
env::var("HOSTNAME")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| fs::read_to_string("/etc/hostname").ok())
|
||||
.or_else(|| command_output("hostname", &[]))
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(|| "HOST-EXAMPLE".to_string())
|
||||
}
|
||||
|
||||
pub fn username() -> String {
|
||||
env::var("USER")
|
||||
.or_else(|_| env::var("USERNAME"))
|
||||
.unwrap_or_else(|_| "unknown".to_string())
|
||||
}
|
||||
|
||||
pub fn domain() -> String {
|
||||
env::var("USERDOMAIN")
|
||||
.or_else(|_| env::var("DOMAIN"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn agent_id(hostname: &str) -> String {
|
||||
format!("awatch-{hostname}")
|
||||
}
|
||||
|
||||
pub fn role_security_events(role: AgentRole) -> Vec<SecurityEventInfo> {
|
||||
if role == AgentRole::Firewall {
|
||||
vec![SecurityEventInfo {
|
||||
event_id: "pfsense-mode-prototype".to_string(),
|
||||
source: "awatch-agent-rs".to_string(),
|
||||
severity: "INFO".to_string(),
|
||||
summary: "pfSense/firewall mode enabled; counters are collected from platform-specific probes when available".to_string(),
|
||||
timestamp: Utc::now(),
|
||||
evidence: vec!["read-only mode".to_string()],
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_session(session_type: &str) -> SessionInfo {
|
||||
SessionInfo {
|
||||
session_id: format!("{}-{}", session_type, username()),
|
||||
username: username(),
|
||||
session_type: session_type.to_string(),
|
||||
session_source: Some("env_sessionname_fallback".to_string()),
|
||||
remote_addr: std::env::var("SSH_CLIENT")
|
||||
.ok()
|
||||
.and_then(|value| value.split_whitespace().next().map(str::to_string)),
|
||||
started_at: None,
|
||||
active: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_trimmed(path: impl AsRef<Path>) -> Option<String> {
|
||||
fs::read_to_string(path)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub fn parse_os_release(path: &Path) -> (String, String) {
|
||||
let text = fs::read_to_string(path).unwrap_or_default();
|
||||
let mut name = String::new();
|
||||
let mut version = String::new();
|
||||
for line in text.lines() {
|
||||
if let Some(value) = line.strip_prefix("NAME=") {
|
||||
name = value.trim_matches('"').to_string();
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("VERSION_ID=") {
|
||||
version = value.trim_matches('"').to_string();
|
||||
}
|
||||
}
|
||||
if name.is_empty() {
|
||||
name = "Linux".to_string();
|
||||
}
|
||||
(name, version)
|
||||
}
|
||||
|
||||
pub fn parse_hex_ipv4(value: &str) -> Option<String> {
|
||||
if value.len() != 8 {
|
||||
return None;
|
||||
}
|
||||
let raw = u32::from_str_radix(value, 16).ok()?;
|
||||
let bytes = raw.to_le_bytes();
|
||||
Some(format!(
|
||||
"{}.{}.{}.{}",
|
||||
bytes[0], bytes[1], bytes[2], bytes[3]
|
||||
))
|
||||
}
|
||||
|
||||
pub fn tcp_state(value: &str) -> &'static str {
|
||||
match value {
|
||||
"01" => "ESTABLISHED",
|
||||
"02" => "SYN_SENT",
|
||||
"03" => "SYN_RECV",
|
||||
"04" => "FIN_WAIT1",
|
||||
"05" => "FIN_WAIT2",
|
||||
"06" => "TIME_WAIT",
|
||||
"07" => "CLOSE",
|
||||
"08" => "CLOSE_WAIT",
|
||||
"09" => "LAST_ACK",
|
||||
"0A" => "LISTEN",
|
||||
"0B" => "CLOSING",
|
||||
_ => "UNKNOWN",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
use std::fs;
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::collectors::common::{
|
||||
agent_id, command_output, current_session, domain, hostname, role_security_events, username,
|
||||
};
|
||||
use crate::config::AgentRole;
|
||||
use crate::telemetry::{
|
||||
IdentityInfo, NetworkConnectionInfo, NetworkInterfaceInfo, NetworkSnapshot, ProcessInfo,
|
||||
ResourceInfo, SecurityEventInfo, SessionSnapshot, TelemetryCollector, WorkforceActivityInfo,
|
||||
dedupe_sessions, diagnostics_for_sessions, empty_workforce_activity,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FreeBsdCollector {
|
||||
role: AgentRole,
|
||||
}
|
||||
|
||||
impl FreeBsdCollector {
|
||||
pub fn new(role: AgentRole) -> Self {
|
||||
Self { role }
|
||||
}
|
||||
}
|
||||
|
||||
impl TelemetryCollector for FreeBsdCollector {
|
||||
fn collect_identity(&self) -> Result<IdentityInfo> {
|
||||
let host = hostname();
|
||||
Ok(IdentityInfo {
|
||||
agent_id: agent_id(&host),
|
||||
hostname: host,
|
||||
os_name: command_output("uname", &["-s"]).unwrap_or_else(|| "FreeBSD".to_string()),
|
||||
os_version: command_output("uname", &["-r"]).unwrap_or_default(),
|
||||
platform: "freebsd".to_string(),
|
||||
username: username(),
|
||||
domain: domain(),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_sessions(&self) -> Result<SessionSnapshot> {
|
||||
let mut active = vec![current_session("local")];
|
||||
let mut ssh = Vec::new();
|
||||
if std::env::var("SSH_CLIENT").is_ok() || std::env::var("SSH_TTY").is_ok() {
|
||||
let session = current_session("ssh");
|
||||
ssh.push(session.clone());
|
||||
active.push(session);
|
||||
}
|
||||
let host = hostname();
|
||||
let active = dedupe_sessions(&host, active);
|
||||
let ssh = dedupe_sessions(&host, ssh);
|
||||
let diagnostics = diagnostics_for_sessions(&active, &[], "env_sessionname_fallback", None);
|
||||
Ok(SessionSnapshot {
|
||||
active_sessions: active,
|
||||
rdp_sessions: Vec::new(),
|
||||
ssh_sessions: ssh,
|
||||
diagnostics,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_processes(&self) -> Result<Vec<ProcessInfo>> {
|
||||
Ok(freebsd_processes(128))
|
||||
}
|
||||
|
||||
fn collect_resources(&self) -> Result<ResourceInfo> {
|
||||
let memory_total = command_output("sysctl", &["-n", "hw.physmem"])
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.unwrap_or(0);
|
||||
Ok(ResourceInfo {
|
||||
uptime_seconds: 0,
|
||||
cpu_usage_percent: 0.0,
|
||||
memory_total,
|
||||
memory_used: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_network(&self) -> Result<NetworkSnapshot> {
|
||||
Ok(NetworkSnapshot {
|
||||
interfaces: freebsd_interfaces(),
|
||||
connections: freebsd_connections(256),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_security_events(&self) -> Result<Vec<SecurityEventInfo>> {
|
||||
let mut events = role_security_events(self.role);
|
||||
if let Some(summary) = freebsd_syslog_summary() {
|
||||
events.push(SecurityEventInfo {
|
||||
event_id: "freebsd-syslog-summary".to_string(),
|
||||
source: "syslog".to_string(),
|
||||
severity: "INFO".to_string(),
|
||||
summary,
|
||||
timestamp: Utc::now(),
|
||||
evidence: vec!["/var/log/messages".to_string()],
|
||||
});
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn collect_workforce_activity(&self) -> Result<WorkforceActivityInfo> {
|
||||
let mut activity = empty_workforce_activity();
|
||||
activity.active_today = true;
|
||||
activity.explanation = vec![
|
||||
"FreeBSD collector reports host/session/process/network context; pfSense mode is read-only".to_string(),
|
||||
];
|
||||
Ok(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fn freebsd_processes(limit: usize) -> Vec<ProcessInfo> {
|
||||
let Some(raw) = command_output("ps", &["-axo", "pid,ppid,comm,rss"]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut items = raw
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| {
|
||||
let cols = line.split_whitespace().collect::<Vec<_>>();
|
||||
let pid = cols.first()?.parse::<u32>().ok()?;
|
||||
let ppid = cols.get(1).and_then(|value| value.parse::<u32>().ok());
|
||||
let name = cols.get(2).unwrap_or(&"process").to_string();
|
||||
let memory_bytes = cols
|
||||
.get(3)
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.map(|value| value.saturating_mul(1024));
|
||||
Some(ProcessInfo {
|
||||
pid,
|
||||
ppid,
|
||||
name,
|
||||
exe: None,
|
||||
username: None,
|
||||
cpu_percent: None,
|
||||
memory_bytes,
|
||||
started_at: None,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
items.truncate(limit);
|
||||
items
|
||||
}
|
||||
|
||||
fn freebsd_interfaces() -> Vec<NetworkInterfaceInfo> {
|
||||
let Some(raw) = command_output("ifconfig", &["-l"]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
raw.split_whitespace()
|
||||
.map(|name| NetworkInterfaceInfo {
|
||||
name: name.to_string(),
|
||||
mac: None,
|
||||
addresses: Vec::new(),
|
||||
up: true,
|
||||
rx_bytes: None,
|
||||
tx_bytes: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn freebsd_connections(limit: usize) -> Vec<NetworkConnectionInfo> {
|
||||
let Some(raw) = command_output("sockstat", &["-4", "-6"]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut items = raw
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(parse_sockstat_line)
|
||||
.collect::<Vec<_>>();
|
||||
items.truncate(limit);
|
||||
items
|
||||
}
|
||||
|
||||
fn parse_sockstat_line(line: &str) -> Option<NetworkConnectionInfo> {
|
||||
let cols = line.split_whitespace().collect::<Vec<_>>();
|
||||
let protocol = cols.get(4)?.to_ascii_lowercase();
|
||||
if protocol != "tcp" && protocol != "udp" {
|
||||
return None;
|
||||
}
|
||||
let (local_addr, local_port) = split_host_port(cols.get(5)?)?;
|
||||
let (remote_addr, remote_port) = cols
|
||||
.get(6)
|
||||
.and_then(|value| split_host_port(value))
|
||||
.unwrap_or_default();
|
||||
Some(NetworkConnectionInfo {
|
||||
protocol: protocol.clone(),
|
||||
local_addr,
|
||||
local_port,
|
||||
remote_addr: Some(remote_addr),
|
||||
remote_port: Some(remote_port),
|
||||
state: if protocol == "tcp" { "OPEN" } else { "UDP" }.to_string(),
|
||||
pid: cols.get(2).and_then(|value| value.parse::<u32>().ok()),
|
||||
})
|
||||
}
|
||||
|
||||
fn split_host_port(value: &str) -> Option<(String, u16)> {
|
||||
let (host, port) = value.rsplit_once(':')?;
|
||||
Some((
|
||||
host.trim_matches(['[', ']']).to_string(),
|
||||
port.parse().ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
fn freebsd_syslog_summary() -> Option<String> {
|
||||
let text = fs::read_to_string("/var/log/messages").ok()?;
|
||||
let count = text
|
||||
.lines()
|
||||
.rev()
|
||||
.take(200)
|
||||
.filter(|line| {
|
||||
let lower = line.to_lowercase();
|
||||
lower.contains("error") || lower.contains("fail") || lower.contains("denied")
|
||||
})
|
||||
.count();
|
||||
Some(format!(
|
||||
"recent FreeBSD syslog warning/error lines: {count}"
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::collectors::common::{
|
||||
agent_id, current_session, domain, hostname, parse_hex_ipv4, parse_os_release, read_trimmed,
|
||||
role_security_events, tcp_state, username,
|
||||
};
|
||||
use crate::config::AgentRole;
|
||||
use crate::telemetry::{
|
||||
IdentityInfo, NetworkConnectionInfo, NetworkInterfaceInfo, NetworkSnapshot, ProcessInfo,
|
||||
ResourceInfo, SecurityEventInfo, SessionSnapshot, TelemetryCollector, WorkforceActivityInfo,
|
||||
dedupe_sessions, diagnostics_for_sessions, empty_workforce_activity,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinuxCollector {
|
||||
role: AgentRole,
|
||||
}
|
||||
|
||||
impl LinuxCollector {
|
||||
pub fn new(role: AgentRole) -> Self {
|
||||
Self { role }
|
||||
}
|
||||
}
|
||||
|
||||
impl TelemetryCollector for LinuxCollector {
|
||||
fn collect_identity(&self) -> Result<IdentityInfo> {
|
||||
let host = hostname();
|
||||
let (os_name, os_version) = parse_os_release(Path::new("/etc/os-release"));
|
||||
Ok(IdentityInfo {
|
||||
agent_id: agent_id(&host),
|
||||
hostname: host,
|
||||
os_name,
|
||||
os_version,
|
||||
platform: "linux".to_string(),
|
||||
username: username(),
|
||||
domain: domain(),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_sessions(&self) -> Result<SessionSnapshot> {
|
||||
let mut active = vec![current_session("local")];
|
||||
let mut ssh = Vec::new();
|
||||
if std::env::var("SSH_CLIENT").is_ok() || std::env::var("SSH_TTY").is_ok() {
|
||||
let session = current_session("ssh");
|
||||
ssh.push(session.clone());
|
||||
active.push(session);
|
||||
}
|
||||
let host = hostname();
|
||||
let active = dedupe_sessions(&host, active);
|
||||
let ssh = dedupe_sessions(&host, ssh);
|
||||
let diagnostics = diagnostics_for_sessions(&active, &[], "env_sessionname_fallback", None);
|
||||
Ok(SessionSnapshot {
|
||||
active_sessions: active,
|
||||
rdp_sessions: Vec::new(),
|
||||
ssh_sessions: ssh,
|
||||
diagnostics,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_processes(&self) -> Result<Vec<ProcessInfo>> {
|
||||
Ok(read_processes(128))
|
||||
}
|
||||
|
||||
fn collect_resources(&self) -> Result<ResourceInfo> {
|
||||
let uptime_seconds = fs::read_to_string("/proc/uptime")
|
||||
.ok()
|
||||
.and_then(|text| text.split_whitespace().next()?.parse::<f64>().ok())
|
||||
.map(|value| value as u64)
|
||||
.unwrap_or(0);
|
||||
let (memory_total, memory_available) = read_meminfo();
|
||||
Ok(ResourceInfo {
|
||||
uptime_seconds,
|
||||
cpu_usage_percent: read_loadavg_percent(),
|
||||
memory_total,
|
||||
memory_used: memory_total.saturating_sub(memory_available),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_network(&self) -> Result<NetworkSnapshot> {
|
||||
Ok(NetworkSnapshot {
|
||||
interfaces: read_interfaces(),
|
||||
connections: read_connections(),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_security_events(&self) -> Result<Vec<SecurityEventInfo>> {
|
||||
let mut events = role_security_events(self.role);
|
||||
if let Some(summary) = recent_syslog_summary() {
|
||||
events.push(SecurityEventInfo {
|
||||
event_id: "linux-syslog-summary".to_string(),
|
||||
source: "syslog".to_string(),
|
||||
severity: "INFO".to_string(),
|
||||
summary,
|
||||
timestamp: Utc::now(),
|
||||
evidence: vec!["/var/log/syslog or /var/log/messages".to_string()],
|
||||
});
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn collect_workforce_activity(&self) -> Result<WorkforceActivityInfo> {
|
||||
let mut activity = empty_workforce_activity();
|
||||
activity.active_today = true;
|
||||
activity.explanation = vec![
|
||||
"Linux collector reports presence and process/network context; application weighting is calculated server-side".to_string(),
|
||||
];
|
||||
Ok(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_meminfo() -> (u64, u64) {
|
||||
let mut total = 0;
|
||||
let mut available = 0;
|
||||
let text = fs::read_to_string("/proc/meminfo").unwrap_or_default();
|
||||
for line in text.lines() {
|
||||
if let Some(value) = line.strip_prefix("MemTotal:") {
|
||||
total = parse_kib(value);
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("MemAvailable:") {
|
||||
available = parse_kib(value);
|
||||
}
|
||||
}
|
||||
(total, available)
|
||||
}
|
||||
|
||||
fn parse_kib(value: &str) -> u64 {
|
||||
value
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.and_then(|item| item.parse::<u64>().ok())
|
||||
.unwrap_or(0)
|
||||
* 1024
|
||||
}
|
||||
|
||||
fn read_loadavg_percent() -> f64 {
|
||||
fs::read_to_string("/proc/loadavg")
|
||||
.ok()
|
||||
.and_then(|text| text.split_whitespace().next()?.parse::<f64>().ok())
|
||||
.map(|load| (load * 100.0).clamp(0.0, 100.0))
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn read_processes(limit: usize) -> Vec<ProcessInfo> {
|
||||
let mut items = fs::read_dir("/proc")
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flat_map(|entries| entries.filter_map(|entry| entry.ok()))
|
||||
.filter_map(|entry| {
|
||||
let pid = entry.file_name().to_string_lossy().parse::<u32>().ok()?;
|
||||
let stat = fs::read_to_string(entry.path().join("stat")).ok()?;
|
||||
let name = stat.split_once('(')?.1.split_once(')')?.0.to_string();
|
||||
let exe = fs::read_link(entry.path().join("exe"))
|
||||
.ok()
|
||||
.map(|path| path.display().to_string());
|
||||
let status = fs::read_to_string(entry.path().join("status")).unwrap_or_default();
|
||||
let ppid = status
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("PPid:"))
|
||||
.and_then(|value| value.trim().parse::<u32>().ok());
|
||||
let memory_bytes = status
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("VmRSS:"))
|
||||
.map(parse_kib);
|
||||
Some(ProcessInfo {
|
||||
pid,
|
||||
ppid,
|
||||
name,
|
||||
exe,
|
||||
username: None,
|
||||
cpu_percent: None,
|
||||
memory_bytes,
|
||||
started_at: None,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
items.sort_by_key(|item| item.pid);
|
||||
items.truncate(limit);
|
||||
items
|
||||
}
|
||||
|
||||
fn read_interfaces() -> Vec<NetworkInterfaceInfo> {
|
||||
fs::read_dir("/sys/class/net")
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flat_map(|entries| entries.filter_map(|entry| entry.ok()))
|
||||
.map(|entry| {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
let up = read_trimmed(path.join("operstate")).is_some_and(|state| state == "up");
|
||||
let rx_bytes =
|
||||
read_trimmed(path.join("statistics/rx_bytes")).and_then(|v| v.parse().ok());
|
||||
let tx_bytes =
|
||||
read_trimmed(path.join("statistics/tx_bytes")).and_then(|v| v.parse().ok());
|
||||
NetworkInterfaceInfo {
|
||||
name,
|
||||
mac: read_trimmed(path.join("address")),
|
||||
addresses: Vec::new(),
|
||||
up,
|
||||
rx_bytes,
|
||||
tx_bytes,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_connections() -> Vec<NetworkConnectionInfo> {
|
||||
let mut items = Vec::new();
|
||||
read_proc_net("/proc/net/tcp", "tcp", &mut items);
|
||||
read_proc_net("/proc/net/udp", "udp", &mut items);
|
||||
items.truncate(256);
|
||||
items
|
||||
}
|
||||
|
||||
fn read_proc_net(path: &str, protocol: &str, items: &mut Vec<NetworkConnectionInfo>) {
|
||||
let text = fs::read_to_string(path).unwrap_or_default();
|
||||
for line in text.lines().skip(1) {
|
||||
let cols = line.split_whitespace().collect::<Vec<_>>();
|
||||
if cols.len() < 4 {
|
||||
continue;
|
||||
}
|
||||
let Some((local_addr, local_port)) = parse_addr(cols[1]) else {
|
||||
continue;
|
||||
};
|
||||
let (remote_addr, remote_port) = parse_addr(cols[2]).unwrap_or_default();
|
||||
items.push(NetworkConnectionInfo {
|
||||
protocol: protocol.to_string(),
|
||||
local_addr,
|
||||
local_port,
|
||||
remote_addr: if remote_addr == "0.0.0.0" {
|
||||
None
|
||||
} else {
|
||||
Some(remote_addr)
|
||||
},
|
||||
remote_port: if remote_port == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(remote_port)
|
||||
},
|
||||
state: if protocol == "tcp" {
|
||||
tcp_state(cols[3]).to_string()
|
||||
} else {
|
||||
"UDP".to_string()
|
||||
},
|
||||
pid: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_addr(value: &str) -> Option<(String, u16)> {
|
||||
let (ip, port) = value.split_once(':')?;
|
||||
Some((parse_hex_ipv4(ip)?, u16::from_str_radix(port, 16).ok()?))
|
||||
}
|
||||
|
||||
fn recent_syslog_summary() -> Option<String> {
|
||||
for path in ["/var/log/syslog", "/var/log/messages"] {
|
||||
let Ok(text) = fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let count = text
|
||||
.lines()
|
||||
.rev()
|
||||
.take(200)
|
||||
.filter(|line| {
|
||||
let lower = line.to_lowercase();
|
||||
lower.contains("error") || lower.contains("fail") || lower.contains("denied")
|
||||
})
|
||||
.count();
|
||||
return Some(format!("recent syslog warning/error lines: {count}"));
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
pub mod common;
|
||||
pub mod freebsd;
|
||||
pub mod linux;
|
||||
pub mod windows;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
use crate::config::AgentRole;
|
||||
use crate::telemetry::TelemetryCollector;
|
||||
|
||||
pub fn platform_collector(role: AgentRole) -> Result<Box<dyn TelemetryCollector>> {
|
||||
if cfg!(target_os = "linux") {
|
||||
return Ok(Box::new(linux::LinuxCollector::new(role)));
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
return Ok(Box::new(windows::WindowsCollector::new(role)));
|
||||
}
|
||||
if cfg!(target_os = "freebsd") {
|
||||
return Ok(Box::new(freebsd::FreeBsdCollector::new(role)));
|
||||
}
|
||||
bail!("unsupported platform for awatch-agent-rs")
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
use anyhow::Result;
|
||||
use chrono::Utc;
|
||||
use std::process::Command;
|
||||
|
||||
use crate::collectors::common::{
|
||||
agent_id, command_output, current_session, domain, hostname, role_security_events, username,
|
||||
};
|
||||
use crate::config::AgentRole;
|
||||
use crate::telemetry::{
|
||||
IdentityInfo, NetworkConnectionInfo, NetworkSnapshot, ProcessInfo, ResourceInfo,
|
||||
SecurityEventInfo, SessionSnapshot, TelemetryCollector, WorkforceActivityInfo, dedupe_sessions,
|
||||
diagnostics_for_sessions, empty_workforce_activity,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WindowsCollector {
|
||||
role: AgentRole,
|
||||
}
|
||||
|
||||
impl WindowsCollector {
|
||||
pub fn new(role: AgentRole) -> Self {
|
||||
Self { role }
|
||||
}
|
||||
}
|
||||
|
||||
impl TelemetryCollector for WindowsCollector {
|
||||
fn collect_identity(&self) -> Result<IdentityInfo> {
|
||||
let host = hostname();
|
||||
Ok(IdentityInfo {
|
||||
agent_id: agent_id(&host),
|
||||
hostname: host,
|
||||
os_name: "Windows".to_string(),
|
||||
os_version: windows_version(),
|
||||
platform: "windows".to_string(),
|
||||
username: username(),
|
||||
domain: domain(),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_sessions(&self) -> Result<SessionSnapshot> {
|
||||
let host = hostname();
|
||||
let mut collection = windows_query_user_sessions();
|
||||
if collection.sessions.is_empty()
|
||||
&& std::env::var("SESSIONNAME")
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase()
|
||||
.contains("rdp")
|
||||
{
|
||||
let mut session = current_session("rdp");
|
||||
session.session_source = Some("env_sessionname_fallback".to_string());
|
||||
collection.sessions.push(session);
|
||||
collection.source = "env_sessionname_fallback".to_string();
|
||||
}
|
||||
if collection.sessions.is_empty() {
|
||||
let mut session = current_session("local");
|
||||
session.session_source = Some("local_fallback".to_string());
|
||||
collection.sessions.push(session);
|
||||
collection.source = "local_fallback".to_string();
|
||||
collection.error = Some("WTS API and quser did not return sessions".to_string());
|
||||
}
|
||||
let mut active = dedupe_sessions(&host, collection.sessions);
|
||||
let mut rdp = active
|
||||
.iter()
|
||||
.filter(|session| session.session_type == "rdp")
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
if std::env::var("SESSIONNAME")
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase()
|
||||
.contains("rdp")
|
||||
{
|
||||
let mut merged = active.clone();
|
||||
merged.push(with_session_source(
|
||||
current_session("rdp"),
|
||||
"env_sessionname_fallback",
|
||||
));
|
||||
active = dedupe_sessions(&host, merged);
|
||||
rdp = active
|
||||
.iter()
|
||||
.filter(|session| session.session_type == "rdp")
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
}
|
||||
rdp = dedupe_sessions(&host, rdp);
|
||||
let diagnostics =
|
||||
diagnostics_for_sessions(&active, &rdp, collection.source, collection.error);
|
||||
Ok(SessionSnapshot {
|
||||
active_sessions: active,
|
||||
rdp_sessions: rdp,
|
||||
ssh_sessions: Vec::new(),
|
||||
diagnostics,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_processes(&self) -> Result<Vec<ProcessInfo>> {
|
||||
Ok(windows_processes(128))
|
||||
}
|
||||
|
||||
fn collect_resources(&self) -> Result<ResourceInfo> {
|
||||
let (memory_total, memory_used) = windows_memory();
|
||||
Ok(ResourceInfo {
|
||||
uptime_seconds: 0,
|
||||
cpu_usage_percent: 0.0,
|
||||
memory_total,
|
||||
memory_used,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_network(&self) -> Result<NetworkSnapshot> {
|
||||
Ok(NetworkSnapshot {
|
||||
interfaces: Vec::new(),
|
||||
connections: windows_connections(256),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_security_events(&self) -> Result<Vec<SecurityEventInfo>> {
|
||||
let mut events = role_security_events(self.role);
|
||||
events.push(SecurityEventInfo {
|
||||
event_id: "windows-collector-v03".to_string(),
|
||||
source: "awatch-agent-rs".to_string(),
|
||||
severity: "INFO".to_string(),
|
||||
summary: "Windows read-only collector is active without PowerShell primary collection; WinAPI/ETW/WMI depth is planned behind the same TelemetryRecord contract".to_string(),
|
||||
timestamp: Utc::now(),
|
||||
evidence: vec!["no PowerShell primary collector".to_string()],
|
||||
});
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn collect_workforce_activity(&self) -> Result<WorkforceActivityInfo> {
|
||||
let mut activity = empty_workforce_activity();
|
||||
activity.active_today = true;
|
||||
activity.explanation = vec![
|
||||
"Windows collector reports session/process/network context; ActivityWatch/workforce scoring is calculated server-side".to_string(),
|
||||
];
|
||||
Ok(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fn windows_version() -> String {
|
||||
command_output("cmd", &["/C", "ver"])
|
||||
.or_else(|| std::env::var("OS").ok())
|
||||
.unwrap_or_else(|| "Windows".to_string())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SessionCollection {
|
||||
sessions: Vec<crate::telemetry::SessionInfo>,
|
||||
source: String,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn with_session_source(
|
||||
mut session: crate::telemetry::SessionInfo,
|
||||
source: &str,
|
||||
) -> crate::telemetry::SessionInfo {
|
||||
session.session_source = Some(source.to_string());
|
||||
session
|
||||
}
|
||||
|
||||
fn windows_query_user_sessions() -> SessionCollection {
|
||||
let native = windows_wts_sessions();
|
||||
if !native.is_empty() {
|
||||
return SessionCollection {
|
||||
sessions: native,
|
||||
source: "wts_api".to_string(),
|
||||
error: None,
|
||||
};
|
||||
}
|
||||
if let Some(raw) = command_output_utf16le("cmd", &["/U", "/C", "query user"])
|
||||
.or_else(|| command_output_utf16le("cmd", &["/U", "/C", "quser"]))
|
||||
{
|
||||
let sessions = parse_query_user_sessions(&raw, "quser_utf16");
|
||||
if !sessions.is_empty() {
|
||||
return SessionCollection {
|
||||
sessions,
|
||||
source: "quser_utf16".to_string(),
|
||||
error: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
if let Some(raw) = command_output_lossy_combined("cmd", &["/C", "query user"])
|
||||
.or_else(|| command_output_lossy_combined("cmd", &["/C", "quser"]))
|
||||
{
|
||||
let sessions = parse_query_user_sessions(&raw, "quser_lossy");
|
||||
if !sessions.is_empty() {
|
||||
return SessionCollection {
|
||||
sessions,
|
||||
source: "quser_lossy".to_string(),
|
||||
error: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
SessionCollection {
|
||||
sessions: Vec::new(),
|
||||
source: "local_fallback".to_string(),
|
||||
error: Some("WTS API and quser returned no sessions".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_query_user_sessions(raw: &str, source: &str) -> Vec<crate::telemetry::SessionInfo> {
|
||||
raw.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| parse_query_user_line(line, source))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn windows_wts_sessions() -> Vec<crate::telemetry::SessionInfo> {
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::System::RemoteDesktop::{
|
||||
WTS_CURRENT_SERVER_HANDLE, WTS_SESSION_INFOW, WTSActive, WTSEnumerateSessionsW,
|
||||
WTSFreeMemory, WTSUserName,
|
||||
};
|
||||
|
||||
let mut sessions_ptr: *mut WTS_SESSION_INFOW = ptr::null_mut();
|
||||
let mut count = 0_u32;
|
||||
let ok = unsafe {
|
||||
WTSEnumerateSessionsW(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
0,
|
||||
1,
|
||||
&mut sessions_ptr,
|
||||
&mut count,
|
||||
)
|
||||
};
|
||||
if ok == 0 || sessions_ptr.is_null() || count == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let sessions =
|
||||
unsafe { std::slice::from_raw_parts(sessions_ptr, usize::try_from(count).unwrap_or(0)) };
|
||||
let mut items = Vec::new();
|
||||
for session in sessions {
|
||||
let username = wts_session_string(session.SessionId, WTSUserName);
|
||||
if username.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let station = unsafe { wide_nul_to_string(session.pWinStationName) };
|
||||
let state = session.State;
|
||||
let session_type = if station.to_ascii_lowercase().contains("rdp") {
|
||||
"rdp"
|
||||
} else {
|
||||
"local"
|
||||
};
|
||||
items.push(crate::telemetry::SessionInfo {
|
||||
session_id: session.SessionId.to_string(),
|
||||
username,
|
||||
session_type: session_type.to_string(),
|
||||
session_source: Some("wts_api".to_string()),
|
||||
remote_addr: None,
|
||||
started_at: None,
|
||||
active: state == WTSActive,
|
||||
});
|
||||
}
|
||||
unsafe {
|
||||
WTSFreeMemory(sessions_ptr.cast());
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn windows_wts_sessions() -> Vec<crate::telemetry::SessionInfo> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn wts_session_string(session_id: u32, class: i32) -> String {
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::System::RemoteDesktop::{
|
||||
WTS_CURRENT_SERVER_HANDLE, WTSFreeMemory, WTSQuerySessionInformationW,
|
||||
};
|
||||
|
||||
let mut buffer = ptr::null_mut();
|
||||
let mut bytes = 0_u32;
|
||||
let ok = unsafe {
|
||||
WTSQuerySessionInformationW(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
session_id,
|
||||
class,
|
||||
&mut buffer,
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
if ok == 0 || buffer.is_null() || bytes == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let len = usize::try_from(bytes / 2).unwrap_or(0);
|
||||
let value = unsafe {
|
||||
let slice = std::slice::from_raw_parts(buffer, len);
|
||||
String::from_utf16_lossy(slice)
|
||||
.trim_matches('\0')
|
||||
.trim()
|
||||
.to_string()
|
||||
};
|
||||
unsafe {
|
||||
WTSFreeMemory(buffer.cast());
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
unsafe fn wide_nul_to_string(ptr: *const u16) -> String {
|
||||
if ptr.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
let mut len = 0;
|
||||
while unsafe { *ptr.add(len) } != 0 {
|
||||
len += 1;
|
||||
}
|
||||
let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
|
||||
String::from_utf16_lossy(slice)
|
||||
}
|
||||
|
||||
fn command_output_utf16le(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new(program).args(args).output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = output.stdout;
|
||||
bytes.extend_from_slice(&output.stderr);
|
||||
if bytes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut words = Vec::new();
|
||||
for chunk in bytes.chunks_exact(2) {
|
||||
words.push(u16::from_le_bytes([chunk[0], chunk[1]]));
|
||||
}
|
||||
String::from_utf16(&words)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn command_output_lossy_combined(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new(program).args(args).output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = output.stdout;
|
||||
bytes.extend_from_slice(&output.stderr);
|
||||
Some(String::from_utf8_lossy(&bytes).trim().to_string()).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn parse_query_user_line(line: &str, source: &str) -> Option<crate::telemetry::SessionInfo> {
|
||||
let cleaned = line.trim().trim_start_matches('>').trim();
|
||||
if cleaned.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let parts = cleaned.split_whitespace().collect::<Vec<_>>();
|
||||
if parts.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let username = parts.first()?.to_string();
|
||||
let (session_name, session_id, state) = if parts.get(1)?.chars().all(|ch| ch.is_ascii_digit()) {
|
||||
("".to_string(), *parts.get(1)?, *parts.get(2)?)
|
||||
} else {
|
||||
(
|
||||
parts.get(1)?.to_string(),
|
||||
*parts.get(2)?,
|
||||
*parts.get(3).unwrap_or(&"Unknown"),
|
||||
)
|
||||
};
|
||||
let active = session_state_active(state);
|
||||
let session_type = if session_name.to_ascii_lowercase().contains("rdp") {
|
||||
"rdp"
|
||||
} else {
|
||||
"local"
|
||||
};
|
||||
Some(crate::telemetry::SessionInfo {
|
||||
session_id: session_id.to_string(),
|
||||
username,
|
||||
session_type: session_type.to_string(),
|
||||
session_source: Some(source.to_string()),
|
||||
remote_addr: None,
|
||||
started_at: None,
|
||||
active,
|
||||
})
|
||||
}
|
||||
|
||||
fn session_state_active(state: &str) -> bool {
|
||||
let lower = state.to_lowercase();
|
||||
lower.contains("active") || lower.contains("актив")
|
||||
}
|
||||
|
||||
fn windows_memory() -> (u64, u64) {
|
||||
let Some(raw) = command_output(
|
||||
"wmic",
|
||||
&[
|
||||
"OS",
|
||||
"get",
|
||||
"FreePhysicalMemory,TotalVisibleMemorySize",
|
||||
"/Value",
|
||||
],
|
||||
) else {
|
||||
return (0, 0);
|
||||
};
|
||||
let mut free_kib = 0;
|
||||
let mut total_kib = 0;
|
||||
for line in raw.lines() {
|
||||
if let Some(value) = line.strip_prefix("FreePhysicalMemory=") {
|
||||
free_kib = value.trim().parse::<u64>().unwrap_or(0);
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("TotalVisibleMemorySize=") {
|
||||
total_kib = value.trim().parse::<u64>().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
let total = total_kib.saturating_mul(1024);
|
||||
let used = total_kib.saturating_sub(free_kib).saturating_mul(1024);
|
||||
(total, used)
|
||||
}
|
||||
|
||||
fn windows_processes(limit: usize) -> Vec<ProcessInfo> {
|
||||
let Some(raw) = command_output("tasklist", &["/FO", "CSV", "/NH"]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut items = raw
|
||||
.lines()
|
||||
.filter_map(parse_tasklist_line)
|
||||
.collect::<Vec<_>>();
|
||||
items.truncate(limit);
|
||||
items
|
||||
}
|
||||
|
||||
fn parse_tasklist_line(line: &str) -> Option<ProcessInfo> {
|
||||
let cols = parse_csv_line(line);
|
||||
let name = cols.first()?.to_string();
|
||||
let pid = cols.get(1)?.parse::<u32>().ok()?;
|
||||
let memory_bytes = cols.get(4).map(|value| parse_tasklist_memory(value));
|
||||
Some(ProcessInfo {
|
||||
pid,
|
||||
ppid: None,
|
||||
name,
|
||||
exe: None,
|
||||
username: None,
|
||||
cpu_percent: None,
|
||||
memory_bytes,
|
||||
started_at: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_csv_line(line: &str) -> Vec<String> {
|
||||
line.trim_matches('"')
|
||||
.split("\",\"")
|
||||
.map(|value| value.trim().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_tasklist_memory(value: &str) -> u64 {
|
||||
value
|
||||
.chars()
|
||||
.filter(|ch| ch.is_ascii_digit())
|
||||
.collect::<String>()
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
.saturating_mul(1024)
|
||||
}
|
||||
|
||||
fn windows_connections(limit: usize) -> Vec<NetworkConnectionInfo> {
|
||||
let Some(raw) = command_output("netstat", &["-ano"]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut items = raw
|
||||
.lines()
|
||||
.filter_map(parse_netstat_line)
|
||||
.collect::<Vec<_>>();
|
||||
items.truncate(limit);
|
||||
items
|
||||
}
|
||||
|
||||
fn parse_netstat_line(line: &str) -> Option<NetworkConnectionInfo> {
|
||||
let cols = line.split_whitespace().collect::<Vec<_>>();
|
||||
let protocol = cols.first()?.to_ascii_lowercase();
|
||||
if protocol != "tcp" && protocol != "udp" {
|
||||
return None;
|
||||
}
|
||||
let (local_addr, local_port) = split_host_port(cols.get(1)?)?;
|
||||
let (remote_addr, remote_port) = split_host_port(cols.get(2)?).unwrap_or_default();
|
||||
let state = if protocol == "tcp" {
|
||||
cols.get(3).unwrap_or(&"UNKNOWN").to_string()
|
||||
} else {
|
||||
"UDP".to_string()
|
||||
};
|
||||
let pid = cols.last().and_then(|value| value.parse::<u32>().ok());
|
||||
Some(NetworkConnectionInfo {
|
||||
protocol,
|
||||
local_addr,
|
||||
local_port,
|
||||
remote_addr: Some(remote_addr),
|
||||
remote_port: Some(remote_port),
|
||||
state,
|
||||
pid,
|
||||
})
|
||||
}
|
||||
|
||||
fn split_host_port(value: &str) -> Option<(String, u16)> {
|
||||
let (host, port) = value.rsplit_once(':')?;
|
||||
Some((
|
||||
host.trim_matches(['[', ']']).to_string(),
|
||||
port.parse().ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_query_user_line_with_rdp_session() {
|
||||
let session = parse_query_user_line(
|
||||
" user1 rdp-tcp#5 3 Active",
|
||||
"quser_utf16",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(session.username, "user1");
|
||||
assert_eq!(session.session_id, "3");
|
||||
assert_eq!(session.session_type, "rdp");
|
||||
assert_eq!(session.session_source.as_deref(), Some("quser_utf16"));
|
||||
assert!(session.active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_query_user_line_without_session_name() {
|
||||
let session =
|
||||
parse_query_user_line(" user2 4 Disc", "quser_lossy").unwrap();
|
||||
assert_eq!(session.username, "user2");
|
||||
assert_eq!(session.session_id, "4");
|
||||
assert_eq!(session.session_type, "local");
|
||||
assert_eq!(session.session_source.as_deref(), Some("quser_lossy"));
|
||||
assert!(!session.active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_russian_active_state() {
|
||||
assert!(session_state_active("Активно"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AgentConfig {
|
||||
pub server_url: String,
|
||||
pub api_key: String,
|
||||
pub collect_interval_seconds: u64,
|
||||
pub role: AgentRole,
|
||||
pub enable_processes: bool,
|
||||
pub enable_network: bool,
|
||||
pub enable_security_events: bool,
|
||||
pub enable_workforce_activity: bool,
|
||||
pub spool_dir: PathBuf,
|
||||
pub timeout_seconds: u64,
|
||||
pub retry_attempts: u32,
|
||||
pub aw_api_base: Option<String>,
|
||||
pub aw_worktime_enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AgentRole {
|
||||
Workstation,
|
||||
Server,
|
||||
Firewall,
|
||||
}
|
||||
|
||||
impl AgentRole {
|
||||
pub fn parse(value: &str) -> Self {
|
||||
match value.trim().to_lowercase().as_str() {
|
||||
"firewall" | "pfsense" => Self::Firewall,
|
||||
"server" => Self::Server,
|
||||
_ => Self::Workstation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AgentConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
server_url: "https://awatch.local/api/telemetry".to_string(),
|
||||
api_key: "change-me".to_string(),
|
||||
collect_interval_seconds: 60,
|
||||
role: AgentRole::Workstation,
|
||||
enable_processes: true,
|
||||
enable_network: true,
|
||||
enable_security_events: true,
|
||||
enable_workforce_activity: true,
|
||||
spool_dir: default_spool_dir(),
|
||||
timeout_seconds: 10,
|
||||
retry_attempts: 3,
|
||||
aw_api_base: None,
|
||||
aw_worktime_enabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_config_path() -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
PathBuf::from(r"C:\ProgramData\AWatch\agent\awatch-agent.toml")
|
||||
} else {
|
||||
PathBuf::from("/etc/awatch-agent/awatch-agent.toml")
|
||||
}
|
||||
}
|
||||
|
||||
fn default_spool_dir() -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
PathBuf::from(r"C:\ProgramData\AWatch\agent\spool")
|
||||
} else {
|
||||
PathBuf::from("/var/lib/awatch-agent/spool")
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentConfig {
|
||||
pub fn load(path: &Path) -> Result<Self> {
|
||||
let text = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
|
||||
Self::parse_toml_like(&text)
|
||||
}
|
||||
|
||||
pub fn parse_toml_like(text: &str) -> Result<Self> {
|
||||
let mut config = Self::default();
|
||||
for raw in text.lines() {
|
||||
let line = raw.split('#').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let key = key.trim();
|
||||
let value = value.trim().trim_matches('"');
|
||||
match key {
|
||||
"server_url" => config.server_url = value.to_string(),
|
||||
"api_key" => config.api_key = value.to_string(),
|
||||
"collect_interval_seconds" => {
|
||||
config.collect_interval_seconds = value.parse().unwrap_or(60)
|
||||
}
|
||||
"role" => config.role = AgentRole::parse(value),
|
||||
"enable_processes" => config.enable_processes = parse_bool(value, true),
|
||||
"enable_network" => config.enable_network = parse_bool(value, true),
|
||||
"enable_security_events" => config.enable_security_events = parse_bool(value, true),
|
||||
"enable_workforce_activity" => {
|
||||
config.enable_workforce_activity = parse_bool(value, true)
|
||||
}
|
||||
"spool_dir" => config.spool_dir = PathBuf::from(value),
|
||||
"timeout_seconds" => config.timeout_seconds = value.parse().unwrap_or(10),
|
||||
"retry_attempts" => config.retry_attempts = value.parse().unwrap_or(3),
|
||||
"aw_api_base" => config.aw_api_base = Some(value.trim_end_matches('/').to_string()),
|
||||
"aw_worktime_enabled" => {
|
||||
config.aw_worktime_enabled = parse_bool(value, false);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bool(value: &str, fallback: bool) -> bool {
|
||||
match value.trim().to_lowercase().as_str() {
|
||||
"1" | "true" | "yes" | "on" => true,
|
||||
"0" | "false" | "no" | "off" => false,
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_agent_config() {
|
||||
let config = AgentConfig::parse_toml_like(
|
||||
r#"
|
||||
server_url = "https://awatch.local/api/telemetry"
|
||||
api_key = "change-me"
|
||||
collect_interval_seconds = 30
|
||||
role = "firewall"
|
||||
enable_processes = false
|
||||
aw_api_base = "http://awatch.local:5600/api/0"
|
||||
aw_worktime_enabled = true
|
||||
spool_dir = "/tmp/awatch-spool"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config.role, AgentRole::Firewall);
|
||||
assert_eq!(config.collect_interval_seconds, 30);
|
||||
assert!(!config.enable_processes);
|
||||
assert!(config.aw_worktime_enabled);
|
||||
assert_eq!(
|
||||
config.aw_api_base.as_deref(),
|
||||
Some("http://awatch.local:5600/api/0")
|
||||
);
|
||||
assert_eq!(config.spool_dir, PathBuf::from("/tmp/awatch-spool"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CpuFeatures {
|
||||
pub architecture: String,
|
||||
pub backend: &'static str,
|
||||
pub features: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn get_cpu_features() -> CpuFeatures {
|
||||
let mut features = Vec::new();
|
||||
collect_cpu_features(&mut features);
|
||||
features.sort();
|
||||
features.dedup();
|
||||
|
||||
CpuFeatures {
|
||||
architecture: std::env::consts::ARCH.to_string(),
|
||||
backend: super::LOWLEVEL_BACKEND,
|
||||
features,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn collect_cpu_features(features: &mut Vec<String>) {
|
||||
for (name, detected) in [
|
||||
("sse2", std::is_x86_feature_detected!("sse2")),
|
||||
("sse4.2", std::is_x86_feature_detected!("sse4.2")),
|
||||
("avx", std::is_x86_feature_detected!("avx")),
|
||||
("avx2", std::is_x86_feature_detected!("avx2")),
|
||||
("aes", std::is_x86_feature_detected!("aes")),
|
||||
] {
|
||||
if detected {
|
||||
features.push(name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
|
||||
fn collect_cpu_features(features: &mut Vec<String>) {
|
||||
for name in compile_time_features() {
|
||||
features.push(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
not(any(target_arch = "x86", target_arch = "x86_64")),
|
||||
target_arch = "aarch64"
|
||||
))]
|
||||
fn compile_time_features() -> &'static [&'static str] {
|
||||
&[
|
||||
#[cfg(target_feature = "aes")]
|
||||
"aes",
|
||||
#[cfg(target_feature = "neon")]
|
||||
"neon",
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
not(any(target_arch = "x86", target_arch = "x86_64")),
|
||||
not(target_arch = "aarch64")
|
||||
))]
|
||||
fn compile_time_features() -> &'static [&'static str] {
|
||||
&[]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cpu_features_have_architecture_and_backend() {
|
||||
let features = get_cpu_features();
|
||||
|
||||
assert!(!features.architecture.trim().is_empty());
|
||||
assert!(!features.backend.trim().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Safe low-level extension point for future agent optimizations.
|
||||
//!
|
||||
//! The default implementation is pure Rust. The `asm-lowlevel` feature is a
|
||||
//! reserved integration point for future platform-specific CPU and timing
|
||||
//! probes implemented through `core::arch`, inline assembly, or native OS
|
||||
//! calls. Keep any future `unsafe` code isolated inside this module.
|
||||
|
||||
pub mod cpu;
|
||||
pub mod timing;
|
||||
|
||||
pub use cpu::{CpuFeatures, get_cpu_features};
|
||||
pub use timing::{high_precision_time_ns, monotonic_ticks};
|
||||
|
||||
#[cfg(feature = "asm-lowlevel")]
|
||||
pub const LOWLEVEL_BACKEND: &str = "asm-lowlevel-ready-rust-fallback";
|
||||
|
||||
#[cfg(not(feature = "asm-lowlevel"))]
|
||||
pub const LOWLEVEL_BACKEND: &str = "rust";
|
||||
@@ -0,0 +1,36 @@
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
static MONOTONIC_START: OnceLock<Instant> = OnceLock::new();
|
||||
|
||||
pub fn monotonic_ticks() -> u128 {
|
||||
MONOTONIC_START
|
||||
.get_or_init(Instant::now)
|
||||
.elapsed()
|
||||
.as_nanos()
|
||||
}
|
||||
|
||||
pub fn high_precision_time_ns() -> u128 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn monotonic_ticks_do_not_go_backwards() {
|
||||
let first = monotonic_ticks();
|
||||
let second = monotonic_ticks();
|
||||
|
||||
assert!(second >= first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_precision_time_is_epoch_based() {
|
||||
assert!(high_precision_time_ns() > 1_000_000_000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
mod collectors;
|
||||
mod config;
|
||||
pub mod lowlevel;
|
||||
mod telemetry;
|
||||
mod transport;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use config::{AgentConfig, AgentRole, default_config_path};
|
||||
use transport::{AwWorktimePublisher, TelemetryTransport, spool_health};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(about = "AWatch-rus Rust telemetry agent")]
|
||||
struct Cli {
|
||||
#[arg(long, env = "AWATCH_AGENT_CONFIG")]
|
||||
config: Option<PathBuf>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_SERVER_URL")]
|
||||
server_url: Option<String>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_API_KEY")]
|
||||
api_key: Option<String>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_ROLE")]
|
||||
role: Option<String>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_AW_API_BASE")]
|
||||
aw_api_base: Option<String>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_AW_WORKTIME_ENABLED")]
|
||||
aw_worktime_enabled: Option<bool>,
|
||||
|
||||
#[arg(long)]
|
||||
once: bool,
|
||||
|
||||
#[arg(long)]
|
||||
print_json: bool,
|
||||
|
||||
#[arg(long)]
|
||||
flush_spool: bool,
|
||||
|
||||
#[arg(long)]
|
||||
spool_health: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let code = match run() {
|
||||
Ok(code) => code,
|
||||
Err(err) => {
|
||||
eprintln!("{err:#}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
fn run() -> Result<i32> {
|
||||
let cli = Cli::parse();
|
||||
let mut config = load_config(cli.config.as_ref())?;
|
||||
if let Some(server_url) = cli.server_url {
|
||||
config.server_url = server_url;
|
||||
}
|
||||
if let Some(api_key) = cli.api_key {
|
||||
config.api_key = api_key;
|
||||
}
|
||||
if let Some(role) = cli.role {
|
||||
config.role = AgentRole::parse(&role);
|
||||
}
|
||||
if let Some(aw_api_base) = cli.aw_api_base {
|
||||
config.aw_api_base = Some(aw_api_base.trim_end_matches('/').to_string());
|
||||
}
|
||||
if let Some(enabled) = cli.aw_worktime_enabled {
|
||||
config.aw_worktime_enabled = enabled;
|
||||
}
|
||||
if cli.spool_health {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&spool_health(&config.spool_dir))?
|
||||
);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let transport = TelemetryTransport::new(&config);
|
||||
let aw_worktime = AwWorktimePublisher::new(&config);
|
||||
if cli.flush_spool {
|
||||
let telemetry_flushed = transport.flush_spool()?;
|
||||
let worktime_flushed = match aw_worktime.as_ref() {
|
||||
Some(publisher) => publisher.flush_spool()?,
|
||||
None => 0,
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({
|
||||
"ok": true,
|
||||
"flushed": telemetry_flushed + worktime_flushed,
|
||||
"telemetry_flushed": telemetry_flushed,
|
||||
"worktime_flushed": worktime_flushed,
|
||||
})
|
||||
);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
loop {
|
||||
let collector = collectors::platform_collector(config.role)?;
|
||||
let record = collector.collect_all()?;
|
||||
if cli.print_json {
|
||||
println!("{}", serde_json::to_string_pretty(&record)?);
|
||||
} else if let Err(err) = transport.send_or_spool(&record) {
|
||||
eprintln!("{err:#}");
|
||||
}
|
||||
if !cli.print_json {
|
||||
if let Some(publisher) = aw_worktime.as_ref() {
|
||||
if let Err(err) = publisher.publish_or_spool(&record) {
|
||||
eprintln!("{err:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if cli.once {
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_secs(config.collect_interval_seconds));
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn load_config(path: Option<&PathBuf>) -> Result<AgentConfig> {
|
||||
let path = path.cloned().unwrap_or_else(default_config_path);
|
||||
if path.exists() {
|
||||
AgentConfig::load(&path)
|
||||
} else {
|
||||
AgentConfig::parse_toml_like("")
|
||||
.with_context(|| format!("load default config because {} is absent", path.display()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
use anyhow::Result;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
pub const COLLECTOR_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TelemetryRecord {
|
||||
pub agent_id: String,
|
||||
pub hostname: String,
|
||||
pub os_name: String,
|
||||
pub os_version: String,
|
||||
pub platform: String,
|
||||
pub username: String,
|
||||
pub domain: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub uptime_seconds: u64,
|
||||
pub cpu_usage_percent: f64,
|
||||
pub memory_total: u64,
|
||||
pub memory_used: u64,
|
||||
pub active_sessions: Vec<SessionInfo>,
|
||||
pub rdp_sessions: Vec<SessionInfo>,
|
||||
pub ssh_sessions: Vec<SessionInfo>,
|
||||
pub processes: Vec<ProcessInfo>,
|
||||
pub network_interfaces: Vec<NetworkInterfaceInfo>,
|
||||
pub network_connections: Vec<NetworkConnectionInfo>,
|
||||
pub workforce_activity: WorkforceActivityInfo,
|
||||
pub security_events: Vec<SecurityEventInfo>,
|
||||
pub diagnostics: AgentDiagnostics,
|
||||
pub collector_version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct IdentityInfo {
|
||||
pub agent_id: String,
|
||||
pub hostname: String,
|
||||
pub os_name: String,
|
||||
pub os_version: String,
|
||||
pub platform: String,
|
||||
pub username: String,
|
||||
pub domain: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ResourceInfo {
|
||||
pub uptime_seconds: u64,
|
||||
pub cpu_usage_percent: f64,
|
||||
pub memory_total: u64,
|
||||
pub memory_used: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct SessionInfo {
|
||||
pub session_id: String,
|
||||
pub username: String,
|
||||
pub session_type: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub session_source: Option<String>,
|
||||
pub remote_addr: Option<String>,
|
||||
pub started_at: Option<DateTime<Utc>>,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct AgentDiagnostics {
|
||||
pub sessions_collected_total: usize,
|
||||
pub rdp_sessions_total: usize,
|
||||
pub active_sessions_total: usize,
|
||||
pub collector_source: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub collector_error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ProcessInfo {
|
||||
pub pid: u32,
|
||||
pub ppid: Option<u32>,
|
||||
pub name: String,
|
||||
pub exe: Option<String>,
|
||||
pub username: Option<String>,
|
||||
pub cpu_percent: Option<f64>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub started_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NetworkInterfaceInfo {
|
||||
pub name: String,
|
||||
pub mac: Option<String>,
|
||||
pub addresses: Vec<String>,
|
||||
pub up: bool,
|
||||
pub rx_bytes: Option<u64>,
|
||||
pub tx_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NetworkConnectionInfo {
|
||||
pub protocol: String,
|
||||
pub local_addr: String,
|
||||
pub local_port: u16,
|
||||
pub remote_addr: Option<String>,
|
||||
pub remote_port: Option<u16>,
|
||||
pub state: String,
|
||||
pub pid: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct WorkforceActivityInfo {
|
||||
pub active_today: bool,
|
||||
pub activity_index: Option<u8>,
|
||||
pub department: Option<String>,
|
||||
pub owner: Option<String>,
|
||||
pub work_applications: Vec<String>,
|
||||
pub idle_seconds: Option<u64>,
|
||||
pub explanation: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct SecurityEventInfo {
|
||||
pub event_id: String,
|
||||
pub source: String,
|
||||
pub severity: String,
|
||||
pub summary: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub evidence: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct SessionSnapshot {
|
||||
pub active_sessions: Vec<SessionInfo>,
|
||||
pub rdp_sessions: Vec<SessionInfo>,
|
||||
pub ssh_sessions: Vec<SessionInfo>,
|
||||
pub diagnostics: AgentDiagnostics,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NetworkSnapshot {
|
||||
pub interfaces: Vec<NetworkInterfaceInfo>,
|
||||
pub connections: Vec<NetworkConnectionInfo>,
|
||||
}
|
||||
|
||||
pub trait TelemetryCollector {
|
||||
fn collect_identity(&self) -> Result<IdentityInfo>;
|
||||
fn collect_sessions(&self) -> Result<SessionSnapshot>;
|
||||
fn collect_processes(&self) -> Result<Vec<ProcessInfo>>;
|
||||
fn collect_resources(&self) -> Result<ResourceInfo>;
|
||||
fn collect_network(&self) -> Result<NetworkSnapshot>;
|
||||
fn collect_security_events(&self) -> Result<Vec<SecurityEventInfo>>;
|
||||
fn collect_workforce_activity(&self) -> Result<WorkforceActivityInfo>;
|
||||
|
||||
fn collect_all(&self) -> Result<TelemetryRecord> {
|
||||
let identity = self.collect_identity()?;
|
||||
let sessions = self.collect_sessions()?;
|
||||
let resources = self.collect_resources()?;
|
||||
let network = self.collect_network()?;
|
||||
Ok(TelemetryRecord {
|
||||
agent_id: identity.agent_id,
|
||||
hostname: identity.hostname,
|
||||
os_name: identity.os_name,
|
||||
os_version: identity.os_version,
|
||||
platform: identity.platform,
|
||||
username: identity.username,
|
||||
domain: identity.domain,
|
||||
timestamp: Utc::now(),
|
||||
uptime_seconds: resources.uptime_seconds,
|
||||
cpu_usage_percent: resources.cpu_usage_percent,
|
||||
memory_total: resources.memory_total,
|
||||
memory_used: resources.memory_used,
|
||||
active_sessions: sessions.active_sessions,
|
||||
rdp_sessions: sessions.rdp_sessions,
|
||||
ssh_sessions: sessions.ssh_sessions,
|
||||
processes: self.collect_processes()?,
|
||||
network_interfaces: network.interfaces,
|
||||
network_connections: network.connections,
|
||||
workforce_activity: self.collect_workforce_activity()?,
|
||||
security_events: self.collect_security_events()?,
|
||||
diagnostics: sessions.diagnostics,
|
||||
collector_version: COLLECTOR_VERSION.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn diagnostics_for_sessions(
|
||||
active_sessions: &[SessionInfo],
|
||||
rdp_sessions: &[SessionInfo],
|
||||
collector_source: impl Into<String>,
|
||||
collector_error: Option<String>,
|
||||
) -> AgentDiagnostics {
|
||||
AgentDiagnostics {
|
||||
sessions_collected_total: active_sessions.len(),
|
||||
rdp_sessions_total: rdp_sessions.len(),
|
||||
active_sessions_total: active_sessions
|
||||
.iter()
|
||||
.filter(|session| session.active)
|
||||
.count(),
|
||||
collector_source: collector_source.into(),
|
||||
collector_error,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dedupe_sessions(hostname: &str, sessions: Vec<SessionInfo>) -> Vec<SessionInfo> {
|
||||
let mut seen = BTreeSet::new();
|
||||
sessions
|
||||
.into_iter()
|
||||
.filter(|session| {
|
||||
seen.insert(format!(
|
||||
"{}\u{1f}{}\u{1f}{}\u{1f}{}",
|
||||
hostname, session.username, session.session_id, session.session_type
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn empty_workforce_activity() -> WorkforceActivityInfo {
|
||||
WorkforceActivityInfo {
|
||||
active_today: false,
|
||||
activity_index: None,
|
||||
department: None,
|
||||
owner: None,
|
||||
work_applications: Vec::new(),
|
||||
idle_seconds: None,
|
||||
explanation: vec!["activity scoring requires workstation activity events".to_string()],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn telemetry_record_serializes_required_fields() {
|
||||
let record = TelemetryRecord {
|
||||
agent_id: "agent-1".to_string(),
|
||||
hostname: "HOST-EXAMPLE".to_string(),
|
||||
os_name: "Linux".to_string(),
|
||||
os_version: "test".to_string(),
|
||||
platform: "linux".to_string(),
|
||||
username: "user".to_string(),
|
||||
domain: "".to_string(),
|
||||
timestamp: Utc::now(),
|
||||
uptime_seconds: 1,
|
||||
cpu_usage_percent: 0.0,
|
||||
memory_total: 10,
|
||||
memory_used: 5,
|
||||
active_sessions: Vec::new(),
|
||||
rdp_sessions: Vec::new(),
|
||||
ssh_sessions: Vec::new(),
|
||||
processes: Vec::new(),
|
||||
network_interfaces: Vec::new(),
|
||||
network_connections: Vec::new(),
|
||||
workforce_activity: empty_workforce_activity(),
|
||||
security_events: Vec::new(),
|
||||
diagnostics: diagnostics_for_sessions(&[], &[], "test", None),
|
||||
collector_version: COLLECTOR_VERSION.to_string(),
|
||||
};
|
||||
let value = serde_json::to_value(record).unwrap();
|
||||
assert_eq!(value["agent_id"], "agent-1");
|
||||
assert!(value.get("network_connections").unwrap().is_array());
|
||||
assert!(value.get("workforce_activity").is_some());
|
||||
assert_eq!(value["diagnostics"]["collector_source"], "test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deduplicates_sessions_by_host_user_id_and_type() {
|
||||
let session = SessionInfo {
|
||||
session_id: "2".to_string(),
|
||||
username: "user".to_string(),
|
||||
session_type: "rdp".to_string(),
|
||||
session_source: Some("wts_api".to_string()),
|
||||
remote_addr: None,
|
||||
started_at: None,
|
||||
active: true,
|
||||
};
|
||||
let deduped = dedupe_sessions("HOST-EXAMPLE", vec![session.clone(), session]);
|
||||
assert_eq!(deduped.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
|
||||
use crate::config::AgentConfig;
|
||||
use crate::telemetry::{SessionInfo, TelemetryRecord};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TelemetryTransport {
|
||||
server_url: String,
|
||||
api_key: String,
|
||||
spool_dir: PathBuf,
|
||||
timeout: Duration,
|
||||
retry_attempts: u32,
|
||||
}
|
||||
|
||||
impl TelemetryTransport {
|
||||
pub fn new(config: &AgentConfig) -> Self {
|
||||
Self {
|
||||
server_url: config.server_url.clone(),
|
||||
api_key: config.api_key.clone(),
|
||||
spool_dir: config.spool_dir.clone(),
|
||||
timeout: Duration::from_secs(config.timeout_seconds),
|
||||
retry_attempts: config.retry_attempts,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_or_spool(&self, record: &TelemetryRecord) -> Result<()> {
|
||||
match self.send(record) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
self.spool(record)?;
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send(&self, record: &TelemetryRecord) -> Result<()> {
|
||||
let client = Client::builder()
|
||||
.timeout(self.timeout)
|
||||
.build()
|
||||
.context("build telemetry HTTP client")?;
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-api-key",
|
||||
HeaderValue::from_str(&self.api_key).context("invalid api key header")?,
|
||||
);
|
||||
let mut last_error = None;
|
||||
for attempt in 0..self.retry_attempts.max(1) {
|
||||
let result = client
|
||||
.post(&self.server_url)
|
||||
.headers(headers.clone())
|
||||
.json(record)
|
||||
.send()
|
||||
.and_then(|response| response.error_for_status())
|
||||
.map(|_| ());
|
||||
match result {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
last_error = Some(err);
|
||||
let backoff = Duration::from_millis(250 * u64::from(attempt + 1));
|
||||
thread::sleep(backoff);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(anyhow!(
|
||||
"telemetry POST failed: {}",
|
||||
last_error
|
||||
.map(|err| err.to_string())
|
||||
.unwrap_or_else(|| "unknown error".to_string())
|
||||
))
|
||||
}
|
||||
|
||||
pub fn spool(&self, record: &TelemetryRecord) -> Result<PathBuf> {
|
||||
fs::create_dir_all(&self.spool_dir)
|
||||
.with_context(|| format!("create spool {}", self.spool_dir.display()))?;
|
||||
let file_name = format!(
|
||||
"{}-{}.json",
|
||||
record.timestamp.format("%Y%m%dT%H%M%S%.3fZ"),
|
||||
sanitize_file_part(&record.agent_id)
|
||||
);
|
||||
let path = self.spool_dir.join(file_name);
|
||||
fs::write(&path, serde_json::to_vec(record)?)
|
||||
.with_context(|| format!("write spool {}", path.display()))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn flush_spool(&self) -> Result<usize> {
|
||||
flush_spool_dir(&self.spool_dir, |record| self.send(record))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AwWorktimePublisher {
|
||||
aw_api_base: String,
|
||||
spool_dir: PathBuf,
|
||||
timeout: Duration,
|
||||
retry_attempts: u32,
|
||||
}
|
||||
|
||||
impl AwWorktimePublisher {
|
||||
pub fn new(config: &AgentConfig) -> Option<Self> {
|
||||
if !config.aw_worktime_enabled {
|
||||
return None;
|
||||
}
|
||||
let aw_api_base = config
|
||||
.aw_api_base
|
||||
.as_ref()?
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
if aw_api_base.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
aw_api_base,
|
||||
spool_dir: config.spool_dir.join("aw-worktime"),
|
||||
timeout: Duration::from_secs(config.timeout_seconds),
|
||||
retry_attempts: config.retry_attempts,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn publish_or_spool(&self, record: &TelemetryRecord) -> Result<()> {
|
||||
if let Err(err) = self.flush_spool() {
|
||||
eprintln!("ActivityWatch worktime spool flush failed: {err:#}");
|
||||
}
|
||||
match self.publish(record) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => {
|
||||
self.spool(record)?;
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn publish(&self, record: &TelemetryRecord) -> Result<usize> {
|
||||
let client = Client::builder()
|
||||
.timeout(self.timeout)
|
||||
.build()
|
||||
.context("build ActivityWatch HTTP client")?;
|
||||
let bucket_id = format!(
|
||||
"aw-worktime-sessions_{}",
|
||||
sanitize_bucket_part(&record.hostname)
|
||||
);
|
||||
ensure_aw_bucket(
|
||||
&client,
|
||||
&self.aw_api_base,
|
||||
&bucket_id,
|
||||
"aw-worktime-session-collector",
|
||||
"aw.worktime.session",
|
||||
&record.hostname,
|
||||
)?;
|
||||
let sessions = if record.active_sessions.is_empty() {
|
||||
vec![SessionInfo {
|
||||
session_id: "0".to_string(),
|
||||
username: record.username.clone(),
|
||||
session_type: "local".to_string(),
|
||||
session_source: Some("local_fallback".to_string()),
|
||||
remote_addr: None,
|
||||
started_at: None,
|
||||
active: true,
|
||||
}]
|
||||
} else {
|
||||
record.active_sessions.clone()
|
||||
};
|
||||
let mut sent = 0;
|
||||
let sample_seconds = 60_i64;
|
||||
for session in sessions {
|
||||
let ignore_for_kpi = ignored_for_kpi(record, &session);
|
||||
let active_for_kpi = session.active && !ignore_for_kpi;
|
||||
let state = if ignore_for_kpi {
|
||||
"IgnoredForKpi"
|
||||
} else if session.active {
|
||||
"Active"
|
||||
} else {
|
||||
"Disconnected"
|
||||
};
|
||||
let payload = serde_json::json!({
|
||||
"timestamp": record.timestamp,
|
||||
"duration": sample_seconds,
|
||||
"data": {
|
||||
"username": session.username,
|
||||
"userId": format!("{}\\{}", record.hostname, session.username),
|
||||
"sessionId": session_id_number(&session),
|
||||
"sessionName": session.session_type,
|
||||
"sessionSource": session.session_source,
|
||||
"state": state,
|
||||
"active": active_for_kpi,
|
||||
"ignoredForKpi": ignore_for_kpi,
|
||||
"qualityNote": if ignore_for_kpi { Some("local_fallback is diagnostics-only and is not accepted as activity proof") } else { None },
|
||||
"sampleSeconds": sample_seconds,
|
||||
"pollSeconds": sample_seconds,
|
||||
"hostname": record.hostname,
|
||||
"source": "awatch-agent-rs",
|
||||
"collectorSource": record.diagnostics.collector_source,
|
||||
"sessionsCollectedTotal": record.diagnostics.sessions_collected_total,
|
||||
"rdpSessionsTotal": record.diagnostics.rdp_sessions_total,
|
||||
"activeSessionsTotal": record.diagnostics.active_sessions_total,
|
||||
"collectorError": record.diagnostics.collector_error,
|
||||
}
|
||||
});
|
||||
post_json_with_retry(
|
||||
&client,
|
||||
&format!(
|
||||
"{}/buckets/{}/heartbeat?pulsetime=180",
|
||||
self.aw_api_base, bucket_id
|
||||
),
|
||||
&payload,
|
||||
self.retry_attempts,
|
||||
)
|
||||
.context("publish ActivityWatch worktime heartbeat")?;
|
||||
sent += 1;
|
||||
}
|
||||
Ok(sent)
|
||||
}
|
||||
|
||||
pub fn spool(&self, record: &TelemetryRecord) -> Result<PathBuf> {
|
||||
fs::create_dir_all(&self.spool_dir)
|
||||
.with_context(|| format!("create worktime spool {}", self.spool_dir.display()))?;
|
||||
let file_name = format!(
|
||||
"{}-{}.json",
|
||||
record.timestamp.format("%Y%m%dT%H%M%S%.3fZ"),
|
||||
sanitize_file_part(&record.agent_id)
|
||||
);
|
||||
let path = self.spool_dir.join(file_name);
|
||||
fs::write(&path, serde_json::to_vec(record)?)
|
||||
.with_context(|| format!("write worktime spool {}", path.display()))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn flush_spool(&self) -> Result<usize> {
|
||||
flush_spool_dir(&self.spool_dir, |record| self.publish(record).map(|_| ()))
|
||||
}
|
||||
}
|
||||
|
||||
fn ignored_for_kpi(record: &TelemetryRecord, session: &SessionInfo) -> bool {
|
||||
record.diagnostics.collector_source == "local_fallback"
|
||||
|| session.session_source.as_deref() == Some("local_fallback")
|
||||
}
|
||||
|
||||
fn ensure_aw_bucket(
|
||||
client: &Client,
|
||||
aw_api_base: &str,
|
||||
bucket_id: &str,
|
||||
client_name: &str,
|
||||
bucket_type: &str,
|
||||
hostname: &str,
|
||||
) -> Result<()> {
|
||||
let bucket_url = format!("{}/buckets/{}", aw_api_base, bucket_id);
|
||||
if client
|
||||
.get(&bucket_url)
|
||||
.send()
|
||||
.and_then(|response| response.error_for_status())
|
||||
.is_ok()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let body = serde_json::json!({
|
||||
"client": client_name,
|
||||
"type": bucket_type,
|
||||
"hostname": hostname,
|
||||
});
|
||||
post_json_with_retry(client, &bucket_url, &body, 3)
|
||||
.context("create ActivityWatch worktime bucket")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn post_json_with_retry(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
payload: &serde_json::Value,
|
||||
retry_attempts: u32,
|
||||
) -> Result<()> {
|
||||
let mut last_error = None;
|
||||
for attempt in 0..retry_attempts.max(1) {
|
||||
let result = client
|
||||
.post(url)
|
||||
.json(payload)
|
||||
.send()
|
||||
.and_then(|response| response.error_for_status())
|
||||
.map(|_| ());
|
||||
match result {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
last_error = Some(err);
|
||||
let backoff = Duration::from_millis(250 * u64::from(attempt + 1));
|
||||
thread::sleep(backoff);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(anyhow!(
|
||||
"HTTP POST failed: {}",
|
||||
last_error
|
||||
.map(|err| err.to_string())
|
||||
.unwrap_or_else(|| "unknown error".to_string())
|
||||
))
|
||||
}
|
||||
|
||||
fn session_id_number(session: &SessionInfo) -> i64 {
|
||||
session
|
||||
.session_id
|
||||
.split(|ch: char| !ch.is_ascii_digit())
|
||||
.find(|part| !part.is_empty())
|
||||
.and_then(|part| part.parse::<i64>().ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn sanitize_bucket_part(value: &str) -> String {
|
||||
value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn flush_spool_dir<F>(spool_dir: &Path, mut sender: F) -> Result<usize>
|
||||
where
|
||||
F: FnMut(&TelemetryRecord) -> Result<()>,
|
||||
{
|
||||
if !spool_dir.exists() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut sent = 0;
|
||||
let mut entries = fs::read_dir(spool_dir)
|
||||
.with_context(|| format!("read spool {}", spool_dir.display()))?
|
||||
.filter_map(|entry| entry.ok())
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.extension().is_some_and(|ext| ext == "json"))
|
||||
.collect::<Vec<_>>();
|
||||
entries.sort();
|
||||
for path in entries {
|
||||
let data = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
|
||||
let record: TelemetryRecord =
|
||||
serde_json::from_slice(&data).with_context(|| format!("parse {}", path.display()))?;
|
||||
sender(&record)?;
|
||||
fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
|
||||
sent += 1;
|
||||
}
|
||||
Ok(sent)
|
||||
}
|
||||
|
||||
fn sanitize_file_part(value: &str) -> String {
|
||||
value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn spool_health(spool_dir: &Path) -> serde_json::Value {
|
||||
let telemetry_queued = count_spool_json_files(spool_dir);
|
||||
let worktime_spool_dir = spool_dir.join("aw-worktime");
|
||||
let worktime_queued = count_spool_json_files(&worktime_spool_dir);
|
||||
serde_json::json!({
|
||||
"generated_at_utc": Utc::now(),
|
||||
"spool_dir": spool_dir.display().to_string(),
|
||||
"worktime_spool_dir": worktime_spool_dir.display().to_string(),
|
||||
"queued": telemetry_queued,
|
||||
"telemetry_queued": telemetry_queued,
|
||||
"worktime_queued": worktime_queued,
|
||||
"total_queued": telemetry_queued + worktime_queued,
|
||||
})
|
||||
}
|
||||
|
||||
fn count_spool_json_files(spool_dir: &Path) -> usize {
|
||||
fs::read_dir(spool_dir)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flat_map(|entries| entries.filter_map(|entry| entry.ok()))
|
||||
.filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json"))
|
||||
.count()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::*;
|
||||
use crate::telemetry::{TelemetryRecord, diagnostics_for_sessions, empty_workforce_activity};
|
||||
|
||||
fn record() -> TelemetryRecord {
|
||||
TelemetryRecord {
|
||||
agent_id: "agent/1".to_string(),
|
||||
hostname: "HOST-EXAMPLE".to_string(),
|
||||
os_name: "Linux".to_string(),
|
||||
os_version: "test".to_string(),
|
||||
platform: "linux".to_string(),
|
||||
username: "user".to_string(),
|
||||
domain: "".to_string(),
|
||||
timestamp: Utc::now(),
|
||||
uptime_seconds: 1,
|
||||
cpu_usage_percent: 0.0,
|
||||
memory_total: 1,
|
||||
memory_used: 1,
|
||||
active_sessions: Vec::new(),
|
||||
rdp_sessions: Vec::new(),
|
||||
ssh_sessions: Vec::new(),
|
||||
processes: Vec::new(),
|
||||
network_interfaces: Vec::new(),
|
||||
network_connections: Vec::new(),
|
||||
workforce_activity: empty_workforce_activity(),
|
||||
security_events: Vec::new(),
|
||||
diagnostics: diagnostics_for_sessions(&[], &[], "test", None),
|
||||
collector_version: "test".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spools_and_flushes_records() {
|
||||
let dir = tempdir().unwrap();
|
||||
let config = AgentConfig {
|
||||
spool_dir: dir.path().to_path_buf(),
|
||||
..AgentConfig::default()
|
||||
};
|
||||
let transport = TelemetryTransport::new(&config);
|
||||
let path = transport.spool(&record()).unwrap();
|
||||
assert!(path.is_file());
|
||||
let mut seen = 0;
|
||||
let flushed = flush_spool_dir(dir.path(), |_| {
|
||||
seen += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(flushed, 1);
|
||||
assert_eq!(seen, 1);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_or_spool_preserves_record_when_server_is_unavailable() {
|
||||
let dir = tempdir().unwrap();
|
||||
let config = AgentConfig {
|
||||
server_url: "http://127.0.0.1:9/api/telemetry".to_string(),
|
||||
retry_attempts: 1,
|
||||
timeout_seconds: 1,
|
||||
spool_dir: dir.path().to_path_buf(),
|
||||
..AgentConfig::default()
|
||||
};
|
||||
let transport = TelemetryTransport::new(&config);
|
||||
assert!(transport.send_or_spool(&record()).is_err());
|
||||
let queued = fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json"))
|
||||
.count();
|
||||
assert_eq!(queued, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flush_spool_keeps_record_when_sender_fails() {
|
||||
let dir = tempdir().unwrap();
|
||||
let config = AgentConfig {
|
||||
spool_dir: dir.path().to_path_buf(),
|
||||
..AgentConfig::default()
|
||||
};
|
||||
let transport = TelemetryTransport::new(&config);
|
||||
let path = transport.spool(&record()).unwrap();
|
||||
let result = flush_spool_dir(dir.path(), |_| anyhow::bail!("transport down"));
|
||||
assert!(result.is_err());
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_id_number_extracts_numeric_id() {
|
||||
let session = SessionInfo {
|
||||
session_id: "rdp-12-user".to_string(),
|
||||
username: "user".to_string(),
|
||||
session_type: "rdp".to_string(),
|
||||
session_source: Some("wts_api".to_string()),
|
||||
remote_addr: None,
|
||||
started_at: None,
|
||||
active: true,
|
||||
};
|
||||
assert_eq!(session_id_number(&session), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_fallback_sessions_are_diagnostics_only_for_kpi() {
|
||||
let mut wts_record = record();
|
||||
wts_record.diagnostics = diagnostics_for_sessions(&[], &[], "wts_api", None);
|
||||
let session = SessionInfo {
|
||||
session_id: "0".to_string(),
|
||||
username: "user".to_string(),
|
||||
session_type: "local".to_string(),
|
||||
session_source: Some("local_fallback".to_string()),
|
||||
remote_addr: None,
|
||||
started_at: None,
|
||||
active: true,
|
||||
};
|
||||
assert!(ignored_for_kpi(&wts_record, &session));
|
||||
|
||||
let mut fallback_record = record();
|
||||
fallback_record.diagnostics = diagnostics_for_sessions(&[], &[], "local_fallback", None);
|
||||
let session = SessionInfo {
|
||||
session_source: Some("wts_api".to_string()),
|
||||
..session
|
||||
};
|
||||
assert!(ignored_for_kpi(&fallback_record, &session));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktime_publisher_is_disabled_by_default() {
|
||||
assert!(AwWorktimePublisher::new(&AgentConfig::default()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktime_publisher_spools_to_separate_dir() {
|
||||
let dir = tempdir().unwrap();
|
||||
let config = AgentConfig {
|
||||
aw_api_base: Some("http://127.0.0.1:9/api/0".to_string()),
|
||||
aw_worktime_enabled: true,
|
||||
spool_dir: dir.path().to_path_buf(),
|
||||
..AgentConfig::default()
|
||||
};
|
||||
let publisher = AwWorktimePublisher::new(&config).unwrap();
|
||||
let path = publisher.spool(&record()).unwrap();
|
||||
assert!(path.starts_with(dir.path().join("aw-worktime")));
|
||||
assert!(path.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spool_health_reports_telemetry_and_worktime_backlog() {
|
||||
let dir = tempdir().unwrap();
|
||||
let config = AgentConfig {
|
||||
aw_api_base: Some("http://127.0.0.1:9/api/0".to_string()),
|
||||
aw_worktime_enabled: true,
|
||||
spool_dir: dir.path().to_path_buf(),
|
||||
..AgentConfig::default()
|
||||
};
|
||||
let transport = TelemetryTransport::new(&config);
|
||||
let publisher = AwWorktimePublisher::new(&config).unwrap();
|
||||
transport.spool(&record()).unwrap();
|
||||
publisher.spool(&record()).unwrap();
|
||||
|
||||
let health = spool_health(dir.path());
|
||||
assert_eq!(health["queued"].as_u64(), Some(1));
|
||||
assert_eq!(health["telemetry_queued"].as_u64(), Some(1));
|
||||
assert_eq!(health["worktime_queued"].as_u64(), Some(1));
|
||||
assert_eq!(health["total_queued"].as_u64(), Some(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "awatch-agent"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
clap.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
tiny_http.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,174 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AgentConfig {
|
||||
pub agent_id: String,
|
||||
pub host_id: String,
|
||||
pub platform: String,
|
||||
pub server_url: String,
|
||||
pub spool_dir: PathBuf,
|
||||
pub health_bind: String,
|
||||
pub request_timeout_seconds: u64,
|
||||
pub retry_max_attempts: u32,
|
||||
pub retry_base_backoff_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for AgentConfig {
|
||||
fn default() -> Self {
|
||||
let hostname = local_hostname();
|
||||
Self {
|
||||
agent_id: uuid_from_seed(&format!("agent:{hostname}")),
|
||||
host_id: uuid_from_seed(&format!("host:{hostname}")),
|
||||
platform: current_platform().to_string(),
|
||||
server_url: "http://127.0.0.1:9/api/agent/telemetry".to_string(),
|
||||
spool_dir: default_spool_dir(),
|
||||
health_bind: "127.0.0.1:8787".to_string(),
|
||||
request_timeout_seconds: 10,
|
||||
retry_max_attempts: 3,
|
||||
retry_base_backoff_ms: 250,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentConfig {
|
||||
pub fn load(path: &Path) -> Result<Self> {
|
||||
let text = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
|
||||
Self::parse_toml_like(&text)
|
||||
}
|
||||
|
||||
pub fn parse_toml_like(text: &str) -> Result<Self> {
|
||||
let mut config = Self::default();
|
||||
for raw in text.lines() {
|
||||
let line = raw.split('#').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let key = key.trim();
|
||||
let value = value.trim().trim_matches('"');
|
||||
match key {
|
||||
"agent_id" => config.agent_id = value.to_string(),
|
||||
"host_id" => config.host_id = value.to_string(),
|
||||
"platform" => config.platform = value.to_string(),
|
||||
"server_url" => config.server_url = value.to_string(),
|
||||
"spool_dir" => config.spool_dir = PathBuf::from(value),
|
||||
"health_bind" => config.health_bind = value.to_string(),
|
||||
"request_timeout_seconds" => {
|
||||
config.request_timeout_seconds = value.parse().unwrap_or(10)
|
||||
}
|
||||
"retry_max_attempts" => config.retry_max_attempts = value.parse().unwrap_or(3),
|
||||
"retry_base_backoff_ms" => {
|
||||
config.retry_base_backoff_ms = value.parse().unwrap_or(250)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn request_timeout(&self) -> Duration {
|
||||
Duration::from_secs(self.request_timeout_seconds)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_config_path() -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
PathBuf::from(r"C:\ProgramData\AWatch-rus\agent\awatch-agent.toml")
|
||||
} else {
|
||||
PathBuf::from("/etc/awatch-agent/awatch-agent.toml")
|
||||
}
|
||||
}
|
||||
|
||||
fn default_spool_dir() -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
PathBuf::from(r"C:\ProgramData\AWatch-rus\agent\spool")
|
||||
} else {
|
||||
PathBuf::from("/var/lib/awatch-agent/spool")
|
||||
}
|
||||
}
|
||||
|
||||
fn current_platform() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macos"
|
||||
} else if cfg!(target_os = "freebsd") {
|
||||
"freebsd"
|
||||
} else {
|
||||
"linux"
|
||||
}
|
||||
}
|
||||
|
||||
fn local_hostname() -> String {
|
||||
std::env::var("COMPUTERNAME")
|
||||
.or_else(|_| std::env::var("HOSTNAME"))
|
||||
.unwrap_or_else(|_| "HOST-EXAMPLE".to_string())
|
||||
}
|
||||
|
||||
fn uuid_from_seed(seed: &str) -> String {
|
||||
let digest = Sha256::digest(seed.as_bytes());
|
||||
let mut bytes = [0_u8; 16];
|
||||
bytes.copy_from_slice(&digest[..16]);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x50;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
format!(
|
||||
"{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
||||
bytes[0],
|
||||
bytes[1],
|
||||
bytes[2],
|
||||
bytes[3],
|
||||
bytes[4],
|
||||
bytes[5],
|
||||
bytes[6],
|
||||
bytes[7],
|
||||
bytes[8],
|
||||
bytes[9],
|
||||
bytes[10],
|
||||
bytes[11],
|
||||
bytes[12],
|
||||
bytes[13],
|
||||
bytes[14],
|
||||
bytes[15]
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_config_without_external_toml_dependency() {
|
||||
let config = AgentConfig::parse_toml_like(
|
||||
r#"
|
||||
agent_id = "00000000-0000-5000-8000-000000000001"
|
||||
host_id = "00000000-0000-5000-8000-000000000002"
|
||||
platform = "windows"
|
||||
server_url = "https://awatch.example/api/agent/telemetry"
|
||||
spool_dir = "/tmp/awatch-agent-spool"
|
||||
health_bind = "127.0.0.1:8788"
|
||||
request_timeout_seconds = 2
|
||||
retry_max_attempts = 5
|
||||
retry_base_backoff_ms = 50
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config.platform, "windows");
|
||||
assert_eq!(config.retry_max_attempts, 5);
|
||||
assert_eq!(config.spool_dir, PathBuf::from("/tmp/awatch-agent-spool"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_ids_are_uuid_shaped() {
|
||||
let id = uuid_from_seed("HOST-EXAMPLE");
|
||||
assert_eq!(id.len(), 36);
|
||||
assert_eq!(&id[14..15], "5");
|
||||
assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::AgentConfig;
|
||||
|
||||
pub const AGENT_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TelemetryEnvelope {
|
||||
pub agent_id: String,
|
||||
pub host_id: String,
|
||||
pub platform: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub records: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Heartbeat {
|
||||
pub agent_version: String,
|
||||
pub platform: String,
|
||||
pub status: AgentStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AgentStatus {
|
||||
Online,
|
||||
Degraded,
|
||||
Offline,
|
||||
}
|
||||
|
||||
impl TelemetryEnvelope {
|
||||
pub fn empty(config: &AgentConfig) -> Self {
|
||||
Self {
|
||||
agent_id: config.agent_id.clone(),
|
||||
host_id: config.host_id.clone(),
|
||||
platform: config.platform.clone(),
|
||||
timestamp: Utc::now(),
|
||||
records: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn heartbeat(config: &AgentConfig) -> Self {
|
||||
let heartbeat = Heartbeat {
|
||||
agent_version: AGENT_VERSION.to_string(),
|
||||
platform: config.platform.clone(),
|
||||
status: AgentStatus::Online,
|
||||
};
|
||||
Self {
|
||||
records: vec![serde_json::json!({
|
||||
"type": "heartbeat",
|
||||
"payload": heartbeat,
|
||||
})],
|
||||
..Self::empty(config)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn heartbeat_contract_is_stable_and_contains_no_inventory() {
|
||||
let config = AgentConfig::default();
|
||||
let envelope = TelemetryEnvelope::heartbeat(&config);
|
||||
let value = serde_json::to_value(&envelope).unwrap();
|
||||
assert_eq!(value["agent_id"], config.agent_id);
|
||||
assert_eq!(value["host_id"], config.host_id);
|
||||
assert_eq!(value["platform"], config.platform);
|
||||
assert!(value["records"].is_array());
|
||||
assert_eq!(value["records"][0]["type"], "heartbeat");
|
||||
assert_eq!(value["records"][0]["payload"]["status"], "online");
|
||||
assert!(value["records"][0]["payload"].get("hostname").is_none());
|
||||
assert!(value["records"][0]["payload"].get("processes").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tiny_http::{Header, Response, Server, StatusCode};
|
||||
|
||||
use crate::envelope::AGENT_VERSION;
|
||||
use crate::metrics::AgentMetrics;
|
||||
|
||||
pub fn serve_health(bind: &str, metrics: AgentMetrics, max_requests: Option<usize>) -> Result<()> {
|
||||
bind.to_socket_addrs()
|
||||
.with_context(|| format!("parse health bind address {bind}"))?;
|
||||
let server =
|
||||
Server::http(bind).map_err(|err| anyhow::anyhow!("bind health endpoint: {err}"))?;
|
||||
let mut served = 0_usize;
|
||||
loop {
|
||||
if max_requests.is_some_and(|limit| served >= limit) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(request) = server
|
||||
.recv_timeout(Duration::from_millis(250))
|
||||
.map_err(|err| anyhow::anyhow!("receive health request: {err}"))?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
served += 1;
|
||||
let response = match (request.method().as_str(), request.url()) {
|
||||
("GET", "/healthz") => json_response(serde_json::json!({
|
||||
"ok": true,
|
||||
"status": "online",
|
||||
"agent_version": AGENT_VERSION,
|
||||
})),
|
||||
("GET", "/metrics") => text_response(metrics.render_prometheus()),
|
||||
_ => Response::from_string("not found").with_status_code(StatusCode(404)),
|
||||
};
|
||||
request
|
||||
.respond(response)
|
||||
.map_err(|err| anyhow::anyhow!("send health response: {err}"))?;
|
||||
}
|
||||
}
|
||||
|
||||
fn json_response(value: serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
let mut response = Response::from_data(serde_json::to_vec(&value).unwrap_or_default());
|
||||
if let Ok(header) = Header::from_bytes("Content-Type", "application/json") {
|
||||
response.add_header(header);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn text_response(value: String) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
let mut response = Response::from_string(value);
|
||||
if let Ok(header) = Header::from_bytes("Content-Type", "text/plain; version=0.0.4") {
|
||||
response.add_header(header);
|
||||
}
|
||||
response
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use chrono::Utc;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct LogLine<'a> {
|
||||
timestamp: String,
|
||||
level: &'a str,
|
||||
agent_id: &'a str,
|
||||
component: &'a str,
|
||||
message: &'a str,
|
||||
}
|
||||
|
||||
pub fn log_json(agent_id: &str, level: &str, component: &str, message: &str) {
|
||||
let line = LogLine {
|
||||
timestamp: Utc::now().to_rfc3339(),
|
||||
level,
|
||||
agent_id,
|
||||
component,
|
||||
message,
|
||||
};
|
||||
if let Ok(json) = serde_json::to_string(&line) {
|
||||
eprintln!("{json}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn structured_log_shape_is_serializable() {
|
||||
let line = LogLine {
|
||||
timestamp: "2026-06-07T00:00:00Z".to_string(),
|
||||
level: "INFO",
|
||||
agent_id: "agent-1",
|
||||
component: "spool",
|
||||
message: "queued",
|
||||
};
|
||||
let value = serde_json::to_value(line).unwrap();
|
||||
assert_eq!(value["level"], "INFO");
|
||||
assert_eq!(value["component"], "spool");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
mod config;
|
||||
mod envelope;
|
||||
mod health;
|
||||
mod logging;
|
||||
mod metrics;
|
||||
mod spool;
|
||||
mod transport;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
|
||||
use config::{AgentConfig, default_config_path};
|
||||
use envelope::TelemetryEnvelope;
|
||||
use logging::log_json;
|
||||
use spool::LocalSpool;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(about = "AWatch-rus Rust agent baseline scaffold")]
|
||||
struct Cli {
|
||||
#[arg(long, env = "AWATCH_AGENT_CONFIG")]
|
||||
config: Option<PathBuf>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_SERVER_URL")]
|
||||
server_url: Option<String>,
|
||||
|
||||
#[arg(long, env = "AWATCH_AGENT_SPOOL_DIR")]
|
||||
spool_dir: Option<PathBuf>,
|
||||
|
||||
#[arg(long)]
|
||||
enqueue_heartbeat: bool,
|
||||
|
||||
#[arg(long)]
|
||||
flush_spool: bool,
|
||||
|
||||
#[arg(long)]
|
||||
metrics: bool,
|
||||
|
||||
#[arg(long)]
|
||||
healthz: bool,
|
||||
|
||||
#[arg(long)]
|
||||
print_envelope: bool,
|
||||
|
||||
#[arg(long)]
|
||||
max_health_requests: Option<usize>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let code = match run() {
|
||||
Ok(code) => code,
|
||||
Err(err) => {
|
||||
eprintln!("{err:#}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
fn run() -> Result<i32> {
|
||||
let cli = Cli::parse();
|
||||
let mut config = load_config(cli.config.as_ref())?;
|
||||
if let Some(server_url) = cli.server_url {
|
||||
config.server_url = server_url;
|
||||
}
|
||||
if let Some(spool_dir) = cli.spool_dir {
|
||||
config.spool_dir = spool_dir;
|
||||
}
|
||||
let spool = LocalSpool::new(config.spool_dir.clone());
|
||||
let mut metrics = spool.metrics().unwrap_or_default();
|
||||
|
||||
if cli.print_envelope {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&TelemetryEnvelope::heartbeat(&config))?
|
||||
);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
if cli.enqueue_heartbeat {
|
||||
spool.enqueue(TelemetryEnvelope::heartbeat(&config))?;
|
||||
metrics.heartbeat_sent = metrics.heartbeat_sent.saturating_add(1);
|
||||
log_json(
|
||||
&config.agent_id,
|
||||
"INFO",
|
||||
"heartbeat",
|
||||
"heartbeat envelope queued",
|
||||
);
|
||||
}
|
||||
|
||||
if cli.flush_spool {
|
||||
let summary = transport::flush_with_retry(&config, &spool, &mut metrics)?;
|
||||
println!("{}", serde_json::to_string_pretty(&summary)?);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
if cli.metrics {
|
||||
let mut current = spool.metrics()?;
|
||||
current.heartbeat_sent = metrics.heartbeat_sent;
|
||||
current.retry_count = metrics.retry_count;
|
||||
print!("{}", current.render_prometheus());
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
if cli.healthz {
|
||||
health::serve_health(
|
||||
&config.health_bind,
|
||||
spool.metrics()?,
|
||||
cli.max_health_requests,
|
||||
)?;
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
if !cli.enqueue_heartbeat {
|
||||
log_json(&config.agent_id, "INFO", "agent", "no action requested");
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn load_config(path: Option<&PathBuf>) -> Result<AgentConfig> {
|
||||
let path = path.cloned().unwrap_or_else(default_config_path);
|
||||
if path.exists() {
|
||||
AgentConfig::load(&path)
|
||||
} else {
|
||||
AgentConfig::parse_toml_like("")
|
||||
.with_context(|| format!("load default config because {} is absent", path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn default_run_has_no_monitoring_side_effect() {
|
||||
let config = AgentConfig::parse_toml_like("").unwrap();
|
||||
let envelope = TelemetryEnvelope::heartbeat(&config);
|
||||
assert_eq!(envelope.records.len(), 1);
|
||||
assert!(envelope.records[0].get("processes").is_none());
|
||||
assert!(envelope.records[0].get("screenshots").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct AgentMetrics {
|
||||
pub queued_records: usize,
|
||||
pub retry_count: u64,
|
||||
pub heartbeat_sent: u64,
|
||||
pub spool_size: u64,
|
||||
}
|
||||
|
||||
impl AgentMetrics {
|
||||
pub fn render_prometheus(&self) -> String {
|
||||
format!(
|
||||
concat!(
|
||||
"# HELP awatch_agent_queued_records Local spool records waiting for delivery.\n",
|
||||
"# TYPE awatch_agent_queued_records gauge\n",
|
||||
"awatch_agent_queued_records {}\n",
|
||||
"# HELP awatch_agent_retry_count Total retry attempts performed by the agent.\n",
|
||||
"# TYPE awatch_agent_retry_count counter\n",
|
||||
"awatch_agent_retry_count {}\n",
|
||||
"# HELP awatch_agent_heartbeat_sent Heartbeat envelopes generated by the agent.\n",
|
||||
"# TYPE awatch_agent_heartbeat_sent counter\n",
|
||||
"awatch_agent_heartbeat_sent {}\n",
|
||||
"# HELP awatch_agent_spool_size Local spool size in bytes.\n",
|
||||
"# TYPE awatch_agent_spool_size gauge\n",
|
||||
"awatch_agent_spool_size {}\n"
|
||||
),
|
||||
self.queued_records, self.retry_count, self.heartbeat_sent, self.spool_size
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renders_prometheus_metrics() {
|
||||
let metrics = AgentMetrics {
|
||||
queued_records: 2,
|
||||
retry_count: 3,
|
||||
heartbeat_sent: 1,
|
||||
spool_size: 512,
|
||||
};
|
||||
let rendered = metrics.render_prometheus();
|
||||
assert!(rendered.contains("awatch_agent_queued_records 2"));
|
||||
assert!(rendered.contains("awatch_agent_retry_count 3"));
|
||||
assert!(rendered.contains("awatch_agent_heartbeat_sent 1"));
|
||||
assert!(rendered.contains("awatch_agent_spool_size 512"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::envelope::TelemetryEnvelope;
|
||||
use crate::metrics::AgentMetrics;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LocalSpool {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct SpoolItem {
|
||||
pub envelope: TelemetryEnvelope,
|
||||
pub enqueued_at: DateTime<Utc>,
|
||||
pub retry_count: u32,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
impl LocalSpool {
|
||||
pub fn new(root: impl Into<PathBuf>) -> Self {
|
||||
Self { root: root.into() }
|
||||
}
|
||||
|
||||
pub fn enqueue(&self, envelope: TelemetryEnvelope) -> Result<PathBuf> {
|
||||
self.ensure_dirs()?;
|
||||
let item = SpoolItem {
|
||||
envelope,
|
||||
enqueued_at: Utc::now(),
|
||||
retry_count: 0,
|
||||
last_error: None,
|
||||
};
|
||||
let file_name = format!(
|
||||
"{}-{}.json",
|
||||
item.enqueued_at.format("%Y%m%dT%H%M%S%.3fZ"),
|
||||
sanitize_file_part(&item.envelope.agent_id)
|
||||
);
|
||||
let path = self.pending_dir().join(file_name);
|
||||
write_json_atomic(&path, &item)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn pending_paths(&self) -> Result<Vec<PathBuf>> {
|
||||
read_json_paths(&self.pending_dir())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn dead_letter_paths(&self) -> Result<Vec<PathBuf>> {
|
||||
read_json_paths(&self.dead_letter_dir())
|
||||
}
|
||||
|
||||
pub fn metrics(&self) -> Result<AgentMetrics> {
|
||||
let paths = self.pending_paths()?;
|
||||
let spool_size = paths
|
||||
.iter()
|
||||
.filter_map(|path| fs::metadata(path).ok())
|
||||
.map(|metadata| metadata.len())
|
||||
.sum();
|
||||
Ok(AgentMetrics {
|
||||
queued_records: paths.len(),
|
||||
spool_size,
|
||||
..AgentMetrics::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn process_pending<F>(&self, max_retry_count: u32, mut sender: F) -> Result<FlushSummary>
|
||||
where
|
||||
F: FnMut(&TelemetryEnvelope) -> Result<()>,
|
||||
{
|
||||
self.ensure_dirs()?;
|
||||
let mut summary = FlushSummary::default();
|
||||
for path in self.pending_paths()? {
|
||||
let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
|
||||
let mut item = match serde_json::from_slice::<SpoolItem>(&bytes) {
|
||||
Ok(item) => item,
|
||||
Err(err) => {
|
||||
self.move_to_dead_letter(&path, Some(format!("corrupt json: {err}")))?;
|
||||
summary.corrupt += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match sender(&item.envelope) {
|
||||
Ok(()) => {
|
||||
fs::remove_file(&path)
|
||||
.with_context(|| format!("remove delivered {}", path.display()))?;
|
||||
summary.delivered += 1;
|
||||
}
|
||||
Err(err) => {
|
||||
item.retry_count = item.retry_count.saturating_add(1);
|
||||
item.last_error = Some(err.to_string());
|
||||
summary.retried += 1;
|
||||
if item.retry_count >= max_retry_count {
|
||||
write_json_atomic(&path, &item)?;
|
||||
self.move_to_dead_letter(&path, item.last_error.clone())?;
|
||||
summary.dead_lettered += 1;
|
||||
} else {
|
||||
write_json_atomic(&path, &item)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
fn ensure_dirs(&self) -> Result<()> {
|
||||
fs::create_dir_all(self.pending_dir())
|
||||
.with_context(|| format!("create {}", self.pending_dir().display()))?;
|
||||
fs::create_dir_all(self.dead_letter_dir())
|
||||
.with_context(|| format!("create {}", self.dead_letter_dir().display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pending_dir(&self) -> PathBuf {
|
||||
self.root.join("pending")
|
||||
}
|
||||
|
||||
fn dead_letter_dir(&self) -> PathBuf {
|
||||
self.root.join("dead-letter")
|
||||
}
|
||||
|
||||
fn move_to_dead_letter(&self, path: &Path, reason: Option<String>) -> Result<()> {
|
||||
self.ensure_dirs()?;
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.map(|value| value.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("{}.json", Utc::now().timestamp_millis()));
|
||||
let target = self.dead_letter_dir().join(file_name);
|
||||
if let Some(reason) = reason {
|
||||
let note_path = target.with_extension("reason.txt");
|
||||
fs::write(note_path, reason)?;
|
||||
}
|
||||
fs::rename(path, target).or_else(|_| {
|
||||
fs::copy(path, self.dead_letter_dir().join("recovered-corrupt.json"))?;
|
||||
fs::remove_file(path)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct FlushSummary {
|
||||
pub delivered: usize,
|
||||
pub retried: usize,
|
||||
pub dead_lettered: usize,
|
||||
pub corrupt: usize,
|
||||
}
|
||||
|
||||
fn read_json_paths(dir: &Path) -> Result<Vec<PathBuf>> {
|
||||
if !dir.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut paths = fs::read_dir(dir)
|
||||
.with_context(|| format!("read {}", dir.display()))?
|
||||
.filter_map(|entry| entry.ok())
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.extension().is_some_and(|ext| ext == "json"))
|
||||
.collect::<Vec<_>>();
|
||||
paths.sort();
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<()> {
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
fs::write(&tmp, serde_json::to_vec_pretty(value)?)
|
||||
.with_context(|| format!("write {}", tmp.display()))?;
|
||||
fs::rename(&tmp, path)
|
||||
.with_context(|| format!("rename {} to {}", tmp.display(), path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sanitize_file_part(value: &str) -> String {
|
||||
value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::anyhow;
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::*;
|
||||
use crate::config::AgentConfig;
|
||||
|
||||
fn envelope() -> TelemetryEnvelope {
|
||||
TelemetryEnvelope::heartbeat(&AgentConfig::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enqueues_and_delivers_spool_item() {
|
||||
let dir = tempdir().unwrap();
|
||||
let spool = LocalSpool::new(dir.path());
|
||||
spool.enqueue(envelope()).unwrap();
|
||||
assert_eq!(spool.pending_paths().unwrap().len(), 1);
|
||||
|
||||
let summary = spool.process_pending(3, |_| Ok(())).unwrap();
|
||||
assert_eq!(summary.delivered, 1);
|
||||
assert_eq!(spool.pending_paths().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_keeps_item_until_max_retry_then_dead_letters() {
|
||||
let dir = tempdir().unwrap();
|
||||
let spool = LocalSpool::new(dir.path());
|
||||
spool.enqueue(envelope()).unwrap();
|
||||
|
||||
let first = spool
|
||||
.process_pending(2, |_| Err(anyhow!("transport down")))
|
||||
.unwrap();
|
||||
assert_eq!(first.retried, 1);
|
||||
assert_eq!(first.dead_lettered, 0);
|
||||
assert_eq!(spool.pending_paths().unwrap().len(), 1);
|
||||
|
||||
let second = spool
|
||||
.process_pending(2, |_| Err(anyhow!("transport down")))
|
||||
.unwrap();
|
||||
assert_eq!(second.dead_lettered, 1);
|
||||
assert_eq!(spool.pending_paths().unwrap().len(), 0);
|
||||
assert_eq!(spool.dead_letter_paths().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_spool_item_moves_to_dead_letter() {
|
||||
let dir = tempdir().unwrap();
|
||||
let spool = LocalSpool::new(dir.path());
|
||||
fs::create_dir_all(dir.path().join("pending")).unwrap();
|
||||
fs::write(dir.path().join("pending/bad.json"), b"{not-json").unwrap();
|
||||
|
||||
let summary = spool.process_pending(3, |_| Ok(())).unwrap();
|
||||
assert_eq!(summary.corrupt, 1);
|
||||
assert_eq!(spool.pending_paths().unwrap().len(), 0);
|
||||
assert_eq!(spool.dead_letter_paths().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metrics_report_queue_and_size() {
|
||||
let dir = tempdir().unwrap();
|
||||
let spool = LocalSpool::new(dir.path());
|
||||
spool.enqueue(envelope()).unwrap();
|
||||
let metrics = spool.metrics().unwrap();
|
||||
assert_eq!(metrics.queued_records, 1);
|
||||
assert!(metrics.spool_size > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use reqwest::blocking::Client;
|
||||
|
||||
use crate::config::AgentConfig;
|
||||
use crate::envelope::TelemetryEnvelope;
|
||||
use crate::metrics::AgentMetrics;
|
||||
use crate::spool::{FlushSummary, LocalSpool};
|
||||
|
||||
pub fn send_envelope(config: &AgentConfig, envelope: &TelemetryEnvelope) -> Result<()> {
|
||||
let client = Client::builder()
|
||||
.timeout(config.request_timeout())
|
||||
.build()
|
||||
.context("build agent telemetry HTTP client")?;
|
||||
client
|
||||
.post(&config.server_url)
|
||||
.json(envelope)
|
||||
.send()
|
||||
.and_then(|response| response.error_for_status())
|
||||
.map(|_| ())
|
||||
.map_err(|err| anyhow!("agent telemetry POST failed: {err}"))
|
||||
}
|
||||
|
||||
pub fn flush_with_retry(
|
||||
config: &AgentConfig,
|
||||
spool: &LocalSpool,
|
||||
metrics: &mut AgentMetrics,
|
||||
) -> Result<FlushSummary> {
|
||||
let mut attempt = 0_u32;
|
||||
loop {
|
||||
let summary = spool.process_pending(config.retry_max_attempts, |envelope| {
|
||||
send_envelope(config, envelope)
|
||||
})?;
|
||||
metrics.retry_count = metrics
|
||||
.retry_count
|
||||
.saturating_add(u64::try_from(summary.retried).unwrap_or(u64::MAX));
|
||||
if summary.retried == 0 || attempt + 1 >= config.retry_max_attempts {
|
||||
return Ok(summary);
|
||||
}
|
||||
let backoff = exponential_backoff(config.retry_base_backoff_ms, attempt);
|
||||
thread::sleep(backoff);
|
||||
attempt += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exponential_backoff(base_ms: u64, attempt: u32) -> Duration {
|
||||
let factor = 1_u64.checked_shl(attempt.min(10)).unwrap_or(1024);
|
||||
Duration::from_millis(base_ms.saturating_mul(factor))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backoff_is_exponential_and_bounded() {
|
||||
assert_eq!(exponential_backoff(100, 0), Duration::from_millis(100));
|
||||
assert_eq!(exponential_backoff(100, 3), Duration::from_millis(800));
|
||||
assert_eq!(exponential_backoff(100, 99), Duration::from_millis(102400));
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ use sha2::{Digest, Sha256};
|
||||
|
||||
const DEFAULT_KIT_DIR: &str = "install-kit-awindows-20260427-211240";
|
||||
const MANIFEST_NAME: &str = "MANIFEST.txt";
|
||||
const ALLOWED_KIT_ONLY_FILES: &[&str] = &["README-INSTALL-KIT.txt"];
|
||||
const ALLOWED_KIT_ONLY_FILES: &[&str] =
|
||||
&["README-INSTALL-KIT.txt", "windows/aw-windows-telemetry.exe"];
|
||||
const ALLOWED_KIT_ONLY_PREFIXES: &[&str] = &["server-configs-"];
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
|
||||
@@ -15,6 +15,7 @@ use serde_json::Value;
|
||||
const DEFAULT_AW_API: &str = "http://192.0.2.13:5600/api/0";
|
||||
const DEFAULT_WORKTIME_URL: &str = "http://192.0.2.13:5610";
|
||||
const DEFAULT_ONE_C_URL: &str = "http://192.0.2.2:8710";
|
||||
const DEFAULT_RDP_HOST: &str = "198.51.100.18";
|
||||
const DEFAULT_HOSTNAME: &str = "HOST-EXAMPLE";
|
||||
const DEFAULT_GATEWAY_HOST: &str = "detmir.example.local";
|
||||
|
||||
@@ -33,6 +34,9 @@ struct Cli {
|
||||
#[arg(long, default_value = DEFAULT_ONE_C_URL)]
|
||||
one_c_url: String,
|
||||
|
||||
#[arg(long, default_value = DEFAULT_RDP_HOST)]
|
||||
rdp_host: String,
|
||||
|
||||
#[arg(long, default_value = DEFAULT_HOSTNAME)]
|
||||
hostname: String,
|
||||
|
||||
@@ -56,11 +60,27 @@ struct Cli {
|
||||
|
||||
#[arg(long, default_value_t = false)]
|
||||
disable_grafana_check: bool,
|
||||
|
||||
#[arg(long, default_value = "disabled")]
|
||||
security_events_backend: String,
|
||||
|
||||
#[arg(long, default_value = "http://127.0.0.1:8123")]
|
||||
clickhouse_url: String,
|
||||
|
||||
#[arg(long, default_value = "analytics_1c")]
|
||||
clickhouse_database: String,
|
||||
|
||||
#[arg(long, default_value = "default")]
|
||||
clickhouse_user: String,
|
||||
|
||||
#[arg(long, default_value = "")]
|
||||
clickhouse_password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum BucketMode {
|
||||
Fresh,
|
||||
InteractiveFresh,
|
||||
InactiveOk,
|
||||
EventDriven,
|
||||
}
|
||||
@@ -69,6 +89,7 @@ impl BucketMode {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Fresh => "fresh",
|
||||
Self::InteractiveFresh => "interactive_fresh",
|
||||
Self::InactiveOk => "inactive_ok",
|
||||
Self::EventDriven => "event_driven",
|
||||
}
|
||||
@@ -145,7 +166,7 @@ fn bucket_specs(hostname: &str) -> Vec<BucketSpec> {
|
||||
label: "AFK watcher",
|
||||
bucket: format!("aw-watcher-afk_{hostname}"),
|
||||
max_age_seconds: Some(15 * 60),
|
||||
mode: BucketMode::Fresh,
|
||||
mode: BucketMode::InteractiveFresh,
|
||||
},
|
||||
BucketSpec {
|
||||
label: "Window watcher",
|
||||
@@ -169,7 +190,7 @@ fn bucket_specs(hostname: &str) -> Vec<BucketSpec> {
|
||||
label: "DLP signals",
|
||||
bucket: format!("aw-dlp-endpoint-signals_{hostname}"),
|
||||
max_age_seconds: Some(10 * 60),
|
||||
mode: BucketMode::Fresh,
|
||||
mode: BucketMode::InteractiveFresh,
|
||||
},
|
||||
BucketSpec {
|
||||
label: "DLP incidents",
|
||||
@@ -298,13 +319,13 @@ fn service_checks(args: &Cli) -> Vec<ServiceCheck> {
|
||||
}
|
||||
|
||||
checks.push(tcp_check(
|
||||
"198.51.100.18",
|
||||
&args.rdp_host,
|
||||
5985,
|
||||
args.tcp_timeout_seconds,
|
||||
true,
|
||||
));
|
||||
checks.push(tcp_check(
|
||||
"198.51.100.18",
|
||||
&args.rdp_host,
|
||||
22,
|
||||
args.tcp_timeout_seconds,
|
||||
true,
|
||||
@@ -312,9 +333,97 @@ fn service_checks(args: &Cli) -> Vec<ServiceCheck> {
|
||||
if !args.disable_grafana_check {
|
||||
checks.push(grafana_data_check(args));
|
||||
}
|
||||
if security_events_clickhouse_enabled(args) {
|
||||
checks.push(clickhouse_security_events_check(args));
|
||||
}
|
||||
checks
|
||||
}
|
||||
|
||||
fn security_events_clickhouse_enabled(args: &Cli) -> bool {
|
||||
args.security_events_backend
|
||||
.trim()
|
||||
.eq_ignore_ascii_case("clickhouse")
|
||||
}
|
||||
|
||||
fn clickhouse_security_events_check(args: &Cli) -> ServiceCheck {
|
||||
let name = "security-events-clickhouse".to_string();
|
||||
let Some(database) = clickhouse_identifier(&args.clickhouse_database) else {
|
||||
return ServiceCheck {
|
||||
name,
|
||||
required: false,
|
||||
ok: false,
|
||||
url: None,
|
||||
payload: None,
|
||||
error: Some("invalid ClickHouse database identifier".to_string()),
|
||||
};
|
||||
};
|
||||
let timeout = Duration::from_secs(args.service_timeout_seconds.min(5));
|
||||
let sql = format!(
|
||||
"SELECT toUInt64(count()) AS events_24h FROM {database}.entity_timeline WHERE ts >= now() - INTERVAL 24 HOUR FORMAT JSONEachRow"
|
||||
);
|
||||
match clickhouse_query_first(args, &sql, timeout) {
|
||||
Ok(payload) => ServiceCheck {
|
||||
name,
|
||||
required: false,
|
||||
ok: true,
|
||||
url: Some(args.clickhouse_url.trim_end_matches('/').to_string()),
|
||||
payload: Some(payload.unwrap_or_else(|| serde_json::json!({"events_24h": 0}))),
|
||||
error: None,
|
||||
},
|
||||
Err(err) => ServiceCheck {
|
||||
name,
|
||||
required: false,
|
||||
ok: false,
|
||||
url: Some(args.clickhouse_url.trim_end_matches('/').to_string()),
|
||||
payload: None,
|
||||
error: Some(err.to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn clickhouse_identifier(value: &str) -> Option<String> {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty()
|
||||
|| !trimmed
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
fn clickhouse_query_first(args: &Cli, sql: &str, timeout: Duration) -> Result<Option<Value>> {
|
||||
let client = Client::builder()
|
||||
.timeout(timeout)
|
||||
.no_proxy()
|
||||
.build()
|
||||
.context("ClickHouse HTTP client")?;
|
||||
let mut request = client
|
||||
.post(args.clickhouse_url.trim_end_matches('/'))
|
||||
.query(&[("database", args.clickhouse_database.trim())])
|
||||
.body(sql.to_string());
|
||||
if !args.clickhouse_user.trim().is_empty() {
|
||||
request = request.basic_auth(
|
||||
args.clickhouse_user.trim().to_string(),
|
||||
Some(args.clickhouse_password.clone()),
|
||||
);
|
||||
}
|
||||
let text = request
|
||||
.send()
|
||||
.context("ClickHouse request")?
|
||||
.error_for_status()
|
||||
.context("ClickHouse HTTP status")?
|
||||
.text()
|
||||
.context("ClickHouse response body")?;
|
||||
let Some(line) = text.lines().map(str::trim).find(|line| !line.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(
|
||||
serde_json::from_str::<Value>(line).context("ClickHouse JSONEachRow")?,
|
||||
))
|
||||
}
|
||||
|
||||
fn grafana_data_check(args: &Cli) -> ServiceCheck {
|
||||
let name = "grafana-data".to_string();
|
||||
let output = read_grafana_check_json_from_ct(args);
|
||||
@@ -463,6 +572,7 @@ fn bucket_health(args: &Cli) -> Result<Vec<BucketCheck>> {
|
||||
Duration::from_secs(args.bucket_timeout_seconds),
|
||||
)?;
|
||||
let now = Utc::now();
|
||||
let interactive_required = interactive_required(&client, &args.hostname, now);
|
||||
let mut out = Vec::new();
|
||||
|
||||
for spec in bucket_specs(&args.hostname) {
|
||||
@@ -485,28 +595,8 @@ fn bucket_health(args: &Cli) -> Result<Vec<BucketCheck>> {
|
||||
Ok(Some(event)) => {
|
||||
let ts = event.timestamp_utc()?;
|
||||
let age = (now - ts).num_seconds();
|
||||
let status = match spec.mode {
|
||||
BucketMode::InactiveOk => {
|
||||
if spec.max_age_seconds.is_some_and(|max_age| age <= max_age) {
|
||||
"FRESH"
|
||||
} else {
|
||||
"INACTIVE"
|
||||
}
|
||||
}
|
||||
BucketMode::Fresh => {
|
||||
if spec.max_age_seconds.is_some_and(|max_age| age <= max_age) {
|
||||
"FRESH"
|
||||
} else {
|
||||
"STALE"
|
||||
}
|
||||
}
|
||||
BucketMode::EventDriven => "EVENT-DRIVEN",
|
||||
};
|
||||
let ok = match spec.mode {
|
||||
BucketMode::InactiveOk => true,
|
||||
BucketMode::Fresh => status == "FRESH",
|
||||
BucketMode::EventDriven => true,
|
||||
};
|
||||
let (status, ok) =
|
||||
classify_bucket(spec.mode, spec.max_age_seconds, age, interactive_required);
|
||||
out.push(BucketCheck {
|
||||
label: spec.label.to_string(),
|
||||
bucket: spec.bucket,
|
||||
@@ -519,17 +609,20 @@ fn bucket_health(args: &Cli) -> Result<Vec<BucketCheck>> {
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
Ok(None) => out.push(BucketCheck {
|
||||
label: spec.label.to_string(),
|
||||
bucket: spec.bucket,
|
||||
mode: spec.mode.as_str().to_string(),
|
||||
status: "DEAD".to_string(),
|
||||
ok: false,
|
||||
event_count_sample: Some(0),
|
||||
latest: None,
|
||||
age_seconds: None,
|
||||
error: None,
|
||||
}),
|
||||
Ok(None) => {
|
||||
let (status, ok) = classify_missing_bucket(spec.mode, interactive_required);
|
||||
out.push(BucketCheck {
|
||||
label: spec.label.to_string(),
|
||||
bucket: spec.bucket,
|
||||
mode: spec.mode.as_str().to_string(),
|
||||
status: status.to_string(),
|
||||
ok,
|
||||
event_count_sample: Some(0),
|
||||
latest: None,
|
||||
age_seconds: None,
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
Err(err) => out.push(BucketCheck {
|
||||
label: spec.label.to_string(),
|
||||
bucket: spec.bucket,
|
||||
@@ -546,6 +639,58 @@ fn bucket_health(args: &Cli) -> Result<Vec<BucketCheck>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn interactive_required(client: &ActivityWatchClient, hostname: &str, now: DateTime<Utc>) -> bool {
|
||||
let bucket = format!("aw-worktime-sessions_{hostname}");
|
||||
let Ok(Some(event)) = client.latest_event(&bucket) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(ts) = event.timestamp_utc() else {
|
||||
return false;
|
||||
};
|
||||
let age = (now - ts).num_seconds();
|
||||
let fresh = (0..=5 * 60).contains(&age);
|
||||
let active = event
|
||||
.data
|
||||
.get("active")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
fresh && active
|
||||
}
|
||||
|
||||
fn classify_bucket(
|
||||
mode: BucketMode,
|
||||
max_age_seconds: Option<i64>,
|
||||
age_seconds: i64,
|
||||
interactive_required: bool,
|
||||
) -> (&'static str, bool) {
|
||||
match mode {
|
||||
BucketMode::InactiveOk => {
|
||||
if max_age_seconds.is_some_and(|max_age| age_seconds <= max_age) {
|
||||
("FRESH", true)
|
||||
} else {
|
||||
("INACTIVE", true)
|
||||
}
|
||||
}
|
||||
BucketMode::InteractiveFresh if !interactive_required => ("INACTIVE", true),
|
||||
BucketMode::InteractiveFresh | BucketMode::Fresh => {
|
||||
if max_age_seconds.is_some_and(|max_age| age_seconds <= max_age) {
|
||||
("FRESH", true)
|
||||
} else {
|
||||
("STALE", false)
|
||||
}
|
||||
}
|
||||
BucketMode::EventDriven => ("EVENT-DRIVEN", true),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_missing_bucket(mode: BucketMode, interactive_required: bool) -> (&'static str, bool) {
|
||||
match mode {
|
||||
BucketMode::InteractiveFresh if !interactive_required => ("INACTIVE", true),
|
||||
BucketMode::EventDriven => ("EVENT-DRIVEN", true),
|
||||
_ => ("DEAD", false),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_report(args: &Cli) -> Result<CheckReport> {
|
||||
let services = service_checks(args);
|
||||
let buckets = bucket_health(args)?;
|
||||
@@ -630,8 +775,15 @@ fn main() -> Result<()> {
|
||||
args.aw_api = env_or_default("DETMIR_AW_API", &args.aw_api);
|
||||
args.worktime_url = env_or_default("DETMIR_WORKTIME_URL", &args.worktime_url);
|
||||
args.one_c_url = env_or_default("DETMIR_ONE_C_URL", &args.one_c_url);
|
||||
args.rdp_host = env_or_default("DETMIR_RDP_HOST", &args.rdp_host);
|
||||
args.hostname = env_or_default("DETMIR_HOSTNAME", &args.hostname);
|
||||
args.grafana_check_json = env_or_default("DETMIR_GRAFANA_CHECK_JSON", &args.grafana_check_json);
|
||||
args.security_events_backend =
|
||||
env_or_default("SECURITY_EVENTS_BACKEND", &args.security_events_backend);
|
||||
args.clickhouse_url = env_or_default("CLICKHOUSE_URL", &args.clickhouse_url);
|
||||
args.clickhouse_database = env_or_default("CLICKHOUSE_DATABASE", &args.clickhouse_database);
|
||||
args.clickhouse_user = env_or_default("CLICKHOUSE_USER", &args.clickhouse_user);
|
||||
args.clickhouse_password = env_or_default("CLICKHOUSE_PASSWORD", &args.clickhouse_password);
|
||||
|
||||
let report = build_report(&args)?;
|
||||
if args.json {
|
||||
@@ -645,3 +797,71 @@ fn main() -> Result<()> {
|
||||
exit_codes::CHECK_FAILED
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interactive_bucket_is_inactive_when_no_interactive_session() {
|
||||
let (status, ok) = classify_bucket(
|
||||
BucketMode::InteractiveFresh,
|
||||
Some(15 * 60),
|
||||
3 * 60 * 60,
|
||||
false,
|
||||
);
|
||||
assert_eq!(status, "INACTIVE");
|
||||
assert!(ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_bucket_is_stale_when_session_is_active() {
|
||||
let (status, ok) = classify_bucket(
|
||||
BucketMode::InteractiveFresh,
|
||||
Some(15 * 60),
|
||||
3 * 60 * 60,
|
||||
true,
|
||||
);
|
||||
assert_eq!(status, "STALE");
|
||||
assert!(!ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_interactive_bucket_is_inactive_when_no_interactive_session() {
|
||||
let (status, ok) = classify_missing_bucket(BucketMode::InteractiveFresh, false);
|
||||
assert_eq!(status, "INACTIVE");
|
||||
assert!(ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn security_events_backend_disabled_by_default() {
|
||||
let args = Cli::parse_from(["detmir-check"]);
|
||||
assert!(!security_events_clickhouse_enabled(&args));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn security_events_backend_clickhouse_is_optional() {
|
||||
let args = Cli::parse_from([
|
||||
"detmir-check",
|
||||
"--security-events-backend",
|
||||
"clickhouse",
|
||||
"--clickhouse-database",
|
||||
"analytics_1c",
|
||||
]);
|
||||
assert!(security_events_clickhouse_enabled(&args));
|
||||
assert_eq!(
|
||||
clickhouse_identifier(&args.clickhouse_database).as_deref(),
|
||||
Some("analytics_1c")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_database_identifier_rejects_injection() {
|
||||
assert_eq!(
|
||||
clickhouse_identifier("analytics_1c").as_deref(),
|
||||
Some("analytics_1c")
|
||||
);
|
||||
assert!(clickhouse_identifier("analytics_1c;DROP TABLE x").is_none());
|
||||
assert!(clickhouse_identifier("").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,37 @@
|
||||
#![deny(unsafe_op_in_unsafe_fn)]
|
||||
|
||||
//! Shared production primitives for AWatch-rus.
|
||||
//!
|
||||
//! This crate intentionally stays small and dependency-light. It contains the
|
||||
//! status, exit-code and runtime-configuration guardrails that are reused by
|
||||
//! operational binaries and health/check tooling. Keep business-specific portal,
|
||||
//! DLP or workforce logic out of this crate.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::{DateTime, SecondsFormat, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Normalized health/check status used by CLI tools, probes and JSON payloads.
|
||||
///
|
||||
/// CONTRACT: serialized values are uppercase and must remain stable because
|
||||
/// deployment scripts, smoke checks and dashboards can key off these strings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum StatusLevel {
|
||||
/// Component is healthy and the check passed.
|
||||
Ok,
|
||||
/// Component works, but a risk or degraded condition needs attention.
|
||||
Warn,
|
||||
/// Component check failed or a required dependency is unavailable.
|
||||
Fail,
|
||||
/// Component did not provide enough information for a reliable status.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl StatusLevel {
|
||||
/// Return the stable uppercase representation used in human and JSON output.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ok => "OK",
|
||||
@@ -23,6 +41,10 @@ impl StatusLevel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Map status to the process exit code expected by operational checks.
|
||||
///
|
||||
/// CONTRACT: `WARN` exits as a failed check rather than success so that
|
||||
/// automation does not silently ignore degraded production state.
|
||||
pub fn exit_code(self) -> i32 {
|
||||
match self {
|
||||
Self::Ok => exit_codes::OK,
|
||||
@@ -48,23 +70,39 @@ impl From<&str> for StatusLevel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable process exit codes for AWatch-rus operational binaries.
|
||||
///
|
||||
/// CONTRACT: keep these numeric values stable. Shell scripts, systemd units,
|
||||
/// smoke tests and runbooks can depend on them.
|
||||
pub mod exit_codes {
|
||||
/// Successful execution.
|
||||
pub const OK: i32 = 0;
|
||||
/// Unexpected runtime or IO error.
|
||||
pub const ERROR: i32 = 1;
|
||||
/// Health/check policy failed or returned a degraded status.
|
||||
pub const CHECK_FAILED: i32 = 2;
|
||||
/// A safety policy denied a requested action.
|
||||
pub const POLICY_DENIED: i32 = 3;
|
||||
}
|
||||
|
||||
/// Return the current UTC timestamp in compact RFC3339/Zulu format.
|
||||
pub fn now_utc_rfc3339() -> String {
|
||||
Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
|
||||
}
|
||||
|
||||
/// Parse an RFC3339 timestamp and normalize it to UTC.
|
||||
pub fn parse_utc_rfc3339(value: &str) -> Result<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc3339(value)
|
||||
.with_context(|| format!("invalid RFC3339 timestamp: {value}"))
|
||||
.map(|ts| ts.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
/// Runtime configuration guardrails.
|
||||
///
|
||||
/// SECURITY: these helpers are deliberately conservative. They reject empty,
|
||||
/// documentation, TEST-NET and common placeholder values before a component is
|
||||
/// allowed to run in production mode. This prevents demo-safe examples from
|
||||
/// accidentally becoming live runtime configuration.
|
||||
pub mod runtime_guard {
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
@@ -82,6 +120,11 @@ pub mod runtime_guard {
|
||||
"PASSWORD",
|
||||
];
|
||||
|
||||
/// Return true when a value looks like a public/demo placeholder.
|
||||
///
|
||||
/// RATIONALE: AWatch-rus documentation intentionally uses TEST-NET ranges
|
||||
/// and HOST-EXAMPLE markers. Production binaries should fail closed when
|
||||
/// such values reach runtime configuration.
|
||||
pub fn is_runtime_placeholder(value: &str) -> bool {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
@@ -106,6 +149,7 @@ pub mod runtime_guard {
|
||||
|| (normalized.starts_with('<') && normalized.ends_with('>'))
|
||||
}
|
||||
|
||||
/// Return true when a value is unsafe for a secret-like configuration field.
|
||||
pub fn is_secret_placeholder(value: &str) -> bool {
|
||||
is_runtime_placeholder(value)
|
||||
|| matches!(
|
||||
@@ -114,6 +158,10 @@ pub mod runtime_guard {
|
||||
)
|
||||
}
|
||||
|
||||
/// Ensure a required runtime value is not empty or demo-only.
|
||||
///
|
||||
/// SECURITY: callers should invoke this before opening network connections,
|
||||
/// starting ingestion or enabling exporters in production mode.
|
||||
pub fn ensure_runtime_value(name: &str, value: &str, context: &str) -> Result<()> {
|
||||
if is_runtime_placeholder(value) {
|
||||
bail!("{name} contains an empty/example/TEST-NET value while {context}");
|
||||
@@ -121,6 +169,7 @@ pub mod runtime_guard {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensure a required secret is not empty or an obvious placeholder.
|
||||
pub fn ensure_secret_value(name: &str, value: &str, context: &str) -> Result<()> {
|
||||
if is_secret_placeholder(value) {
|
||||
bail!("{name} contains an empty/example secret value while {context}");
|
||||
@@ -128,6 +177,7 @@ pub mod runtime_guard {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensure an iterator of runtime values is non-empty and production-safe.
|
||||
pub fn ensure_runtime_values<'a>(
|
||||
name: &str,
|
||||
values: impl IntoIterator<Item = &'a String>,
|
||||
@@ -144,6 +194,12 @@ pub mod runtime_guard {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate a complete InfluxDB exporter configuration block.
|
||||
///
|
||||
/// CONTRACT: when an exporter is enabled, URL, org, bucket, token and host
|
||||
/// list must all be real runtime values. A partial/demo exporter config is
|
||||
/// more dangerous than a disabled exporter because it creates false
|
||||
/// confidence in monitoring readiness.
|
||||
pub fn ensure_influx_runtime_config(
|
||||
prefix: &str,
|
||||
url: &str,
|
||||
|
||||
@@ -5,7 +5,7 @@ use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
|
||||
const DEFAULT_SSH_TARGET: &str = "igor@192.0.2.13";
|
||||
const DEFAULT_REMOTE_COMMAND: &str = "sudo -n /usr/local/bin/dlp-health-check --json";
|
||||
const DEFAULT_REMOTE_COMMAND: &str = "sudo -n env AW_DLP_HEALTH_ENDPOINT_SEND_FAILURE_WARN_COUNT=10 AW_DLP_HEALTH_FILEOPS_SEND_FAILURE_WARN_COUNT=10 /usr/local/bin/dlp-health-check --json";
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(about = "Run the DetMir DLP health check on the AW server over SSH.")]
|
||||
|
||||
@@ -21,3 +21,7 @@ tiny_http.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints.clippy]
|
||||
comparison_chain = "allow"
|
||||
search_is_some = "allow"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//! External command execution helpers for the portal.
|
||||
//!
|
||||
//! CONTRACT: these helpers are intentionally small and side-effect explicit.
|
||||
//! They preserve stdout/stderr error text because readiness verification APIs
|
||||
//! expose command failure diagnostics to operators.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
pub(crate) fn run_in_dir(dir: &Path, command: &mut Command) -> std::result::Result<(), String> {
|
||||
let output = command
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.map_err(|err| format!("run command in {}: {err}", dir.display()))?;
|
||||
if output.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)
|
||||
.trim()
|
||||
.to_string())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,362 @@
|
||||
export type ISODateTime = string;
|
||||
|
||||
export type PortalRole = "executive" | "manager" | "security" | "forensics" | "admin";
|
||||
export type RiskLevel = "LOW" | "MEDIUM" | "HIGH" | "CRITICAL" | "UNKNOWN";
|
||||
export type ReviewStatus =
|
||||
| "NEW"
|
||||
| "IN_REVIEW"
|
||||
| "CONFIRMED"
|
||||
| "FALSE_POSITIVE"
|
||||
| "POSTPONED";
|
||||
export type CaseStatus = "OPEN" | "IN_PROGRESS" | "RESOLVED" | "REJECTED" | "ARCHIVED";
|
||||
|
||||
export interface JsonObject {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface EndpointDescriptor {
|
||||
method: string;
|
||||
path: string;
|
||||
purpose?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ContractIndex {
|
||||
ok: boolean;
|
||||
contract_version: string;
|
||||
generated_by?: string;
|
||||
api_base: "/api" | string;
|
||||
compatibility?: JsonObject;
|
||||
targets?: string[];
|
||||
artifacts: {
|
||||
openapi: string;
|
||||
typescript: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
stable_endpoints: EndpointDescriptor[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface RoleContext {
|
||||
role: PortalRole;
|
||||
role_label?: string;
|
||||
scope: string;
|
||||
allowed_scopes?: string[];
|
||||
server_enforced: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ExecutiveDashboard {
|
||||
trust_kpi_score?: number;
|
||||
agent_coverage_pct?: number;
|
||||
high_risk_departments?: number;
|
||||
critical_candidates?: number;
|
||||
open_cases?: number;
|
||||
resolved_cases_30d?: number;
|
||||
forensics_readiness?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface RiskNarrative {
|
||||
ok: boolean;
|
||||
role_context?: RoleContext;
|
||||
scope?: "aggregate" | "department" | string;
|
||||
query?: {
|
||||
date?: string | null;
|
||||
department?: string | null;
|
||||
module?: string | null;
|
||||
employee_id_supported: false;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
risk_level: "low" | "guarded" | "medium" | "high" | "critical" | string;
|
||||
risk_score: number;
|
||||
confidence?: "high" | "medium" | "low" | "unknown" | string;
|
||||
classification?: "confirmed_risk" | "likely_risk" | "needs_investigation" | "insufficient_data" | string;
|
||||
title: string;
|
||||
summary: string;
|
||||
why: string[];
|
||||
evidence: Array<{
|
||||
source: string;
|
||||
label: string;
|
||||
value: string;
|
||||
severity: "low" | "medium" | "high" | "critical" | string;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
recommended_actions: string[];
|
||||
limitations: string[];
|
||||
model?: JsonObject;
|
||||
generated_at_utc?: ISODateTime;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type ActionPriority = "low" | "medium" | "high" | "critical";
|
||||
export type ActionOwnerRole = "executive" | "manager" | "security" | "forensics" | "admin";
|
||||
|
||||
export interface ActionItem {
|
||||
priority: ActionPriority | string;
|
||||
title: string;
|
||||
summary: string;
|
||||
owner_role: ActionOwnerRole | string;
|
||||
recommended_deadline: string;
|
||||
reason_codes: string[];
|
||||
evidence: string[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ActionCenterResponse {
|
||||
ok: boolean;
|
||||
role_context?: RoleContext;
|
||||
actions: ActionItem[];
|
||||
model?: JsonObject;
|
||||
generated_at_utc?: ISODateTime;
|
||||
limitations?: string[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface AgentQuality {
|
||||
collector_source?: string;
|
||||
collector_error?: string | null;
|
||||
sessions_collected_total?: number;
|
||||
active_sessions_total?: number;
|
||||
rdp_sessions_total?: number;
|
||||
quality_status?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface AgentCoverageSla {
|
||||
expected_nodes?: number;
|
||||
reporting_nodes_24h?: number;
|
||||
stale_nodes?: number;
|
||||
missing_nodes?: number;
|
||||
coverage_pct?: number;
|
||||
freshness_pct?: number;
|
||||
sla_status?: "OK" | "WARNING" | "CRITICAL" | "UNKNOWN" | string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface WorkforceKpiExplainFactor {
|
||||
name: string;
|
||||
label: string;
|
||||
impact: string;
|
||||
explanation: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface WorkforceKpiExplainResponse {
|
||||
ok: boolean;
|
||||
role_context?: RoleContext;
|
||||
scope?: "aggregate" | string;
|
||||
kpi_score: number;
|
||||
kpi_status?: string;
|
||||
confidence: "high" | "medium" | "low" | string;
|
||||
coverage: {
|
||||
agent_coverage_percent: number;
|
||||
data_freshness: "fresh" | "stale" | "missing" | string;
|
||||
missing_sources: string[];
|
||||
[key: string]: unknown;
|
||||
};
|
||||
factors: WorkforceKpiExplainFactor[];
|
||||
top_applications: JsonObject[];
|
||||
warnings: string[];
|
||||
recommendations: string[];
|
||||
model?: JsonObject;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BusinessRiskItem {
|
||||
department?: string;
|
||||
trust_score?: number;
|
||||
activity_score?: number;
|
||||
trend?: string;
|
||||
risk_level?: RiskLevel;
|
||||
reasons?: string[];
|
||||
recommendation?: string;
|
||||
problem_nodes_count?: number;
|
||||
missing_nodes_count?: number;
|
||||
stale_nodes_count?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface IncidentCandidate {
|
||||
id?: string;
|
||||
department?: string;
|
||||
owner?: string;
|
||||
hostname?: string;
|
||||
risk_level?: RiskLevel;
|
||||
reason?: string;
|
||||
evidence?: unknown;
|
||||
first_seen_utc?: ISODateTime;
|
||||
last_seen_utc?: ISODateTime;
|
||||
recommendation?: string;
|
||||
review?: IncidentReview;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface IncidentReview {
|
||||
candidate_id: string;
|
||||
status: ReviewStatus;
|
||||
reviewer?: string;
|
||||
comment?: string;
|
||||
updated_at?: ISODateTime;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface IncidentReviewRequest {
|
||||
candidate_id: string;
|
||||
status: ReviewStatus;
|
||||
reviewer?: string;
|
||||
comment?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface CaseItem {
|
||||
case_id?: string;
|
||||
candidate_id?: string;
|
||||
title?: string;
|
||||
status?: CaseStatus;
|
||||
owner?: string;
|
||||
created_at_utc?: ISODateTime;
|
||||
updated_at_utc?: ISODateTime;
|
||||
summary?: string;
|
||||
decision?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface CreateCaseRequest {
|
||||
candidate_id: string;
|
||||
title?: string;
|
||||
owner?: string;
|
||||
summary?: string;
|
||||
decision?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface CaseStatusRequest {
|
||||
status: CaseStatus;
|
||||
decision?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ReportsResponse {
|
||||
ok: boolean;
|
||||
role_context?: RoleContext;
|
||||
generated_at_utc?: ISODateTime;
|
||||
executive_points?: string[];
|
||||
executive_dashboard?: ExecutiveDashboard;
|
||||
risk_narrative?: RiskNarrative;
|
||||
recommended_actions?: ActionItem[];
|
||||
agent_quality?: AgentQuality;
|
||||
agent_coverage_sla?: AgentCoverageSla;
|
||||
business_risk?: BusinessRiskItem[];
|
||||
risk_incident_candidates?: IncidentCandidate[];
|
||||
cases?: CaseItem[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UebaResponse {
|
||||
ok: boolean;
|
||||
role_context?: RoleContext;
|
||||
score: number | null;
|
||||
severity: "normal" | "low" | "medium" | "high" | "critical" | string;
|
||||
status?: string;
|
||||
confidence: "high" | "medium" | "low" | "unknown" | string;
|
||||
confidence_score?: number | null;
|
||||
classification: "confirmed_risk" | "likely_risk" | "needs_investigation" | "insufficient_data" | string;
|
||||
classification_reason?: string;
|
||||
confidence_reasons: string[];
|
||||
confidence_contributors?: JsonObject[];
|
||||
evidence_status?: "available" | "not_available" | string;
|
||||
score_components: {
|
||||
activity_anomaly: number;
|
||||
time_anomaly: number;
|
||||
application_anomaly: number;
|
||||
network_anomaly: number;
|
||||
history_anomaly: number;
|
||||
};
|
||||
reason_codes: string[];
|
||||
explanation: string;
|
||||
model: JsonObject;
|
||||
risk: JsonObject;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PfsenseFirewallEvent {
|
||||
timestamp: ISODateTime;
|
||||
source_host: string;
|
||||
destination: string;
|
||||
action: string;
|
||||
rule_id?: string;
|
||||
protocol?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PfsenseVpnEvent {
|
||||
timestamp: ISODateTime;
|
||||
source_host: string;
|
||||
user_ref?: string;
|
||||
action: string;
|
||||
tunnel?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PfsenseReadinessResponse {
|
||||
ok: boolean;
|
||||
role_context?: RoleContext;
|
||||
contract_version: string;
|
||||
status: "contract_only" | "available" | string;
|
||||
siem: boolean;
|
||||
ingestion_available: boolean;
|
||||
firewall_events: PfsenseFirewallEvent[];
|
||||
vpn_events: PfsenseVpnEvent[];
|
||||
traffic_summary: JsonObject;
|
||||
top_destinations: JsonObject[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface CaseListResponse {
|
||||
ok: boolean;
|
||||
cases: CaseItem[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DetMirPortalApi {
|
||||
getContracts(): Promise<ContractIndex>;
|
||||
getHealth(): Promise<JsonObject>;
|
||||
getOperator(): Promise<JsonObject>;
|
||||
getManager(): Promise<JsonObject>;
|
||||
getOwner(): Promise<JsonObject>;
|
||||
getReports(options?: { anonymize?: boolean; role?: PortalRole }): Promise<ReportsResponse>;
|
||||
getExecutive(options?: { role?: PortalRole }): Promise<ReportsResponse>;
|
||||
getWorkforce(options?: { role?: PortalRole }): Promise<ReportsResponse>;
|
||||
getSecurity(options?: { role?: PortalRole }): Promise<ReportsResponse>;
|
||||
getForensics(options?: { role?: PortalRole }): Promise<ReportsResponse>;
|
||||
getUeba(options?: { role?: PortalRole }): Promise<UebaResponse>;
|
||||
getRiskNarrative(options?: {
|
||||
date?: string;
|
||||
department?: string;
|
||||
module?: string;
|
||||
role?: PortalRole;
|
||||
}): Promise<RiskNarrative>;
|
||||
getActions(options?: { role?: PortalRole }): Promise<ActionCenterResponse>;
|
||||
getPfsense(options?: { role?: PortalRole }): Promise<PfsenseReadinessResponse>;
|
||||
getIncidents(): Promise<JsonObject>;
|
||||
getCases(): Promise<CaseListResponse>;
|
||||
createCase(request: CreateCaseRequest): Promise<JsonObject>;
|
||||
setCaseStatus(caseId: string, request: CaseStatusRequest): Promise<JsonObject>;
|
||||
setIncidentReview(request: IncidentReviewRequest): Promise<JsonObject>;
|
||||
getInvestigationPack(
|
||||
candidateId: string,
|
||||
options?: { format?: "json" | "markdown" },
|
||||
): Promise<JsonObject | string>;
|
||||
getDlpEvidence(): Promise<JsonObject>;
|
||||
getReadinessLatest(): Promise<JsonObject>;
|
||||
getReadinessBundle(): Promise<JsonObject>;
|
||||
verifyReadiness(): Promise<JsonObject>;
|
||||
getWorkforcePolicyExplain(options?: { anonymize?: boolean }): Promise<JsonObject>;
|
||||
getWorkforceKpiExplain(options?: {
|
||||
date?: string;
|
||||
department?: string;
|
||||
owner?: string;
|
||||
role?: PortalRole;
|
||||
}): Promise<WorkforceKpiExplainResponse>;
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
use chrono::Utc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{PortalRole, role_envelope};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(crate) struct ExecutiveAction {
|
||||
pub priority: ActionPriority,
|
||||
pub title: String,
|
||||
pub summary: String,
|
||||
pub owner_role: ActionOwnerRole,
|
||||
pub recommended_deadline: String,
|
||||
pub reason_codes: Vec<String>,
|
||||
pub evidence: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum ActionPriority {
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
Critical,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum ActionOwnerRole {
|
||||
Executive,
|
||||
Manager,
|
||||
Security,
|
||||
Forensics,
|
||||
Admin,
|
||||
}
|
||||
|
||||
pub(crate) fn build_action_center_from_report(report: &Value, role: PortalRole) -> Value {
|
||||
let actions = generate_actions(report)
|
||||
.into_iter()
|
||||
.filter(|action| action_visible_for_role(action.owner_role, role))
|
||||
.collect::<Vec<_>>();
|
||||
json!({
|
||||
"ok": true,
|
||||
"role_context": role_envelope(role, "actions"),
|
||||
"actions": actions,
|
||||
"model": {
|
||||
"type": "rule_based",
|
||||
"version": "executive-action-center-v1",
|
||||
"ml": false,
|
||||
"llm": false,
|
||||
"auto_remediation": false
|
||||
},
|
||||
"generated_at_utc": Utc::now().to_rfc3339(),
|
||||
"limitations": [
|
||||
"Рекомендуемые действия не выполняются автоматически",
|
||||
"Action Center не блокирует пользователей и не меняет политики",
|
||||
"Все действия требуют ручного подтверждения ответственным контуром"
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn filter_actions_for_role(actions: &Value, role: PortalRole) -> Value {
|
||||
let filtered = actions
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|item| {
|
||||
item.get("owner_role")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(parse_owner_role)
|
||||
.is_some_and(|owner| action_visible_for_role(owner, role))
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
Value::Array(filtered)
|
||||
}
|
||||
|
||||
pub(crate) fn actions_from_center(center: &Value) -> Value {
|
||||
center
|
||||
.get("actions")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.map(Value::Array)
|
||||
.unwrap_or_else(|| Value::Array(Vec::new()))
|
||||
}
|
||||
|
||||
fn generate_actions(report: &Value) -> Vec<ExecutiveAction> {
|
||||
let mut actions = Vec::new();
|
||||
add_workforce_kpi_action(report, &mut actions);
|
||||
add_coverage_action(report, &mut actions);
|
||||
add_ueba_confidence_action(report, &mut actions);
|
||||
add_ueba_action(report, &mut actions);
|
||||
add_security_correlation_action(report, &mut actions);
|
||||
add_incident_candidate_action(report, &mut actions);
|
||||
add_risk_narrative_action(report, &mut actions);
|
||||
if actions.is_empty() {
|
||||
actions.push(ExecutiveAction {
|
||||
priority: ActionPriority::Low,
|
||||
title: "Продолжить наблюдение".to_string(),
|
||||
summary: "Критичных управленческих действий по текущему срезу не требуется".to_string(),
|
||||
owner_role: ActionOwnerRole::Manager,
|
||||
recommended_deadline: "72h".to_string(),
|
||||
reason_codes: vec!["NORMAL_OBSERVATION".to_string()],
|
||||
evidence: vec!["Критичные сигналы не выявлены".to_string()],
|
||||
});
|
||||
}
|
||||
actions.sort_by(|left, right| {
|
||||
right
|
||||
.priority
|
||||
.cmp(&left.priority)
|
||||
.then_with(|| left.owner_role.as_str().cmp(right.owner_role.as_str()))
|
||||
.then_with(|| left.title.cmp(&right.title))
|
||||
});
|
||||
actions
|
||||
}
|
||||
|
||||
fn add_workforce_kpi_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let Some(score) = report
|
||||
.pointer("/workforce_kpi_explain/kpi_score")
|
||||
.and_then(Value::as_u64)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if score >= 70 {
|
||||
return;
|
||||
}
|
||||
let mut reason_codes = vec!["LOW_WORKFORCE_KPI".to_string()];
|
||||
let mut evidence = vec![format!("Workforce KPI ниже целевого уровня: {score}%")];
|
||||
if has_kpi_factor(report, "remote_session_activity") {
|
||||
reason_codes.push("HIGH_REMOTE_ACTIVITY".to_string());
|
||||
evidence.push("Рост удаленных сессий влияет на управленческий риск".to_string());
|
||||
}
|
||||
if let Some(confidence) = report
|
||||
.pointer("/workforce_kpi_explain/confidence")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| *value == "low")
|
||||
{
|
||||
reason_codes.push("LOW_KPI_CONFIDENCE".to_string());
|
||||
evidence.push(format!("Доверие к KPI: {confidence}"));
|
||||
}
|
||||
actions.push(ExecutiveAction {
|
||||
priority: if score < 50 {
|
||||
ActionPriority::Critical
|
||||
} else {
|
||||
ActionPriority::High
|
||||
},
|
||||
title: "Проверить подразделение с низким индексом активности".to_string(),
|
||||
summary:
|
||||
"Индекс активности ниже управленческого порога; требуется проверка причины просадки"
|
||||
.to_string(),
|
||||
owner_role: ActionOwnerRole::Manager,
|
||||
recommended_deadline: if score < 50 { "4h" } else { "24h" }.to_string(),
|
||||
reason_codes,
|
||||
evidence,
|
||||
});
|
||||
}
|
||||
|
||||
fn add_coverage_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let coverage = report
|
||||
.pointer("/agent_coverage_sla/coverage_pct")
|
||||
.or_else(|| report.pointer("/workforce_kpi_explain/coverage/agent_coverage_percent"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(100);
|
||||
let sla_status = report
|
||||
.pointer("/agent_coverage_sla/sla_status")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("OK");
|
||||
if coverage >= 80 && !matches!(sla_status, "WARNING" | "CRITICAL") {
|
||||
return;
|
||||
}
|
||||
actions.push(ExecutiveAction {
|
||||
priority: if coverage < 60 || sla_status == "CRITICAL" {
|
||||
ActionPriority::Critical
|
||||
} else {
|
||||
ActionPriority::High
|
||||
},
|
||||
title: "Проверить состояние агентов".to_string(),
|
||||
summary: "Полнота данных ниже целевого уровня; показатели могут быть нерепрезентативны"
|
||||
.to_string(),
|
||||
owner_role: ActionOwnerRole::Admin,
|
||||
recommended_deadline: if coverage < 60 { "4h" } else { "24h" }.to_string(),
|
||||
reason_codes: vec!["LOW_COVERAGE".to_string()],
|
||||
evidence: vec![
|
||||
format!("Покрытие агентов: {coverage}%"),
|
||||
format!("SLA полноты данных: {sla_status}"),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
fn add_ueba_confidence_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let score = report
|
||||
.pointer("/ueba_risk/score")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let explicit_confidence = report
|
||||
.pointer("/ueba_risk/confidence_level")
|
||||
.and_then(Value::as_str);
|
||||
let explicit_classification = report
|
||||
.pointer("/ueba_risk/classification")
|
||||
.and_then(Value::as_str);
|
||||
if score < 70 && explicit_confidence.is_none() && explicit_classification.is_none() {
|
||||
return;
|
||||
}
|
||||
let confidence = report
|
||||
.pointer("/ueba_risk/confidence_level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let classification = report
|
||||
.pointer("/ueba_risk/classification")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("insufficient_data");
|
||||
if score < 70 && !matches!(classification, "needs_investigation" | "insufficient_data") {
|
||||
return;
|
||||
}
|
||||
if !matches!(confidence, "low" | "unknown")
|
||||
&& !matches!(classification, "needs_investigation" | "insufficient_data")
|
||||
{
|
||||
return;
|
||||
}
|
||||
let reasons = report
|
||||
.pointer("/ueba_risk/confidence_reasons")
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.take(3)
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut evidence = vec![
|
||||
format!("UEBA confidence: {confidence}"),
|
||||
format!("UEBA classification: {classification}"),
|
||||
];
|
||||
evidence.extend(reasons);
|
||||
actions.push(ExecutiveAction {
|
||||
priority: ActionPriority::Critical,
|
||||
title: "Проверить полноту данных".to_string(),
|
||||
summary: "Перед жестким выводом по UEBA нужно подтвердить покрытие, свежесть и полноту телеметрии"
|
||||
.to_string(),
|
||||
owner_role: ActionOwnerRole::Admin,
|
||||
recommended_deadline: "4h".to_string(),
|
||||
reason_codes: vec![
|
||||
"LOW_UEBA_CONFIDENCE".to_string(),
|
||||
"CHECK_DATA_COMPLETENESS".to_string(),
|
||||
],
|
||||
evidence,
|
||||
});
|
||||
}
|
||||
|
||||
fn add_ueba_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let score = report
|
||||
.pointer("/ueba_risk/score")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let level = report
|
||||
.pointer("/ueba_risk/level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("low");
|
||||
if score < 70 && !matches!(level, "high" | "critical") {
|
||||
return;
|
||||
}
|
||||
actions.push(ExecutiveAction {
|
||||
priority: if score >= 90 || level == "critical" {
|
||||
ActionPriority::Critical
|
||||
} else {
|
||||
ActionPriority::High
|
||||
},
|
||||
title: "Передать данные в контур ИБ".to_string(),
|
||||
summary: "UEBA score повышен; требуется ручная проверка безопасности".to_string(),
|
||||
owner_role: ActionOwnerRole::Security,
|
||||
recommended_deadline: if score >= 90 { "4h" } else { "24h" }.to_string(),
|
||||
reason_codes: vec!["HIGH_UEBA".to_string()],
|
||||
evidence: vec![format!("UEBA score: {score}, уровень: {level}")],
|
||||
});
|
||||
}
|
||||
|
||||
fn add_security_correlation_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let max_score = report
|
||||
.get("security_correlation")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|item| item.get("correlation_score").and_then(Value::as_u64))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if max_score < 60 {
|
||||
return;
|
||||
}
|
||||
actions.push(ExecutiveAction {
|
||||
priority: if max_score >= 80 {
|
||||
ActionPriority::Critical
|
||||
} else {
|
||||
ActionPriority::High
|
||||
},
|
||||
title: "Проверить связь активности и ИБ-событий".to_string(),
|
||||
summary: "Есть корреляция между операционным риском и событиями безопасности".to_string(),
|
||||
owner_role: ActionOwnerRole::Security,
|
||||
recommended_deadline: "24h".to_string(),
|
||||
reason_codes: vec!["HIGH_SECURITY_CORRELATION".to_string()],
|
||||
evidence: vec![format!("Security correlation score: {max_score}")],
|
||||
});
|
||||
}
|
||||
|
||||
fn add_incident_candidate_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let Some(candidates) = report
|
||||
.get("risk_incident_candidates")
|
||||
.and_then(Value::as_array)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if candidates.is_empty() {
|
||||
return;
|
||||
}
|
||||
let critical = candidates.iter().any(|item| {
|
||||
item.get("risk_level")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|level| level.eq_ignore_ascii_case("critical"))
|
||||
});
|
||||
actions.push(ExecutiveAction {
|
||||
priority: if critical {
|
||||
ActionPriority::Critical
|
||||
} else {
|
||||
ActionPriority::High
|
||||
},
|
||||
title: "Провести расследование кандидатов".to_string(),
|
||||
summary: "В очереди есть кандидаты на проверку; требуется ручной разбор и фиксация решения"
|
||||
.to_string(),
|
||||
owner_role: ActionOwnerRole::Forensics,
|
||||
recommended_deadline: if critical { "4h" } else { "24h" }.to_string(),
|
||||
reason_codes: vec!["INCIDENT_CANDIDATE".to_string()],
|
||||
evidence: vec![format!("Кандидатов на проверку: {}", candidates.len())],
|
||||
});
|
||||
}
|
||||
|
||||
fn add_risk_narrative_action(report: &Value, actions: &mut Vec<ExecutiveAction>) {
|
||||
let score = report
|
||||
.pointer("/risk_narrative/risk_score")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
if score < 75 {
|
||||
return;
|
||||
}
|
||||
let level = report
|
||||
.pointer("/risk_narrative/risk_level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("high");
|
||||
actions.push(ExecutiveAction {
|
||||
priority: if score >= 90 {
|
||||
ActionPriority::Critical
|
||||
} else {
|
||||
ActionPriority::High
|
||||
},
|
||||
title: "Назначить владельца корректирующих действий".to_string(),
|
||||
summary: "Риск-нарратив показывает высокий управленческий риск; нужен ответственный и срок контроля"
|
||||
.to_string(),
|
||||
owner_role: ActionOwnerRole::Executive,
|
||||
recommended_deadline: if score >= 90 { "4h" } else { "24h" }.to_string(),
|
||||
reason_codes: vec!["RISK_NARRATIVE_HIGH".to_string()],
|
||||
evidence: vec![format!("Risk Narrative: {score}/100, уровень: {level}")],
|
||||
});
|
||||
}
|
||||
|
||||
fn has_kpi_factor(report: &Value, factor_name: &str) -> bool {
|
||||
report
|
||||
.pointer("/workforce_kpi_explain/factors")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|item| item.get("name").and_then(Value::as_str) == Some(factor_name))
|
||||
}
|
||||
|
||||
fn action_visible_for_role(owner_role: ActionOwnerRole, role: PortalRole) -> bool {
|
||||
match role {
|
||||
PortalRole::Admin => true,
|
||||
PortalRole::Executive => matches!(
|
||||
owner_role,
|
||||
ActionOwnerRole::Executive | ActionOwnerRole::Manager | ActionOwnerRole::Admin
|
||||
),
|
||||
PortalRole::Manager => matches!(owner_role, ActionOwnerRole::Manager),
|
||||
PortalRole::Security => {
|
||||
matches!(
|
||||
owner_role,
|
||||
ActionOwnerRole::Security | ActionOwnerRole::Forensics
|
||||
)
|
||||
}
|
||||
PortalRole::Forensics => {
|
||||
matches!(
|
||||
owner_role,
|
||||
ActionOwnerRole::Forensics | ActionOwnerRole::Security
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_owner_role(value: &str) -> Option<ActionOwnerRole> {
|
||||
match value {
|
||||
"executive" => Some(ActionOwnerRole::Executive),
|
||||
"manager" => Some(ActionOwnerRole::Manager),
|
||||
"security" => Some(ActionOwnerRole::Security),
|
||||
"forensics" => Some(ActionOwnerRole::Forensics),
|
||||
"admin" => Some(ActionOwnerRole::Admin),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl ActionOwnerRole {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Executive => "executive",
|
||||
Self::Manager => "manager",
|
||||
Self::Security => "security",
|
||||
Self::Forensics => "forensics",
|
||||
Self::Admin => "admin",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_report() -> Value {
|
||||
json!({
|
||||
"workforce_kpi_explain": {
|
||||
"kpi_score": 48,
|
||||
"confidence": "low",
|
||||
"coverage": {"agent_coverage_percent": 58},
|
||||
"factors": [{"name": "remote_session_activity"}]
|
||||
},
|
||||
"ueba_risk": {"score": 91, "level": "critical"},
|
||||
"agent_coverage_sla": {"coverage_pct": 58, "sla_status": "CRITICAL"},
|
||||
"security_correlation": [{"correlation_score": 81}],
|
||||
"risk_incident_candidates": [{"risk_level": "CRITICAL"}],
|
||||
"risk_narrative": {"risk_score": 92, "risk_level": "critical"}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generates_rule_based_actions_with_priorities() {
|
||||
let payload = build_action_center_from_report(&sample_report(), PortalRole::Admin);
|
||||
let actions = payload["actions"].as_array().unwrap();
|
||||
assert!(actions.len() >= 5);
|
||||
assert_eq!(payload["model"]["type"], "rule_based");
|
||||
assert_eq!(payload["model"]["ml"], false);
|
||||
assert_eq!(payload["model"]["llm"], false);
|
||||
assert!(actions.iter().any(|item| {
|
||||
item["reason_codes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|code| code == "LOW_WORKFORCE_KPI")
|
||||
}));
|
||||
assert!(actions.iter().any(|item| {
|
||||
item["reason_codes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|code| code == "LOW_UEBA_CONFIDENCE")
|
||||
}));
|
||||
assert!(actions.iter().any(|item| item["priority"] == "critical"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_actions_by_role() {
|
||||
let admin = build_action_center_from_report(&sample_report(), PortalRole::Admin);
|
||||
let security = filter_actions_for_role(&actions_from_center(&admin), PortalRole::Security);
|
||||
let security_actions = security.as_array().unwrap();
|
||||
assert!(!security_actions.is_empty());
|
||||
assert!(
|
||||
security_actions
|
||||
.iter()
|
||||
.all(|item| item["owner_role"] == "security" || item["owner_role"] == "forensics")
|
||||
);
|
||||
|
||||
let manager = filter_actions_for_role(&actions_from_center(&admin), PortalRole::Manager);
|
||||
let manager_actions = manager.as_array().unwrap();
|
||||
assert!(
|
||||
manager_actions
|
||||
.iter()
|
||||
.all(|item| item["owner_role"] == "manager")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_observation_when_no_rule_matches() {
|
||||
let payload = build_action_center_from_report(&json!({}), PortalRole::Executive);
|
||||
let actions = payload["actions"].as_array().unwrap();
|
||||
assert_eq!(actions.len(), 1);
|
||||
assert_eq!(actions[0]["priority"], "low");
|
||||
assert_eq!(actions[0]["reason_codes"][0], "NORMAL_OBSERVATION");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,77 @@
|
||||
//! Portal role model and access-scope contract.
|
||||
//!
|
||||
//! CONTRACT: role aliases, serialized values and allowed scopes are part of
|
||||
//! the portal API/security boundary. Keep changes explicit and covered by
|
||||
//! existing role-gate tests in `main.rs`.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum PortalRole {
|
||||
Executive,
|
||||
Manager,
|
||||
Security,
|
||||
Forensics,
|
||||
Admin,
|
||||
}
|
||||
|
||||
impl PortalRole {
|
||||
pub(crate) fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"executive" | "owner" | "rukovoditel" | "руководитель" => {
|
||||
Some(Self::Executive)
|
||||
}
|
||||
"manager" | "workforce" | "руководитель_подразделения" => {
|
||||
Some(Self::Manager)
|
||||
}
|
||||
"security" | "ib" | "soc" | "безопасность" => Some(Self::Security),
|
||||
"forensics" | "investigation" | "расследования" => Some(Self::Forensics),
|
||||
"admin" | "operations" | "operator" | "эксплуатация" => Some(Self::Admin),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Executive => "executive",
|
||||
Self::Manager => "manager",
|
||||
Self::Security => "security",
|
||||
Self::Forensics => "forensics",
|
||||
Self::Admin => "admin",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn label_ru(self) -> &'static str {
|
||||
match self {
|
||||
Self::Executive => "Руководитель",
|
||||
Self::Manager => "Руководитель подразделения",
|
||||
Self::Security => "Безопасность",
|
||||
Self::Forensics => "Расследования",
|
||||
Self::Admin => "Администратор",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn allowed_scopes(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Executive => &["executive", "workforce"],
|
||||
Self::Manager => &["executive", "workforce"],
|
||||
Self::Security => &["security", "incidents", "ueba", "pfsense"],
|
||||
Self::Forensics => &["forensics", "incidents", "ueba"],
|
||||
Self::Admin => &[
|
||||
"executive",
|
||||
"workforce",
|
||||
"security",
|
||||
"forensics",
|
||||
"incidents",
|
||||
"ueba",
|
||||
"pfsense",
|
||||
"admin",
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn can_access(self, scope: &str) -> bool {
|
||||
self.allowed_scopes().contains(&scope)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Liveness probe payload.
|
||||
//!
|
||||
//! CONTRACT: `/healthz` is intentionally shallow. It proves that the portal
|
||||
//! process can answer HTTP, while dependency checks belong to `/readyz`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::now;
|
||||
|
||||
pub(crate) fn build_healthz() -> Value {
|
||||
json!({
|
||||
"status": "ok",
|
||||
"generated_at_utc": now(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! Configuration and request-bound validation for production portal routes.
|
||||
//!
|
||||
//! RATIONALE: the portal can aggregate reports, evidence and external service
|
||||
//! payloads. Query and body limits keep pilot installations responsive and make
|
||||
//! expensive report routes fail closed instead of exhausting memory or blocking
|
||||
//! the single-process runtime.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::NaiveDate;
|
||||
use serde_json::{Value, json};
|
||||
use tiny_http::StatusCode;
|
||||
|
||||
use crate::{
|
||||
Cli, MAX_ALLOWED_PAGE_SIZE, MAX_ALLOWED_REPORT_DATE_RANGE_DAYS, MAX_ALLOWED_REQUEST_BODY_BYTES,
|
||||
MAX_ALLOWED_REQUEST_TIMEOUT_SECONDS, query_param,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ApiLimitError {
|
||||
pub(crate) status: StatusCode,
|
||||
pub(crate) payload: Value,
|
||||
}
|
||||
|
||||
pub(crate) fn validate_portal_config(args: &Cli) -> Result<()> {
|
||||
let (host, port) = args
|
||||
.bind
|
||||
.rsplit_once(':')
|
||||
.ok_or_else(|| anyhow!("invalid config bind: expected host:port"))?;
|
||||
if host.trim().is_empty() {
|
||||
return Err(anyhow!("invalid config host: value is empty"));
|
||||
}
|
||||
let port = port
|
||||
.parse::<u16>()
|
||||
.map_err(|_| anyhow!("invalid config port: expected 1..65535"))?;
|
||||
if port == 0 {
|
||||
return Err(anyhow!("invalid config port: expected 1..65535"));
|
||||
}
|
||||
|
||||
// RATIONALE: page and date limits protect heavy report endpoints while
|
||||
// preserving monthly pilot reporting. Hard upper bounds prevent accidental
|
||||
// production overrides from turning the portal into an unbounded exporter.
|
||||
if args.max_page_size == 0 || args.max_page_size > MAX_ALLOWED_PAGE_SIZE {
|
||||
return Err(anyhow!(
|
||||
"invalid config max_page_size: expected 1..={MAX_ALLOWED_PAGE_SIZE}"
|
||||
));
|
||||
}
|
||||
if args.default_page_size == 0 || args.default_page_size > args.max_page_size {
|
||||
return Err(anyhow!(
|
||||
"invalid config default_page_size: expected 1..=max_page_size"
|
||||
));
|
||||
}
|
||||
if args.max_report_date_range_days <= 0
|
||||
|| args.max_report_date_range_days > MAX_ALLOWED_REPORT_DATE_RANGE_DAYS
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"invalid config max_report_date_range_days: expected 1..={MAX_ALLOWED_REPORT_DATE_RANGE_DAYS}"
|
||||
));
|
||||
}
|
||||
if args.request_timeout_seconds == 0
|
||||
|| args.request_timeout_seconds > MAX_ALLOWED_REQUEST_TIMEOUT_SECONDS
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"invalid config request_timeout_seconds: expected 1..={MAX_ALLOWED_REQUEST_TIMEOUT_SECONDS}"
|
||||
));
|
||||
}
|
||||
if args.timeout_seconds == 0 || args.timeout_seconds > MAX_ALLOWED_REQUEST_TIMEOUT_SECONDS {
|
||||
return Err(anyhow!(
|
||||
"invalid config timeout_seconds: expected 1..={MAX_ALLOWED_REQUEST_TIMEOUT_SECONDS}"
|
||||
));
|
||||
}
|
||||
if args.max_request_body_bytes < 1024
|
||||
|| args.max_request_body_bytes > MAX_ALLOWED_REQUEST_BODY_BYTES
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"invalid config max_request_body_bytes: expected 1024..={MAX_ALLOWED_REQUEST_BODY_BYTES}"
|
||||
));
|
||||
}
|
||||
|
||||
// SECURITY: environment and module names can reach metrics/log labels.
|
||||
// Restrict them to short ASCII tokens to avoid label injection and runaway
|
||||
// cardinality from free-form deployment names.
|
||||
if !is_safe_environment_name(&args.environment) {
|
||||
return Err(anyhow!(
|
||||
"invalid config environment: use 1..32 chars from A-Z, a-z, 0-9, _, -"
|
||||
));
|
||||
}
|
||||
let modules = enabled_modules(&args.enabled_modules);
|
||||
if modules.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"invalid config enabled_modules: no modules enabled"
|
||||
));
|
||||
}
|
||||
let allowed = [
|
||||
"executive",
|
||||
"workforce",
|
||||
"security",
|
||||
"forensics",
|
||||
"admin",
|
||||
"ueba",
|
||||
"pfsense",
|
||||
"reports",
|
||||
];
|
||||
for module in modules {
|
||||
if !allowed.contains(&module.as_str()) {
|
||||
return Err(anyhow!(
|
||||
"invalid config enabled_modules: unsupported module {module}"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_safe_environment_name(value: &str) -> bool {
|
||||
let value = value.trim();
|
||||
!value.is_empty()
|
||||
&& value.len() <= 32
|
||||
&& value
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-'))
|
||||
}
|
||||
|
||||
fn enabled_modules(value: &str) -> BTreeSet<String> {
|
||||
value
|
||||
.split(',')
|
||||
.map(|item| item.trim().to_ascii_lowercase())
|
||||
.filter(|item| !item.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn is_limited_api_route(path: &str) -> bool {
|
||||
matches!(
|
||||
path,
|
||||
"/api/reports"
|
||||
| "/api/executive"
|
||||
| "/api/workforce"
|
||||
| "/api/security"
|
||||
| "/api/forensics"
|
||||
| "/api/ueba"
|
||||
| "/api/pfsense"
|
||||
| "/api/workforce/kpi/explain"
|
||||
| "/api/risk/narrative"
|
||||
| "/api/actions"
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_api_query_limits(
|
||||
url: &str,
|
||||
args: &Cli,
|
||||
) -> std::result::Result<(), ApiLimitError> {
|
||||
for key in ["page_size", "limit"] {
|
||||
if let Some(value) = query_param(url, key) {
|
||||
let parsed = value.parse::<u32>().ok();
|
||||
if parsed.is_none_or(|page_size| page_size == 0 || page_size > args.max_page_size) {
|
||||
return Err(api_limit_error(
|
||||
StatusCode(400),
|
||||
"invalid_page_size",
|
||||
&format!("{key} must be between 1 and {}", args.max_page_size),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (from_key, to_key) in [("date_from", "date_to"), ("from", "to"), ("start", "end")] {
|
||||
let Some(from) = query_param(url, from_key).and_then(|value| parse_query_date(&value))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(to) = query_param(url, to_key).and_then(|value| parse_query_date(&value)) else {
|
||||
continue;
|
||||
};
|
||||
let days = (to - from).num_days().abs() + 1;
|
||||
if days > args.max_report_date_range_days {
|
||||
return Err(api_limit_error(
|
||||
StatusCode(400),
|
||||
"report_range_too_large",
|
||||
&format!(
|
||||
"report date range must be <= {} days",
|
||||
args.max_report_date_range_days
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn parse_query_date(value: &str) -> Option<NaiveDate> {
|
||||
let date = value.split('T').next().unwrap_or(value);
|
||||
NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()
|
||||
}
|
||||
|
||||
fn api_limit_error(status: StatusCode, code: &str, message: &str) -> ApiLimitError {
|
||||
ApiLimitError {
|
||||
status,
|
||||
payload: json!({
|
||||
"ok": false,
|
||||
"error_code": code,
|
||||
"message": message,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
DEFAULT_MAX_PAGE_SIZE, DEFAULT_MAX_REPORT_DATE_RANGE_DAYS, DEFAULT_MAX_REQUEST_BODY_BYTES,
|
||||
DEFAULT_PAGE_SIZE, DEFAULT_REQUEST_TIMEOUT_SECONDS, DEFAULT_SLOW_REQUEST_LOG_MS,
|
||||
};
|
||||
|
||||
fn test_cli(dir: &Path) -> Cli {
|
||||
Cli {
|
||||
bind: "127.0.0.1:8720".to_string(),
|
||||
status_cmd: "true".to_string(),
|
||||
check_cmd: "true".to_string(),
|
||||
failed_units_cmd: "true".to_string(),
|
||||
worktime_url: "http://127.0.0.1".to_string(),
|
||||
one_c_url: "http://127.0.0.1".to_string(),
|
||||
workforce_policy_path: dir.join("workforce-policy.json"),
|
||||
ueba_policy_path: dir.join("ueba-policy.yaml"),
|
||||
timeout_seconds: 1,
|
||||
max_page_size: DEFAULT_MAX_PAGE_SIZE,
|
||||
default_page_size: DEFAULT_PAGE_SIZE,
|
||||
max_report_date_range_days: DEFAULT_MAX_REPORT_DATE_RANGE_DAYS,
|
||||
request_timeout_seconds: DEFAULT_REQUEST_TIMEOUT_SECONDS,
|
||||
max_request_body_bytes: DEFAULT_MAX_REQUEST_BODY_BYTES,
|
||||
slow_request_log_ms: DEFAULT_SLOW_REQUEST_LOG_MS,
|
||||
environment: "test".to_string(),
|
||||
enabled_modules: "executive,workforce,security,forensics,admin".to_string(),
|
||||
state_dir: dir.join("state"),
|
||||
dlp_db_path: dir.join("dlp.sqlite"),
|
||||
evidence_root: dir.to_path_buf(),
|
||||
readiness_bundle_dir: dir.join("readiness-bundle"),
|
||||
evidence_limit: 10,
|
||||
evidence_max_bytes: 1024,
|
||||
json_smoke: false,
|
||||
evidence_only: false,
|
||||
evidence_upload_token: None,
|
||||
telemetry_api_key: "test-key".to_string(),
|
||||
telemetry_store_path: dir.join("telemetry.jsonl"),
|
||||
expected_nodes_path: dir.join("expected_nodes.json"),
|
||||
security_events_backend: "disabled".to_string(),
|
||||
clickhouse_url: "http://127.0.0.1:8123".to_string(),
|
||||
clickhouse_database: "analytics_1c".to_string(),
|
||||
clickhouse_user: "default".to_string(),
|
||||
clickhouse_password: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_rejects_bad_values() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let args = test_cli(dir.path());
|
||||
assert!(validate_portal_config(&args).is_ok());
|
||||
|
||||
let mut invalid = args.clone();
|
||||
invalid.bind = "127.0.0.1:bad".to_string();
|
||||
assert!(
|
||||
validate_portal_config(&invalid)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("port")
|
||||
);
|
||||
|
||||
let mut invalid = args.clone();
|
||||
invalid.max_page_size = 0;
|
||||
assert!(
|
||||
validate_portal_config(&invalid)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("max_page_size")
|
||||
);
|
||||
|
||||
let mut invalid = args.clone();
|
||||
invalid.max_report_date_range_days = 0;
|
||||
assert!(
|
||||
validate_portal_config(&invalid)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("max_report_date_range_days")
|
||||
);
|
||||
|
||||
let mut invalid = args.clone();
|
||||
invalid.request_timeout_seconds = 0;
|
||||
assert!(
|
||||
validate_portal_config(&invalid)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("request_timeout_seconds")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_limits_reject_page_size_and_report_range() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let args = test_cli(dir.path());
|
||||
assert!(validate_api_query_limits("/api/reports?page_size=100", &args).is_ok());
|
||||
let page_error =
|
||||
validate_api_query_limits("/api/reports?page_size=999999", &args).unwrap_err();
|
||||
assert_eq!(page_error.status.0, 400);
|
||||
assert_eq!(page_error.payload["error_code"], "invalid_page_size");
|
||||
|
||||
let range_error = validate_api_query_limits(
|
||||
"/api/reports?date_from=2026-01-01&date_to=2026-12-31",
|
||||
&args,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(range_error.status.0, 400);
|
||||
assert_eq!(range_error.payload["error_code"], "report_range_too_large");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Structured HTTP access logging for the portal runtime.
|
||||
//!
|
||||
//! CONTRACT: logs are emitted as single-line JSON to stderr so systemd/journald,
|
||||
//! container runtimes and log forwarders can parse them without scraping free
|
||||
//! text. Do not log raw request bodies, secrets, evidence bytes or personal
|
||||
//! payloads here.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use tiny_http::StatusCode;
|
||||
|
||||
use super::request_context::HttpRequestMetadata;
|
||||
use crate::now;
|
||||
|
||||
pub(crate) fn log_http_request(
|
||||
metadata: &HttpRequestMetadata,
|
||||
status: StatusCode,
|
||||
response_bytes: usize,
|
||||
) {
|
||||
let level = if status.0 >= 500 {
|
||||
"ERROR"
|
||||
} else if status.0 >= 400 {
|
||||
"WARN"
|
||||
} else {
|
||||
"INFO"
|
||||
};
|
||||
let error_code = if status.0 >= 400 {
|
||||
Value::String(format!("http_{}", status.0))
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
|
||||
// SECURITY: include routing/correlation fields, but do not include query
|
||||
// values, request body, headers or tokens. Those can contain employee data,
|
||||
// screenshots, evidence references or API keys.
|
||||
eprintln!(
|
||||
"{}",
|
||||
json!({
|
||||
"timestamp": now(),
|
||||
"level": level,
|
||||
"request_id": &metadata.request_id,
|
||||
"correlation_id": &metadata.correlation_id,
|
||||
"method": &metadata.method,
|
||||
"path": &metadata.path,
|
||||
"route": &metadata.route,
|
||||
"status": status.0,
|
||||
"latency_ms": metadata.latency_ms,
|
||||
"user_role": &metadata.role,
|
||||
"module": &metadata.module,
|
||||
"error_code": error_code,
|
||||
"response_bytes": response_bytes,
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! In-process Prometheus-style metrics for the portal.
|
||||
//!
|
||||
//! CONTRACT: metric names and label keys are part of the operational contract
|
||||
//! used by dashboards and smoke checks. Additive metrics are allowed; renaming
|
||||
//! existing metrics requires synchronized dashboard/documentation changes.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use tiny_http::StatusCode;
|
||||
|
||||
use super::readiness::build_readyz;
|
||||
use super::request_context::HttpRequestMetadata;
|
||||
use crate::Cli;
|
||||
|
||||
static PORTAL_METRICS: OnceLock<Mutex<PortalMetrics>> = OnceLock::new();
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct HttpMetricKey {
|
||||
method: String,
|
||||
route: String,
|
||||
status: u16,
|
||||
module: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct HttpMetricValue {
|
||||
requests_total: u64,
|
||||
duration_seconds_sum: f64,
|
||||
duration_seconds_count: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PortalMetrics {
|
||||
http: BTreeMap<HttpMetricKey, HttpMetricValue>,
|
||||
reports_generated_total: u64,
|
||||
ingestion_records_total: u64,
|
||||
ingestion_rejected_total: u64,
|
||||
role_denied_total: u64,
|
||||
}
|
||||
|
||||
fn portal_metrics() -> &'static Mutex<PortalMetrics> {
|
||||
PORTAL_METRICS.get_or_init(|| Mutex::new(PortalMetrics::default()))
|
||||
}
|
||||
|
||||
pub(crate) fn record_http_metric(metadata: &HttpRequestMetadata, status: StatusCode) {
|
||||
if let Ok(mut metrics) = portal_metrics().lock() {
|
||||
let entry = metrics
|
||||
.http
|
||||
.entry(HttpMetricKey {
|
||||
method: metadata.method.clone(),
|
||||
route: metadata.route.clone(),
|
||||
status: status.0,
|
||||
module: metadata.module.clone(),
|
||||
})
|
||||
.or_default();
|
||||
entry.requests_total = entry.requests_total.saturating_add(1);
|
||||
entry.duration_seconds_sum += metadata.latency_ms as f64 / 1_000.0;
|
||||
entry.duration_seconds_count = entry.duration_seconds_count.saturating_add(1);
|
||||
if status.0 == 403 {
|
||||
metrics.role_denied_total = metrics.role_denied_total.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_report_generated() {
|
||||
if let Ok(mut metrics) = portal_metrics().lock() {
|
||||
metrics.reports_generated_total = metrics.reports_generated_total.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_ingestion_accepted() {
|
||||
if let Ok(mut metrics) = portal_metrics().lock() {
|
||||
metrics.ingestion_records_total = metrics.ingestion_records_total.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_ingestion_rejected() {
|
||||
if let Ok(mut metrics) = portal_metrics().lock() {
|
||||
metrics.ingestion_rejected_total = metrics.ingestion_rejected_total.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_prometheus_metrics(args: &Cli) -> String {
|
||||
let mut text = String::new();
|
||||
let ready_value = if build_readyz(args)
|
||||
.get("status")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("not_ready")
|
||||
== "ready"
|
||||
{
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
writeln!(
|
||||
&mut text,
|
||||
"# HELP awatch_http_requests_total HTTP requests handled by AWatch-rus portal"
|
||||
)
|
||||
.ok();
|
||||
writeln!(&mut text, "# TYPE awatch_http_requests_total counter").ok();
|
||||
let metrics = portal_metrics()
|
||||
.lock()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_default();
|
||||
for (key, value) in &metrics.http {
|
||||
writeln!(
|
||||
&mut text,
|
||||
"awatch_http_requests_total{{method=\"{}\",route=\"{}\",status=\"{}\",module=\"{}\"}} {}",
|
||||
prom_escape(&key.method),
|
||||
prom_escape(&key.route),
|
||||
key.status,
|
||||
prom_escape(&key.module),
|
||||
value.requests_total
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
writeln!(
|
||||
&mut text,
|
||||
"# HELP awatch_http_request_duration_seconds HTTP request duration in seconds"
|
||||
)
|
||||
.ok();
|
||||
writeln!(
|
||||
&mut text,
|
||||
"# TYPE awatch_http_request_duration_seconds summary"
|
||||
)
|
||||
.ok();
|
||||
for (key, value) in &metrics.http {
|
||||
writeln!(
|
||||
&mut text,
|
||||
"awatch_http_request_duration_seconds_sum{{method=\"{}\",route=\"{}\",status=\"{}\",module=\"{}\"}} {:.6}",
|
||||
prom_escape(&key.method),
|
||||
prom_escape(&key.route),
|
||||
key.status,
|
||||
prom_escape(&key.module),
|
||||
value.duration_seconds_sum
|
||||
)
|
||||
.ok();
|
||||
writeln!(
|
||||
&mut text,
|
||||
"awatch_http_request_duration_seconds_count{{method=\"{}\",route=\"{}\",status=\"{}\",module=\"{}\"}} {}",
|
||||
prom_escape(&key.method),
|
||||
prom_escape(&key.route),
|
||||
key.status,
|
||||
prom_escape(&key.module),
|
||||
value.duration_seconds_count
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
for (name, help, value) in [
|
||||
(
|
||||
"awatch_reports_generated_total",
|
||||
"Reports generated by the portal",
|
||||
metrics.reports_generated_total,
|
||||
),
|
||||
(
|
||||
"awatch_ingestion_records_total",
|
||||
"Telemetry ingestion records accepted",
|
||||
metrics.ingestion_records_total,
|
||||
),
|
||||
(
|
||||
"awatch_ingestion_rejected_total",
|
||||
"Telemetry ingestion records rejected",
|
||||
metrics.ingestion_rejected_total,
|
||||
),
|
||||
(
|
||||
"awatch_role_denied_total",
|
||||
"Requests denied by role gates",
|
||||
metrics.role_denied_total,
|
||||
),
|
||||
] {
|
||||
writeln!(&mut text, "# HELP {name} {help}").ok();
|
||||
writeln!(&mut text, "# TYPE {name} counter").ok();
|
||||
writeln!(&mut text, "{name} {value}").ok();
|
||||
}
|
||||
writeln!(
|
||||
&mut text,
|
||||
"# HELP awatch_readyz_status Portal readiness status, 1=ready, 0=not_ready"
|
||||
)
|
||||
.ok();
|
||||
writeln!(&mut text, "# TYPE awatch_readyz_status gauge").ok();
|
||||
writeln!(&mut text, "awatch_readyz_status {ready_value}").ok();
|
||||
text
|
||||
}
|
||||
|
||||
fn prom_escape(value: &str) -> String {
|
||||
// SECURITY: metric label values are route/module tokens, but escaping keeps
|
||||
// the endpoint safe if future callers pass proxy-derived values.
|
||||
value.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Production-facing portal runtime support.
|
||||
//!
|
||||
//! This module groups the cross-cutting concerns that must stay consistent
|
||||
//! across all portal routes: health/readiness/version contracts, query and
|
||||
//! configuration limits, structured logging, Prometheus-style metrics and
|
||||
//! request correlation metadata.
|
||||
//!
|
||||
//! CONTRACT: keep this module free from role-specific business rendering. It is
|
||||
//! the operational boundary around the portal, not the workforce/security report
|
||||
//! implementation itself.
|
||||
|
||||
pub(crate) mod health;
|
||||
pub(crate) mod limits;
|
||||
pub(crate) mod logging;
|
||||
pub(crate) mod metrics;
|
||||
pub(crate) mod readiness;
|
||||
pub(crate) mod request_context;
|
||||
pub(crate) mod version;
|
||||
|
||||
pub(crate) use health::build_healthz;
|
||||
pub(crate) use limits::{is_limited_api_route, validate_api_query_limits, validate_portal_config};
|
||||
pub(crate) use logging::log_http_request;
|
||||
pub(crate) use metrics::{
|
||||
record_http_metric, record_ingestion_accepted, record_ingestion_rejected,
|
||||
record_report_generated, render_prometheus_metrics,
|
||||
};
|
||||
pub(crate) use readiness::build_readyz;
|
||||
pub(crate) use request_context::{http_request_metadata, mark_request_started};
|
||||
pub(crate) use version::build_version;
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Readiness probe payload.
|
||||
//!
|
||||
//! CONTRACT: `/readyz` checks whether the portal is safe to receive normal
|
||||
//! traffic. It must remain conservative: configuration errors and broken state
|
||||
//! storage make the process `not_ready`; optional integrations can report
|
||||
//! `disabled`, `not_required` or `contract_only` without failing the whole probe.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::limits::validate_portal_config;
|
||||
use crate::{Cli, now};
|
||||
|
||||
pub(crate) fn build_readyz(args: &Cli) -> Value {
|
||||
let config_ok = validate_portal_config(args).is_ok();
|
||||
let storage_status = storage_readiness_status(&args.state_dir);
|
||||
let telemetry_status = storage_parent_readiness_status(&args.telemetry_store_path);
|
||||
let evidence_status = storage_readiness_status(&args.evidence_root);
|
||||
let ready = config_ok && !matches!(storage_status.as_str(), "error");
|
||||
json!({
|
||||
"status": if ready { "ready" } else { "not_ready" },
|
||||
"generated_at_utc": now(),
|
||||
"checks": {
|
||||
"config": if config_ok { "ok" } else { "error" },
|
||||
"storage": storage_status,
|
||||
"telemetry_store": telemetry_status,
|
||||
"evidence_storage": evidence_status,
|
||||
"pfsense": "contract_only",
|
||||
"security_events": security_events_readiness_status(args),
|
||||
"clickhouse": if args.security_events_backend == "clickhouse" { "configured" } else { "not_required" }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn storage_readiness_status(path: &Path) -> String {
|
||||
if path.exists() {
|
||||
if path.is_dir() {
|
||||
"ok".to_string()
|
||||
} else {
|
||||
"error".to_string()
|
||||
}
|
||||
} else {
|
||||
"not_configured".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn storage_parent_readiness_status(path: &Path) -> String {
|
||||
path.parent()
|
||||
.map(storage_readiness_status)
|
||||
.unwrap_or_else(|| "not_configured".to_string())
|
||||
}
|
||||
|
||||
fn security_events_readiness_status(args: &Cli) -> &'static str {
|
||||
match args
|
||||
.security_events_backend
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
.as_str()
|
||||
{
|
||||
"disabled" | "" => "disabled",
|
||||
"clickhouse" => "configured",
|
||||
_ => "configured",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Request correlation and route classification for portal observability.
|
||||
//!
|
||||
//! CONTRACT: generated route names must not expose volatile identifiers such as
|
||||
//! case IDs, candidate IDs or evidence IDs; use route templates instead.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tiny_http::Request;
|
||||
|
||||
use crate::{
|
||||
normalize_path, parse_case_path, parse_case_status_path, parse_evidence_screenshot_path,
|
||||
parse_investigation_pack_path, portal_role_from_request,
|
||||
};
|
||||
|
||||
static REQUEST_SEQUENCE: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
thread_local! {
|
||||
static REQUEST_STARTED_AT: RefCell<Option<Instant>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct HttpRequestMetadata {
|
||||
pub(crate) method: String,
|
||||
pub(crate) path: String,
|
||||
pub(crate) route: String,
|
||||
pub(crate) module: String,
|
||||
pub(crate) role: String,
|
||||
pub(crate) request_id: String,
|
||||
pub(crate) correlation_id: String,
|
||||
pub(crate) latency_ms: u64,
|
||||
}
|
||||
|
||||
pub(crate) fn mark_request_started() {
|
||||
REQUEST_STARTED_AT.with(|started| {
|
||||
*started.borrow_mut() = Some(Instant::now());
|
||||
});
|
||||
}
|
||||
|
||||
fn request_latency_ms() -> u64 {
|
||||
REQUEST_STARTED_AT.with(|started| {
|
||||
started
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(|instant| instant.elapsed().as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn http_request_metadata(request: &Request) -> HttpRequestMetadata {
|
||||
let raw_url = request.url().to_string();
|
||||
let path = normalize_path(&raw_url);
|
||||
let method = request.method().as_str().to_string();
|
||||
let route = metrics_route(&path);
|
||||
let module = metrics_module(&route).to_string();
|
||||
let role = portal_role_from_request(request, &raw_url)
|
||||
.as_str()
|
||||
.to_string();
|
||||
let request_id =
|
||||
request_header(request, "X-Request-Id").or_else(|| request_header(request, "X-Request-ID"));
|
||||
let correlation_id = request_header(request, "X-Correlation-Id")
|
||||
.or_else(|| request_header(request, "X-Correlation-ID"));
|
||||
let (request_id, correlation_id) = resolve_request_ids(request_id, correlation_id);
|
||||
HttpRequestMetadata {
|
||||
method,
|
||||
path,
|
||||
route,
|
||||
module,
|
||||
role,
|
||||
request_id,
|
||||
correlation_id,
|
||||
latency_ms: request_latency_ms(),
|
||||
}
|
||||
}
|
||||
|
||||
fn request_header(request: &Request, name: &str) -> Option<String> {
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|header| header.field.as_str().as_str().eq_ignore_ascii_case(name))
|
||||
.map(|header| header.value.as_str().to_string())
|
||||
}
|
||||
|
||||
fn resolve_request_ids(
|
||||
request_id: Option<String>,
|
||||
correlation_id: Option<String>,
|
||||
) -> (String, String) {
|
||||
let request_id = request_id
|
||||
.map(sanitize_request_token)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(generate_request_id);
|
||||
let correlation_id = correlation_id
|
||||
.map(sanitize_request_token)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(|| request_id.clone());
|
||||
(request_id, correlation_id)
|
||||
}
|
||||
|
||||
fn sanitize_request_token(value: String) -> String {
|
||||
value
|
||||
.chars()
|
||||
.filter(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | ':'))
|
||||
.take(96)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn generate_request_id() -> String {
|
||||
let seq = REQUEST_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_millis())
|
||||
.unwrap_or(0);
|
||||
format!("awatch-{millis}-{seq}")
|
||||
}
|
||||
|
||||
fn metrics_route(path: &str) -> String {
|
||||
if parse_investigation_pack_path(path).is_some() {
|
||||
return "/api/investigation-pack/{candidate_id}".to_string();
|
||||
}
|
||||
if parse_case_path(path).is_some() {
|
||||
return "/api/cases/{case_id}".to_string();
|
||||
}
|
||||
if parse_case_status_path(path).is_some() {
|
||||
return "/api/cases/{case_id}/status".to_string();
|
||||
}
|
||||
if parse_evidence_screenshot_path(path).is_some() {
|
||||
return "/api/dlp/evidence/{evidence_id}/asset".to_string();
|
||||
}
|
||||
match path {
|
||||
"/" | "/operator" | "/manager" | "/owner" | "/incidents" | "/reports" | "/architecture" => {
|
||||
path.to_string()
|
||||
}
|
||||
"/healthz" | "/api/healthz" => "/healthz".to_string(),
|
||||
"/readyz" | "/api/readyz" => "/readyz".to_string(),
|
||||
"/version" | "/api/version" => "/version".to_string(),
|
||||
"/metrics" | "/api/metrics" => "/metrics".to_string(),
|
||||
_ if path.starts_with("/api/") => path.to_string(),
|
||||
_ => "other".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn metrics_module(route: &str) -> &'static str {
|
||||
if route.starts_with("/healthz")
|
||||
|| route.starts_with("/readyz")
|
||||
|| route.starts_with("/version")
|
||||
|| route.starts_with("/metrics")
|
||||
{
|
||||
"runtime"
|
||||
} else if route.contains("/workforce") || route == "/manager" {
|
||||
"workforce"
|
||||
} else if route.contains("/security")
|
||||
|| route.contains("/incidents")
|
||||
|| route.contains("/incident-review")
|
||||
{
|
||||
"security"
|
||||
} else if route.contains("/forensics")
|
||||
|| route.contains("/investigation-pack")
|
||||
|| route.contains("/cases")
|
||||
|| route.contains("/dlp/evidence")
|
||||
{
|
||||
"forensics"
|
||||
} else if route.contains("/ueba") {
|
||||
"ueba"
|
||||
} else if route.contains("/pfsense") {
|
||||
"pfsense"
|
||||
} else if route.contains("/reports") || route.contains("/executive") || route == "/operator" {
|
||||
"reports"
|
||||
} else {
|
||||
"portal"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn request_id_and_correlation_id_are_sanitized_and_linked() {
|
||||
let (request_id, correlation_id) = resolve_request_ids(
|
||||
Some(" req-123\nbad ".to_string()),
|
||||
Some("corr-456/ignored".to_string()),
|
||||
);
|
||||
assert_eq!(request_id, "req-123bad");
|
||||
assert_eq!(correlation_id, "corr-456ignored");
|
||||
|
||||
let (request_id, correlation_id) =
|
||||
resolve_request_ids(Some("rid_1".to_string()), Some(" \n ".to_string()));
|
||||
assert_eq!(request_id, "rid_1");
|
||||
assert_eq!(correlation_id, "rid_1");
|
||||
|
||||
let (generated, generated_correlation) = resolve_request_ids(None, None);
|
||||
assert!(generated.starts_with("awatch-"));
|
||||
assert_eq!(generated, generated_correlation);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Build/version probe payload.
|
||||
//!
|
||||
//! CONTRACT: `/version` is used by smoke tests, runbooks and release evidence.
|
||||
//! Keep field names stable and add new fields only in a backward-compatible way.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Cli, PORTAL_SCHEMA_VERSION};
|
||||
|
||||
pub(crate) fn build_version(args: &Cli) -> Value {
|
||||
json!({
|
||||
"app_version": env!("CARGO_PKG_VERSION"),
|
||||
"git_commit": option_env!("GIT_COMMIT").unwrap_or("unknown"),
|
||||
"build_time": option_env!("BUILD_TIME").unwrap_or("unknown"),
|
||||
"schema_version": PORTAL_SCHEMA_VERSION,
|
||||
"environment": args.environment,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::production::limits::parse_query_date;
|
||||
use crate::{
|
||||
AgentCoverageSla, ExecutiveDashboard, PortalRole, RiskHeatmapItem, RiskIncidentCandidate,
|
||||
SecurityCorrelationItem, SecurityEventsSummary, Snapshot, query_param, role_envelope,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct RiskNarrativeQuery {
|
||||
date: Option<String>,
|
||||
department: Option<String>,
|
||||
module: Option<String>,
|
||||
}
|
||||
|
||||
impl RiskNarrativeQuery {
|
||||
pub(crate) fn from_url(url: &str) -> Self {
|
||||
Self {
|
||||
date: query_param(url, "date").filter(|value| parse_query_date(value).is_some()),
|
||||
department: query_param(url, "department").filter(|value| !value.trim().is_empty()),
|
||||
module: query_param(url, "module").filter(|value| !value.trim().is_empty()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct RiskNarrativeInputs<'a> {
|
||||
pub(crate) snapshot: &'a Snapshot,
|
||||
pub(crate) workforce_kpi_explain: &'a Value,
|
||||
pub(crate) ueba_risk: &'a Value,
|
||||
pub(crate) agent_coverage_sla: &'a AgentCoverageSla,
|
||||
pub(crate) risk_heatmap: &'a [RiskHeatmapItem],
|
||||
pub(crate) security_correlation: &'a [SecurityCorrelationItem],
|
||||
pub(crate) risk_incident_candidates: &'a [RiskIncidentCandidate],
|
||||
pub(crate) executive_dashboard: &'a ExecutiveDashboard,
|
||||
pub(crate) security_events_summary: &'a SecurityEventsSummary,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct NarrativeSignal {
|
||||
score: u8,
|
||||
level: &'static str,
|
||||
confidence: String,
|
||||
classification: String,
|
||||
why: Vec<String>,
|
||||
evidence: Vec<Value>,
|
||||
recommended_actions: Vec<String>,
|
||||
limitations: Vec<String>,
|
||||
department: Option<String>,
|
||||
generated_at_utc: String,
|
||||
}
|
||||
|
||||
pub(crate) fn build_risk_narrative(
|
||||
inputs: RiskNarrativeInputs<'_>,
|
||||
role: PortalRole,
|
||||
query: &RiskNarrativeQuery,
|
||||
) -> Value {
|
||||
let selected_heatmap = select_heatmap_item(inputs.risk_heatmap, query.department.as_deref());
|
||||
let selected_correlation = select_correlation_item(
|
||||
inputs.security_correlation,
|
||||
selected_heatmap
|
||||
.map(|item| item.department.as_str())
|
||||
.or(query.department.as_deref()),
|
||||
);
|
||||
let mut signal = NarrativeSignal {
|
||||
score: 0,
|
||||
level: "low",
|
||||
confidence: "unknown".to_string(),
|
||||
classification: "insufficient_data".to_string(),
|
||||
why: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
recommended_actions: Vec::new(),
|
||||
limitations: risk_narrative_limitations(),
|
||||
department: selected_heatmap
|
||||
.map(|item| item.department.clone())
|
||||
.or_else(|| query.department.clone()),
|
||||
generated_at_utc: inputs.snapshot.generated_at_utc.clone(),
|
||||
};
|
||||
|
||||
add_workforce_kpi_signal(&mut signal, inputs.workforce_kpi_explain);
|
||||
add_ueba_signal(&mut signal, inputs.ueba_risk);
|
||||
add_ueba_confidence_guardrails(&mut signal, inputs.ueba_risk);
|
||||
add_coverage_signal(
|
||||
&mut signal,
|
||||
inputs.agent_coverage_sla,
|
||||
inputs.workforce_kpi_explain,
|
||||
);
|
||||
add_heatmap_signal(&mut signal, selected_heatmap);
|
||||
add_security_correlation_signal(&mut signal, selected_correlation);
|
||||
let department_scope = signal.department.clone();
|
||||
add_incident_candidate_signal(
|
||||
&mut signal,
|
||||
inputs.risk_incident_candidates,
|
||||
department_scope.as_deref(),
|
||||
);
|
||||
add_security_events_signal(&mut signal, inputs.security_events_summary);
|
||||
add_remote_activity_signal(&mut signal, inputs.workforce_kpi_explain);
|
||||
add_pfsense_contract_signal(&mut signal);
|
||||
|
||||
signal.score = signal.score.min(100);
|
||||
signal.level = risk_level(signal.score);
|
||||
finalize_recommendations(&mut signal, inputs.executive_dashboard);
|
||||
narrative_payload(signal, role, query)
|
||||
}
|
||||
|
||||
pub(crate) fn build_risk_narrative_from_report(
|
||||
report: &Value,
|
||||
role: PortalRole,
|
||||
query: &RiskNarrativeQuery,
|
||||
) -> Value {
|
||||
let mut signal = NarrativeSignal {
|
||||
score: 0,
|
||||
level: "low",
|
||||
confidence: "unknown".to_string(),
|
||||
classification: "insufficient_data".to_string(),
|
||||
why: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
recommended_actions: Vec::new(),
|
||||
limitations: risk_narrative_limitations(),
|
||||
department: query.department.clone(),
|
||||
generated_at_utc: report
|
||||
.get("generated_at_utc")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown")
|
||||
.to_string(),
|
||||
};
|
||||
|
||||
add_workforce_kpi_signal(
|
||||
&mut signal,
|
||||
report.get("workforce_kpi_explain").unwrap_or(&Value::Null),
|
||||
);
|
||||
add_ueba_signal(&mut signal, report.get("ueba_risk").unwrap_or(&Value::Null));
|
||||
add_ueba_confidence_guardrails(&mut signal, report.get("ueba_risk").unwrap_or(&Value::Null));
|
||||
add_coverage_from_report_signal(&mut signal, report);
|
||||
let selected_heatmap = select_heatmap_value(
|
||||
report.get("risk_heatmap").and_then(Value::as_array),
|
||||
query.department.as_deref(),
|
||||
);
|
||||
if let Some(item) = selected_heatmap {
|
||||
if signal.department.is_none() {
|
||||
signal.department = item
|
||||
.get("department")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
}
|
||||
add_heatmap_value_signal(&mut signal, item);
|
||||
}
|
||||
let selected_correlation = select_correlation_value(
|
||||
report.get("security_correlation").and_then(Value::as_array),
|
||||
signal.department.as_deref().or(query.department.as_deref()),
|
||||
);
|
||||
if let Some(item) = selected_correlation {
|
||||
add_security_correlation_value_signal(&mut signal, item);
|
||||
}
|
||||
add_incident_candidate_value_signal(
|
||||
&mut signal,
|
||||
report
|
||||
.get("risk_incident_candidates")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]),
|
||||
);
|
||||
add_security_events_value_signal(
|
||||
&mut signal,
|
||||
report
|
||||
.get("security_events_summary")
|
||||
.unwrap_or(&Value::Null),
|
||||
);
|
||||
add_remote_activity_signal(
|
||||
&mut signal,
|
||||
report.get("workforce_kpi_explain").unwrap_or(&Value::Null),
|
||||
);
|
||||
add_pfsense_contract_signal(&mut signal);
|
||||
|
||||
signal.score = signal.score.min(100);
|
||||
signal.level = risk_level(signal.score);
|
||||
finalize_recommendations_from_report(&mut signal, report);
|
||||
narrative_payload(signal, role, query)
|
||||
}
|
||||
|
||||
fn select_heatmap_item<'a>(
|
||||
items: &'a [RiskHeatmapItem],
|
||||
department: Option<&str>,
|
||||
) -> Option<&'a RiskHeatmapItem> {
|
||||
if let Some(department) = department {
|
||||
items
|
||||
.iter()
|
||||
.find(|item| item.department.eq_ignore_ascii_case(department))
|
||||
} else {
|
||||
items.first()
|
||||
}
|
||||
}
|
||||
|
||||
fn select_correlation_item<'a>(
|
||||
items: &'a [SecurityCorrelationItem],
|
||||
department: Option<&str>,
|
||||
) -> Option<&'a SecurityCorrelationItem> {
|
||||
department
|
||||
.and_then(|department| {
|
||||
items
|
||||
.iter()
|
||||
.find(|item| item.department.eq_ignore_ascii_case(department))
|
||||
})
|
||||
.or_else(|| items.iter().max_by_key(|item| item.correlation_score))
|
||||
}
|
||||
|
||||
fn select_heatmap_value<'a>(
|
||||
items: Option<&'a Vec<Value>>,
|
||||
department: Option<&str>,
|
||||
) -> Option<&'a Value> {
|
||||
let items = items?;
|
||||
if let Some(department) = department {
|
||||
items.iter().find(|item| {
|
||||
item.get("department")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case(department))
|
||||
})
|
||||
} else {
|
||||
items.first()
|
||||
}
|
||||
}
|
||||
|
||||
fn select_correlation_value<'a>(
|
||||
items: Option<&'a Vec<Value>>,
|
||||
department: Option<&str>,
|
||||
) -> Option<&'a Value> {
|
||||
let items = items?;
|
||||
department
|
||||
.and_then(|department| {
|
||||
items.iter().find(|item| {
|
||||
item.get("department")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case(department))
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().max_by_key(|item| {
|
||||
item.get("correlation_score")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn add_workforce_kpi_signal(signal: &mut NarrativeSignal, explain: &Value) {
|
||||
let kpi_score = explain.get("kpi_score").and_then(Value::as_u64);
|
||||
let confidence = explain
|
||||
.get("confidence")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("low");
|
||||
if let Some(score) = kpi_score {
|
||||
let risk = 100_u64.saturating_sub(score.min(100));
|
||||
if risk >= 50 {
|
||||
add_score(
|
||||
signal,
|
||||
30,
|
||||
"Индекс активности существенно ниже рабочего ориентира",
|
||||
);
|
||||
} else if risk >= 30 {
|
||||
add_score(signal, 20, "Индекс активности ниже среднего уровня");
|
||||
} else if risk >= 15 {
|
||||
add_score(signal, 10, "Индекс активности немного ниже целевого уровня");
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"workforce_kpi",
|
||||
"Индекс активности",
|
||||
&format!("{score}%"),
|
||||
score_to_severity(score as u8),
|
||||
));
|
||||
} else {
|
||||
add_score(signal, 12, "Индекс активности не рассчитан");
|
||||
signal.evidence.push(evidence(
|
||||
"workforce_kpi",
|
||||
"Индекс активности",
|
||||
"нет данных",
|
||||
"medium",
|
||||
));
|
||||
}
|
||||
match confidence {
|
||||
"low" => add_score(signal, 20, "Низкое доверие к KPI"),
|
||||
"medium" => add_score(
|
||||
signal,
|
||||
10,
|
||||
"KPI рассчитан с частичными ограничениями данных",
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"workforce_kpi",
|
||||
"Доверие к KPI",
|
||||
confidence,
|
||||
match confidence {
|
||||
"low" => "high",
|
||||
"medium" => "medium",
|
||||
_ => "low",
|
||||
},
|
||||
));
|
||||
if let Some(missing) = explain
|
||||
.pointer("/coverage/missing_sources")
|
||||
.and_then(Value::as_array)
|
||||
{
|
||||
let count = missing.len();
|
||||
if count > 0 {
|
||||
add_score(
|
||||
signal,
|
||||
(count as u8).saturating_mul(6).min(18),
|
||||
"Есть пропуски источников данных",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_ueba_signal(signal: &mut NarrativeSignal, risk: &Value) {
|
||||
let level = risk
|
||||
.get("level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("normal");
|
||||
let score = risk
|
||||
.get("score")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0)
|
||||
.min(100);
|
||||
match level {
|
||||
"critical" => add_score(signal, 30, "UEBA score находится на критическом уровне"),
|
||||
"high" => add_score(signal, 22, "UEBA score повышен до high"),
|
||||
"medium" => add_score(signal, 12, "UEBA score находится на среднем уровне"),
|
||||
"low" => add_score(signal, 5, "UEBA score показывает низкий, но ненулевой риск"),
|
||||
_ => {}
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"ueba",
|
||||
"UEBA score",
|
||||
&format!("{level} · {score}/100"),
|
||||
match level {
|
||||
"critical" => "critical",
|
||||
"high" => "high",
|
||||
"medium" => "medium",
|
||||
_ => "low",
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn add_ueba_confidence_guardrails(signal: &mut NarrativeSignal, risk: &Value) {
|
||||
let confidence = risk
|
||||
.get("confidence_level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let classification = risk
|
||||
.get("classification")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("insufficient_data");
|
||||
signal.confidence = confidence.to_string();
|
||||
signal.classification = classification.to_string();
|
||||
if matches!(confidence, "low" | "unknown") {
|
||||
push_unique(&mut signal.why, "Уверенность в выводе ниже целевого уровня");
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Проверить полноту данных до управленческого вывода",
|
||||
);
|
||||
push_unique(
|
||||
&mut signal.limitations,
|
||||
"Низкая уверенность не подтверждает инцидент без ручной проверки",
|
||||
);
|
||||
}
|
||||
if classification == "needs_investigation" {
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Зафиксировать статус Needs Investigation и передать на ручной разбор",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_coverage_signal(
|
||||
signal: &mut NarrativeSignal,
|
||||
sla: &AgentCoverageSla,
|
||||
workforce_kpi_explain: &Value,
|
||||
) {
|
||||
let coverage = if sla.expected_nodes > 0 {
|
||||
Some(sla.coverage_pct)
|
||||
} else {
|
||||
workforce_kpi_explain
|
||||
.pointer("/coverage/agent_coverage_percent")
|
||||
.and_then(Value::as_u64)
|
||||
.map(|value| value.min(100) as u8)
|
||||
};
|
||||
if let Some(value) = coverage {
|
||||
if value < 50 {
|
||||
add_score(
|
||||
signal,
|
||||
25,
|
||||
"Покрытие агентов критически ниже целевого уровня",
|
||||
);
|
||||
} else if value < 75 {
|
||||
add_score(signal, 18, "Покрытие агентов ниже целевого уровня");
|
||||
} else if value < 90 {
|
||||
add_score(signal, 8, "Покрытие агентов требует внимания");
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"coverage",
|
||||
"Покрытие агентов",
|
||||
&format!("{value}%"),
|
||||
if value < 50 {
|
||||
"high"
|
||||
} else if value < 75 {
|
||||
"medium"
|
||||
} else {
|
||||
"low"
|
||||
},
|
||||
));
|
||||
} else {
|
||||
add_score(signal, 10, "Покрытие агентов не подтверждено");
|
||||
}
|
||||
}
|
||||
|
||||
fn add_coverage_from_report_signal(signal: &mut NarrativeSignal, report: &Value) {
|
||||
let coverage = report
|
||||
.pointer("/agent_coverage_sla/coverage_pct")
|
||||
.and_then(Value::as_u64)
|
||||
.or_else(|| {
|
||||
report
|
||||
.pointer("/workforce_kpi_explain/coverage/agent_coverage_percent")
|
||||
.and_then(Value::as_u64)
|
||||
})
|
||||
.map(|value| value.min(100) as u8);
|
||||
if let Some(value) = coverage {
|
||||
if value < 50 {
|
||||
add_score(
|
||||
signal,
|
||||
25,
|
||||
"Покрытие агентов критически ниже целевого уровня",
|
||||
);
|
||||
} else if value < 75 {
|
||||
add_score(signal, 18, "Покрытие агентов ниже целевого уровня");
|
||||
} else if value < 90 {
|
||||
add_score(signal, 8, "Покрытие агентов требует внимания");
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"coverage",
|
||||
"Покрытие агентов",
|
||||
&format!("{value}%"),
|
||||
if value < 50 {
|
||||
"high"
|
||||
} else if value < 75 {
|
||||
"medium"
|
||||
} else {
|
||||
"low"
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn add_heatmap_signal(signal: &mut NarrativeSignal, item: Option<&RiskHeatmapItem>) {
|
||||
let Some(item) = item else {
|
||||
return;
|
||||
};
|
||||
match item.heat_level.as_str() {
|
||||
"CRITICAL" => add_score(signal, 25, "Карта рисков показывает критический уровень"),
|
||||
"HIGH" => add_score(signal, 18, "Карта рисков показывает высокий уровень"),
|
||||
"MEDIUM" => add_score(signal, 10, "Карта рисков показывает средний уровень"),
|
||||
_ => {}
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"risk_heatmap",
|
||||
"Карта рисков",
|
||||
&format!("{} · {}", item.department, item.heat_level),
|
||||
heatmap_severity(&item.heat_level),
|
||||
));
|
||||
}
|
||||
|
||||
fn add_heatmap_value_signal(signal: &mut NarrativeSignal, item: &Value) {
|
||||
let level = item
|
||||
.get("heat_level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("UNKNOWN");
|
||||
match level {
|
||||
"CRITICAL" => add_score(signal, 25, "Карта рисков показывает критический уровень"),
|
||||
"HIGH" => add_score(signal, 18, "Карта рисков показывает высокий уровень"),
|
||||
"MEDIUM" => add_score(signal, 10, "Карта рисков показывает средний уровень"),
|
||||
_ => {}
|
||||
}
|
||||
let department = item
|
||||
.get("department")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("-");
|
||||
signal.evidence.push(evidence(
|
||||
"risk_heatmap",
|
||||
"Карта рисков",
|
||||
&format!("{department} · {level}"),
|
||||
heatmap_severity(level),
|
||||
));
|
||||
}
|
||||
|
||||
fn add_security_correlation_signal(
|
||||
signal: &mut NarrativeSignal,
|
||||
item: Option<&SecurityCorrelationItem>,
|
||||
) {
|
||||
let Some(item) = item else {
|
||||
return;
|
||||
};
|
||||
let score = item.correlation_score;
|
||||
if score >= 85 {
|
||||
add_score(signal, 22, "Связь рисков и активности высокая");
|
||||
} else if score >= 60 {
|
||||
add_score(signal, 15, "Связь рисков и активности повышена");
|
||||
} else if score >= 35 {
|
||||
add_score(signal, 8, "Есть умеренная связь рисков и активности");
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"security_correlation",
|
||||
"Связь рисков и активности",
|
||||
&format!("{score}/100"),
|
||||
if score >= 85 {
|
||||
"high"
|
||||
} else if score >= 60 {
|
||||
"medium"
|
||||
} else {
|
||||
"low"
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn add_security_correlation_value_signal(signal: &mut NarrativeSignal, item: &Value) {
|
||||
let score = item
|
||||
.get("correlation_score")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0)
|
||||
.min(100) as u8;
|
||||
if score >= 85 {
|
||||
add_score(signal, 22, "Связь рисков и активности высокая");
|
||||
} else if score >= 60 {
|
||||
add_score(signal, 15, "Связь рисков и активности повышена");
|
||||
} else if score >= 35 {
|
||||
add_score(signal, 8, "Есть умеренная связь рисков и активности");
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"security_correlation",
|
||||
"Связь рисков и активности",
|
||||
&format!("{score}/100"),
|
||||
if score >= 85 {
|
||||
"high"
|
||||
} else if score >= 60 {
|
||||
"medium"
|
||||
} else {
|
||||
"low"
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn add_incident_candidate_signal(
|
||||
signal: &mut NarrativeSignal,
|
||||
candidates: &[RiskIncidentCandidate],
|
||||
department: Option<&str>,
|
||||
) {
|
||||
let count = candidates
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
department.is_none_or(|department| {
|
||||
item.department
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case(department))
|
||||
})
|
||||
})
|
||||
.filter(|item| {
|
||||
matches!(
|
||||
item.risk_level.as_deref().unwrap_or("UNKNOWN"),
|
||||
"HIGH" | "CRITICAL"
|
||||
)
|
||||
})
|
||||
.count();
|
||||
if count > 0 {
|
||||
add_score(
|
||||
signal,
|
||||
(count as u8).saturating_mul(10).min(25),
|
||||
"Есть кандидаты на ручную проверку",
|
||||
);
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"incident_candidates",
|
||||
"Кандидаты на проверку",
|
||||
&count.to_string(),
|
||||
if count > 0 { "medium" } else { "low" },
|
||||
));
|
||||
}
|
||||
|
||||
fn add_incident_candidate_value_signal(signal: &mut NarrativeSignal, candidates: &[Value]) {
|
||||
let count = candidates
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
matches!(
|
||||
item.get("risk_level")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("UNKNOWN"),
|
||||
"HIGH" | "CRITICAL"
|
||||
)
|
||||
})
|
||||
.count();
|
||||
if count > 0 {
|
||||
add_score(
|
||||
signal,
|
||||
(count as u8).saturating_mul(10).min(25),
|
||||
"Есть кандидаты на ручную проверку",
|
||||
);
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"incident_candidates",
|
||||
"Кандидаты на проверку",
|
||||
&count.to_string(),
|
||||
if count > 0 { "medium" } else { "low" },
|
||||
));
|
||||
}
|
||||
|
||||
fn add_security_events_signal(signal: &mut NarrativeSignal, summary: &SecurityEventsSummary) {
|
||||
if summary.fallback_used {
|
||||
add_score(
|
||||
signal,
|
||||
8,
|
||||
"Агрегированные события безопасности доступны в резервном режиме",
|
||||
);
|
||||
}
|
||||
if summary.events_24h > 0 {
|
||||
add_score(
|
||||
signal,
|
||||
summary.events_24h.saturating_mul(3).min(15) as u8,
|
||||
"Есть агрегированные события безопасности за 24 часа",
|
||||
);
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"security_events",
|
||||
"События безопасности",
|
||||
&summary.events_24h.to_string(),
|
||||
if summary.events_24h > 0 {
|
||||
"medium"
|
||||
} else {
|
||||
"low"
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn add_security_events_value_signal(signal: &mut NarrativeSignal, summary: &Value) {
|
||||
let events = summary
|
||||
.get("events_24h")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
if summary
|
||||
.get("fallback_used")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
add_score(
|
||||
signal,
|
||||
8,
|
||||
"Агрегированные события безопасности доступны в резервном режиме",
|
||||
);
|
||||
}
|
||||
if events > 0 {
|
||||
add_score(
|
||||
signal,
|
||||
events.saturating_mul(3).min(15) as u8,
|
||||
"Есть агрегированные события безопасности за 24 часа",
|
||||
);
|
||||
}
|
||||
signal.evidence.push(evidence(
|
||||
"security_events",
|
||||
"События безопасности",
|
||||
&events.to_string(),
|
||||
if events > 0 { "medium" } else { "low" },
|
||||
));
|
||||
}
|
||||
|
||||
fn add_remote_activity_signal(signal: &mut NarrativeSignal, explain: &Value) {
|
||||
let factors = explain
|
||||
.get("factors")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]);
|
||||
let afterhours = factors
|
||||
.iter()
|
||||
.find(|item| item.get("name").and_then(Value::as_str) == Some("afterhours_activity"));
|
||||
if let Some(item) = afterhours {
|
||||
let impact = item.get("impact").and_then(Value::as_str).unwrap_or("0");
|
||||
if impact.starts_with('-') && impact != "-0" {
|
||||
add_score(signal, 8, "Есть признаки активности вне рабочего времени");
|
||||
signal.evidence.push(evidence(
|
||||
"workforce_kpi",
|
||||
"Активность вне рабочего времени",
|
||||
impact,
|
||||
"medium",
|
||||
));
|
||||
}
|
||||
}
|
||||
if factors.iter().any(|item| {
|
||||
item.get("name").and_then(Value::as_str) == Some("remote_session_activity")
|
||||
&& item.get("impact").and_then(Value::as_str).unwrap_or("0") != "0"
|
||||
}) {
|
||||
signal.evidence.push(evidence(
|
||||
"workforce_kpi",
|
||||
"Удаленные сессии",
|
||||
"обнаружены",
|
||||
"low",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn add_pfsense_contract_signal(signal: &mut NarrativeSignal) {
|
||||
add_score(signal, 3, "pfSense находится в contract_only режиме");
|
||||
signal.evidence.push(evidence(
|
||||
"pfsense",
|
||||
"pfSense readiness",
|
||||
"contract_only",
|
||||
"low",
|
||||
));
|
||||
}
|
||||
|
||||
fn add_score(signal: &mut NarrativeSignal, points: u8, reason: &str) {
|
||||
signal.score = signal.score.saturating_add(points);
|
||||
if !signal.why.iter().any(|item| item == reason) {
|
||||
signal.why.push(reason.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize_recommendations(signal: &mut NarrativeSignal, dashboard: &ExecutiveDashboard) {
|
||||
finalize_common_recommendations(signal);
|
||||
if dashboard
|
||||
.critical_candidates
|
||||
.as_ref()
|
||||
.is_some_and(|items| !items.is_empty())
|
||||
{
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Передать кандидатов на проверку в контур ИБ",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize_recommendations_from_report(signal: &mut NarrativeSignal, report: &Value) {
|
||||
finalize_common_recommendations(signal);
|
||||
if report
|
||||
.get("risk_incident_candidates")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| !items.is_empty())
|
||||
{
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Передать кандидатов на проверку в контур ИБ",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize_common_recommendations(signal: &mut NarrativeSignal) {
|
||||
if signal
|
||||
.why
|
||||
.iter()
|
||||
.any(|item| item.contains("Покрытие") || item.contains("пропуски"))
|
||||
{
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Проверить подразделения с низким покрытием данных",
|
||||
);
|
||||
}
|
||||
if signal.why.iter().any(|item| item.contains("UEBA")) {
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Передать security-события в контур ИБ для анализа",
|
||||
);
|
||||
}
|
||||
if signal
|
||||
.evidence
|
||||
.iter()
|
||||
.any(|item| item.get("label").and_then(Value::as_str) == Some("Удаленные сессии"))
|
||||
{
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Проверить рост удаленных сессий",
|
||||
);
|
||||
}
|
||||
if signal.recommended_actions.is_empty() {
|
||||
push_unique(
|
||||
&mut signal.recommended_actions,
|
||||
"Продолжить наблюдение и контролировать полноту данных",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_unique(items: &mut Vec<String>, value: &str) {
|
||||
if !items.iter().any(|item| item == value) {
|
||||
items.push(value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn risk_narrative_limitations() -> Vec<String> {
|
||||
vec![
|
||||
"pfSense находится в contract_only режиме".to_string(),
|
||||
"Risk Narrative не является ML-прогнозом".to_string(),
|
||||
"Risk Narrative не подтверждает нарушение без ручной проверки".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn narrative_payload(
|
||||
signal: NarrativeSignal,
|
||||
role: PortalRole,
|
||||
query: &RiskNarrativeQuery,
|
||||
) -> Value {
|
||||
json!({
|
||||
"ok": true,
|
||||
"role_context": role_envelope(role, "risk_narrative"),
|
||||
"scope": if signal.department.is_some() { "department" } else { "aggregate" },
|
||||
"query": {
|
||||
"date": query.date,
|
||||
"department": query.department,
|
||||
"module": query.module,
|
||||
"employee_id_supported": false
|
||||
},
|
||||
"risk_level": signal.level,
|
||||
"risk_score": signal.score,
|
||||
"confidence": signal.confidence,
|
||||
"classification": signal.classification,
|
||||
"title": risk_title(signal.level),
|
||||
"summary": risk_summary(signal.level, signal.department.as_deref(), &signal.why),
|
||||
"why": signal.why,
|
||||
"evidence": signal.evidence,
|
||||
"recommended_actions": signal.recommended_actions,
|
||||
"limitations": signal.limitations,
|
||||
"model": {
|
||||
"type": "rule_based",
|
||||
"ml": false,
|
||||
"llm": false,
|
||||
"predictive": false,
|
||||
"version": "risk-narrative-v1"
|
||||
},
|
||||
"generated_at_utc": signal.generated_at_utc,
|
||||
})
|
||||
}
|
||||
|
||||
fn risk_level(score: u8) -> &'static str {
|
||||
match score {
|
||||
0..=24 => "low",
|
||||
25..=49 => "guarded",
|
||||
50..=74 => "medium",
|
||||
75..=89 => "high",
|
||||
_ => "critical",
|
||||
}
|
||||
}
|
||||
|
||||
fn risk_title(level: &str) -> &'static str {
|
||||
match level {
|
||||
"critical" => "Критический рост операционного риска",
|
||||
"high" => "Высокий операционный риск",
|
||||
"medium" => "Умеренный рост операционного риска",
|
||||
"guarded" => "Риск требует наблюдения",
|
||||
_ => "Риск низкий",
|
||||
}
|
||||
}
|
||||
|
||||
fn risk_summary(level: &str, department: Option<&str>, why: &[String]) -> String {
|
||||
let scope = department
|
||||
.map(|value| format!("в зоне {value}"))
|
||||
.unwrap_or_else(|| "по текущему срезу".to_string());
|
||||
let reason = why
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "существенных негативных признаков не выявлено".to_string());
|
||||
match level {
|
||||
"critical" | "high" => {
|
||||
format!("{scope} риск повышен: {reason}. Требуется ручная проверка.")
|
||||
}
|
||||
"medium" => format!(
|
||||
"{scope} есть умеренный риск: {reason}. Нужно проверить причины и полноту данных."
|
||||
),
|
||||
"guarded" => format!("{scope} риск требует наблюдения: {reason}."),
|
||||
_ => format!("{scope} риск низкий: {reason}."),
|
||||
}
|
||||
}
|
||||
|
||||
fn evidence(source: &str, label: &str, value: &str, severity: &str) -> Value {
|
||||
json!({
|
||||
"source": source,
|
||||
"label": label,
|
||||
"value": value,
|
||||
"severity": severity,
|
||||
})
|
||||
}
|
||||
|
||||
fn score_to_severity(score: u8) -> &'static str {
|
||||
if score < 50 {
|
||||
"high"
|
||||
} else if score < 75 {
|
||||
"medium"
|
||||
} else {
|
||||
"low"
|
||||
}
|
||||
}
|
||||
|
||||
fn heatmap_severity(level: &str) -> &'static str {
|
||||
match level {
|
||||
"CRITICAL" => "critical",
|
||||
"HIGH" => "high",
|
||||
"MEDIUM" => "medium",
|
||||
_ => "low",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn risk_level_thresholds_are_stable() {
|
||||
assert_eq!(risk_level(0), "low");
|
||||
assert_eq!(risk_level(24), "low");
|
||||
assert_eq!(risk_level(25), "guarded");
|
||||
assert_eq!(risk_level(50), "medium");
|
||||
assert_eq!(risk_level(75), "high");
|
||||
assert_eq!(risk_level(90), "critical");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn report_builder_is_rule_based_and_does_not_support_employee_scope() {
|
||||
let report = json!({
|
||||
"generated_at_utc": "2026-06-07T10:00:00Z",
|
||||
"workforce_kpi_explain": {
|
||||
"kpi_score": 62,
|
||||
"confidence": "medium",
|
||||
"coverage": {
|
||||
"agent_coverage_percent": 70,
|
||||
"missing_sources": ["applications"]
|
||||
},
|
||||
"factors": [
|
||||
{"name": "afterhours_activity", "impact": "-2"},
|
||||
{"name": "remote_session_activity", "impact": "+2"}
|
||||
]
|
||||
},
|
||||
"ueba_risk": {"level": "high", "score": 72},
|
||||
"agent_coverage_sla": {"coverage_pct": 70},
|
||||
"risk_heatmap": [{"department": "DEPT-1", "heat_level": "HIGH"}],
|
||||
"security_correlation": [{"department": "DEPT-1", "correlation_score": 65}],
|
||||
"risk_incident_candidates": [{"risk_level": "HIGH"}],
|
||||
"security_events_summary": {"events_24h": 2, "fallback_used": false}
|
||||
});
|
||||
let query = RiskNarrativeQuery {
|
||||
department: Some("DEPT-1".to_string()),
|
||||
..RiskNarrativeQuery::default()
|
||||
};
|
||||
let narrative = build_risk_narrative_from_report(&report, PortalRole::Executive, &query);
|
||||
assert_eq!(narrative["ok"], true);
|
||||
assert_eq!(narrative["query"]["employee_id_supported"], false);
|
||||
assert_eq!(narrative["model"]["ml"], false);
|
||||
assert_eq!(narrative["model"]["llm"], false);
|
||||
assert!(
|
||||
narrative["risk_score"].as_u64().unwrap() >= 50,
|
||||
"expected elevated risk narrative"
|
||||
);
|
||||
assert!(
|
||||
narrative["why"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|item| item.as_str().unwrap().contains("UEBA"))
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,80 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>AWatch-rus Product Architecture</title>
|
||||
<link rel="stylesheet" href="/portal/app.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-layout">
|
||||
<aside class="sidebar" aria-label="Основная навигация">
|
||||
<div class="sidebar-brand">
|
||||
<strong>AWatch-rus</strong>
|
||||
<span>Архитектура продукта</span>
|
||||
</div>
|
||||
<nav class="tabs">
|
||||
<a class="nav-link" href="/portal/">Портал</a>
|
||||
<a class="nav-link is-active" href="/portal/architecture">Архитектура</a>
|
||||
</nav>
|
||||
</aside>
|
||||
<main class="shell architecture-page">
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<p class="eyebrow">AWatch-rus</p>
|
||||
<h1>Product Architecture</h1>
|
||||
<p class="lead">Текущие компоненты, предусмотренные расширения и будущие направления без заявления фиктивных collectors.</p>
|
||||
</div>
|
||||
<div class="topbar-side">
|
||||
<a class="small-button" href="/portal/">Вернуться в портал</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="content-panel architecture-content" aria-label="Архитектура продукта">
|
||||
<section class="card">
|
||||
<h2>Current Components</h2>
|
||||
<p>Эти элементы относятся к текущему рабочему контуру AWatch-rus.</p>
|
||||
<div class="architecture-grid">
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>Backend</strong><p>Rust-first серверные helpers, report layer и portal runtime.</p></article>
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>Portal</strong><p>Rust server-rendered HTML + HTMX-compatible JSON API.</p></article>
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>Rust Agent</strong><p>Агентский Rust runtime и Windows telemetry paths в текущей parity-модели.</p></article>
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>Reports</strong><p>Workforce, Security и Forensics отчеты, включая Markdown export.</p></article>
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>UEBA v1</strong><p>Прозрачная rule-based модель без ML, LLM и внешних SaaS.</p></article>
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>Forensics</strong><p>Карточки расследований, timeline и evidence package.</p></article>
|
||||
<article><span class="status-pill status-ok">implemented</span><strong>Role gates</strong><p>Серверные проверки доступа для Pilot v1 ролей.</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Planned Extensions</h2>
|
||||
<p>Эти направления предусмотрены архитектурой, но не являются готовой функциональностью без отдельной реализации и тестов.</p>
|
||||
<div class="architecture-grid">
|
||||
<article><span class="status-pill status-warn">planned</span><strong>PowerShell Provider</strong><p>Agentless/legacy Windows source после формализации provider contract.</p></article>
|
||||
<article><span class="status-pill status-warn">planned</span><strong>SSH Provider</strong><p>Read-only probes и existing logs для Linux/Unix/network hosts.</p></article>
|
||||
<article><span class="status-pill status-warn">planned</span><strong>Syslog Provider</strong><p>Нормализация событий от внешних log sources.</p></article>
|
||||
<article><span class="status-pill status-warn">planned</span><strong>1C Provider</strong><p>Расширение текущего file-based 1C analytics сценария до формального provider.</p></article>
|
||||
<article><span class="status-pill status-unknown">contract_only</span><strong>pfSense Provider</strong><p>Readiness contracts и demo fixture без заявления production ingestion.</p></article>
|
||||
<article><span class="status-pill status-warn">planned</span><strong>Russian OS validation</strong><p>Astra Linux, РЕД ОС, Альт и РОСА требуют distro-specific smoke и compatibility matrix.</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Future</h2>
|
||||
<p>Эти элементы являются будущими направлениями, а не частью текущего Pilot v1.</p>
|
||||
<div class="architecture-grid">
|
||||
<article><span class="status-pill status-unknown">future</span><strong>SCUD Provider</strong><p>Сопоставление с физическим доступом после отдельного vendor/source contract.</p></article>
|
||||
<article><span class="status-pill status-unknown">future</span><strong>VPN Provider</strong><p>Сетевой контекст для расследований после отдельной реализации.</p></article>
|
||||
<article><span class="status-pill status-unknown">future</span><strong>React/TypeScript Enterprise UI</strong><p>Будущий enterprise UI, не текущий основной portal UI.</p></article>
|
||||
<article><span class="status-pill status-unknown">future</span><strong>Tauri Desktop Forensics</strong><p>Отдельный desktop-контур для forensic workflows.</p></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Граница заявления</h2>
|
||||
<p>Страница является информационной. Она не добавляет backend API, collectors или ingestion. Planned и future элементы не считаются implemented.</p>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,30 +3,96 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>DetMir Portal</title>
|
||||
<title>AWatch-rus Portal</title>
|
||||
<link rel="stylesheet" href="app.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<p class="eyebrow">DetMir Portal</p>
|
||||
<h1>Контур компании</h1>
|
||||
<div class="app-layout">
|
||||
<aside class="sidebar" aria-label="Основная навигация">
|
||||
<div class="sidebar-brand">
|
||||
<strong>AWatch-rus</strong>
|
||||
<span>Активность и риски</span>
|
||||
</div>
|
||||
<div id="globalStatus" class="status-pill status-unknown">Загрузка</div>
|
||||
</header>
|
||||
<nav class="tabs">
|
||||
<button class="tab is-active" data-tab="operator">Обзор</button>
|
||||
<button class="tab" data-tab="employees">Сотрудники</button>
|
||||
<button class="tab" data-tab="departments">Подразделения</button>
|
||||
<button class="tab" data-tab="owner">Риски</button>
|
||||
<button class="tab" data-tab="incidents">Расследования</button>
|
||||
<button class="tab" data-tab="perimeter">Сетевой периметр</button>
|
||||
<button class="tab" data-tab="reports">Отчеты</button>
|
||||
<button class="tab" data-tab="settings">Настройки</button>
|
||||
<a class="nav-link" href="/portal/architecture">Архитектура</a>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<nav class="tabs" aria-label="Разделы портала">
|
||||
<button class="tab is-active" data-tab="operator">Оператор</button>
|
||||
<button class="tab" data-tab="manager">Руководитель</button>
|
||||
<button class="tab" data-tab="owner">Владелец</button>
|
||||
<button class="tab" data-tab="incidents">Инциденты ИБ</button>
|
||||
<button class="tab" data-tab="reports">Отчеты</button>
|
||||
</nav>
|
||||
<main class="shell">
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<p class="eyebrow">AWatch-rus</p>
|
||||
<h1>Пульс организации</h1>
|
||||
<p class="lead">Активность сотрудников, риски подразделений и материалы расследований за выбранный период</p>
|
||||
</div>
|
||||
<div class="topbar-side" aria-label="Параметры отчета">
|
||||
<div class="control-strip">
|
||||
<label>
|
||||
<span>Период</span>
|
||||
<select id="periodFilter">
|
||||
<option value="today">Сегодня</option>
|
||||
<option value="week">7 дней</option>
|
||||
<option value="month">30 дней</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Подразделение</span>
|
||||
<select id="departmentFilter">
|
||||
<option>Все</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="view-switch" aria-label="Ролевое представление">
|
||||
<span>Роль</span>
|
||||
<button class="view-button is-active" data-view-mode="executive" type="button">Руководитель</button>
|
||||
<button class="view-button" data-view-mode="manager" type="button">Менеджер</button>
|
||||
<button class="view-button" data-view-mode="security" type="button">Безопасность</button>
|
||||
<button class="view-button" data-view-mode="forensics" type="button">Расследования</button>
|
||||
<button class="view-button" data-view-mode="admin" type="button">Админ</button>
|
||||
</div>
|
||||
<div class="demo-switch" aria-label="Pilot v1 demo navigation">
|
||||
<span>Pilot v1 demo</span>
|
||||
<button class="demo-button is-active" data-demo-view-mode="executive" type="button">Executive demo</button>
|
||||
<button class="demo-button" data-demo-view-mode="manager" type="button">Manager demo</button>
|
||||
<button class="demo-button" data-demo-view-mode="security" type="button">Security demo</button>
|
||||
<button class="demo-button" data-demo-view-mode="forensics" type="button">Forensics demo</button>
|
||||
<button class="demo-button" data-demo-view-mode="admin" type="button">Admin demo</button>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button class="small-button primary" data-open-reports="true">Сформировать отчет</button>
|
||||
<button class="small-button" data-export-markdown="true">Текстовый отчет</button>
|
||||
<button class="small-button" data-print-report="true">PDF-отчет</button>
|
||||
<a class="small-button" href="/portal/api/reports" target="_blank" rel="noopener noreferrer">Данные</a>
|
||||
<div id="globalStatus" class="status-pill status-unknown">Загрузка данных</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section id="summary" class="summary-grid"></section>
|
||||
<section id="content" class="content-panel" aria-live="polite"></section>
|
||||
</main>
|
||||
<script src="app.js"></script>
|
||||
<section id="loadingStatus" class="loading-status loading-status-unknown" aria-live="polite">
|
||||
<div class="loading-status-head">
|
||||
<div>
|
||||
<strong id="loadingStateText">Загрузка данных</strong>
|
||||
<span id="loadingStageText">Получение данных</span>
|
||||
</div>
|
||||
<span id="loadingUpdatedText">последнее обновление: -</span>
|
||||
</div>
|
||||
<div class="loading-progress" aria-hidden="true">
|
||||
<div id="loadingProgressBar" style="width: 0%"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="content" class="content-panel" aria-live="polite"></section>
|
||||
<section id="summary" class="summary-grid service-summary"></section>
|
||||
</main>
|
||||
</div>
|
||||
<script src="app.js?v=20260604-security-cache"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,729 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::production::limits::parse_query_date;
|
||||
use crate::{
|
||||
PortalRole, Snapshot, display_text_opt, query_param, role_envelope, trend_status,
|
||||
workforce_index, workforce_index_status, workforce_trend_json, worktime_totals,
|
||||
};
|
||||
|
||||
struct KpiFactorInputs<'a> {
|
||||
users_count: usize,
|
||||
active_seconds: i64,
|
||||
apps_count: usize,
|
||||
kpi_score: u8,
|
||||
agent_coverage_percent: u8,
|
||||
missing_sources: &'a [String],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct KpiExplainQuery {
|
||||
date: Option<String>,
|
||||
department: Option<String>,
|
||||
owner: Option<String>,
|
||||
}
|
||||
|
||||
impl KpiExplainQuery {
|
||||
pub(crate) fn from_url(url: &str) -> Self {
|
||||
Self {
|
||||
date: query_param(url, "date").filter(|value| parse_query_date(value).is_some()),
|
||||
department: query_param(url, "department"),
|
||||
owner: query_param(url, "owner"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn build_workforce_kpi_explain(
|
||||
snapshot: &Snapshot,
|
||||
policy_explain: &Value,
|
||||
role: PortalRole,
|
||||
query: &KpiExplainQuery,
|
||||
anonymize: bool,
|
||||
) -> Value {
|
||||
let (users_count, active_seconds, apps_count) = worktime_totals(snapshot);
|
||||
let base_index = workforce_index(users_count, active_seconds);
|
||||
let policy_index = policy_explain
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.map(|value| value.min(100) as u8);
|
||||
let kpi_score = policy_index.or(base_index).unwrap_or(0);
|
||||
let agent_coverage_percent = kpi_agent_coverage(snapshot);
|
||||
let data_freshness = kpi_data_freshness(snapshot);
|
||||
let missing_sources = kpi_missing_sources(snapshot, users_count, apps_count);
|
||||
let confidence = kpi_confidence(
|
||||
users_count,
|
||||
agent_coverage_percent,
|
||||
&data_freshness,
|
||||
&missing_sources,
|
||||
);
|
||||
let factors = kpi_explain_factors(
|
||||
snapshot,
|
||||
policy_explain,
|
||||
KpiFactorInputs {
|
||||
users_count,
|
||||
active_seconds,
|
||||
apps_count,
|
||||
kpi_score,
|
||||
agent_coverage_percent,
|
||||
missing_sources: &missing_sources,
|
||||
},
|
||||
);
|
||||
let top_applications = kpi_top_applications(snapshot, anonymize);
|
||||
let warnings = kpi_warnings(kpi_score, confidence, &data_freshness, &missing_sources);
|
||||
let recommendations = kpi_recommendations(confidence, &missing_sources, kpi_score);
|
||||
let mut payload = json!({
|
||||
"ok": true,
|
||||
"scope": "aggregate",
|
||||
"role_context": role_envelope(role, "workforce_kpi_explain"),
|
||||
"query": {
|
||||
"date": query.date.clone(),
|
||||
"department": query.department.clone(),
|
||||
"owner": query.owner.clone(),
|
||||
"employee_id_supported": false
|
||||
},
|
||||
"kpi_score": kpi_score,
|
||||
"kpi_status": workforce_index_status(Some(kpi_score)),
|
||||
"confidence": confidence,
|
||||
"coverage": {
|
||||
"agent_coverage_percent": agent_coverage_percent,
|
||||
"data_freshness": data_freshness,
|
||||
"missing_sources": missing_sources,
|
||||
},
|
||||
"factors": factors,
|
||||
"top_applications": top_applications,
|
||||
"warnings": warnings,
|
||||
"recommendations": recommendations,
|
||||
"formula": "rule_based: activity + business app usage - idle/afterhours/missing data with coverage confidence",
|
||||
"model": {
|
||||
"type": "rule_based",
|
||||
"ml": false,
|
||||
"llm": false,
|
||||
"version": "workforce-kpi-explain-v1"
|
||||
},
|
||||
"generated_at_utc": snapshot.generated_at_utc,
|
||||
});
|
||||
filter_kpi_explain_for_role(&mut payload, role);
|
||||
payload
|
||||
}
|
||||
|
||||
fn kpi_agent_coverage(snapshot: &Snapshot) -> u8 {
|
||||
if snapshot.agent_coverage_sla.expected_nodes > 0 {
|
||||
snapshot.agent_coverage_sla.coverage_pct
|
||||
} else if snapshot.agent_quality.sessions_collected_total > 0 {
|
||||
75
|
||||
} else if snapshot.worktime.ok {
|
||||
60
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn kpi_data_freshness(snapshot: &Snapshot) -> String {
|
||||
if snapshot.worktime.status.eq_ignore_ascii_case("OK")
|
||||
&& snapshot
|
||||
.worktime_management
|
||||
.status
|
||||
.eq_ignore_ascii_case("OK")
|
||||
{
|
||||
"fresh".to_string()
|
||||
} else if snapshot.worktime.status.eq_ignore_ascii_case("DEGRADED")
|
||||
|| snapshot
|
||||
.worktime_management
|
||||
.status
|
||||
.eq_ignore_ascii_case("DEGRADED")
|
||||
|| snapshot
|
||||
.worktime
|
||||
.summary
|
||||
.to_ascii_lowercase()
|
||||
.contains("stale")
|
||||
|| snapshot
|
||||
.worktime_management
|
||||
.summary
|
||||
.to_ascii_lowercase()
|
||||
.contains("stale")
|
||||
{
|
||||
"stale".to_string()
|
||||
} else {
|
||||
"missing".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn kpi_missing_sources(snapshot: &Snapshot, users_count: usize, apps_count: usize) -> Vec<String> {
|
||||
let mut missing = Vec::new();
|
||||
if !snapshot.worktime.ok || users_count == 0 {
|
||||
missing.push("worktime".to_string());
|
||||
}
|
||||
if !snapshot.worktime_management.ok {
|
||||
missing.push("worktime_management".to_string());
|
||||
}
|
||||
if apps_count == 0 {
|
||||
missing.push("applications".to_string());
|
||||
}
|
||||
if snapshot.agent_coverage_sla.expected_nodes > 0
|
||||
&& snapshot.agent_coverage_sla.coverage_pct < 50
|
||||
{
|
||||
missing.push("agent_coverage".to_string());
|
||||
}
|
||||
missing.sort();
|
||||
missing.dedup();
|
||||
missing
|
||||
}
|
||||
|
||||
fn kpi_confidence(
|
||||
users_count: usize,
|
||||
agent_coverage_percent: u8,
|
||||
data_freshness: &str,
|
||||
missing_sources: &[String],
|
||||
) -> &'static str {
|
||||
if users_count == 0
|
||||
|| agent_coverage_percent < 50
|
||||
|| data_freshness == "missing"
|
||||
|| missing_sources.iter().any(|item| item == "worktime")
|
||||
{
|
||||
"low"
|
||||
} else if agent_coverage_percent < 80
|
||||
|| data_freshness != "fresh"
|
||||
|| !missing_sources.is_empty()
|
||||
{
|
||||
"medium"
|
||||
} else {
|
||||
"high"
|
||||
}
|
||||
}
|
||||
|
||||
fn kpi_explain_factors(
|
||||
snapshot: &Snapshot,
|
||||
policy_explain: &Value,
|
||||
inputs: KpiFactorInputs<'_>,
|
||||
) -> Vec<Value> {
|
||||
let planned_seconds = (inputs.users_count as i64).saturating_mul(8 * 3600);
|
||||
let idle_ratio = if planned_seconds > 0 {
|
||||
((planned_seconds - inputs.active_seconds).max(0) as f64 / planned_seconds as f64)
|
||||
.clamp(0.0, 1.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let weighted_apps = policy_explain
|
||||
.get("matched_applications")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let afterhours_seconds = kpi_afterhours_seconds(snapshot);
|
||||
let remote_sessions = snapshot.agent_quality.rdp_sessions_total as u64;
|
||||
let trend = trend_status(&workforce_trend_json(snapshot));
|
||||
|
||||
vec![
|
||||
kpi_factor(
|
||||
"productive_activity",
|
||||
"Полезная активность",
|
||||
positive_impact((inputs.kpi_score as i64 * 40) / 100),
|
||||
if inputs.kpi_score >= 80 {
|
||||
"Высокая доля активности относительно планового рабочего времени"
|
||||
} else if inputs.kpi_score >= 60 {
|
||||
"Активность близка к рабочему уровню, но есть просадка"
|
||||
} else {
|
||||
"Активность ниже ожидаемого рабочего уровня"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"business_app_usage",
|
||||
"Рабочие приложения",
|
||||
positive_impact(
|
||||
((weighted_apps.max(inputs.apps_count as u64).min(12) as i64) * 2).min(24),
|
||||
),
|
||||
if weighted_apps > 0 {
|
||||
"В данных есть приложения, попавшие под рабочие правила"
|
||||
} else if inputs.apps_count > 0 {
|
||||
"Есть активность по приложениям, но правила рабочих приложений требуют настройки"
|
||||
} else {
|
||||
"Данных о рабочих приложениях нет"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"idle_time",
|
||||
"Простой",
|
||||
negative_impact((idle_ratio * 30.0).round() as i64),
|
||||
if idle_ratio > 0.35 {
|
||||
"Есть значимые периоды неактивности в рабочее время"
|
||||
} else {
|
||||
"Простой не является основным фактором снижения индекса"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"afterhours_activity",
|
||||
"Активность вне рабочего времени",
|
||||
negative_impact((afterhours_seconds / 3600).min(12)),
|
||||
if afterhours_seconds > 0 {
|
||||
"Есть признаки активности за пределами рабочего окна"
|
||||
} else {
|
||||
"Существенная активность вне рабочего времени не выявлена"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"remote_session_activity",
|
||||
"Удаленные сессии",
|
||||
positive_impact((remote_sessions.min(5) * 2) as i64),
|
||||
if remote_sessions > 0 {
|
||||
"RDP/удаленные сессии подтверждают источник активности"
|
||||
} else {
|
||||
"Удаленные сессии не подтверждены текущим срезом"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"data_coverage",
|
||||
"Полнота данных",
|
||||
if inputs.agent_coverage_percent >= 80 {
|
||||
positive_impact(12)
|
||||
} else {
|
||||
negative_impact(
|
||||
((80_u8.saturating_sub(inputs.agent_coverage_percent) as i64) / 4).max(1),
|
||||
)
|
||||
},
|
||||
if inputs.agent_coverage_percent >= 80 {
|
||||
"Покрытие данных достаточно для уверенного управленческого вывода"
|
||||
} else {
|
||||
"Покрытие данных снижает доверие к индексу"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"missing_data",
|
||||
"Отсутствующие данные",
|
||||
negative_impact((inputs.missing_sources.len() as i64 * 8).min(32)),
|
||||
if inputs.missing_sources.is_empty() {
|
||||
"Критичных пропусков источников не выявлено"
|
||||
} else {
|
||||
"Есть пропуски источников, влияющие на надежность KPI"
|
||||
},
|
||||
),
|
||||
kpi_factor(
|
||||
"trend_change",
|
||||
"Изменение тренда",
|
||||
match trend.as_str() {
|
||||
"monthly" | "weekly" => positive_impact(6),
|
||||
"daily_only" => negative_impact(2),
|
||||
_ => "0".to_string(),
|
||||
},
|
||||
match trend.as_str() {
|
||||
"monthly" => "Есть месячная история для оценки тренда",
|
||||
"weekly" => "Есть недельная история для оценки тренда",
|
||||
"daily_only" => "Доступен только дневной срез, исторический тренд ограничен",
|
||||
_ => "История тренда пока не накоплена",
|
||||
},
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn kpi_factor(name: &str, label: &str, impact: String, explanation: &str) -> Value {
|
||||
json!({
|
||||
"name": name,
|
||||
"label": label,
|
||||
"impact": impact,
|
||||
"explanation": explanation,
|
||||
})
|
||||
}
|
||||
|
||||
fn positive_impact(value: i64) -> String {
|
||||
format!("+{}", value.max(0))
|
||||
}
|
||||
|
||||
fn negative_impact(value: i64) -> String {
|
||||
if value <= 0 {
|
||||
"0".to_string()
|
||||
} else {
|
||||
format!("-{value}")
|
||||
}
|
||||
}
|
||||
|
||||
fn kpi_afterhours_seconds(snapshot: &Snapshot) -> i64 {
|
||||
snapshot
|
||||
.worktime_management
|
||||
.payload
|
||||
.as_ref()
|
||||
.and_then(|payload| payload.get("department_rollups"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
let total = item
|
||||
.get("calendar_total_active_seconds")
|
||||
.or_else(|| item.get("total_active_seconds"))
|
||||
.and_then(Value::as_i64)?;
|
||||
let workday = item
|
||||
.get("workday_total_active_seconds")
|
||||
.or_else(|| item.get("active_seconds"))
|
||||
.and_then(Value::as_i64)
|
||||
.unwrap_or(total);
|
||||
Some((total - workday).max(0))
|
||||
})
|
||||
.sum()
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn kpi_top_applications(snapshot: &Snapshot, anonymize: bool) -> Vec<Value> {
|
||||
let Some(apps) = snapshot
|
||||
.worktime
|
||||
.payload
|
||||
.as_ref()
|
||||
.and_then(|payload| payload.get("true_active_apps"))
|
||||
.and_then(Value::as_array)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut items = apps
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, app)| {
|
||||
let raw_name = app.get("application").and_then(Value::as_str)?;
|
||||
let seconds = app
|
||||
.get("proved_work_seconds")
|
||||
.or_else(|| app.get("active_seconds"))
|
||||
.and_then(Value::as_i64)
|
||||
.unwrap_or(0)
|
||||
.max(0);
|
||||
if seconds == 0 {
|
||||
return None;
|
||||
}
|
||||
let name = if anonymize {
|
||||
format!("Приложение {}", idx + 1)
|
||||
} else {
|
||||
display_text_opt(Some(raw_name), &format!("Приложение {}", idx + 1))
|
||||
};
|
||||
let category = kpi_application_category(raw_name);
|
||||
let contribution = if category == "business" {
|
||||
"positive"
|
||||
} else {
|
||||
"neutral"
|
||||
};
|
||||
Some(json!({
|
||||
"name": name,
|
||||
"category": category,
|
||||
"active_minutes": seconds / 60,
|
||||
"contribution": contribution,
|
||||
}))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
items.sort_by_key(|item| {
|
||||
-item
|
||||
.get("active_minutes")
|
||||
.and_then(Value::as_i64)
|
||||
.unwrap_or(0)
|
||||
});
|
||||
items.truncate(8);
|
||||
items
|
||||
}
|
||||
|
||||
fn kpi_application_category(name: &str) -> &'static str {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
let lower_ru = name.to_lowercase();
|
||||
if lower.contains("1c")
|
||||
|| lower_ru.contains("1с")
|
||||
|| lower.contains("erp")
|
||||
|| lower.contains("sap")
|
||||
|| lower.contains("excel")
|
||||
|| lower.contains("office")
|
||||
|| lower.contains("word")
|
||||
{
|
||||
"business"
|
||||
} else if lower.contains("browser")
|
||||
|| lower.contains("chrome")
|
||||
|| lower.contains("edge")
|
||||
|| lower.contains("firefox")
|
||||
{
|
||||
"mixed"
|
||||
} else {
|
||||
"other"
|
||||
}
|
||||
}
|
||||
|
||||
fn kpi_warnings(
|
||||
kpi_score: u8,
|
||||
confidence: &str,
|
||||
data_freshness: &str,
|
||||
missing_sources: &[String],
|
||||
) -> Vec<String> {
|
||||
let mut warnings = Vec::new();
|
||||
if confidence == "low" {
|
||||
warnings
|
||||
.push("Низкое доверие к KPI: данных недостаточно для уверенного вывода.".to_string());
|
||||
}
|
||||
if data_freshness != "fresh" {
|
||||
warnings.push(format!("Свежесть данных: {data_freshness}."));
|
||||
}
|
||||
for source in missing_sources {
|
||||
warnings.push(format!("Не хватает источника данных: {source}."));
|
||||
}
|
||||
if kpi_score < 60 {
|
||||
warnings.push("Индекс активности ниже рабочего ориентира.".to_string());
|
||||
}
|
||||
warnings
|
||||
}
|
||||
|
||||
fn kpi_recommendations(confidence: &str, missing_sources: &[String], kpi_score: u8) -> Vec<String> {
|
||||
let mut recommendations = Vec::new();
|
||||
if !missing_sources.is_empty() {
|
||||
recommendations
|
||||
.push("Проверить свежесть источников и восстановить пропущенные данные.".to_string());
|
||||
}
|
||||
if confidence != "high" {
|
||||
recommendations.push(
|
||||
"Перед управленческим выводом проверить покрытие данных рабочих мест.".to_string(),
|
||||
);
|
||||
}
|
||||
if kpi_score < 60 {
|
||||
recommendations
|
||||
.push("Проверить подразделения или ответственных с низкой активностью.".to_string());
|
||||
}
|
||||
if recommendations.is_empty() {
|
||||
recommendations.push("Использовать KPI как агрегированный управленческий индикатор, не как персональную HR-оценку.".to_string());
|
||||
}
|
||||
recommendations
|
||||
}
|
||||
|
||||
fn filter_kpi_explain_for_role(payload: &mut Value, role: PortalRole) {
|
||||
match role {
|
||||
PortalRole::Executive | PortalRole::Manager => {
|
||||
payload["scope_note"] = json!("Агрегированный Workforce KPI без персональных деталей.");
|
||||
}
|
||||
PortalRole::Security => {
|
||||
payload["scope_note"] =
|
||||
json!("ИБ видит только факторы, релевантные риску и надежности данных.");
|
||||
filter_kpi_factors(
|
||||
payload,
|
||||
&[
|
||||
"afterhours_activity",
|
||||
"remote_session_activity",
|
||||
"data_coverage",
|
||||
"missing_data",
|
||||
"trend_change",
|
||||
],
|
||||
);
|
||||
payload["top_applications"] = Value::Array(Vec::new());
|
||||
}
|
||||
PortalRole::Forensics => {
|
||||
payload["scope_note"] = json!(
|
||||
"Расследования видят только контекст надежности данных и временных отклонений."
|
||||
);
|
||||
filter_kpi_factors(
|
||||
payload,
|
||||
&["afterhours_activity", "data_coverage", "missing_data"],
|
||||
);
|
||||
payload["top_applications"] = Value::Array(Vec::new());
|
||||
}
|
||||
PortalRole::Admin => {
|
||||
payload["scope_note"] =
|
||||
json!("Администратор видит техническое покрытие источников и rule-based факторы.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_kpi_factors(payload: &mut Value, allowed: &[&str]) {
|
||||
if let Some(factors) = payload.get_mut("factors").and_then(Value::as_array_mut) {
|
||||
factors.retain(|item| {
|
||||
item.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|name| allowed.contains(&name))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
AgentCoverageSla, AgentQuality, AgentQualityHistorySummary, AgentQualityNodesSummary,
|
||||
SecurityEventsSummary, SourceStatus,
|
||||
};
|
||||
|
||||
fn kpi_snapshot(
|
||||
worktime_ok: bool,
|
||||
coverage_pct: u8,
|
||||
active_seconds: i64,
|
||||
apps: Vec<Value>,
|
||||
) -> Snapshot {
|
||||
let rows = if active_seconds > 0 {
|
||||
json!([
|
||||
{"user": "USER-1", "user_id": "EMP-1", "active_seconds": active_seconds}
|
||||
])
|
||||
} else {
|
||||
json!([])
|
||||
};
|
||||
Snapshot {
|
||||
generated_at_utc: "2026-06-07T10:00:00Z".to_string(),
|
||||
detmir_status: SourceStatus {
|
||||
ok: true,
|
||||
status: "OK".to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: None,
|
||||
},
|
||||
detmir_check: SourceStatus {
|
||||
ok: true,
|
||||
status: "OK".to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: None,
|
||||
},
|
||||
failed_units: SourceStatus {
|
||||
ok: true,
|
||||
status: "OK".to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: None,
|
||||
},
|
||||
worktime: SourceStatus {
|
||||
ok: worktime_ok,
|
||||
status: if worktime_ok { "OK" } else { "FAIL" }.to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: worktime_ok.then(|| {
|
||||
json!({
|
||||
"rows": rows,
|
||||
"true_active_apps": apps
|
||||
})
|
||||
}),
|
||||
},
|
||||
worktime_management: SourceStatus {
|
||||
ok: worktime_ok,
|
||||
status: if worktime_ok { "OK" } else { "FAIL" }.to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: worktime_ok.then(|| {
|
||||
json!({
|
||||
"department_rollups": [
|
||||
{
|
||||
"name": "DEPT-1",
|
||||
"users_count": 1,
|
||||
"active_users": 1,
|
||||
"portfolio_coverage_pct": coverage_pct,
|
||||
"workday_total_active_seconds": active_seconds,
|
||||
"calendar_total_active_seconds": active_seconds
|
||||
}
|
||||
],
|
||||
"trend": [
|
||||
{"report_date": "2026-06-06", "portfolio_coverage_pct": coverage_pct},
|
||||
{"report_date": "2026-06-07", "portfolio_coverage_pct": coverage_pct}
|
||||
]
|
||||
})
|
||||
}),
|
||||
},
|
||||
one_c: SourceStatus {
|
||||
ok: true,
|
||||
status: "OK".to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: None,
|
||||
},
|
||||
one_c_overview: SourceStatus {
|
||||
ok: true,
|
||||
status: "OK".to_string(),
|
||||
summary: String::new(),
|
||||
error: None,
|
||||
payload: None,
|
||||
},
|
||||
agent_quality: AgentQuality {
|
||||
collector_source: "awatch-agent-rs".to_string(),
|
||||
collector_error: None,
|
||||
sessions_collected_total: if worktime_ok { 1 } else { 0 },
|
||||
active_sessions_total: if worktime_ok { 1 } else { 0 },
|
||||
rdp_sessions_total: if worktime_ok { 1 } else { 0 },
|
||||
quality_status: if worktime_ok { "OK" } else { "UNKNOWN" }.to_string(),
|
||||
},
|
||||
agent_quality_history: Vec::new(),
|
||||
agent_quality_history_summary: AgentQualityHistorySummary::default(),
|
||||
agent_quality_nodes: Vec::new(),
|
||||
agent_quality_nodes_summary: AgentQualityNodesSummary::default(),
|
||||
agent_coverage_sla: AgentCoverageSla {
|
||||
expected_nodes: 1,
|
||||
reporting_nodes_24h: if worktime_ok { 1 } else { 0 },
|
||||
stale_nodes: 0,
|
||||
missing_nodes: if worktime_ok { 0 } else { 1 },
|
||||
coverage_pct,
|
||||
freshness_pct: coverage_pct,
|
||||
sla_status: if coverage_pct >= 80 { "OK" } else { "CRITICAL" }.to_string(),
|
||||
problem_nodes: Vec::new(),
|
||||
},
|
||||
security_events_summary: SecurityEventsSummary::disabled(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confidence_is_low_when_required_data_is_missing() {
|
||||
let snapshot = kpi_snapshot(false, 0, 0, Vec::new());
|
||||
let explain = build_workforce_kpi_explain(
|
||||
&snapshot,
|
||||
&json!({"configured": false}),
|
||||
PortalRole::Executive,
|
||||
&KpiExplainQuery::default(),
|
||||
false,
|
||||
);
|
||||
assert_eq!(explain["confidence"], "low");
|
||||
assert_eq!(explain["kpi_score"], 0);
|
||||
assert!(
|
||||
explain["warnings"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|item| item.as_str().unwrap().contains("Низкое доверие"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factors_are_deterministic_and_role_filtered() {
|
||||
let snapshot = kpi_snapshot(
|
||||
true,
|
||||
95,
|
||||
8 * 3600,
|
||||
vec![json!({"application": "1C", "proved_work_seconds": 6 * 3600})],
|
||||
);
|
||||
let policy = json!({
|
||||
"configured": true,
|
||||
"index": 82,
|
||||
"matched_applications": 1
|
||||
});
|
||||
let explain = build_workforce_kpi_explain(
|
||||
&snapshot,
|
||||
&policy,
|
||||
PortalRole::Executive,
|
||||
&KpiExplainQuery::default(),
|
||||
false,
|
||||
);
|
||||
assert_eq!(explain["kpi_score"], 82);
|
||||
assert_eq!(explain["confidence"], "high");
|
||||
let factors = explain["factors"].as_array().unwrap();
|
||||
assert_eq!(factors.len(), 8);
|
||||
assert_eq!(factors[0]["name"], "productive_activity");
|
||||
assert!(
|
||||
factors
|
||||
.iter()
|
||||
.any(|item| item["name"] == "business_app_usage")
|
||||
);
|
||||
assert!(
|
||||
explain["top_applications"][0]["name"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("1C")
|
||||
);
|
||||
assert!(
|
||||
serde_json::to_string(&explain)
|
||||
.unwrap()
|
||||
.find("EMP-1")
|
||||
.is_none()
|
||||
);
|
||||
|
||||
let security = build_workforce_kpi_explain(
|
||||
&snapshot,
|
||||
&policy,
|
||||
PortalRole::Security,
|
||||
&KpiExplainQuery::default(),
|
||||
false,
|
||||
);
|
||||
assert_eq!(security["top_applications"].as_array().unwrap().len(), 0);
|
||||
assert!(
|
||||
security["factors"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|item| item["name"] != "productive_activity")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -120,8 +120,6 @@ fn process_one(zip_path: &Path) -> Result<ProcessResult> {
|
||||
"process-inbox".to_string(),
|
||||
"--mode".to_string(),
|
||||
mode.clone(),
|
||||
"--limit".to_string(),
|
||||
"1".to_string(),
|
||||
],
|
||||
)?;
|
||||
let latest = read_json_file(Path::new(LATEST_INTAKE))?;
|
||||
|
||||
@@ -92,7 +92,8 @@ fn decode_optional_json(body: String) -> Result<Value> {
|
||||
|
||||
pub fn read_json_file(path: &Path) -> Result<Value> {
|
||||
let text = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
|
||||
serde_json::from_str(&text).with_context(|| format!("decode {}", path.display()))
|
||||
serde_json::from_str(text.trim_start_matches('\u{feff}'))
|
||||
.with_context(|| format!("decode {}", path.display()))
|
||||
}
|
||||
|
||||
pub fn write_json_pretty(value: &Value) -> Result<String> {
|
||||
|
||||
@@ -10,10 +10,15 @@ use sha2::{Digest, Sha256};
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
const KIT_DIR: &str = "install-kit-awindows-20260427-211240";
|
||||
const README: &str = r#"ActivityWatch DetMir Windows Install Kit
|
||||
const WINDOWS_TELEMETRY_EXE_SOURCE: &str =
|
||||
"adk-rust/target/x86_64-pc-windows-gnu/release/aw-windows-telemetry.exe";
|
||||
const WINDOWS_TELEMETRY_EXE_DEST: &str = "windows/aw-windows-telemetry.exe";
|
||||
|
||||
const README: &str = r#"AWatch-rus Windows Install Kit
|
||||
|
||||
Includes:
|
||||
- windows/* (deploy scripts, collectors, common module, configs/examples)
|
||||
- windows/aw-windows-telemetry.exe (Rust Windows telemetry runtime)
|
||||
- ansible/* (Windows and AW server playbooks, examples, inventory, tasks)
|
||||
- aw-server/* (server installer, health orchestrator, RU patch loader, host groups, default settings)
|
||||
- scripts/* (install-kit rebuild/validation, quality gates, browser/web smoke checks)
|
||||
@@ -57,9 +62,13 @@ const AW_SERVER_FILES: &[&str] = &[
|
||||
"aw-server/aw-server.env.example",
|
||||
"aw-server/aw-sw-cleanup.js",
|
||||
"aw-server/aw-worktime-api.service",
|
||||
"aw-server/aw-worktime-autoheal.service",
|
||||
"aw-server/aw-worktime-autoheal.timer",
|
||||
"aw-server/aw-worktime-prewarm.service",
|
||||
"aw-server/aw-worktime-prewarm.timer",
|
||||
"aw-server/aw-worktime-panel.js",
|
||||
"aw-server/aw-worktime-ui-bridge.service",
|
||||
"aw-server/aw-worktime-ui-bridge.timer",
|
||||
"aw-server/install_aw_server.sh",
|
||||
"aw-server/settings/classes-worktime.json",
|
||||
"aw-server/settings/views-default.json",
|
||||
@@ -94,6 +103,7 @@ const SCRIPTS_FILES: &[&str] = &[
|
||||
"scripts/rebuild_install_kit.sh",
|
||||
"scripts/validate_install_kit.sh",
|
||||
"scripts/verify_innosetup_installer.sh",
|
||||
"scripts/worktime-degraded-smoke.mjs",
|
||||
];
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
@@ -138,6 +148,12 @@ fn rebuild(root: &Path) -> Result<()> {
|
||||
{
|
||||
copy_file(root, &kit, rel)?;
|
||||
}
|
||||
copy_file_as(
|
||||
root,
|
||||
&kit,
|
||||
WINDOWS_TELEMETRY_EXE_SOURCE,
|
||||
WINDOWS_TELEMETRY_EXE_DEST,
|
||||
)?;
|
||||
|
||||
write_file_replace(&kit.join("README-INSTALL-KIT.txt"), README.as_bytes())
|
||||
.with_context(|| format!("write {}", kit.join("README-INSTALL-KIT.txt").display()))?;
|
||||
@@ -166,8 +182,12 @@ fn remove_server_config_dirs(kit: &Path) -> Result<()> {
|
||||
}
|
||||
|
||||
fn copy_file(root: &Path, kit: &Path, rel: &str) -> Result<()> {
|
||||
let src = root.join(rel);
|
||||
let dest = kit.join(rel);
|
||||
copy_file_as(root, kit, rel, rel)
|
||||
}
|
||||
|
||||
fn copy_file_as(root: &Path, kit: &Path, src_rel: &str, dest_rel: &str) -> Result<()> {
|
||||
let src = root.join(src_rel);
|
||||
let dest = kit.join(dest_rel);
|
||||
fs::create_dir_all(dest.parent().context("destination parent")?)
|
||||
.with_context(|| format!("create parent for {}", dest.display()))?;
|
||||
let bytes = fs::read(&src).with_context(|| format!("read {}", src.display()))?;
|
||||
|
||||
@@ -16,10 +16,20 @@ const MANIFEST_NAME: &str = "MANIFEST.txt";
|
||||
const REQUIRED_RELATIVE_FILES: &[&str] = &[
|
||||
"MANIFEST.txt",
|
||||
"README-INSTALL-KIT.txt",
|
||||
"windows/aw-windows-telemetry.exe",
|
||||
"windows/deploy-ensemble.ps1",
|
||||
"windows/validate-deployment.ps1",
|
||||
"ansible/deploy_aw_windows.yml",
|
||||
"aw-server/install_aw_server.sh",
|
||||
"aw-server/aw-worktime-api.service",
|
||||
"aw-server/aw-worktime-autoheal.service",
|
||||
"aw-server/aw-worktime-autoheal.timer",
|
||||
"aw-server/aw-worktime-prewarm.service",
|
||||
"aw-server/aw-worktime-prewarm.timer",
|
||||
"aw-server/aw-worktime-ui-bridge.service",
|
||||
"aw-server/aw-worktime-ui-bridge.timer",
|
||||
"aw-server/aw-rus-healthd.service",
|
||||
"aw-server/aw-rus-healthd.timer",
|
||||
"scripts/rebuild_install_kit.sh",
|
||||
"scripts/validate_install_kit.sh",
|
||||
"scripts/check_install_kit_vs_repo.sh",
|
||||
@@ -450,7 +460,10 @@ mod tests {
|
||||
use tempfile::tempdir;
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
use super::{Config, DEFAULT_KIT_DIR, check_archive_composition, read_manifest, validate};
|
||||
use super::{
|
||||
Config, DEFAULT_KIT_DIR, REQUIRED_RELATIVE_FILES, check_archive_composition, read_manifest,
|
||||
validate,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn manifest_parser_rejects_bad_line() {
|
||||
@@ -473,8 +486,14 @@ mod tests {
|
||||
);
|
||||
let report = validate(&cfg);
|
||||
assert!(report.ok, "{report:#?}");
|
||||
assert_eq!(report.manifest_completeness.tracked_files, 9);
|
||||
assert_eq!(report.archive_composition.files, 10);
|
||||
assert_eq!(
|
||||
report.manifest_completeness.tracked_files,
|
||||
REQUIRED_RELATIVE_FILES.len() - 1
|
||||
);
|
||||
assert_eq!(
|
||||
report.archive_composition.files,
|
||||
REQUIRED_RELATIVE_FILES.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -519,34 +538,13 @@ mod tests {
|
||||
|
||||
fn create_fixture(root: &std::path::Path, matching_archives: bool) {
|
||||
let kit = root.join(DEFAULT_KIT_DIR);
|
||||
for rel in [
|
||||
"windows/deploy-ensemble.ps1",
|
||||
"windows/validate-deployment.ps1",
|
||||
"ansible/deploy_aw_windows.yml",
|
||||
"aw-server/install_aw_server.sh",
|
||||
"scripts/rebuild_install_kit.sh",
|
||||
"scripts/validate_install_kit.sh",
|
||||
"scripts/check_install_kit_vs_repo.sh",
|
||||
"scripts/quality-gate.sh",
|
||||
] {
|
||||
for rel in fixture_files_without_manifest() {
|
||||
let path = kit.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, rel).unwrap();
|
||||
}
|
||||
fs::write(kit.join("README-INSTALL-KIT.txt"), "readme").unwrap();
|
||||
let files = [
|
||||
"README-INSTALL-KIT.txt",
|
||||
"windows/deploy-ensemble.ps1",
|
||||
"windows/validate-deployment.ps1",
|
||||
"ansible/deploy_aw_windows.yml",
|
||||
"aw-server/install_aw_server.sh",
|
||||
"scripts/rebuild_install_kit.sh",
|
||||
"scripts/validate_install_kit.sh",
|
||||
"scripts/check_install_kit_vs_repo.sh",
|
||||
"scripts/quality-gate.sh",
|
||||
];
|
||||
let mut manifest = String::new();
|
||||
for rel in files {
|
||||
for rel in fixture_files_without_manifest() {
|
||||
let path = kit.join(rel);
|
||||
let digest = super::sha256_file(&path).unwrap();
|
||||
manifest.push_str(&format!("{digest} {DEFAULT_KIT_DIR}/{rel}\n"));
|
||||
@@ -556,25 +554,23 @@ mod tests {
|
||||
write_tar(root, matching_archives);
|
||||
}
|
||||
|
||||
fn archive_files(matching: bool) -> Vec<(&'static str, &'static [u8])> {
|
||||
let mut files = vec![
|
||||
("README-INSTALL-KIT.txt", b"readme".as_slice()),
|
||||
("MANIFEST.txt", b"manifest".as_slice()),
|
||||
("windows/deploy-ensemble.ps1", b"deploy".as_slice()),
|
||||
("windows/validate-deployment.ps1", b"validate".as_slice()),
|
||||
("ansible/deploy_aw_windows.yml", b"ansible".as_slice()),
|
||||
("aw-server/install_aw_server.sh", b"server".as_slice()),
|
||||
("scripts/rebuild_install_kit.sh", b"rebuild".as_slice()),
|
||||
(
|
||||
"scripts/validate_install_kit.sh",
|
||||
b"validate-kit".as_slice(),
|
||||
),
|
||||
("scripts/check_install_kit_vs_repo.sh", b"check".as_slice()),
|
||||
("scripts/quality-gate.sh", b"quality".as_slice()),
|
||||
];
|
||||
fn fixture_files_without_manifest() -> Vec<&'static str> {
|
||||
REQUIRED_RELATIVE_FILES
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|rel| *rel != "MANIFEST.txt")
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn archive_files(matching: bool) -> Vec<(&'static str, Vec<u8>)> {
|
||||
let mut files: Vec<(&'static str, Vec<u8>)> = REQUIRED_RELATIVE_FILES
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|rel| (rel, rel.as_bytes().to_vec()))
|
||||
.collect();
|
||||
if !matching {
|
||||
files.pop();
|
||||
files.push(("scripts/other.sh", b"other".as_slice()));
|
||||
files.push(("scripts/other.sh", b"other".to_vec()));
|
||||
}
|
||||
files
|
||||
}
|
||||
@@ -587,7 +583,7 @@ mod tests {
|
||||
for (rel, data) in archive_files(true) {
|
||||
zip.start_file(format!("{DEFAULT_KIT_DIR}/{rel}"), options)
|
||||
.unwrap();
|
||||
zip.write_all(data).unwrap();
|
||||
zip.write_all(&data).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
@@ -603,7 +599,11 @@ mod tests {
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
builder
|
||||
.append_data(&mut header, format!("{DEFAULT_KIT_DIR}/{rel}"), data)
|
||||
.append_data(
|
||||
&mut header,
|
||||
format!("{DEFAULT_KIT_DIR}/{rel}"),
|
||||
data.as_slice(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
builder.finish().unwrap();
|
||||
|
||||
@@ -14,8 +14,11 @@ const REQUIRED_FILES: &[&str] = &[
|
||||
"windows/AWatchRusCollectorGuardService.cs",
|
||||
"windows/aw-collector-guard.ps1",
|
||||
"windows/install-collector-guard-service.ps1",
|
||||
"windows/aw-windows-telemetry.exe",
|
||||
"windows/dlp-policy.native-cross-os.example.json",
|
||||
];
|
||||
const WINDOWS_TELEMETRY_EXE_SOURCE: &str =
|
||||
"adk-rust/target/x86_64-pc-windows-gnu/release/aw-windows-telemetry.exe";
|
||||
const GUARD_MARKER: &str = "collector guard self-test OK";
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
@@ -145,7 +148,11 @@ fn verify(root: &Path, installer: &Path, wineprefix: &Path) -> Report {
|
||||
let mut checked = Vec::new();
|
||||
for rel in REQUIRED_FILES {
|
||||
let extracted = install_dir.join(rel);
|
||||
let repo = root.join(rel);
|
||||
let repo = if *rel == "windows/aw-windows-telemetry.exe" {
|
||||
root.join(WINDOWS_TELEMETRY_EXE_SOURCE)
|
||||
} else {
|
||||
root.join(rel)
|
||||
};
|
||||
if !extracted.is_file() {
|
||||
errors.push(format!("Missing extracted file: {rel}"));
|
||||
continue;
|
||||
|
||||
@@ -16,3 +16,7 @@ serde_json.workspace = true
|
||||
tiny_http.workspace = true
|
||||
url.workspace = true
|
||||
urlencoding.workspace = true
|
||||
regex.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -3,7 +3,10 @@ use std::{
|
||||
fs,
|
||||
io::Cursor,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
sync::{
|
||||
Arc, Mutex, OnceLock,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
@@ -13,6 +16,7 @@ use chrono::{
|
||||
TimeZone, Utc,
|
||||
};
|
||||
use clap::Parser;
|
||||
use regex::Regex;
|
||||
use reqwest::{
|
||||
blocking::Client,
|
||||
header::{CONNECTION, HeaderMap, HeaderValue},
|
||||
@@ -137,12 +141,23 @@ type IdentitySamples = BTreeMap<(String, String), Vec<(DateTime<Utc>, AwEvent)>>
|
||||
type DateBounds = (DateTime<Utc>, DateTime<Utc>);
|
||||
type EventsForDate = (DateBounds, Vec<AwEvent>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct RuntimeMetrics {
|
||||
aw_query_duration_ms: AtomicU64,
|
||||
aw_query_timeout_count: AtomicU64,
|
||||
report_build_error_count: AtomicU64,
|
||||
report_cache_hit: AtomicU64,
|
||||
report_stale_served: AtomicU64,
|
||||
report_degraded: AtomicU64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct App {
|
||||
config: Arc<Config>,
|
||||
aw: Client,
|
||||
events_cache: EventsCache,
|
||||
report_cache: ReportCache,
|
||||
metrics: Arc<RuntimeMetrics>,
|
||||
}
|
||||
|
||||
fn env(name: &str, fallback: &str) -> String {
|
||||
@@ -327,7 +342,7 @@ fn load_config() -> Config {
|
||||
.filter(|item| !item.is_empty())
|
||||
.collect(),
|
||||
events_cache_ttl_seconds: env_i64("AW_WORKTIME_EVENTS_CACHE_TTL_SECONDS", 30).max(0),
|
||||
worktime_events_limit: env_usize("AW_WORKTIME_EVENTS_LIMIT", 50_000).max(1000),
|
||||
worktime_events_limit: env_usize("AW_WORKTIME_EVENTS_LIMIT", 50_000).clamp(100, 50_000),
|
||||
aw_http_timeout_seconds: env_f64("AW_WORKTIME_AW_HTTP_TIMEOUT_SECONDS", 8.0).max(0.5),
|
||||
source_http_timeout_seconds: env_f64("AW_WORKTIME_SOURCE_HTTP_TIMEOUT_SECONDS", 1.5)
|
||||
.max(0.25),
|
||||
@@ -376,6 +391,7 @@ impl App {
|
||||
aw,
|
||||
events_cache: Arc::new(Mutex::new(HashMap::new())),
|
||||
report_cache: Arc::new(Mutex::new(HashMap::new())),
|
||||
metrics: Arc::new(RuntimeMetrics::default()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -392,12 +408,17 @@ impl App {
|
||||
let url = format!("{}{}", self.config.aw_api_base, path);
|
||||
let mut last_error = None;
|
||||
for attempt in 1..=attempts.max(1) {
|
||||
let started = Instant::now();
|
||||
let mut request = self.aw.get(&url);
|
||||
if let Some(timeout) = timeout {
|
||||
request = request.timeout(timeout);
|
||||
}
|
||||
match request.send() {
|
||||
Ok(response) => {
|
||||
self.metrics.aw_query_duration_ms.store(
|
||||
started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow!("AW {path} returned HTTP {}", response.status()));
|
||||
}
|
||||
@@ -406,7 +427,16 @@ impl App {
|
||||
.with_context(|| format!("decode AW JSON {path}"));
|
||||
}
|
||||
Err(error) => {
|
||||
self.metrics.aw_query_duration_ms.store(
|
||||
started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
let is_timeout = error.is_timeout();
|
||||
if is_timeout {
|
||||
self.metrics
|
||||
.aw_query_timeout_count
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
last_error = Some(error);
|
||||
if is_timeout {
|
||||
break;
|
||||
@@ -430,13 +460,135 @@ impl App {
|
||||
Ok(events) => events,
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"[aw-worktime-api-rust] events fetch failed bucket={bucket_id}: {error:#}"
|
||||
"[aw-worktime-api-rust] events fetch failed bucket={} error={}",
|
||||
sanitize_bucket_for_log(bucket_id),
|
||||
sanitize_error_for_log(&format!("{error:#}"))
|
||||
);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn health_payload(&self) -> Value {
|
||||
let degraded = self.metrics.report_degraded.load(Ordering::Relaxed) > 0;
|
||||
json!({
|
||||
"ok": !degraded,
|
||||
"status": if degraded { "DEGRADED" } else { "OK" },
|
||||
"generated_at_utc": to_iso_utc(Utc::now()),
|
||||
"report_timezone": "Europe/Moscow",
|
||||
"default_host": self.config.default_host,
|
||||
"aw_api_base": self.config.aw_api_base,
|
||||
"runtime": self.runtime_metrics_payload(false, false),
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_metrics_payload(&self, report_cache_hit: bool, report_stale_served: bool) -> Value {
|
||||
json!({
|
||||
"worktime_events_limit": self.config.worktime_events_limit,
|
||||
"aw_http_timeout_seconds": self.config.aw_http_timeout_seconds,
|
||||
"report_cache_hit": report_cache_hit,
|
||||
"report_stale_served": report_stale_served,
|
||||
"aw_query_duration_ms": self.metrics.aw_query_duration_ms.load(Ordering::Relaxed),
|
||||
"aw_query_timeout_count": self.metrics.aw_query_timeout_count.load(Ordering::Relaxed),
|
||||
"report_build_error_count": self.metrics.report_build_error_count.load(Ordering::Relaxed),
|
||||
"report_cache_hit_count": self.metrics.report_cache_hit.load(Ordering::Relaxed),
|
||||
"report_stale_served_count": self.metrics.report_stale_served.load(Ordering::Relaxed),
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_headers(&self, cache_state: &str) -> Vec<(String, String)> {
|
||||
vec![
|
||||
("X-AW-Worktime-Cache".into(), cache_state.to_string()),
|
||||
(
|
||||
"X-AW-Worktime-Events-Limit".into(),
|
||||
self.config.worktime_events_limit.to_string(),
|
||||
),
|
||||
(
|
||||
"X-AW-Worktime-AW-Timeout-Seconds".into(),
|
||||
format!("{:.3}", self.config.aw_http_timeout_seconds),
|
||||
),
|
||||
(
|
||||
"X-AW-Worktime-AW-Query-Duration-Ms".into(),
|
||||
self.metrics
|
||||
.aw_query_duration_ms
|
||||
.load(Ordering::Relaxed)
|
||||
.to_string(),
|
||||
),
|
||||
(
|
||||
"X-AW-Worktime-AW-Query-Timeout-Count".into(),
|
||||
self.metrics
|
||||
.aw_query_timeout_count
|
||||
.load(Ordering::Relaxed)
|
||||
.to_string(),
|
||||
),
|
||||
(
|
||||
"X-AW-Worktime-Report-Build-Error-Count".into(),
|
||||
self.metrics
|
||||
.report_build_error_count
|
||||
.load(Ordering::Relaxed)
|
||||
.to_string(),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn log_report_runtime(
|
||||
&self,
|
||||
path: &str,
|
||||
outcome: &str,
|
||||
cache_state: &str,
|
||||
report_cache_hit: bool,
|
||||
report_stale_served: bool,
|
||||
error: Option<&str>,
|
||||
) {
|
||||
let error_suffix = error
|
||||
.map(|value| format!(" error={}", sanitize_error_for_log(value)))
|
||||
.unwrap_or_default();
|
||||
eprintln!(
|
||||
"[aw-worktime-api-rust] report {outcome} path={path} cache={cache_state} worktime_events_limit={} aw_http_timeout_seconds={:.3} report_cache_hit={} report_stale_served={} aw_query_duration_ms={} aw_query_timeout_count={} report_build_error_count={}{}",
|
||||
self.config.worktime_events_limit,
|
||||
self.config.aw_http_timeout_seconds,
|
||||
report_cache_hit,
|
||||
report_stale_served,
|
||||
self.metrics.aw_query_duration_ms.load(Ordering::Relaxed),
|
||||
self.metrics.aw_query_timeout_count.load(Ordering::Relaxed),
|
||||
self.metrics
|
||||
.report_build_error_count
|
||||
.load(Ordering::Relaxed),
|
||||
error_suffix
|
||||
);
|
||||
}
|
||||
|
||||
fn add_runtime_to_json(
|
||||
&self,
|
||||
data: Vec<u8>,
|
||||
content_type: &str,
|
||||
report_cache_hit: bool,
|
||||
report_stale_served: bool,
|
||||
degraded_reason: Option<&str>,
|
||||
) -> Vec<u8> {
|
||||
if !content_type.starts_with("application/json") {
|
||||
return data;
|
||||
}
|
||||
let Ok(mut payload) = serde_json::from_slice::<Value>(&data) else {
|
||||
return data;
|
||||
};
|
||||
let Some(object) = payload.as_object_mut() else {
|
||||
return data;
|
||||
};
|
||||
object.insert(
|
||||
"runtime".to_string(),
|
||||
self.runtime_metrics_payload(report_cache_hit, report_stale_served),
|
||||
);
|
||||
if let Some(reason) = degraded_reason {
|
||||
object.insert("ok".to_string(), json!(false));
|
||||
object.insert("status".to_string(), json!("DEGRADED"));
|
||||
object.insert("degraded".to_string(), json!(true));
|
||||
object.insert("stale".to_string(), json!(report_stale_served));
|
||||
object.insert("degraded_reason".to_string(), json!(reason));
|
||||
}
|
||||
serde_json::to_vec_pretty(&payload).unwrap_or(data)
|
||||
}
|
||||
|
||||
fn fetch_bucket_events_result(
|
||||
&self,
|
||||
bucket_id: &str,
|
||||
@@ -526,45 +678,103 @@ impl App {
|
||||
&department,
|
||||
);
|
||||
if let Some(cached) = self.get_report_cache(&cache_key, false) {
|
||||
return (
|
||||
cached.data,
|
||||
cached.content_type,
|
||||
vec![
|
||||
("X-AW-Worktime-Cache".into(), "fresh".into()),
|
||||
("X-AW-Worktime-Cache-Reason".into(), "ttl".into()),
|
||||
],
|
||||
);
|
||||
self.metrics
|
||||
.report_cache_hit
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
let data =
|
||||
self.add_runtime_to_json(cached.data, &cached.content_type, true, false, None);
|
||||
let mut headers = self.runtime_headers("fresh");
|
||||
headers.push(("X-AW-Worktime-Cache-Reason".into(), "ttl".into()));
|
||||
self.log_report_runtime(path, "ok", "fresh", true, false, None);
|
||||
return (data, cached.content_type, headers);
|
||||
}
|
||||
let built =
|
||||
self.build_report_response(path, params, &fmt, &host, report_date, &owner, &department);
|
||||
match built {
|
||||
Ok((data, content_type)) => {
|
||||
self.metrics.report_degraded.store(0, Ordering::Relaxed);
|
||||
let data = self.add_runtime_to_json(data, &content_type, false, false, None);
|
||||
self.save_report_cache(cache_key, data.clone(), content_type.clone());
|
||||
(data, content_type, Vec::new())
|
||||
self.log_report_runtime(path, "ok", "miss", false, false, None);
|
||||
(data, content_type, self.runtime_headers("miss"))
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("[aw-worktime-api-rust] report build failed path={path}: {error:#}");
|
||||
self.metrics
|
||||
.report_build_error_count
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
self.metrics.report_degraded.store(1, Ordering::Relaxed);
|
||||
let sanitized_error = sanitize_error_for_log(&format!("{error:#}"));
|
||||
if let Some(cached) = self.get_report_cache(&cache_key, true) {
|
||||
return (
|
||||
self.metrics
|
||||
.report_cache_hit
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
self.metrics
|
||||
.report_stale_served
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
let data = self.add_runtime_to_json(
|
||||
cached.data,
|
||||
cached.content_type,
|
||||
vec![
|
||||
("X-AW-Worktime-Cache".into(), "stale".into()),
|
||||
("X-AW-Worktime-Cache-Reason".into(), "build-error".into()),
|
||||
],
|
||||
&cached.content_type,
|
||||
true,
|
||||
true,
|
||||
Some("stale_cache_served_after_build_error"),
|
||||
);
|
||||
let mut headers = self.runtime_headers("stale");
|
||||
headers.push(("X-AW-Worktime-Cache-Reason".into(), "build-error".into()));
|
||||
self.log_report_runtime(
|
||||
path,
|
||||
"degraded",
|
||||
"stale",
|
||||
true,
|
||||
true,
|
||||
Some(&sanitized_error),
|
||||
);
|
||||
return (data, cached.content_type, headers);
|
||||
}
|
||||
self.log_report_runtime(
|
||||
path,
|
||||
"degraded",
|
||||
"degraded",
|
||||
false,
|
||||
false,
|
||||
Some(&sanitized_error),
|
||||
);
|
||||
let data = serde_json::to_vec_pretty(&json!({
|
||||
"ok": false,
|
||||
"error": "report_unavailable",
|
||||
"status": "DEGRADED",
|
||||
"degraded": true,
|
||||
"stale": false,
|
||||
"reason": "report_unavailable",
|
||||
"message": "report build failed and no cached response is available",
|
||||
"generated_at_utc": to_iso_utc(Utc::now()),
|
||||
"report_timezone": "Europe/Moscow",
|
||||
"host": host,
|
||||
"report_date": report_date.to_string(),
|
||||
"rows": [],
|
||||
"actions": [],
|
||||
"sources": [],
|
||||
"summary": {
|
||||
"users_count": 0,
|
||||
"active_users": 0,
|
||||
"inactive_users": 0,
|
||||
"portfolio_coverage_pct": 0.0,
|
||||
"actions_count": 0,
|
||||
"critical_actions_count": 0
|
||||
},
|
||||
"executive": {
|
||||
"portfolio_state": "degraded",
|
||||
"headline": "Данные рабочего времени временно недоступны; используется безопасный degraded-режим.",
|
||||
"message": "ActivityWatch API не ответил в заданный лимит, тяжелые повторные запросы не выполняются.",
|
||||
"focus_items": [],
|
||||
"stale_sources": [],
|
||||
"stale_sources_count": 0
|
||||
},
|
||||
"runtime": self.runtime_metrics_payload(false, false),
|
||||
}))
|
||||
.unwrap_or_default();
|
||||
(
|
||||
data,
|
||||
"application/json; charset=utf-8".to_string(),
|
||||
Vec::new(),
|
||||
self.runtime_headers("degraded"),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -925,6 +1135,39 @@ fn sessions_bucket(host: &str) -> String {
|
||||
format!("aw-worktime-sessions_{host}")
|
||||
}
|
||||
|
||||
fn sanitize_bucket_for_log(bucket_id: &str) -> String {
|
||||
for prefix in [
|
||||
"aw-worktime-sessions_",
|
||||
"aw-watcher-afk_",
|
||||
"aw-watcher-window_",
|
||||
"aw-rdp-afk_",
|
||||
"aw-rdp-window_",
|
||||
"aw-file-operations_",
|
||||
"aw-dlp-endpoint-signals_",
|
||||
"aw-watcher-web-chrome_",
|
||||
"aw-watcher-web-edge_",
|
||||
"aw-detmir-web-category_",
|
||||
"aw-session-events_",
|
||||
] {
|
||||
if bucket_id.starts_with(prefix) {
|
||||
return format!("{prefix}<HOST>");
|
||||
}
|
||||
}
|
||||
bucket_id.to_string()
|
||||
}
|
||||
|
||||
fn sanitize_error_for_log(value: &str) -> String {
|
||||
static IP_RE: OnceLock<Regex> = OnceLock::new();
|
||||
static BUCKET_HOST_RE: OnceLock<Regex> = OnceLock::new();
|
||||
let ip_re = IP_RE.get_or_init(|| Regex::new(r"\b(?:\d{1,3}\.){3}\d{1,3}\b").unwrap());
|
||||
let bucket_re =
|
||||
BUCKET_HOST_RE.get_or_init(|| Regex::new(r"(aw-[A-Za-z0-9-]+_)[A-Za-z0-9_.-]+").unwrap());
|
||||
let redacted_ips = ip_re.replace_all(value, "<IP>").into_owned();
|
||||
bucket_re
|
||||
.replace_all(&redacted_ips, "$1<HOST>")
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
fn resolve_report_date(config: &Config, day: Option<&str>, date: Option<&str>) -> NaiveDate {
|
||||
if let Some(date) = date.and_then(|d| NaiveDate::parse_from_str(d, "%Y-%m-%d").ok()) {
|
||||
return date;
|
||||
@@ -1771,11 +2014,34 @@ impl App {
|
||||
host: &str,
|
||||
interactive_required: bool,
|
||||
) -> (Vec<Value>, Vec<Value>) {
|
||||
let critical_max_age = self.config.manager_critical_source_max_age_seconds;
|
||||
let rust_sessions_bucket = sessions_bucket(host);
|
||||
let watcher_afk_bucket = format!("aw-watcher-afk_{host}");
|
||||
let rust_sessions_fresh = self
|
||||
.latest_bucket_event(&rust_sessions_bucket)
|
||||
.and_then(|event| {
|
||||
event
|
||||
.timestamp
|
||||
.as_deref()
|
||||
.and_then(parse_iso_utc)
|
||||
.map(|dt| (Utc::now() - dt).num_seconds().max(0) <= critical_max_age)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
let watcher_afk_fresh = self
|
||||
.latest_bucket_event(&watcher_afk_bucket)
|
||||
.and_then(|event| {
|
||||
event
|
||||
.timestamp
|
||||
.as_deref()
|
||||
.and_then(parse_iso_utc)
|
||||
.map(|dt| (Utc::now() - dt).num_seconds().max(0) <= critical_max_age)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
let specs = vec![
|
||||
(
|
||||
"worktime_sessions",
|
||||
"RDP worktime sessions",
|
||||
sessions_bucket(host),
|
||||
rust_sessions_bucket,
|
||||
self.config.manager_critical_source_max_age_seconds,
|
||||
true,
|
||||
false,
|
||||
@@ -1891,6 +2157,18 @@ impl App {
|
||||
} else {
|
||||
format!("stale ({}s)", age.unwrap())
|
||||
};
|
||||
let legacy_rdp_covered = legacy_rdp_covered_by_rust_sources(
|
||||
source_id,
|
||||
status,
|
||||
rust_sessions_fresh,
|
||||
watcher_afk_fresh,
|
||||
);
|
||||
let effective_required = required && !legacy_rdp_covered;
|
||||
if legacy_rdp_covered {
|
||||
status = "inactive";
|
||||
summary =
|
||||
"legacy RDP source covered by fresh Rust worktime/watcher sources".to_string();
|
||||
}
|
||||
if interactive_only && !interactive_required && status != "ok" {
|
||||
status = "inactive";
|
||||
summary = "inactive: no active interactive users".to_string();
|
||||
@@ -1903,7 +2181,7 @@ impl App {
|
||||
"bucket_id": bucket,
|
||||
"timestamp": event.as_ref().and_then(|e| e.timestamp.clone()).unwrap_or_default(),
|
||||
"age_seconds": age,
|
||||
"required": required,
|
||||
"required": effective_required,
|
||||
"interactive_only": interactive_only,
|
||||
"interactive_required": interactive_required,
|
||||
"max_age_seconds": max_age,
|
||||
@@ -1913,13 +2191,13 @@ impl App {
|
||||
if !matches!(status, "ok" | "inactive") {
|
||||
actions.push(action(
|
||||
"source_freshness_review",
|
||||
if required { "critical" } else { "medium" },
|
||||
if effective_required { "critical" } else { "medium" },
|
||||
"ops",
|
||||
if required { "today" } else { "3d" },
|
||||
if effective_required { "today" } else { "3d" },
|
||||
&format!("Источник '{label}' в состоянии {}: {}.", source_status_label(status), summary),
|
||||
"Проверить collector/service, причину отставания и подтвердить, что управленческие выводы по данным ещё надёжны.",
|
||||
"",
|
||||
json!({"source_id": source_id, "bucket_id": bucket, "age_seconds": age, "required": required}),
|
||||
json!({"source_id": source_id, "bucket_id": bucket, "age_seconds": age, "required": effective_required}),
|
||||
));
|
||||
}
|
||||
sources.push(source);
|
||||
@@ -1975,6 +2253,18 @@ fn source_status_label(status: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_rdp_covered_by_rust_sources(
|
||||
source_id: &str,
|
||||
status: &str,
|
||||
rust_sessions_fresh: bool,
|
||||
watcher_afk_fresh: bool,
|
||||
) -> bool {
|
||||
matches!(source_id, "rdp_window" | "rdp_afk")
|
||||
&& status != "ok"
|
||||
&& rust_sessions_fresh
|
||||
&& watcher_afk_fresh
|
||||
}
|
||||
|
||||
fn source_summary(event: &AwEvent) -> String {
|
||||
let d = &event.data;
|
||||
let signal = value_string(d, "signalType");
|
||||
@@ -2118,26 +2408,9 @@ fn build_rollups(rows: &[Value], actions: &[Value], field: &str) -> Vec<Value> {
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("unassigned")
|
||||
.to_string();
|
||||
let group = groups.entry(name.clone()).or_insert_with(|| {
|
||||
let mut g = Map::new();
|
||||
g.insert("name".into(), json!(name));
|
||||
for key in [
|
||||
"users_count",
|
||||
"active_users",
|
||||
"inactive_users",
|
||||
"below_target_users",
|
||||
"workday_total_active_seconds",
|
||||
"actions_count",
|
||||
"critical_actions_count",
|
||||
"high_actions_count",
|
||||
"medium_actions_count",
|
||||
"low_actions_count",
|
||||
] {
|
||||
g.insert(key.into(), json!(0));
|
||||
}
|
||||
g.insert("users".into(), json!([]));
|
||||
g
|
||||
});
|
||||
let Some(group) = groups.get_mut(&name) else {
|
||||
continue;
|
||||
};
|
||||
inc(group, "actions_count", 1);
|
||||
let key = match action.get("priority").and_then(Value::as_str).unwrap_or("") {
|
||||
"critical" => "critical_actions_count",
|
||||
@@ -2178,6 +2451,12 @@ fn inc(map: &mut Map<String, Value>, key: &str, amount: i64) {
|
||||
fn compact_rollup_points(rollups: &[Value]) -> Vec<Value> {
|
||||
rollups
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
item.get("users_count")
|
||||
.and_then(Value::as_i64)
|
||||
.unwrap_or(0)
|
||||
> 0
|
||||
})
|
||||
.map(|item| {
|
||||
json!({
|
||||
"name": item.get("name").cloned().unwrap_or(json!("")),
|
||||
@@ -2405,6 +2684,10 @@ fn add_rollup_history_insights(
|
||||
continue;
|
||||
};
|
||||
for item in items {
|
||||
let users = item.get("users_count").and_then(Value::as_i64).unwrap_or(0);
|
||||
if users <= 0 {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = item.get("name").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
@@ -2909,7 +3192,20 @@ fn history_component(value: &str) -> String {
|
||||
|
||||
fn load_management_history_point(path: &Path) -> Option<Value> {
|
||||
let payload: Value = serde_json::from_slice(&fs::read(path).ok()?).ok()?;
|
||||
payload.get("point").cloned()
|
||||
payload.get("point").cloned().map(sanitize_trend_point)
|
||||
}
|
||||
|
||||
fn sanitize_trend_point(mut point: Value) -> Value {
|
||||
let Some(object) = point.as_object_mut() else {
|
||||
return point;
|
||||
};
|
||||
for key in ["department_rollups", "owner_rollups"] {
|
||||
let Some(items) = object.get(key).and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
object.insert(key.to_string(), json!(compact_rollup_points(items)));
|
||||
}
|
||||
point
|
||||
}
|
||||
|
||||
fn today_csv(rows: &[Value]) -> String {
|
||||
@@ -3142,13 +3438,7 @@ fn handle(app: &App, request: Request) {
|
||||
let url = request.url().to_string();
|
||||
let (path, query) = url.split_once('?').unwrap_or((&url, ""));
|
||||
if path == "/health" || path == "/api/health" {
|
||||
let payload = json!({
|
||||
"ok": true,
|
||||
"generated_at_utc": to_iso_utc(Utc::now()),
|
||||
"report_timezone": "Europe/Moscow",
|
||||
"default_host": app.config.default_host,
|
||||
"aw_api_base": app.config.aw_api_base,
|
||||
});
|
||||
let payload = app.health_payload();
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
@@ -3216,7 +3506,7 @@ fn handle(app: &App, request: Request) {
|
||||
let status = if content_type.starts_with("application/json")
|
||||
&& serde_json::from_slice::<Value>(&data)
|
||||
.ok()
|
||||
.and_then(|v| v.get("error").cloned())
|
||||
.and_then(|v| v.get("error").or_else(|| v.get("http_error")).cloned())
|
||||
.is_some()
|
||||
{
|
||||
503
|
||||
@@ -3248,6 +3538,21 @@ mod tests {
|
||||
load_config()
|
||||
}
|
||||
|
||||
fn degraded_test_config(cache_dir: &Path) -> Config {
|
||||
let mut cfg = test_config();
|
||||
cfg.aw_api_base = "http://127.0.0.1:9/api/0".to_string();
|
||||
cfg.default_host = DEFAULT_HOST.to_string();
|
||||
cfg.worktime_events_limit = 250;
|
||||
cfg.aw_http_timeout_seconds = 0.5;
|
||||
cfg.source_http_timeout_seconds = 0.25;
|
||||
cfg.report_cache_ttl_seconds = 0;
|
||||
cfg.report_stale_ttl_seconds = 600;
|
||||
cfg.report_disk_stale_ttl_seconds = 600;
|
||||
cfg.report_disk_cache_dir = cache_dir.to_path_buf();
|
||||
cfg.management_history_dir = cache_dir.join("history");
|
||||
cfg
|
||||
}
|
||||
|
||||
fn event(ts: &str, username: &str, sid: i64, active: bool, extra: Value) -> AwEvent {
|
||||
let mut data = Map::new();
|
||||
data.insert("username".into(), json!(username));
|
||||
@@ -3361,6 +3666,225 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn management_history_ignores_action_only_rollups() {
|
||||
let cfg = test_config();
|
||||
let trend = ["2026-05-12", "2026-05-13", "2026-05-14"]
|
||||
.into_iter()
|
||||
.map(|date| {
|
||||
json!({
|
||||
"report_date": date,
|
||||
"portfolio_coverage_pct": 50.0,
|
||||
"department_rollups": [
|
||||
{"name": "ops", "users_count": 0, "portfolio_coverage_pct": 0.0},
|
||||
{"name": "Отдел продаж", "users_count": 2, "portfolio_coverage_pct": 10.0}
|
||||
],
|
||||
"owner_rollups": [
|
||||
{"name": "ops", "users_count": 0, "portfolio_coverage_pct": 0.0},
|
||||
{"name": "Руководитель", "users_count": 1, "portfolio_coverage_pct": 10.0}
|
||||
]
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let insights = build_management_insights(
|
||||
&cfg,
|
||||
&json!({
|
||||
"calendar_total_active_seconds": 0,
|
||||
"workday_total_active_seconds": 0
|
||||
}),
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
&trend,
|
||||
NaiveDate::from_ymd_opt(2026, 5, 14).unwrap(),
|
||||
);
|
||||
assert!(!insights.iter().any(|item| item["subject"] == "ops"));
|
||||
assert!(
|
||||
insights
|
||||
.iter()
|
||||
.any(|item| item["subject"] == "Отдел продаж")
|
||||
);
|
||||
assert!(
|
||||
insights
|
||||
.iter()
|
||||
.any(|item| item["subject"] == "Руководитель")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_rollup_points_hides_action_only_groups() {
|
||||
let points = compact_rollup_points(&[
|
||||
json!({"name": "ops", "users_count": 0, "portfolio_coverage_pct": 0.0, "actions_count": 2}),
|
||||
json!({"name": "Отдел продаж", "users_count": 2, "portfolio_coverage_pct": 50.0, "actions_count": 1}),
|
||||
]);
|
||||
assert_eq!(points.len(), 1);
|
||||
assert_eq!(points[0]["name"], "Отдел продаж");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_rollups_does_not_create_action_only_groups() {
|
||||
let rows = vec![json!({
|
||||
"user": "user1",
|
||||
"department": "Отдел продаж",
|
||||
"manager_owner": "Руководитель",
|
||||
"status": "below_target",
|
||||
"workday_active_seconds": 3600
|
||||
})];
|
||||
let actions = vec![
|
||||
action(
|
||||
"source_freshness_review",
|
||||
"critical",
|
||||
"ops",
|
||||
"today",
|
||||
"техническая проверка источника",
|
||||
"проверить сервис",
|
||||
"",
|
||||
json!({}),
|
||||
),
|
||||
action(
|
||||
"manager_review",
|
||||
"high",
|
||||
"Руководитель",
|
||||
"today",
|
||||
"проверка руководителя",
|
||||
"разобрать нагрузку",
|
||||
"",
|
||||
json!({}),
|
||||
),
|
||||
];
|
||||
let rollups = build_rollups(&rows, &actions, "manager_owner");
|
||||
assert_eq!(rollups.len(), 1);
|
||||
assert_eq!(rollups[0]["name"], "Руководитель");
|
||||
assert_eq!(rollups[0]["actions_count"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_legacy_rdp_sources_are_covered_by_fresh_rust_sources() {
|
||||
assert!(legacy_rdp_covered_by_rust_sources(
|
||||
"rdp_window",
|
||||
"fail",
|
||||
true,
|
||||
true
|
||||
));
|
||||
assert!(legacy_rdp_covered_by_rust_sources(
|
||||
"rdp_afk", "warn", true, true
|
||||
));
|
||||
assert!(!legacy_rdp_covered_by_rust_sources(
|
||||
"rdp_window",
|
||||
"fail",
|
||||
true,
|
||||
false
|
||||
));
|
||||
assert!(!legacy_rdp_covered_by_rust_sources(
|
||||
"worktime_sessions",
|
||||
"fail",
|
||||
true,
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degraded_report_without_cache_returns_compact_response() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app = App::new(degraded_test_config(dir.path())).unwrap();
|
||||
let started = Instant::now();
|
||||
let (data, content_type, headers) = app.report_response(
|
||||
"/reports/worktime/management",
|
||||
&Params::parse("format=json&host=HOST-EXAMPLE"),
|
||||
"application/json",
|
||||
);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(3),
|
||||
"degraded response must be bounded"
|
||||
);
|
||||
assert!(content_type.starts_with("application/json"));
|
||||
assert!(
|
||||
headers
|
||||
.iter()
|
||||
.any(|(key, value)| { key == "X-AW-Worktime-Cache" && value == "degraded" })
|
||||
);
|
||||
let payload: Value = serde_json::from_slice(&data).unwrap();
|
||||
assert_eq!(payload["ok"], false);
|
||||
assert_eq!(payload["status"], "DEGRADED");
|
||||
assert_eq!(payload["stale"], false);
|
||||
assert_eq!(payload["runtime"]["worktime_events_limit"], 250);
|
||||
assert_eq!(payload["runtime"]["report_build_error_count"], 1);
|
||||
let health = app.health_payload();
|
||||
assert_eq!(health["ok"], false);
|
||||
assert_eq!(health["status"], "DEGRADED");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_cache_is_served_after_report_build_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cfg = degraded_test_config(dir.path());
|
||||
let report_date = resolve_report_date(&cfg, None, None);
|
||||
let app = App::new(cfg).unwrap();
|
||||
let cache_key = make_report_cache_key(
|
||||
"/reports/worktime/management",
|
||||
"json",
|
||||
"HOST-EXAMPLE",
|
||||
report_date,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
);
|
||||
let cached_payload = json!({
|
||||
"generated_at_utc": to_iso_utc(Utc::now()),
|
||||
"host": "HOST-EXAMPLE",
|
||||
"report_date": report_date.to_string(),
|
||||
"report_timezone": "Europe/Moscow",
|
||||
"summary": {"portfolio_coverage_pct": 75.0},
|
||||
"rows": [{"user": "demo", "workday_active_seconds": 60}],
|
||||
"actions": [],
|
||||
"sources": [],
|
||||
"department_rollups": [],
|
||||
"owner_rollups": []
|
||||
});
|
||||
app.save_report_cache(
|
||||
cache_key,
|
||||
serde_json::to_vec_pretty(&cached_payload).unwrap(),
|
||||
"application/json; charset=utf-8".to_string(),
|
||||
);
|
||||
|
||||
let (data, _content_type, headers) = app.report_response(
|
||||
"/reports/worktime/management",
|
||||
&Params::parse("format=json&host=HOST-EXAMPLE"),
|
||||
"application/json",
|
||||
);
|
||||
assert!(
|
||||
headers
|
||||
.iter()
|
||||
.any(|(key, value)| { key == "X-AW-Worktime-Cache" && value == "stale" })
|
||||
);
|
||||
let payload: Value = serde_json::from_slice(&data).unwrap();
|
||||
assert_eq!(payload["ok"], false);
|
||||
assert_eq!(payload["status"], "DEGRADED");
|
||||
assert_eq!(payload["stale"], true);
|
||||
assert_eq!(payload["runtime"]["report_cache_hit"], true);
|
||||
assert_eq!(payload["runtime"]["report_stale_served"], true);
|
||||
assert_eq!(payload["runtime"]["report_stale_served_count"], 1);
|
||||
assert_eq!(app.health_payload()["ok"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_trend_point_removes_legacy_action_only_rollups() {
|
||||
let point = sanitize_trend_point(json!({
|
||||
"department_rollups": [
|
||||
{"name": "ops", "users_count": 0, "portfolio_coverage_pct": 0.0},
|
||||
{"name": "Отдел продаж", "users_count": 2, "portfolio_coverage_pct": 50.0}
|
||||
],
|
||||
"owner_rollups": [
|
||||
{"name": "ops", "users_count": 0, "portfolio_coverage_pct": 0.0},
|
||||
{"name": "Руководитель", "users_count": 1, "portfolio_coverage_pct": 50.0}
|
||||
]
|
||||
}));
|
||||
assert_eq!(point["department_rollups"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(point["owner_rollups"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(point["department_rollups"][0]["name"], "Отдел продаж");
|
||||
assert_eq!(point["owner_rollups"][0]["name"], "Руководитель");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpretation_policy_accepts_fraction_thresholds() {
|
||||
let policy: InterpretationPolicy = serde_json::from_value(json!({
|
||||
|
||||
+8
-5
@@ -92,8 +92,8 @@ ansible-playbook -i inventory.ini provision_proxmox_ct_matrix_and_deploy_aw.yml
|
||||
Важно:
|
||||
|
||||
- `WinRM` здесь остаётся транспортом для `Ansible deploy` и `validation`;
|
||||
- для интерактивной PowerShell-работы из Linux/Codex по DetMir используйте project MCP-over-SSH путь, а не `WSMan`;
|
||||
- каноника лежит в `docs/DETMIR_POWERSHELL_MCP_REMOTE_RU.md` и `scripts/install_detmir_powershell_mcp.sh`.
|
||||
- для интерактивной PowerShell-работы из Linux/Codex по AWatch-rus используйте project MCP-over-SSH путь, а не `WSMan`;
|
||||
- каноника лежит в `docs/POWERSHELL_MCP_REMOTE_RU.md` и `scripts/install_detmir_powershell_mcp.sh`.
|
||||
|
||||
1. Подготовьте inventory и vars:
|
||||
- `cp ansible/inventory.example.ini ansible/inventory.ini`
|
||||
@@ -157,6 +157,7 @@ Playbook:
|
||||
- `aw_windows_hayabusa_auto_upload_hours_back: 6` — lookback для каждого запуска;
|
||||
- `aw_windows_hayabusa_auto_upload_mode: "incident"` — mode для server-side processing;
|
||||
- `aw_windows_hayabusa_auto_upload_task_name: "ActivityWatch Hayabusa Upload"` — имя scheduled task.
|
||||
- `aw_windows_hayabusa_auto_upload_run_as_user: "Администратор"` — production principal для scheduled task на RDP-хосте. На `SHARKON2025` запуск `powershell.exe` из `SYSTEM` возвращал `0xC0000142`, поэтому авто-upload должен идти как interactive/highest task от локального администратора.
|
||||
|
||||
## Server-side Hayabusa auto-case и Telegram alerting
|
||||
|
||||
@@ -176,6 +177,8 @@ Playbook:
|
||||
- пишет bounded metadata в `forensics.hayabusa`;
|
||||
- отправляет Telegram alert.
|
||||
|
||||
Для Windows direct upload пользователь `awops` на AW-server должен иметь право записи в `/opt/activitywatch/aw-rus-ops/drop`; нормальное состояние каталога: owner/group `awops:awops`, mode `0750`. Unit `aw-hayabusa-drop.service` работает от root и после обработки очищает `drop`.
|
||||
|
||||
Основные vars:
|
||||
|
||||
- `aw_hayabusa_auto_case_enabled: true`
|
||||
@@ -232,9 +235,9 @@ Playbook:
|
||||
|
||||
По умолчанию импортируются:
|
||||
|
||||
- `DetMir: Работа пользователей в RDP`
|
||||
- `DetMir: DLP и ИБ обзор`
|
||||
- `DetMir: ИБ сводка для руководства`
|
||||
- `AWatch-rus: Работа пользователей в RDP`
|
||||
- `AWatch-rus: DLP и ИБ обзор`
|
||||
- `AWatch-rus: ИБ сводка для руководства`
|
||||
- `AW-rus: DLP обзор`
|
||||
|
||||
Подробная документация: `docs/GRAFANA_DASHBOARDS_RU.md`
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
aw_release_install_dir: "{{ aw_release_root }}/aw-server-rust-{{ aw_server_version }}"
|
||||
aw_ru_patch_cache_bust: "{{ lookup('file', aw_repo_root + '/aw-server/aw-ru-patch.js') | hash('sha1') | truncate(12, true, '') }}"
|
||||
aw_sw_cleanup_cache_bust: "{{ lookup('file', aw_repo_root + '/aw-server/aw-sw-cleanup.js') | hash('sha1') | truncate(12, true, '') }}"
|
||||
aw_host_sanitize_cache_bust: "{{ lookup('file', aw_repo_root + '/aw-server/aw-host-sanitize.js') | hash('sha1') | truncate(12, true, '') }}"
|
||||
aw_worktime_classes: "{{ lookup('file', aw_repo_root + '/aw-server/settings/classes-worktime.json') | from_json }}"
|
||||
aw_default_views: "{{ lookup('file', aw_repo_root + '/aw-server/settings/views-default.json') | from_json }}"
|
||||
aw_rust_release_dir: "{{ (lookup('env', 'CARGO_TARGET_DIR') | default(aw_repo_root + '/adk-rust/target', true)) + '/release' }}"
|
||||
@@ -448,6 +449,7 @@
|
||||
loop:
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-ru-patch.js", dest: "{{ aw_server_webui_dir }}/js/ru-patch-v5.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-sw-cleanup.js", dest: "{{ aw_server_webui_dir }}/js/sw-cleanup.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-host-sanitize.js", dest: "{{ aw_server_webui_dir }}/js/aw-host-sanitize.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-worktime-panel.js", dest: "{{ aw_server_webui_dir }}/js/aw-worktime-panel.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-host-groups.json", dest: "{{ aw_server_webui_dir }}/js/aw-host-groups.json", mode: "0644" }
|
||||
|
||||
@@ -465,6 +467,7 @@
|
||||
loop:
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-ru-patch.js", dest: "/opt/detmir/bootstrap/aw-ru-patch.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-sw-cleanup.js", dest: "/opt/detmir/bootstrap/aw-sw-cleanup.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-host-sanitize.js", dest: "/opt/detmir/bootstrap/aw-host-sanitize.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-worktime-panel.js", dest: "/opt/detmir/bootstrap/aw-worktime-panel.js", mode: "0644" }
|
||||
- { src: "{{ aw_repo_root }}/aw-server/aw-host-groups.json", dest: "/opt/detmir/bootstrap/aw-host-groups.json", mode: "0644" }
|
||||
|
||||
@@ -593,11 +596,13 @@
|
||||
failed_when: false
|
||||
no_log: true
|
||||
|
||||
- name: Подготовить effective Influx tokens без вывода секретов
|
||||
- name: Подготовить effective runtime values без вывода секретов
|
||||
ansible.builtin.set_fact:
|
||||
aw_existing_server_env_text: "{{ aw_existing_server_env_raw.content | default('') | b64decode }}"
|
||||
aw_existing_worktime_influx_token: "{{ (aw_existing_server_env_raw.content | default('') | b64decode | regex_search('(?m)^AW_WORKTIME_INFLUX_TOKEN=.*$') | default('', true) | regex_replace('^AW_WORKTIME_INFLUX_TOKEN=', '')) }}"
|
||||
aw_existing_dlp_influx_token: "{{ (aw_existing_server_env_raw.content | default('') | b64decode | regex_search('(?m)^AW_DLP_INFLUX_TOKEN=.*$') | default('', true) | regex_replace('^AW_DLP_INFLUX_TOKEN=', '')) }}"
|
||||
aw_existing_monitored_windows_host: "{{ (aw_existing_server_env_raw.content | default('') | b64decode | regex_search('(?m)^AW_MONITORED_WINDOWS_HOST=.*$') | default('', true) | regex_replace('^AW_MONITORED_WINDOWS_HOST=', '')) }}"
|
||||
aw_existing_monitored_windows_hostname: "{{ (aw_existing_server_env_raw.content | default('') | b64decode | regex_search('(?m)^AW_MONITORED_WINDOWS_HOSTNAME=.*$') | default('', true) | regex_replace('^AW_MONITORED_WINDOWS_HOSTNAME=', '')) }}"
|
||||
no_log: true
|
||||
|
||||
- name: Выбрать effective Influx tokens
|
||||
@@ -606,6 +611,53 @@
|
||||
aw_effective_dlp_influx_token: "{{ (aw_dlp_influx_token | default('') | string) if ((aw_dlp_influx_token | default('') | string | length) > 0) else aw_existing_dlp_influx_token }}"
|
||||
no_log: true
|
||||
|
||||
- name: Выбрать effective monitored Windows target
|
||||
ansible.builtin.set_fact:
|
||||
aw_effective_monitored_windows_host: >-
|
||||
{{
|
||||
(aw_monitored_windows_host | default('') | string)
|
||||
if (
|
||||
(aw_monitored_windows_host | default('') | string | length) > 0
|
||||
and (aw_monitored_windows_host | default('') | string | regex_search('192\\.0\\.2\\.|198\\.51\\.100\\.|203\\.0\\.113\\.|<|>|WINDOWS_USER_EXAMPLE')) is none
|
||||
)
|
||||
else aw_existing_monitored_windows_host
|
||||
}}
|
||||
aw_effective_monitored_windows_hostname: >-
|
||||
{{
|
||||
(aw_monitored_windows_hostname | default('') | string)
|
||||
if (
|
||||
(aw_monitored_windows_hostname | default('') | string | length) > 0
|
||||
and (aw_monitored_windows_hostname | default('') | string | regex_search('192\\.0\\.2\\.|198\\.51\\.100\\.|203\\.0\\.113\\.|<|>|WINDOWS_USER_EXAMPLE')) is none
|
||||
)
|
||||
else aw_existing_monitored_windows_hostname
|
||||
}}
|
||||
no_log: true
|
||||
|
||||
- name: Выбрать effective worktime host
|
||||
ansible.builtin.set_fact:
|
||||
aw_effective_worktime_host: >-
|
||||
{{
|
||||
(aw_worktime_host | default('') | string)
|
||||
if (
|
||||
(aw_worktime_host | default('') | string | length) > 0
|
||||
and (aw_worktime_host | default('') | string | regex_search('192\\.0\\.2\\.|198\\.51\\.100\\.|203\\.0\\.113\\.|<|>|WINDOWS_USER_EXAMPLE')) is none
|
||||
)
|
||||
else aw_effective_monitored_windows_hostname
|
||||
}}
|
||||
no_log: true
|
||||
|
||||
- name: Проверить monitored Windows target для production healthd
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- (aw_effective_monitored_windows_host | default('') | string | length) > 0
|
||||
- (aw_effective_monitored_windows_host | default('') | string | regex_search('192\\.0\\.2\\.|198\\.51\\.100\\.|203\\.0\\.113\\.|<|>|WINDOWS_USER_EXAMPLE')) is none
|
||||
- (aw_effective_monitored_windows_hostname | default('') | string | length) > 0
|
||||
- (aw_effective_monitored_windows_hostname | default('') | string | regex_search('192\\.0\\.2\\.|198\\.51\\.100\\.|203\\.0\\.113\\.|<|>|WINDOWS_USER_EXAMPLE')) is none
|
||||
- (aw_effective_worktime_host | default('') | string | length) > 0
|
||||
- (aw_effective_worktime_host | default('') | string | regex_search('192\\.0\\.2\\.|198\\.51\\.100\\.|203\\.0\\.113\\.|<|>|WINDOWS_USER_EXAMPLE')) is none
|
||||
fail_msg: "aw-rus-healthd получил public example/TEST-NET Windows target. Задайте live значения в private inventory/env или сохраните их в runtime /etc/activitywatch/aw-server.env."
|
||||
when: aw_server_post_deploy_health_check_enabled | default(true) | bool
|
||||
|
||||
- name: Проверить Influx token для AW worktime exporter
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
@@ -636,7 +688,6 @@
|
||||
- (aw_worktime_influx_bucket | default('') | string | length) > 0
|
||||
- (aw_worktime_influx_bucket | default('') | string | lower | regex_search('example|change_me|changeme|replace-me|replace_me|your_|<|>')) is none
|
||||
- (aw_worktime_influx_hosts | default('') | string | length) > 0
|
||||
- "'HOST-EXAMPLE' not in (aw_worktime_influx_hosts | default('') | string)"
|
||||
- "'WINDOWS_USER_EXAMPLE' not in (aw_worktime_influx_hosts | default('') | string)"
|
||||
fail_msg: "aw_worktime_influx_enabled=true, но URL/org/bucket/hosts похожи на public example/TEST-NET значения. Задайте live значения в private inventory/env, не в public repo."
|
||||
when: aw_worktime_influx_enabled | default(false) | bool
|
||||
@@ -653,7 +704,6 @@
|
||||
- (aw_dlp_influx_bucket | default('') | string | length) > 0
|
||||
- (aw_dlp_influx_bucket | default('') | string | lower | regex_search('example|change_me|changeme|replace-me|replace_me|your_|<|>')) is none
|
||||
- (aw_dlp_influx_hosts | default('') | string | length) > 0
|
||||
- "'HOST-EXAMPLE' not in (aw_dlp_influx_hosts | default('') | string)"
|
||||
- "'WINDOWS_USER_EXAMPLE' not in (aw_dlp_influx_hosts | default('') | string)"
|
||||
fail_msg: "aw_dlp_influx_enabled=true, но URL/org/bucket/hosts похожи на public example/TEST-NET значения. Задайте live значения в private inventory/env, не в public repo."
|
||||
when: aw_dlp_influx_enabled | default(false) | bool
|
||||
@@ -675,7 +725,13 @@
|
||||
AW_SERVER_GROUP={{ aw_server_group }}
|
||||
AW_WORKTIME_REPORT_BASE={{ aw_worktime_report_base }}
|
||||
AW_WORKTIME_TZ={{ aw_worktime_timezone }}
|
||||
AW_WORKTIME_HOST={{ aw_worktime_host | default(aw_monitored_windows_hostname | default('HOST-EXAMPLE')) }}
|
||||
AW_WORKTIME_HOST={{ aw_effective_worktime_host | default(aw_effective_monitored_windows_hostname | default('SHARKON2025')) }}
|
||||
AW_WORKTIME_EVENTS_LIMIT={{ aw_worktime_events_limit | default(5000) }}
|
||||
AW_WORKTIME_AW_HTTP_TIMEOUT_SECONDS={{ aw_worktime_aw_http_timeout_seconds | default(6) }}
|
||||
AW_WORKTIME_EVENTS_CACHE_TTL_SECONDS={{ aw_worktime_events_cache_ttl_seconds | default(300) }}
|
||||
AW_WORKTIME_REPORT_CACHE_TTL_SECONDS={{ aw_worktime_report_cache_ttl_seconds | default(300) }}
|
||||
AW_WORKTIME_REPORT_STALE_TTL_SECONDS={{ aw_worktime_report_stale_ttl_seconds | default(3600) }}
|
||||
AW_WORKTIME_REPORT_DISK_STALE_TTL_SECONDS={{ aw_worktime_report_disk_stale_ttl_seconds | default(86400) }}
|
||||
AW_DLP_IOC_DIR={{ aw_dlp_ioc_workdir }}/output
|
||||
AW_DLP_POLICY_ENGINE_BIND_HOST={{ aw_dlp_policy_engine_bind_host }}
|
||||
AW_DLP_POLICY_ENGINE_PORT={{ aw_dlp_policy_engine_port }}
|
||||
@@ -692,7 +748,7 @@
|
||||
AW_WORKTIME_INFLUX_URL={{ aw_worktime_influx_url | default('') }}
|
||||
AW_WORKTIME_INFLUX_ORG={{ aw_worktime_influx_org | default('proxmox') }}
|
||||
AW_WORKTIME_INFLUX_BUCKET={{ aw_worktime_influx_bucket | default('aw_metrics') }}
|
||||
AW_WORKTIME_INFLUX_HOSTS={{ aw_worktime_influx_hosts | default('HOST-EXAMPLE') }}
|
||||
AW_WORKTIME_INFLUX_HOSTS={{ aw_worktime_influx_hosts | default('SHARKON2025') }}
|
||||
AW_WORKTIME_INFLUX_DAYS={{ aw_worktime_influx_days | default('today,yesterday') }}
|
||||
AW_WORKTIME_INFLUX_TOKEN={{ aw_effective_worktime_influx_token | default('') }}
|
||||
AW_WORKTIME_MANAGEMENT_HISTORY_DIR={{ aw_worktime_management_history_dir | default(aw_server_data_dir ~ '/worktime-management-history') }}
|
||||
@@ -707,7 +763,7 @@
|
||||
AW_DLP_INFLUX_URL={{ aw_dlp_influx_url | default('') }}
|
||||
AW_DLP_INFLUX_ORG={{ aw_dlp_influx_org | default('proxmox') }}
|
||||
AW_DLP_INFLUX_BUCKET={{ aw_dlp_influx_bucket | default('aw_metrics') }}
|
||||
AW_DLP_INFLUX_HOSTS={{ aw_dlp_influx_hosts | default('HOST-EXAMPLE') }}
|
||||
AW_DLP_INFLUX_HOSTS={{ aw_dlp_influx_hosts | default('SHARKON2025') }}
|
||||
AW_DLP_INFLUX_LOOKBACK_DAYS={{ aw_dlp_influx_lookback_days | default(30) }}
|
||||
AW_DLP_INFLUX_EVENT_LIMIT={{ aw_dlp_influx_event_limit | default(2000) }}
|
||||
AW_DLP_INFLUX_TOKEN={{ aw_effective_dlp_influx_token | default('') }}
|
||||
@@ -717,8 +773,8 @@
|
||||
AW_EXPECT_ALWAYS_ACTIVE_PATTERN={{ aw_server_always_active_pattern | default('') }}
|
||||
AW_EXPECT_LANDINGPAGE={{ aw_server_landingpage | default('') }}
|
||||
AW_HEALTH_STRICT_FILEOPS={{ aw_health_strict_fileops | default(0) }}
|
||||
AW_MONITORED_WINDOWS_HOST={{ aw_monitored_windows_host }}
|
||||
AW_MONITORED_WINDOWS_HOSTNAME={{ aw_monitored_windows_hostname }}
|
||||
AW_MONITORED_WINDOWS_HOST={{ aw_effective_monitored_windows_host }}
|
||||
AW_MONITORED_WINDOWS_HOSTNAME={{ aw_effective_monitored_windows_hostname }}
|
||||
AW_RUS_HEALTH_WORKTIME_API={{ aw_rus_health_worktime_api_base | default('http://127.0.0.1:5610') }}
|
||||
AW_RUS_HEALTH_STATE_DIR={{ aw_rus_health_state_dir }}
|
||||
AW_RUS_HEALTH_VALIDATION_DIR={{ aw_rus_health_validation_dir }}
|
||||
@@ -731,7 +787,7 @@
|
||||
AW_RUS_SLO_TARGET_PERCENT={{ aw_rus_slo_target_percent | default('99.97') }}
|
||||
AW_BROWSER_SMOKE_AW_BASE=http://127.0.0.1:5600
|
||||
AW_BROWSER_SMOKE_WORKTIME_BASE={{ aw_rus_health_worktime_api_base | default('http://127.0.0.1:5610') }}
|
||||
AW_BROWSER_SMOKE_HOST={{ aw_monitored_windows_hostname }}
|
||||
AW_BROWSER_SMOKE_HOST={{ aw_effective_monitored_windows_hostname }}
|
||||
AW_BROWSER_SMOKE_OUTPUT_DIR={{ aw_server_data_dir }}/browser-smoke
|
||||
AW_BROWSER_SMOKE_ENGINE={{ aw_browser_smoke_engine | default('chromium-cli') }}
|
||||
AW_BROWSER_SMOKE_TIMEOUT_MS={{ aw_browser_smoke_timeout_ms | default(20000) }}
|
||||
@@ -1885,7 +1941,7 @@
|
||||
- name: Удалить старые теги RU patch из index.html
|
||||
ansible.builtin.replace:
|
||||
path: "{{ aw_server_webui_dir }}/index.html"
|
||||
regexp: '<script[^>]+(?:ru-patch-v5\.js|sw-cleanup\.js|aw-ru-patch\.js|aw-sw-cleanup\.js)[^>]*></script>'
|
||||
regexp: '<script[^>]+(?:ru-patch-v5\.js|sw-cleanup\.js|aw-host-sanitize\.js|aw-ru-patch\.js|aw-sw-cleanup\.js)[^>]*></script>'
|
||||
replace: ''
|
||||
|
||||
- name: Добавить cleanup script RU patch в index.html
|
||||
@@ -1894,6 +1950,12 @@
|
||||
regexp: '</head>'
|
||||
replace: '<script src="/js/sw-cleanup.js?v={{ aw_sw_cleanup_cache_bust }}"></script></head>'
|
||||
|
||||
- name: Добавить ранний guard hostname перед WebUI bundle
|
||||
ansible.builtin.replace:
|
||||
path: "{{ aw_server_webui_dir }}/index.html"
|
||||
regexp: '(<script defer="defer" src="/js/chunk-vendors[^"]+"></script>)'
|
||||
replace: '<script src="/js/aw-host-sanitize.js?v={{ aw_host_sanitize_cache_bust }}"></script>\1'
|
||||
|
||||
- name: Добавить загрузчик RU patch перед закрытием body
|
||||
ansible.builtin.replace:
|
||||
path: "{{ aw_server_webui_dir }}/index.html"
|
||||
@@ -2529,6 +2591,22 @@
|
||||
- /opt/activitywatch/aw-rus-ops/ansible
|
||||
- /opt/activitywatch/aw-rus-ops/drop
|
||||
|
||||
- name: Проверить наличие upload user awops для Hayabusa drop-zone
|
||||
ansible.builtin.command:
|
||||
cmd: id -u awops
|
||||
register: aw_hayabusa_drop_upload_user
|
||||
changed_when: false
|
||||
failed_when: false
|
||||
|
||||
- name: Разрешить awops писать в Hayabusa drop-zone
|
||||
ansible.builtin.file:
|
||||
path: /opt/activitywatch/aw-rus-ops/drop
|
||||
state: directory
|
||||
owner: awops
|
||||
group: awops
|
||||
mode: "0750"
|
||||
when: aw_hayabusa_drop_upload_user.rc == 0
|
||||
|
||||
- name: Положить исходный wrapper в server-side ops bundle
|
||||
ansible.builtin.copy:
|
||||
src: "{{ aw_repo_root }}/aw-server/hayabusa/aw-hayabusa.sh"
|
||||
|
||||
@@ -8,12 +8,17 @@
|
||||
ansible_winrm_read_timeout_sec: 180
|
||||
aw_windows_repo_root: "{{ playbook_dir | dirname }}"
|
||||
aw_windows_deploy_root: "C:\\Program Files\\AWatch-rus"
|
||||
aw_windows_rust_target_root: "{{ lookup('env', 'CARGO_TARGET_DIR') | default('/tmp/detmir-adk-rust-target', true) }}"
|
||||
aw_windows_telemetry_exe_source_candidates:
|
||||
- "{{ aw_windows_repo_root }}/windows/aw-windows-telemetry.exe"
|
||||
- "{{ aw_windows_rust_target_root }}/x86_64-pc-windows-gnu/release/aw-windows-telemetry.exe"
|
||||
aw_windows_telemetry_exe_source: ""
|
||||
aw_windows_server_scheme: "http"
|
||||
aw_windows_server_port: 5600
|
||||
aw_windows_package_version: "v0.13.2"
|
||||
aw_windows_package_url: "https://github.com/ActivityWatch/activitywatch/releases/download/v0.13.2/activitywatch-v0.13.2-windows-x86_64.zip"
|
||||
aw_windows_package_zip_path: ""
|
||||
aw_windows_domain: "HOST-EXAMPLE"
|
||||
aw_windows_domain: "SHARKON2025"
|
||||
aw_windows_builtin_administrator_name: "Администратор"
|
||||
aw_windows_users:
|
||||
- Администратор
|
||||
@@ -36,9 +41,11 @@
|
||||
aw_windows_hayabusa_auto_upload_hours_back: 6
|
||||
aw_windows_hayabusa_auto_upload_mode: "incident"
|
||||
aw_windows_hayabusa_auto_upload_task_name: "ActivityWatch Hayabusa Upload"
|
||||
aw_windows_hayabusa_auto_upload_run_as_user: ""
|
||||
aw_windows_file_1c_auto_upload_enabled: true
|
||||
aw_windows_file_1c_auto_upload_interval_hours: 6
|
||||
aw_windows_file_1c_auto_upload_interval_minutes: 15
|
||||
aw_windows_file_1c_auto_upload_task_name: "ActivityWatch File1C Upload"
|
||||
aw_windows_file_1c_auto_upload_run_as_user: "{{ aw_windows_domain }}\\{{ aw_windows_builtin_administrator_name }}"
|
||||
aw_windows_file_1c_target_user: "igor"
|
||||
aw_windows_file_1c_registry_workbook_path: "E:\\USER1\\СПИСОК ПРЕДПРИЯТИЙ И ИХ РАСПРЕДЕЛЕНИЕ.xlsx"
|
||||
aw_windows_afk_enabled_default: true
|
||||
@@ -165,18 +172,15 @@
|
||||
- "{{ aw_windows_deploy_root }}"
|
||||
- "{{ aw_windows_deploy_root }}\\windows"
|
||||
|
||||
- name: Загрузить Windows toolkit развёртывания
|
||||
- name: Загрузить Windows toolkit развёртывания (без PS-дубликатов — заменены Rust)
|
||||
ansible.windows.win_copy:
|
||||
src: "{{ aw_windows_repo_root }}/windows/{{ item }}"
|
||||
dest: "{{ aw_windows_deploy_root }}\\windows\\{{ item }}"
|
||||
loop:
|
||||
- ActivityWatch.Windows.Common.psd1
|
||||
- ActivityWatch.Windows.Common.psm1
|
||||
- browser-domains-native-collector.ps1
|
||||
- dlp-endpoint-signals-collector.ps1
|
||||
- dlp-policy-client.ps1
|
||||
- email-outbound-collector.ps1
|
||||
- file-operations-collector.ps1
|
||||
- worktime-session-collector.ps1
|
||||
- export-evtx-for-hayabusa.ps1
|
||||
- export-upload-hayabusa-to-aw-server.ps1
|
||||
@@ -187,7 +191,6 @@
|
||||
- deploy-ensemble.ps1
|
||||
- hardening-recovery.ps1
|
||||
- AWatchRusCollectorGuardService.cs
|
||||
- aw-collector-guard.ps1
|
||||
- install-collector-guard-service.ps1
|
||||
- rebuild-worktime-tasks.ps1
|
||||
- audit-cryptopro.ps1
|
||||
@@ -195,6 +198,43 @@
|
||||
- web-category-rules.example.json
|
||||
- dlp-policy.example.json
|
||||
|
||||
- name: Проверить кандидаты Rust Windows telemetry binary
|
||||
ansible.builtin.stat:
|
||||
path: "{{ item }}"
|
||||
loop: "{{ aw_windows_telemetry_exe_source_candidates }}"
|
||||
delegate_to: localhost
|
||||
become: false
|
||||
register: aw_windows_telemetry_exe_candidate_stats
|
||||
|
||||
- name: Выбрать Rust Windows telemetry binary
|
||||
ansible.builtin.set_fact:
|
||||
aw_windows_telemetry_exe_source_effective: >-
|
||||
{{
|
||||
aw_windows_telemetry_exe_source
|
||||
if (aw_windows_telemetry_exe_source | string | length) > 0
|
||||
else (
|
||||
aw_windows_telemetry_exe_candidate_stats.results
|
||||
| selectattr('stat.exists')
|
||||
| map(attribute='item')
|
||||
| list
|
||||
| first
|
||||
| default('')
|
||||
)
|
||||
}}
|
||||
|
||||
- name: Проверить наличие Rust Windows telemetry binary
|
||||
ansible.builtin.fail:
|
||||
msg: >-
|
||||
Не найден aw-windows-telemetry.exe. Соберите его командой:
|
||||
cargo build --release --target x86_64-pc-windows-gnu -p aw-windows-telemetry
|
||||
или используйте актуальный install-kit с windows/aw-windows-telemetry.exe.
|
||||
when: aw_windows_telemetry_exe_source_effective | length == 0
|
||||
|
||||
- name: Загрузить Rust Windows telemetry binary
|
||||
ansible.windows.win_copy:
|
||||
src: "{{ aw_windows_telemetry_exe_source_effective }}"
|
||||
dest: "{{ aw_windows_deploy_root }}\\windows\\aw-windows-telemetry.exe"
|
||||
|
||||
- name: Нормализовать кодировку PowerShell файлов (UTF-8 BOM для Windows PowerShell)
|
||||
ansible.windows.win_powershell:
|
||||
script: |
|
||||
@@ -272,9 +312,11 @@
|
||||
HayabusaAutoUploadHoursBack = {{ aw_windows_hayabusa_auto_upload_hours_back | int }}
|
||||
HayabusaAutoUploadMode = "{{ aw_windows_hayabusa_auto_upload_mode }}"
|
||||
HayabusaAutoUploadTaskName = "{{ aw_windows_hayabusa_auto_upload_task_name }}"
|
||||
HayabusaAutoUploadRunAsUser = "{{ aw_windows_hayabusa_auto_upload_run_as_user }}"
|
||||
File1CAutoUploadEnabled = {{ '$true' if (aw_windows_file_1c_auto_upload_enabled | bool) else '$false' }}
|
||||
File1CAutoUploadIntervalHours = {{ aw_windows_file_1c_auto_upload_interval_hours | int }}
|
||||
File1CAutoUploadIntervalMinutes = {{ aw_windows_file_1c_auto_upload_interval_minutes | int }}
|
||||
File1CAutoUploadTaskName = "{{ aw_windows_file_1c_auto_upload_task_name }}"
|
||||
File1CAutoUploadRunAsUser = "{{ aw_windows_file_1c_auto_upload_run_as_user }}"
|
||||
File1CTargetHost = "{{ aw_windows_file_1c_target_host_effective }}"
|
||||
File1CTargetUser = "{{ aw_windows_file_1c_target_user }}"
|
||||
File1CRegistryWorkbookPath = "{{ aw_windows_file_1c_registry_workbook_path }}"
|
||||
|
||||
@@ -46,19 +46,79 @@
|
||||
content: |
|
||||
DETMIR_PORTAL_BIND={{ detmir_portal_bind }}
|
||||
DETMIR_PORTAL_STATUS_CMD=detmir-status --json
|
||||
DETMIR_PORTAL_CHECK_CMD=detmir-check --json
|
||||
DETMIR_PORTAL_CHECK_CMD='cat /var/lib/detmir-ai/latest-run/detmir-check.json'
|
||||
DETMIR_PORTAL_FAILED_UNITS_CMD=systemctl --failed --no-pager
|
||||
DETMIR_PORTAL_WORKTIME_URL={{ detmir_portal_worktime_url }}
|
||||
DETMIR_PORTAL_ONE_C_URL={{ detmir_portal_one_c_url }}
|
||||
DETMIR_PORTAL_WORKFORCE_POLICY_PATH={{ detmir_portal_workforce_policy_path }}
|
||||
DETMIR_PORTAL_UEBA_POLICY_PATH={{ detmir_portal_ueba_policy_path }}
|
||||
DETMIR_PORTAL_TIMEOUT_SECONDS=10
|
||||
DETMIR_PORTAL_TIMEOUT_SECONDS=25
|
||||
DETMIR_PORTAL_STATE_DIR=/var/lib/detmir-portal
|
||||
DETMIR_PORTAL_DLP_DB_PATH=/var/lib/activitywatch/dlp_warehouse.sqlite
|
||||
DETMIR_PORTAL_EVIDENCE_ROOT=/var/lib/detmir-portal/evidence
|
||||
DETMIR_PORTAL_READINESS_BUNDLE_DIR={{ detmir_portal_readiness_bundle_dir }}
|
||||
DETMIR_PORTAL_EVIDENCE_LIMIT=30
|
||||
DETMIR_PORTAL_EVIDENCE_MAX_BYTES=8388608
|
||||
SECURITY_EVENTS_BACKEND={{ detmir_security_events_backend | default('disabled') }}
|
||||
CLICKHOUSE_URL={{ detmir_clickhouse_url | default('http://127.0.0.1:8123') }}
|
||||
CLICKHOUSE_DATABASE={{ detmir_clickhouse_database | default('analytics_1c') }}
|
||||
CLICKHOUSE_USER={{ detmir_clickhouse_user | default('default') }}
|
||||
CLICKHOUSE_PASSWORD={{ detmir_clickhouse_password | default('') }}
|
||||
|
||||
- name: Preserve local ClickHouse security-events settings when available
|
||||
ansible.builtin.shell: |
|
||||
set -euo pipefail
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
|
||||
source = Path("/opt/activitywatch/clickhouse-1c/.env")
|
||||
target = Path("{{ detmir_portal_env_path }}")
|
||||
if not source.exists() or not target.exists():
|
||||
raise SystemExit(0)
|
||||
|
||||
kv = {}
|
||||
for line in source.read_text().splitlines():
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
kv[key.strip()] = value.strip().strip('"').strip("'")
|
||||
|
||||
updates = {
|
||||
"SECURITY_EVENTS_BACKEND": "clickhouse",
|
||||
"CLICKHOUSE_URL": "http://127.0.0.1:8123",
|
||||
"CLICKHOUSE_DATABASE": kv.get("CLICKHOUSE_DB", "analytics_1c"),
|
||||
"CLICKHOUSE_USER": kv.get("CLICKHOUSE_USER", "default"),
|
||||
"CLICKHOUSE_PASSWORD": kv.get("CLICKHOUSE_PASSWORD", ""),
|
||||
}
|
||||
|
||||
lines = []
|
||||
seen = set()
|
||||
for line in target.read_text().splitlines():
|
||||
if "=" in line and not line.startswith("#"):
|
||||
key = line.split("=", 1)[0].strip()
|
||||
if key in updates:
|
||||
lines.append(f"{key}={updates[key]}")
|
||||
seen.add(key)
|
||||
continue
|
||||
lines.append(line)
|
||||
for key, value in updates.items():
|
||||
if key not in seen:
|
||||
lines.append(f"{key}={value}")
|
||||
target.write_text("\n".join(lines) + "\n")
|
||||
PY
|
||||
args:
|
||||
executable: /bin/bash
|
||||
no_log: true
|
||||
when: detmir_security_events_backend | default('clickhouse') == 'clickhouse'
|
||||
|
||||
- name: Remove stale detmir-portal systemd overrides
|
||||
ansible.builtin.file:
|
||||
path: "{{ item }}"
|
||||
state: absent
|
||||
loop:
|
||||
- /etc/systemd/system/detmir-portal.service.d/20-timeouts.conf
|
||||
- /etc/systemd/system/detmir-portal.service.d/30-warm-cache.conf
|
||||
register: detmir_portal_stale_overrides
|
||||
|
||||
- name: Install initial workforce policy when absent
|
||||
ansible.builtin.copy:
|
||||
@@ -105,6 +165,7 @@
|
||||
[Service]
|
||||
Type=simple
|
||||
EnvironmentFile=-{{ detmir_portal_env_path }}
|
||||
EnvironmentFile=-/etc/detmir/detmir-check.env
|
||||
ExecStart=/usr/local/bin/detmir-portal
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
@@ -116,7 +177,6 @@
|
||||
- name: Reload systemd
|
||||
ansible.builtin.systemd:
|
||||
daemon_reload: true
|
||||
when: detmir_portal_service_unit.changed
|
||||
|
||||
- name: Enable and restart detmir-portal
|
||||
ansible.builtin.systemd:
|
||||
@@ -140,11 +200,15 @@
|
||||
method: GET
|
||||
status_code: 200
|
||||
return_content: true
|
||||
timeout: 90
|
||||
register: detmir_portal_reports
|
||||
failed_when: >
|
||||
detmir_portal_reports.status != 200
|
||||
or detmir_portal_reports.json.kpis is not defined
|
||||
or 'derived detections/cases' not in (detmir_portal_reports.json.markdown | default(''))
|
||||
or (
|
||||
'derived detections/cases' not in (detmir_portal_reports.json.markdown | default(''))
|
||||
and 'расчетными выводами' not in (detmir_portal_reports.json.markdown | default(''))
|
||||
)
|
||||
changed_when: false
|
||||
|
||||
- name: Deploy DetMir DLP evidence API on AW server
|
||||
|
||||
@@ -7,8 +7,12 @@
|
||||
aw_repo_root: "{{ playbook_dir | dirname }}"
|
||||
aw_windows_state_root: "C:\\ProgramData\\AWatch-rus"
|
||||
aw_windows_deploy_root: "C:\\Program Files\\AWatch-rus"
|
||||
aw_windows_rust_target_root: "{{ lookup('env', 'CARGO_TARGET_DIR') | default('/tmp/detmir-adk-rust-target', true) }}"
|
||||
aw_windows_telemetry_exe_source: "{{ aw_windows_rust_target_root }}/x86_64-pc-windows-gnu/release/aw-windows-telemetry.exe"
|
||||
aw_windows_telemetry_exe_path: "{{ aw_windows_deploy_root }}\\windows\\aw-windows-telemetry.exe"
|
||||
aw_windows_evidence_sync_task_name: "ActivityWatch DLP Evidence Sync"
|
||||
aw_windows_evidence_sync_interval_minutes: 5
|
||||
aw_windows_evidence_sync_interval_minutes: 15
|
||||
aw_windows_evidence_sync_run_as_user: "HOST-EXAMPLE\\Администратор"
|
||||
aw_windows_evidence_sync_api_url: "http://192.0.2.13:8721/api/dlp/evidence/upload"
|
||||
aw_windows_evidence_sync_script: "{{ aw_windows_state_root }}\\sync-dlp-evidence-artifacts.ps1"
|
||||
aw_windows_evidence_sync_token_path: "{{ aw_windows_state_root }}\\dlp-evidence-upload-token.txt"
|
||||
@@ -38,6 +42,11 @@
|
||||
src: "{{ aw_repo_root }}/windows/sync-dlp-evidence-artifacts.ps1"
|
||||
dest: "{{ aw_windows_evidence_sync_script }}"
|
||||
|
||||
- name: Install Rust Windows telemetry binary
|
||||
ansible.windows.win_copy:
|
||||
src: "{{ aw_windows_telemetry_exe_source }}"
|
||||
dest: "{{ aw_windows_telemetry_exe_path }}"
|
||||
|
||||
- name: Normalize DLP evidence sync script encoding
|
||||
ansible.windows.win_powershell:
|
||||
script: |
|
||||
@@ -76,23 +85,26 @@
|
||||
script: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$taskName = "{{ aw_windows_evidence_sync_task_name }}"
|
||||
$ps = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
||||
$telemetryExe = "{{ aw_windows_telemetry_exe_path }}"
|
||||
$args = @(
|
||||
'-NoProfile',
|
||||
'-ExecutionPolicy', 'Bypass',
|
||||
'-File', '"{{ aw_windows_evidence_sync_script }}"',
|
||||
'-EvidenceApiUrl', '"{{ aw_windows_evidence_sync_api_url }}"',
|
||||
'-TokenPath', '"{{ aw_windows_evidence_sync_token_path }}"',
|
||||
'-StatePath', '"{{ aw_windows_evidence_sync_state_path }}"',
|
||||
'-LogPath', '"{{ aw_windows_evidence_sync_log_path }}"'
|
||||
'dlp-evidence-sync',
|
||||
'--evidence-api-url', '"{{ aw_windows_evidence_sync_api_url }}"',
|
||||
'--token-path', '"{{ aw_windows_evidence_sync_token_path }}"',
|
||||
'--state-path', '"{{ aw_windows_evidence_sync_state_path }}"',
|
||||
'--log-path', '"{{ aw_windows_evidence_sync_log_path }}"'
|
||||
) -join ' '
|
||||
$action = New-ScheduledTaskAction -Execute $ps -Argument $args
|
||||
$action = New-ScheduledTaskAction -Execute $telemetryExe -Argument $args
|
||||
$trigger = New-ScheduledTaskTrigger `
|
||||
-Once `
|
||||
-At ((Get-Date).AddMinutes(1)) `
|
||||
-RepetitionInterval (New-TimeSpan -Minutes {{ aw_windows_evidence_sync_interval_minutes | int }}) `
|
||||
-RepetitionDuration (New-TimeSpan -Days 3650)
|
||||
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
|
||||
$runAsUser = "{{ aw_windows_evidence_sync_run_as_user }}"
|
||||
if ([string]::IsNullOrWhiteSpace($runAsUser)) {
|
||||
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
|
||||
} else {
|
||||
$principal = New-ScheduledTaskPrincipal -UserId $runAsUser -LogonType Interactive -RunLevel Highest
|
||||
}
|
||||
$settings = New-ScheduledTaskSettingsSet `
|
||||
-AllowStartIfOnBatteries `
|
||||
-StartWhenAvailable `
|
||||
@@ -112,11 +124,12 @@
|
||||
ansible.windows.win_powershell:
|
||||
script: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$result = & "{{ aw_windows_evidence_sync_script }}" `
|
||||
-EvidenceApiUrl "{{ aw_windows_evidence_sync_api_url }}" `
|
||||
-TokenPath "{{ aw_windows_evidence_sync_token_path }}" `
|
||||
-StatePath "{{ aw_windows_evidence_sync_state_path }}" `
|
||||
-LogPath "{{ aw_windows_evidence_sync_log_path }}"
|
||||
$result = & "{{ aw_windows_telemetry_exe_path }}" `
|
||||
dlp-evidence-sync `
|
||||
--evidence-api-url "{{ aw_windows_evidence_sync_api_url }}" `
|
||||
--token-path "{{ aw_windows_evidence_sync_token_path }}" `
|
||||
--state-path "{{ aw_windows_evidence_sync_state_path }}" `
|
||||
--log-path "{{ aw_windows_evidence_sync_log_path }}"
|
||||
$result
|
||||
register: aw_windows_evidence_sync_smoke
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
vars:
|
||||
aw_file_1c_repo_root: "{{ playbook_dir | dirname }}"
|
||||
aw_rust_release_dir: "{{ (lookup('env', 'CARGO_TARGET_DIR') | default(aw_file_1c_repo_root + '/adk-rust/target', true)) + '/release' }}"
|
||||
aw_file_1c_release_root: /opt/activitywatch/releases
|
||||
aw_file_1c_release_dir: "{{ aw_file_1c_release_root }}/clickhouse-1c"
|
||||
aw_file_1c_root: /opt/activitywatch/clickhouse-1c
|
||||
@@ -230,6 +231,26 @@
|
||||
- 04_company_intelligence.sql
|
||||
- 05_financial_reporting.sql
|
||||
|
||||
- name: Проверить локальный Rust binary aw-1c-ingest
|
||||
ansible.builtin.stat:
|
||||
path: "{{ aw_rust_release_dir }}/aw-1c-ingest"
|
||||
delegate_to: localhost
|
||||
become: false
|
||||
register: aw_file_1c_ingest_binary
|
||||
|
||||
- name: Остановить deploy без Rust binary aw-1c-ingest
|
||||
ansible.builtin.fail:
|
||||
msg: "Missing {{ aw_rust_release_dir }}/aw-1c-ingest. Build with cargo build --release -p aw-1c-ingest."
|
||||
when: not (aw_file_1c_ingest_binary.stat.exists | default(false))
|
||||
|
||||
- name: Установить Rust binary aw-1c-ingest
|
||||
ansible.builtin.copy:
|
||||
src: "{{ aw_rust_release_dir }}/aw-1c-ingest"
|
||||
dest: /usr/local/bin/aw-1c-ingest-rust
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0755"
|
||||
|
||||
- name: Установить systemd unit aw-1c-ingest.service
|
||||
ansible.builtin.copy:
|
||||
src: "{{ aw_file_1c_repo_root }}/clickhouse-1c/ops/aw-1c-ingest.service"
|
||||
|
||||
@@ -7,9 +7,13 @@
|
||||
aw_windows_repo_root: "{{ playbook_dir | dirname }}"
|
||||
aw_windows_state_root: "C:\\ProgramData\\AWatch-rus"
|
||||
aw_windows_deploy_root: "C:\\Program Files\\AWatch-rus"
|
||||
aw_windows_rust_target_root: "{{ lookup('env', 'CARGO_TARGET_DIR') | default('/tmp/detmir-adk-rust-target', true) }}"
|
||||
aw_windows_telemetry_exe_source: "{{ aw_windows_rust_target_root }}/x86_64-pc-windows-gnu/release/aw-windows-telemetry.exe"
|
||||
aw_windows_telemetry_exe_path: "{{ aw_windows_deploy_root }}\\windows\\aw-windows-telemetry.exe"
|
||||
aw_windows_file_1c_target_user: "igor"
|
||||
aw_windows_file_1c_auto_upload_interval_hours: 6
|
||||
aw_windows_file_1c_auto_upload_interval_minutes: 15
|
||||
aw_windows_file_1c_auto_upload_task_name: "ActivityWatch File1C Upload"
|
||||
aw_windows_file_1c_auto_upload_run_as_user: "HOST-EXAMPLE\\Администратор"
|
||||
aw_windows_file_1c_remote_root: "/opt/activitywatch/clickhouse-1c/landing"
|
||||
aw_windows_file_1c_remote_key_path: ""
|
||||
aw_windows_file_1c_registry_workbook_path: "E:\\USER1\\СПИСОК ПРЕДПРИЯТИЙ И ИХ РАСПРЕДЕЛЕНИЕ.xlsx"
|
||||
@@ -67,6 +71,11 @@
|
||||
src: "{{ aw_windows_repo_root }}/windows/export-upload-file-1c-telemetry.ps1"
|
||||
dest: "{{ aw_windows_deploy_root }}\\windows\\export-upload-file-1c-telemetry.ps1"
|
||||
|
||||
- name: Загрузить Rust telemetry binary в toolkit
|
||||
ansible.windows.win_copy:
|
||||
src: "{{ aw_windows_telemetry_exe_source }}"
|
||||
dest: "{{ aw_windows_telemetry_exe_path }}"
|
||||
|
||||
- name: Загрузить file-1C telemetry script в state root
|
||||
ansible.windows.win_copy:
|
||||
src: "{{ aw_windows_repo_root }}/windows/export-upload-file-1c-telemetry.ps1"
|
||||
@@ -87,6 +96,11 @@
|
||||
} else {
|
||||
$config.paths | Add-Member -NotePropertyName 'file1cTelemetryScript' -NotePropertyValue "{{ aw_windows_state_root }}\export-upload-file-1c-telemetry.ps1"
|
||||
}
|
||||
if ($config.paths.PSObject.Properties.Name -contains 'file1cTelemetryExecutable') {
|
||||
$config.paths.file1cTelemetryExecutable = "{{ aw_windows_telemetry_exe_path }}"
|
||||
} else {
|
||||
$config.paths | Add-Member -NotePropertyName 'file1cTelemetryExecutable' -NotePropertyValue "{{ aw_windows_telemetry_exe_path }}"
|
||||
}
|
||||
|
||||
if ($config.PSObject.Properties.Name -notcontains 'analytics') {
|
||||
$config | Add-Member -NotePropertyName 'analytics' -NotePropertyValue ([pscustomobject]@{})
|
||||
@@ -94,10 +108,11 @@
|
||||
|
||||
$automation = [pscustomobject]@{
|
||||
enabled = $true
|
||||
intervalHours = {{ aw_windows_file_1c_auto_upload_interval_hours | int }}
|
||||
intervalMinutes = {{ aw_windows_file_1c_auto_upload_interval_minutes | int }}
|
||||
taskName = "{{ aw_windows_file_1c_auto_upload_task_name }}"
|
||||
targetHost = "{{ aw_windows_file_1c_target_host_effective }}"
|
||||
targetUser = "{{ aw_windows_file_1c_target_user }}"
|
||||
runAsUser = "{{ aw_windows_file_1c_auto_upload_run_as_user }}"
|
||||
remoteRoot = "{{ aw_windows_file_1c_remote_root }}"
|
||||
registryWorkbookPath = "{{ aw_windows_file_1c_registry_workbook_path }}"
|
||||
remoteKeyPath = "{{ aw_windows_file_1c_remote_key_path }}"
|
||||
@@ -154,19 +169,20 @@
|
||||
script: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$taskName = "{{ aw_windows_file_1c_auto_upload_task_name }}"
|
||||
$powerShellExe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
||||
$taskCommand = "`"$powerShellExe`" -NoProfile -ExecutionPolicy Bypass -File `"{{ aw_windows_state_root }}\export-upload-file-1c-telemetry.ps1`" -ConfigPath `"{{ aw_windows_state_root }}\deployment-config.json`""
|
||||
$telemetryExe = "{{ aw_windows_telemetry_exe_path }}"
|
||||
$runAsUser = "{{ aw_windows_file_1c_auto_upload_run_as_user }}"
|
||||
$taskArgs = "file1c-upload --config-path `"{{ aw_windows_state_root }}\deployment-config.json`""
|
||||
$action = New-ScheduledTaskAction -Execute $telemetryExe -Argument $taskArgs
|
||||
$trigger = New-ScheduledTaskTrigger -Once -At ((Get-Date).Date) -RepetitionInterval (New-TimeSpan -Minutes {{ aw_windows_file_1c_auto_upload_interval_minutes | int }}) -RepetitionDuration (New-TimeSpan -Days 3650)
|
||||
if ([string]::IsNullOrWhiteSpace($runAsUser)) {
|
||||
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
|
||||
} else {
|
||||
$principal = New-ScheduledTaskPrincipal -UserId $runAsUser -LogonType Interactive -RunLevel Highest
|
||||
}
|
||||
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
|
||||
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
||||
if ($existingTask) {
|
||||
$action = New-ScheduledTaskAction -Execute $powerShellExe -Argument "-NoProfile -ExecutionPolicy Bypass -File `"{{ aw_windows_state_root }}\export-upload-file-1c-telemetry.ps1`" -ConfigPath `"{{ aw_windows_state_root }}\deployment-config.json`""
|
||||
try {
|
||||
Set-ScheduledTask -TaskName $taskName -Action $action -ErrorAction Stop | Out-Null
|
||||
} catch {
|
||||
Write-Host "skip task action update for $taskName because the existing principal requires stored credentials: $($_.Exception.Message)"
|
||||
}
|
||||
Set-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -ErrorAction Stop | Out-Null
|
||||
} else {
|
||||
& schtasks.exe /Create /TN $taskName /TR $taskCommand /SC HOURLY /MO {{ aw_windows_file_1c_auto_upload_interval_hours | int }} /ST 00:00 /RU SYSTEM /RL HIGHEST /F | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Не удалось создать scheduled task $taskName"
|
||||
}
|
||||
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings | Out-Null
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
proxmox_web_gateway_tls_cert_path: "{{ proxmox_web_gateway_tls_dir }}/fullchain.pem"
|
||||
proxmox_web_gateway_tls_key_path: "{{ proxmox_web_gateway_tls_dir }}/privkey.pem"
|
||||
proxmox_web_gateway_health_path: "/healthz"
|
||||
proxmox_web_gateway_auth_realm: "DetMir operations gateway"
|
||||
proxmox_web_gateway_auth_realm: "AWatch-rus portal 2026-06-06"
|
||||
proxmox_web_gateway_auth_user: "detmir"
|
||||
proxmox_web_gateway_auth_file: "/etc/nginx/proxmox-web-gateway.htpasswd"
|
||||
proxmox_web_gateway_credentials_file: "/etc/detmir/proxmox-web-gateway.credentials"
|
||||
@@ -162,7 +162,12 @@
|
||||
path: "{{ proxmox_web_gateway_auth_file }}"
|
||||
register: proxmox_web_gateway_auth_stat
|
||||
|
||||
- name: Создать gateway Basic Auth credential при первом запуске
|
||||
- name: Проверить наличие gateway credential файла
|
||||
ansible.builtin.stat:
|
||||
path: "{{ proxmox_web_gateway_credentials_file }}"
|
||||
register: proxmox_web_gateway_credentials_stat
|
||||
|
||||
- name: Создать согласованные gateway Basic Auth credential
|
||||
ansible.builtin.shell: |
|
||||
set -eu
|
||||
umask 077
|
||||
@@ -172,9 +177,10 @@
|
||||
printf 'url=https://{{ proxmox_web_gateway_public_hostname }}/\nuser={{ proxmox_web_gateway_auth_user }}\npassword=%s\n' "$password" > '{{ proxmox_web_gateway_credentials_file }}'
|
||||
args:
|
||||
executable: /bin/sh
|
||||
creates: "{{ proxmox_web_gateway_auth_file }}"
|
||||
no_log: true
|
||||
when: not proxmox_web_gateway_auth_stat.stat.exists
|
||||
when: >
|
||||
not (proxmox_web_gateway_auth_stat.stat.exists | default(false))
|
||||
or not (proxmox_web_gateway_credentials_stat.stat.exists | default(false))
|
||||
|
||||
- name: Зафиксировать права gateway Basic Auth файла
|
||||
ansible.builtin.file:
|
||||
|
||||
@@ -12,6 +12,12 @@ aw_server_inventory_host: "{{ (groups['aw_server'] | default([]) | first) | defa
|
||||
aw_server_public_host: "{{ (hostvars[aw_server_inventory_host].ansible_host | default(aw_server_inventory_host, true)) if (aw_server_inventory_host | length) > 0 else 'aw-server' }}"
|
||||
aw_worktime_report_base: "http://{{ aw_server_public_host }}:5610"
|
||||
aw_worktime_timezone: "Europe/Moscow"
|
||||
aw_worktime_events_limit: 250
|
||||
aw_worktime_aw_http_timeout_seconds: 6
|
||||
aw_worktime_events_cache_ttl_seconds: 300
|
||||
aw_worktime_report_cache_ttl_seconds: 300
|
||||
aw_worktime_report_stale_ttl_seconds: 3600
|
||||
aw_worktime_report_disk_stale_ttl_seconds: 86400
|
||||
aw_worktime_influx_enabled: false
|
||||
aw_worktime_influx_url: "http://<INFLUXDB_HOST>:8086"
|
||||
aw_worktime_influx_org: "proxmox"
|
||||
|
||||
@@ -12,6 +12,12 @@ aw_server_inventory_host: "{{ (groups['aw_server'] | default([]) | first) | defa
|
||||
aw_server_public_host: "{{ (hostvars[aw_server_inventory_host].ansible_host | default(aw_server_inventory_host, true)) if (aw_server_inventory_host | length) > 0 else 'aw-server' }}"
|
||||
aw_worktime_report_base: "http://{{ aw_server_public_host }}:5610"
|
||||
aw_worktime_timezone: "Europe/Moscow"
|
||||
aw_worktime_events_limit: 250
|
||||
aw_worktime_aw_http_timeout_seconds: 6
|
||||
aw_worktime_events_cache_ttl_seconds: 300
|
||||
aw_worktime_report_cache_ttl_seconds: 300
|
||||
aw_worktime_report_stale_ttl_seconds: 3600
|
||||
aw_worktime_report_disk_stale_ttl_seconds: 86400
|
||||
aw_worktime_influx_enabled: true
|
||||
aw_worktime_influx_url: "http://192.0.2.10:8086"
|
||||
aw_worktime_influx_org: "proxmox"
|
||||
|
||||
@@ -39,6 +39,7 @@ aw_windows_hayabusa_auto_upload_interval_hours: 6
|
||||
aw_windows_hayabusa_auto_upload_hours_back: 6
|
||||
aw_windows_hayabusa_auto_upload_mode: "incident"
|
||||
aw_windows_hayabusa_auto_upload_task_name: "ActivityWatch Hayabusa Upload"
|
||||
aw_windows_hayabusa_auto_upload_run_as_user: "{{ aw_windows_builtin_administrator_name }}"
|
||||
|
||||
aw_windows_afk_enabled: true
|
||||
aw_windows_window_enabled: true
|
||||
|
||||
@@ -9,6 +9,7 @@ aw_windows_hayabusa_auto_upload_interval_hours: 6
|
||||
aw_windows_hayabusa_auto_upload_hours_back: 6
|
||||
aw_windows_hayabusa_auto_upload_mode: "incident"
|
||||
aw_windows_hayabusa_auto_upload_task_name: "ActivityWatch Hayabusa Upload"
|
||||
aw_windows_hayabusa_auto_upload_run_as_user: ""
|
||||
aw_windows_package_version: "v0.13.2"
|
||||
aw_windows_package_url: "https://github.com/ActivityWatch/activitywatch/releases/download/v0.13.2/activitywatch-v0.13.2-windows-x86_64.zip"
|
||||
aw_windows_package_zip_path: ""
|
||||
|
||||
@@ -38,6 +38,9 @@ server {
|
||||
add_header X-Robots-Tag "noindex, nofollow, noarchive" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||
|
||||
charset utf-8;
|
||||
charset_types text/plain text/css application/json application/javascript text/javascript application/xml text/xml;
|
||||
|
||||
root {{ proxmox_web_gateway_root }};
|
||||
index index.html;
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var BAD_HOST = ["HOST", "EXAMPLE"].join("-");
|
||||
var DEFAULT_HOST = "SHARKON2025";
|
||||
|
||||
function decode(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch (error) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function hostFromHash() {
|
||||
var hash = window.location.hash || "";
|
||||
var match = hash.match(/#?\/activity\/([^/]+)/i) || hash.match(/#?\/trends\/([^/?#]+)/i);
|
||||
var host = match && match[1] ? decode(match[1]) : "";
|
||||
if (host && host !== BAD_HOST && host !== "unknown" && host !== "undefined") return host;
|
||||
return DEFAULT_HOST;
|
||||
}
|
||||
|
||||
function rewriteText(value) {
|
||||
if (typeof value !== "string" || value.indexOf(BAD_HOST) === -1) return value;
|
||||
return value.split(BAD_HOST).join(hostFromHash());
|
||||
}
|
||||
|
||||
function sanitizeStorage(storage) {
|
||||
if (!storage) return;
|
||||
try {
|
||||
for (var i = 0; i < storage.length; i += 1) {
|
||||
var key = storage.key(i);
|
||||
if (!key) continue;
|
||||
var value = storage.getItem(key);
|
||||
var next = rewriteText(value);
|
||||
if (next !== value) storage.setItem(key, next);
|
||||
}
|
||||
if (storage.landingpage && storage.landingpage.indexOf(BAD_HOST) !== -1) {
|
||||
storage.landingpage = "/activity/" + hostFromHash() + "/view/";
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeRoute() {
|
||||
var hash = window.location.hash || "";
|
||||
var next = rewriteText(hash);
|
||||
if (next !== hash) window.location.replace(next);
|
||||
}
|
||||
|
||||
sanitizeStorage(window.localStorage);
|
||||
sanitizeStorage(window.sessionStorage);
|
||||
sanitizeRoute();
|
||||
|
||||
var originalFetch = window.fetch;
|
||||
if (typeof originalFetch === "function" && !originalFetch.__awHostSanitizePatched) {
|
||||
var patchedFetch = function (input, init) {
|
||||
var nextInput = input;
|
||||
var nextInit = init;
|
||||
try {
|
||||
if (typeof nextInput === "string") {
|
||||
nextInput = rewriteText(nextInput);
|
||||
} else if (nextInput && typeof nextInput.url === "string") {
|
||||
var nextUrl = rewriteText(nextInput.url);
|
||||
if (nextUrl !== nextInput.url && typeof Request === "function") {
|
||||
nextInput = new Request(nextUrl, nextInput);
|
||||
}
|
||||
}
|
||||
if (nextInit && typeof nextInit.body === "string") {
|
||||
nextInit = Object.assign({}, nextInit, { body: rewriteText(nextInit.body) });
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
return originalFetch.call(this, nextInput, nextInit);
|
||||
};
|
||||
patchedFetch.__awHostSanitizePatched = true;
|
||||
window.fetch = patchedFetch;
|
||||
}
|
||||
|
||||
if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && !window.XMLHttpRequest.prototype.__awHostSanitizePatched) {
|
||||
var proto = window.XMLHttpRequest.prototype;
|
||||
var originalOpen = proto.open;
|
||||
var originalSend = proto.send;
|
||||
proto.open = function (method, url) {
|
||||
if (typeof url === "string") arguments[1] = rewriteText(url);
|
||||
return originalOpen.apply(this, arguments);
|
||||
};
|
||||
proto.send = function (body) {
|
||||
if (typeof body === "string") body = rewriteText(body);
|
||||
return originalSend.call(this, body);
|
||||
};
|
||||
proto.__awHostSanitizePatched = true;
|
||||
}
|
||||
})();
|
||||
@@ -1,9 +1,9 @@
|
||||
[Unit]
|
||||
Description=Run AW-RUS unified health orchestrator every 2 minutes
|
||||
Description=Run AW-RUS unified health orchestrator every 5 minutes
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:0/2:25
|
||||
AccuracySec=15s
|
||||
OnCalendar=*:0/5:25
|
||||
AccuracySec=30s
|
||||
RandomizedDelaySec=15s
|
||||
Unit=aw-rus-healthd.service
|
||||
Persistent=false
|
||||
|
||||
@@ -16,6 +16,13 @@ AW_SERVER_GROUP=activitywatch
|
||||
AW_SERVER_PUBLIC_HOST=aw-server
|
||||
AW_WORKTIME_REPORT_BASE=http://aw-server:5610
|
||||
AW_WORKTIME_TZ=Europe/Moscow
|
||||
AW_WORKTIME_HOST=SHARKON2025
|
||||
AW_WORKTIME_EVENTS_LIMIT=5000
|
||||
AW_WORKTIME_AW_HTTP_TIMEOUT_SECONDS=6
|
||||
AW_WORKTIME_EVENTS_CACHE_TTL_SECONDS=300
|
||||
AW_WORKTIME_REPORT_CACHE_TTL_SECONDS=300
|
||||
AW_WORKTIME_REPORT_STALE_TTL_SECONDS=3600
|
||||
AW_WORKTIME_REPORT_DISK_STALE_TTL_SECONDS=86400
|
||||
AW_SERVER_URL=http://127.0.0.1:5600
|
||||
AW_DLP_AW_API_BASE=http://127.0.0.1:5600/api/0
|
||||
AW_WORKTIME_MANAGER_CACHE_TTL_SECONDS=300
|
||||
@@ -43,10 +50,10 @@ AW_HEALTH_CHECK_ENABLED=true
|
||||
AW_HEALTH_CHECK_INTERVAL=60
|
||||
AW_EXPECT_START_OF_DAY=00:00
|
||||
AW_EXPECT_ALWAYS_ACTIVE_PATTERN=aw-watcher-window
|
||||
AW_EXPECT_LANDINGPAGE=/#/activity/HOST-EXAMPLE/view/
|
||||
AW_EXPECT_LANDINGPAGE=/#/activity/SHARKON2025/view/
|
||||
AW_HEALTH_STRICT_FILEOPS=0
|
||||
AW_MONITORED_WINDOWS_HOST=<WINDOWS_HOST>
|
||||
AW_MONITORED_WINDOWS_HOSTNAME=HOST-EXAMPLE
|
||||
AW_MONITORED_WINDOWS_HOSTNAME=SHARKON2025
|
||||
AW_RUS_HEALTH_WORKTIME_API=http://127.0.0.1:5610
|
||||
AW_RUS_HEALTH_STATE_DIR=/var/lib/activitywatch/health
|
||||
AW_RUS_HEALTH_VALIDATION_DIR=/var/lib/activitywatch/health/windows-validation
|
||||
@@ -58,7 +65,7 @@ AW_RUS_SLO_WORKTIME_BASE=http://127.0.0.1:5610
|
||||
AW_RUS_SLO_TARGET_PERCENT=99.97
|
||||
AW_BROWSER_SMOKE_AW_BASE=http://127.0.0.1:5600
|
||||
AW_BROWSER_SMOKE_WORKTIME_BASE=http://127.0.0.1:5610
|
||||
AW_BROWSER_SMOKE_HOST=HOST-EXAMPLE
|
||||
AW_BROWSER_SMOKE_HOST=SHARKON2025
|
||||
AW_BROWSER_SMOKE_OUTPUT_DIR=/var/lib/activitywatch/browser-smoke
|
||||
AW_BROWSER_SMOKE_KEEP_RUNS=24
|
||||
AW_BROWSER_SMOKE_ENGINE=chromium-cli
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[Unit]
|
||||
Description=AW Worktime Autoheal (HOST-EXAMPLE)
|
||||
Description=AW Worktime Autoheal
|
||||
After=network-online.target activitywatch-server.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
EnvironmentFile=/etc/activitywatch/aw-server.env
|
||||
Environment=AW_URL=http://127.0.0.1:5600
|
||||
Environment=AW_WORKTIME_HOST=HOST-EXAMPLE
|
||||
ExecStart=/usr/local/bin/aw-worktime-autoheal-rust
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
[Unit]
|
||||
Description=Run AW Worktime Autoheal every 3 minutes
|
||||
Description=Run AW Worktime Autoheal every 15 minutes
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:1/3:35
|
||||
OnCalendar=*:0/15:35
|
||||
AccuracySec=30s
|
||||
Unit=aw-worktime-autoheal.service
|
||||
Persistent=false
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Description=Run AW Worktime Report Cache Prewarm
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:2/5:40
|
||||
OnCalendar=*:0/15:40
|
||||
AccuracySec=30s
|
||||
Persistent=false
|
||||
Unit=aw-worktime-prewarm.service
|
||||
|
||||
@@ -7,8 +7,8 @@ StartLimitIntervalSec=120
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
EnvironmentFile=/etc/activitywatch/aw-server.env
|
||||
Environment=AW_SERVER_URL=http://127.0.0.1:5600
|
||||
Environment=AW_WORKTIME_HOST=HOST-EXAMPLE
|
||||
ExecStart=/usr/local/bin/aw-worktime-ui-bridge-rust
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
[Unit]
|
||||
Description=Run AW Worktime UI bridge every 30 seconds
|
||||
Description=Run AW Worktime UI bridge every 5 minutes
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:0/1:15
|
||||
AccuracySec=10s
|
||||
OnCalendar=*:0/5:15
|
||||
AccuracySec=15s
|
||||
Unit=aw-worktime-ui-bridge.service
|
||||
Persistent=false
|
||||
|
||||
|
||||
@@ -105,4 +105,17 @@ Server-side prerequisite for user `awops`:
|
||||
printf '%s\n' 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILoFWQmgoUJj1P7mp1/fB5aBkI3fVgjPme9jmK8Gh9jr igor@snb-live' | sudo tee /var/lib/awops/.ssh/authorized_keys >/dev/null
|
||||
sudo chown awops:awops /var/lib/awops/.ssh/authorized_keys
|
||||
sudo chmod 600 /var/lib/awops/.ssh/authorized_keys
|
||||
sudo chown awops:awops /opt/activitywatch/aw-rus-ops/drop
|
||||
sudo chmod 0750 /opt/activitywatch/aw-rus-ops/drop
|
||||
```
|
||||
|
||||
Production scheduled task on `SHARKON2025`:
|
||||
|
||||
- task name: `ActivityWatch Hayabusa Upload`
|
||||
- action: `C:\ProgramData\AWatch-rus\export-upload-hayabusa-to-aw-server.ps1 -HoursBack 6 -Mode incident`
|
||||
- principal: `Администратор`, `LogonType=Interactive`, `RunLevel=Highest`
|
||||
- normal `LastTaskResult`: `0`
|
||||
|
||||
Do not switch this task back to `SYSTEM` on the current RDP host: Task Scheduler starts `powershell.exe` under `SYSTEM`, but the process exits with `0xC0000142` before the upload script starts.
|
||||
|
||||
Server-side processing accepts Windows zip packages with backslash path separators and UTF-8 BOM in sidecar JSON. `aw-hayabusa-autoprocess` processes the full incoming queue after accepting a drop package, so stale incoming files from an earlier failed run are drained before the latest intake is recorded.
|
||||
|
||||
@@ -113,19 +113,36 @@ detect_host_from_manifest() {
|
||||
extract_zip_normalized() {
|
||||
local package_path="$1"
|
||||
local dest_dir="$2"
|
||||
command -v zipinfo >/dev/null 2>&1 || fail "zipinfo is required to inspect ${package_path}"
|
||||
command -v unzip >/dev/null 2>&1 || fail "unzip is required to extract ${package_path}"
|
||||
command -v python3 >/dev/null 2>&1 || fail "python3 is required to extract ${package_path}"
|
||||
mkdir -p "${dest_dir}"
|
||||
local entry normalized
|
||||
while IFS= read -r entry; do
|
||||
normalized="${entry//\\//}"
|
||||
case "${normalized}" in
|
||||
""|.|/*|*"/../"*|../*|*"..")
|
||||
fail "unsafe zip entry: ${entry}"
|
||||
;;
|
||||
esac
|
||||
done < <(zipinfo -1 "${package_path}")
|
||||
unzip -q "${package_path}" -d "${dest_dir}"
|
||||
python3 - "${package_path}" "${dest_dir}" <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
package_path = sys.argv[1]
|
||||
dest_dir = os.path.abspath(sys.argv[2])
|
||||
|
||||
with zipfile.ZipFile(package_path) as archive:
|
||||
for info in archive.infolist():
|
||||
name = info.filename.replace("\\", "/")
|
||||
is_dir = info.is_dir() or name.endswith("/")
|
||||
if is_dir:
|
||||
name = name.rstrip("/")
|
||||
parts = [part for part in name.split("/") if part]
|
||||
if not parts or name.startswith("/") or any(part in (".", "..") for part in parts):
|
||||
raise SystemExit(f"unsafe zip entry: {info.filename}")
|
||||
target_path = os.path.abspath(os.path.join(dest_dir, *parts))
|
||||
if os.path.commonpath([dest_dir, target_path]) != dest_dir:
|
||||
raise SystemExit(f"unsafe zip entry: {info.filename}")
|
||||
if is_dir:
|
||||
os.makedirs(target_path, exist_ok=True)
|
||||
continue
|
||||
os.makedirs(os.path.dirname(target_path), exist_ok=True)
|
||||
with archive.open(info) as src, open(target_path, "wb") as dst:
|
||||
shutil.copyfileobj(src, dst)
|
||||
PY
|
||||
}
|
||||
|
||||
write_package_manifest() {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user