commit full of PRs
PRs full of commit basically i used the ENTIRE mimo grant to convert a system to another. hope this one is good. may fail.
This commit is contained in:
+1
-1
@@ -18,7 +18,7 @@ tw = "t --target=x86_64-pc-windows-msvc"
|
||||
|
||||
|
||||
check-all = "check --workspace --all-features --all-targets"
|
||||
clippy-all = "clippy --workspace --all-features --all-targets"
|
||||
clippy-all = "clippy --workspace --all-targets --all-features" # -- -D warnings
|
||||
test-all = "test --workspace --all-features --all-targets"
|
||||
fmt-all = "fmt --all"
|
||||
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
# Wakey Checkpoint (2026-04-11)
|
||||
|
||||
## Snapshot
|
||||
|
||||
This checkpoint captures the current state after control-plane migration, logging hardening, config ergonomics, and state storage upgrades.
|
||||
|
||||
## What Is Done
|
||||
|
||||
- Legacy router-hosted HTTP/static layer removed from `wakey` crate.
|
||||
- New `wakey-control-plane` crate is active for:
|
||||
- enroll-token issuance
|
||||
- agent enrollment
|
||||
- connected-agent websocket registry
|
||||
- command relay to agent
|
||||
- `wakey-agent` is active for outbound websocket execution and local command dispatch.
|
||||
|
||||
## Logging + Telemetry
|
||||
|
||||
- High-signal logs were added across:
|
||||
- control-plane API relay path
|
||||
- control-plane websocket lifecycle
|
||||
- control-plane state lifecycle
|
||||
- agent command lifecycle, session lifecycle, and enrollment
|
||||
- Correlated relay spans include command context (`agent_id`, `request_id`, `command`).
|
||||
- Control-plane telemetry is config-driven:
|
||||
- optional OTLP endpoint
|
||||
- optional JSON logs
|
||||
- fallback local logs when OTLP endpoint is not set
|
||||
|
||||
## Config Ergonomics
|
||||
|
||||
### Control-plane
|
||||
|
||||
- Config file support is wired (`/etc/wakey-control-plane/config.toml` by default).
|
||||
- `serve` can read defaults from config file and CLI can override.
|
||||
- New `init-config` command scaffolds a control-plane config file.
|
||||
|
||||
### Agent
|
||||
|
||||
- Existing `init-config` command scaffolds agent config.
|
||||
- Enrollment can optionally signal reload of running daemon.
|
||||
|
||||
## State Storage Upgrade
|
||||
|
||||
- Control-plane state backend moved from JSON snapshot to embedded `sled` DB.
|
||||
- Default state path changed to `/var/lib/wakey-control-plane/state.db`.
|
||||
- Legacy JSON migration support has been removed; sled is now the only supported
|
||||
state format.
|
||||
- Enroll tokens include persisted expiry timestamps and are validated on enroll.
|
||||
- Periodic and explicit garbage collection remove expired tokens.
|
||||
|
||||
## Operator Commands
|
||||
|
||||
### Control-plane bootstrap
|
||||
|
||||
```sh
|
||||
wakey-control-plane init-config
|
||||
wakey-control-plane serve --config-file /etc/wakey-control-plane/config.toml
|
||||
```
|
||||
|
||||
### Issue enroll token (live daemon path)
|
||||
|
||||
```sh
|
||||
wakey-control-plane issue-enroll-token --public-url https://cp.example.com
|
||||
```
|
||||
|
||||
### Agent bootstrap
|
||||
|
||||
```sh
|
||||
wakey-agent enroll --server-url https://cp.example.com --enroll-token <token>
|
||||
wakey-agent serve --config /etc/wakey-agent/config.toml
|
||||
```
|
||||
|
||||
## Build Health
|
||||
|
||||
- Last verified passing:
|
||||
- `cargo check --workspace`
|
||||
- `cargo clippy --workspace`
|
||||
|
||||
## Test Coverage Added In This Pass
|
||||
|
||||
- Unit tests in `wakey-control-plane/src/state/store.rs` now cover:
|
||||
- expired-token garbage collection removes persisted stale tokens
|
||||
- enroll rejects expired tokens and consumes stale entries
|
||||
- state stats counters for agents and expired token totals
|
||||
|
||||
## Known Tradeoffs / Follow-ups
|
||||
|
||||
- Reload semantics with `sled` are now mostly no-op for in-memory state (data is durable in DB).
|
||||
- No dedicated state-inspection CLI command yet (suggestion: add `state-stats` command).
|
||||
- OTLP configuration is currently control-plane focused; agent parity can be added if needed.
|
||||
|
||||
## Suggested Next Steps
|
||||
|
||||
1. Add a control-plane `state-stats` command to print DB path, agent count, token count.
|
||||
2. Add symmetric telemetry config support in `wakey-agent` config file.
|
||||
3. Add integration tests for:
|
||||
- enroll + relay over websocket
|
||||
- legacy JSON-to-sled migration path
|
||||
- init-config command behavior and overrides
|
||||
@@ -1,82 +0,0 @@
|
||||
# Wakey Checkpoint (2026-04-12)
|
||||
|
||||
## Snapshot
|
||||
|
||||
This checkpoint captures progress after adding audit persistence, alert evaluation and transitions, control-plane alert APIs, and websocket timing diagnostics across agent and control-plane.
|
||||
|
||||
## Major Changes Landed
|
||||
|
||||
- Control-plane audit system implemented with persistent sled-backed events.
|
||||
- Audit emission wired into:
|
||||
- enroll accept/reject
|
||||
- token issue/list/revoke
|
||||
- command dispatch/result/error/timeout
|
||||
- websocket auth accept/reject and disconnect
|
||||
- Audit query API added:
|
||||
- `GET /api/v1/control/audit/events`
|
||||
- Active alert engine added with deterministic rules over audit + live session state.
|
||||
- Alert APIs added:
|
||||
- `GET /api/v1/control/alerts`
|
||||
- `GET /api/v1/control/alerts/history`
|
||||
- `GET /api/v1/control/alerts/ws`
|
||||
- Alert transition persistence added (open/resolve transitions tracked across evaluations).
|
||||
- Route classes split explicitly in runtime:
|
||||
- public routes (enroll/ws/health)
|
||||
- control routes (`/api/v1/control/*`)
|
||||
- Caddy template added for edge policy and Cloudflare Access boundary:
|
||||
- `deploy/Caddyfile.control-plane.example`
|
||||
|
||||
## Reliability and Diagnostics Improvements
|
||||
|
||||
- Agent websocket connect diagnostics now include:
|
||||
- DNS resolution timing (`dns_resolve_ms`)
|
||||
- websocket connect timing (`ws_connect_ms`)
|
||||
- Control-plane websocket lifecycle logs include:
|
||||
- connect-to-hello timing
|
||||
- connect-to-auth timing
|
||||
- hello-to-auth timing
|
||||
- Slow connect warnings are now emitted when timing thresholds are exceeded.
|
||||
|
||||
## Root-Cause Findings Captured
|
||||
|
||||
- Long agent websocket connect delays were reproduced and traced to hostname resolution path.
|
||||
- Switching agent `server_url` hostname to direct IP made connect immediate.
|
||||
- This confirms app-level relay logic was not the source of the startup delay.
|
||||
|
||||
## Verification Status
|
||||
|
||||
- `cargo check --workspace` passing after all changes.
|
||||
- Added and passing tests include:
|
||||
- audit event append/filter in state store
|
||||
- alert transition open/resolve persistence
|
||||
- alert evaluator rule checks (offline + timeout, auth/enroll rejection spikes)
|
||||
|
||||
## Current API Surface for UI Start
|
||||
|
||||
- Agents and command execution:
|
||||
- `GET /api/v1/control/agents`
|
||||
- `POST /api/v1/control/agents/{agent_id}/command`
|
||||
- Audits:
|
||||
- `GET /api/v1/control/audit/events`
|
||||
- Alerts:
|
||||
- `GET /api/v1/control/alerts`
|
||||
- `GET /api/v1/control/alerts/history`
|
||||
- websocket subscribe: `GET /api/v1/control/alerts/ws`
|
||||
|
||||
## Remaining Plan Items (Most Significant)
|
||||
|
||||
1. UI implementation (`/ui` app shell and pages) is still open.
|
||||
2. Alert dedupe/cooldown persistence and tuning are still basic and need hardening.
|
||||
3. Audit retention pruning policy and long-run storage controls are not finalized.
|
||||
4. Edge auth enforcement tests and deployment rehearsals remain to be added.
|
||||
5. Multi-day soak drills and failure-injection validation remain open.
|
||||
|
||||
## Suggested Next Actions
|
||||
|
||||
1. Build minimal UI shell with three views:
|
||||
- agents/commands
|
||||
- audit timeline
|
||||
- alerts panel (active + history + websocket stream)
|
||||
2. Add periodic retention task for audit and alert transition trees.
|
||||
3. Add proxy-level integration tests that assert private endpoints are blocked without Access headers.
|
||||
4. Run a 48-72h soak with hostname vs IP connect-path metrics collected.
|
||||
@@ -1,14 +0,0 @@
|
||||
# Control Plane Review
|
||||
|
||||
## Findings
|
||||
|
||||
1. High: the admin/control API is effectively unauthenticated, so anyone who can reach the server can issue enroll tokens, list/revoke tokens, inspect audit/alerts, and send live commands to agents. In [`wakey-control-plane/src/runtime/mod.rs:61`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/runtime/mod.rs#L61) through [`wakey-control-plane/src/runtime/mod.rs:109`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/runtime/mod.rs#L109), `control_api_routes()` is merged straight into the app with no auth middleware despite the comment saying these routes are “admin-only.” The UI also calls those endpoints directly with plain `fetch` and no auth material in [`ui/src/api.ts:60`](c:/Users/Admin/Documents/realshit/wakey/ui/src/api.ts#L60) through [`ui/src/api.ts:123`](c:/Users/Admin/Documents/realshit/wakey/ui/src/api.ts#L123). This is a full remote-takeover issue for the control plane, not just a missing polish item.
|
||||
|
||||
2. High: a second websocket connection for the same `agent_id` silently replaces the current session, but the old authenticated socket is left alive and can still submit `result`/`error` frames against pending requests. In [`wakey-control-plane/src/ws.rs:195`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/ws.rs#L195) through [`wakey-control-plane/src/ws.rs:200`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/ws.rs#L200), a successful auth simply overwrites `sessions[agent_id] = tx.clone()`. The previous socket is not closed or demoted. Later, any authenticated socket can satisfy pending requests in [`wakey-control-plane/src/ws.rs:229`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/ws.rs#L229) through [`wakey-control-plane/src/ws.rs:247`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/ws.rs#L247), while requests are correlated only by `request_id` created in [`wakey-control-plane/src/api/commands.rs:91`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/api/commands.rs#L91) through [`wakey-control-plane/src/api/commands.rs:97`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/api/commands.rs#L97). That creates a split-brain/race condition where a stale or malicious prior session for the same agent can inject or win replies.
|
||||
|
||||
3. Medium: configured seed enroll tokens are reinserted into the database on every startup, so “one-time” tokens become reusable after a restart if they remain in config. In [`wakey-control-plane/src/state/store.rs:52`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/state/store.rs#L52) through [`wakey-control-plane/src/state/store.rs:68`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/state/store.rs#L68), `load_or_init()` blindly seeds `daemon.enroll_tokens` into sled every time the process starts. Enrollment consumes tokens in [`wakey-control-plane/src/state/store.rs:91`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/state/store.rs#L91) through [`wakey-control-plane/src/state/store.rs:109`](c:/Users/Admin/Documents/realshit/wakey/wakey-control-plane/src/state/store.rs#L109), but that consumption is undone on the next boot if the token still exists in config. That breaks the “short-lived/one-time” assumption and makes operational mistakes much more likely.
|
||||
|
||||
## Residual Risks
|
||||
|
||||
- The control-plane/UI surface is growing quickly and currently assumes a trusted environment in multiple places. Even after adding admin auth, I would expect more authz/session-boundary issues to surface.
|
||||
- The command relay path is conceptually good, but it needs stronger session ownership rules before it is trustworthy under reconnect races or duplicated agents.
|
||||
@@ -1,57 +0,0 @@
|
||||
## Plan: Audit, Alerts, UI, and Safe Edge Exposure
|
||||
|
||||
Recommended approach: ship in this order audit first, alerts second, UI third, then edge hardening and soak. This gives you observability truth before you build subscriptions and screens, and keeps risky control APIs private behind Cloudflare Access at Caddy.
|
||||
|
||||
**Steps**
|
||||
1. Phase A: Lock trust boundaries and endpoint classes.
|
||||
2. Public Agent API stays exposed: /api/v1/agents/enroll, /api/v1/agent/ws, /healthz.
|
||||
3. Private Control API stays protected: /api/v1/control/* and /ui/*.
|
||||
4. Phase A: Define AuditEvent schema and retention defaults.
|
||||
5. Phase B: Add audit persistence in sled and emit at key points.
|
||||
6. Emit audit on token issue/list/revoke, ws auth/disconnect, command dispatch/result/timeout/error, and reload/config operations.
|
||||
7. Phase B: Add audit query API with filters and pagination.
|
||||
8. Phase C: Implement deterministic alert rules and evaluator loop.
|
||||
9. Start with offline agent threshold, timeout-rate threshold, auth-failure spike, token misuse attempts.
|
||||
10. Add dedupe and cooldown so alerts do not flap.
|
||||
11. Phase C: Add alert delivery APIs.
|
||||
12. Poll-first endpoint for active alerts and recent transitions, websocket stream optional after rules stabilize.
|
||||
13. Phase D: Build same-domain UI app shell at /ui with origin-relative API client.
|
||||
14. Phase D: Build pages: Agent Health, Command Runner, Audit Timeline, Alerts Panel.
|
||||
15. Phase E: Add Caddy deployment template with Cloudflare Access policy boundaries and websocket support.
|
||||
16. Phase E: Run end-to-end drills and 48-72h soak.
|
||||
|
||||
**Relevant files**
|
||||
- [wakey-control-plane/src/runtime/mod.rs](wakey-control-plane/src/runtime/mod.rs)
|
||||
- [wakey-control-plane/src/api/commands.rs](wakey-control-plane/src/api/commands.rs)
|
||||
- [wakey-control-plane/src/api/control.rs](wakey-control-plane/src/api/control.rs)
|
||||
- [wakey-control-plane/src/ws.rs](wakey-control-plane/src/ws.rs)
|
||||
- [wakey-control-plane/src/state/store.rs](wakey-control-plane/src/state/store.rs)
|
||||
- [wakey-control-plane/src/state/types.rs](wakey-control-plane/src/state/types.rs)
|
||||
- [wakey-control-plane/src/config/types.rs](wakey-control-plane/src/config/types.rs)
|
||||
- [wakey-control-plane/src/config/resolve.rs](wakey-control-plane/src/config/resolve.rs)
|
||||
- [wakey-control-plane/src/cli.rs](wakey-control-plane/src/cli.rs)
|
||||
- [README.md](README.md)
|
||||
- [scripts/init/openwrt/wakey](scripts/init/openwrt/wakey)
|
||||
- [.github/plan-controlPlaneAppV1.prompt.md](.github/plan-controlPlaneAppV1.prompt.md)
|
||||
|
||||
**Verification**
|
||||
1. Unit tests for audit append/query, pagination, retention pruning.
|
||||
2. Unit tests for alert rule evaluation, dedupe, cooldown.
|
||||
3. Contract tests for request_id correlation across command result and timeout/error audit records.
|
||||
4. Integration tests for ws auth/disconnect audit events and command timeout event emission.
|
||||
5. API tests for audit and alert endpoints.
|
||||
6. Edge security tests that unauthenticated /api/v1/control/* and /ui/* are denied.
|
||||
7. Soak tests for reconnect churn and audit growth stability.
|
||||
|
||||
**Decisions captured**
|
||||
- Admin auth default: Cloudflare Access only, enforced at Caddy.
|
||||
- UI host: same domain path deployment.
|
||||
- Shell bridge: excluded from v1 due high risk and low break-glass value during hard router failures.
|
||||
- Alert delivery: poll-first in v1, websocket stream optional.
|
||||
|
||||
**Caddy policy shape for this plan**
|
||||
1. Route /api/v1/agents/enroll and /api/v1/agent/ws to control-plane upstream without Cloudflare Access gate.
|
||||
2. Route /api/v1/control/* and /ui/* only when Cloudflare Access authentication is valid.
|
||||
3. Preserve websocket upgrade headers on /api/v1/agent/ws.
|
||||
4. Keep control-plane process bound to private interface or localhost behind Caddy.
|
||||
5. Deny direct exposure of /api/v1/control/* from origin network paths.
|
||||
@@ -1,32 +0,0 @@
|
||||
## Plan: Control Plane App v1
|
||||
|
||||
Build an end-to-end, ops-ready v1 over 6+ weeks by reusing current wakey and wakey-core logic, keeping wakey-agent as outbound executor, and adding a dedicated control-plane server plus minimal operator UI.
|
||||
|
||||
**Steps**
|
||||
1. Phase 1, contract baseline: finalize relay contract for command, result, error, request correlation, timeout, retry, and forward compatibility behavior.
|
||||
2. Phase 1, boundary lock: keep execution in wakey service functions and keep domain DTOs in wakey-core while removing legacy HTTP/static compatibility code.
|
||||
3. Phase 2, server skeleton: implement enrollment endpoint, agent registry, websocket acceptor, and request correlation map. Depends on step 1 and step 2.
|
||||
4. Phase 2, relay core: implement command submission to connected agents, request_id correlation, timeout paths, and structured relay errors. Depends on step 3.
|
||||
5. Phase 2, persistence and identity: durable agent records, enroll token lifecycle, and safe credential metadata. Parallel with step 4 after schema is stable.
|
||||
6. Phase 3, operator surface: add API for agent inventory, health, command execution, and recent outcomes; add minimal UI for core operations. Depends on step 4 and step 5.
|
||||
7. Phase 3, ops hardening: metrics, logs, audits, heartbeat liveness checks, and alert thresholds. Parallel with step 6.
|
||||
8. Phase 4, deployment pipeline: add server build and deploy artifacts, environment templates, and rollback workflow. Depends on step 6 and step 7.
|
||||
9. Phase 4, validation and soak: run enrollment-to-command end-to-end tests and disconnect/failure drills with multi-day soak. Depends on step 8.
|
||||
|
||||
**Relevant files to reuse**
|
||||
- [wakey-agent/src/protocol.rs](wakey-agent/src/protocol.rs)
|
||||
- [wakey-agent/src/session.rs](wakey-agent/src/session.rs)
|
||||
- [wakey-agent/src/dispatch.rs](wakey-agent/src/dispatch.rs)
|
||||
- [src/service/mod.rs](src/service/mod.rs)
|
||||
- [wakey-core/src/model](wakey-core/src/model)
|
||||
- [scripts/package_rootfs.ps1](scripts/package_rootfs.ps1)
|
||||
- [.gitea/workflows/release.yml](.gitea/workflows/release.yml)
|
||||
|
||||
**Verification**
|
||||
1. Contract tests for command and result serialization, request_id stability, and unknown frame tolerance.
|
||||
2. Relay integration tests for enrollment, websocket auth flow, correlation, and timeout handling.
|
||||
3. Security tests for token lifecycle and invalid credential rejection.
|
||||
4. API tests for registry and command execution behavior.
|
||||
5. Observability tests for heartbeat, reconnect counters, latency, and failure alerts.
|
||||
6. Deployment tests for build, release, rollback rehearsal, and staging smoke checks.
|
||||
7. On-device tests for enroll, procd lifecycle, reconnect, and remote command round trips.
|
||||
@@ -1,184 +0,0 @@
|
||||
# Plan: Observation Store And Sync V1
|
||||
|
||||
## Summary
|
||||
|
||||
Build device observation support in layers:
|
||||
|
||||
1. Local router observations are captured by `wakey observe ...` from OpenWrt hotplug.
|
||||
2. `wakey-linux` stores current observed DHCP/neigh state locally.
|
||||
3. `wakey-agent` forwards compact observations to the control plane.
|
||||
4. The control plane stores observations per agent and later joins them to known devices through `device_identifiers`.
|
||||
|
||||
This is separate from durable identity. Observations are facts an agent saw at a time; known devices are manual/user-approved identity records.
|
||||
|
||||
## Network/API Boundary
|
||||
|
||||
The control plane has two route classes:
|
||||
|
||||
- Public agent routes: intended to be reachable by agents.
|
||||
- Protected control routes: intended to sit behind Cloudflare Access/admin auth.
|
||||
|
||||
Observation upload belongs on the public agent route surface because routers/agents must call it:
|
||||
|
||||
```text
|
||||
POST /api/v1/agents/observations
|
||||
```
|
||||
|
||||
The endpoint must require normal agent authentication, using the same persistent `agent_id`/`agent_token` trust model as WebSocket auth. It must not be a Cloudflare Access-only admin endpoint.
|
||||
|
||||
Admin/UI read APIs belong under protected control routes:
|
||||
|
||||
```text
|
||||
GET /api/v1/control/observations
|
||||
GET /api/v1/control/devices
|
||||
```
|
||||
|
||||
## Step 1: Local Observation Store
|
||||
|
||||
Replace the narrow `/tmp/wakey_mac_names.json` cache with a local observation store owned by `wakey-linux`.
|
||||
|
||||
Minimum local tables/state:
|
||||
|
||||
```text
|
||||
observed_dhcp_clients:
|
||||
mac
|
||||
ip
|
||||
hostname
|
||||
first_seen_unix
|
||||
last_seen_unix
|
||||
last_action
|
||||
|
||||
observed_neighbors:
|
||||
key
|
||||
mac
|
||||
ip
|
||||
first_seen_unix
|
||||
last_seen_unix
|
||||
last_action
|
||||
```
|
||||
|
||||
Behavior:
|
||||
|
||||
- Hotplug scripts stay minimal and call `wakey-agent observe ...`.
|
||||
- `wakey-agent observe ...` delegates to `wakey observe ...`.
|
||||
- `wakey observe dhcp ...` writes DHCP observations.
|
||||
- `wakey observe neigh ...` writes neighbor observations.
|
||||
- Existing `wakey leases` and `wakey inventory` still read live sources first, then enrich from the local observation store.
|
||||
- Do not make local queries depend exclusively on hotplug events yet.
|
||||
|
||||
## Step 2: Control-Plane Observation Tables
|
||||
|
||||
Add observation tables early so future API/UI work does not need another major state refactor.
|
||||
|
||||
Control-plane schema:
|
||||
|
||||
```text
|
||||
agent_device_observations:
|
||||
observation_key TEXT PRIMARY KEY
|
||||
agent_id TEXT NOT NULL
|
||||
kind TEXT NOT NULL
|
||||
mac TEXT
|
||||
ip TEXT
|
||||
hostname TEXT
|
||||
first_seen_unix INTEGER NOT NULL
|
||||
last_seen_unix INTEGER NOT NULL
|
||||
last_action TEXT NOT NULL
|
||||
|
||||
agent_device_observation_events:
|
||||
event_id TEXT PRIMARY KEY
|
||||
agent_id TEXT NOT NULL
|
||||
kind TEXT NOT NULL
|
||||
action TEXT NOT NULL
|
||||
mac TEXT
|
||||
ip TEXT
|
||||
hostname TEXT
|
||||
ts_unix INTEGER NOT NULL
|
||||
```
|
||||
|
||||
Keep `agent_device_observation_events` optional in behavior if needed, but create it in schema early. Current-state rows are the primary path; event history is for debugging/audit.
|
||||
|
||||
Indexes:
|
||||
|
||||
```text
|
||||
agent_device_observations(agent_id)
|
||||
agent_device_observations(mac)
|
||||
agent_device_observations(ip)
|
||||
agent_device_observations(hostname)
|
||||
agent_device_observations(last_seen_unix)
|
||||
agent_device_observation_events(agent_id, ts_unix)
|
||||
agent_device_observation_events(mac)
|
||||
```
|
||||
|
||||
## Step 3: Agent Upload
|
||||
|
||||
Add agent upload payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"observations": [
|
||||
{
|
||||
"kind": "dhcp",
|
||||
"action": "update",
|
||||
"mac": "04:7c:16:79:6d:ee",
|
||||
"ip": "192.168.100.94",
|
||||
"hostname": "lda",
|
||||
"first_seen_unix": 1770000000,
|
||||
"last_seen_unix": 1770000123
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Agent may send snapshots periodically and after local observe events.
|
||||
- Control plane upserts current-state rows by stable observation key.
|
||||
- Observation keys should be deterministic from `agent_id`, `kind`, and the best available identifier:
|
||||
- DHCP with MAC: `agent:{agent_id}:dhcp:mac:{mac}`
|
||||
- Neigh with MAC: `agent:{agent_id}:neigh:mac:{mac}`
|
||||
- Neigh without MAC: `agent:{agent_id}:neigh:ip:{ip}`
|
||||
- Uploads must not create known devices automatically.
|
||||
|
||||
## Step 4: Join Observations To Known Devices
|
||||
|
||||
Known devices already have durable IDs and manual identifiers:
|
||||
|
||||
```text
|
||||
known_devices
|
||||
device_identifiers
|
||||
```
|
||||
|
||||
Join rule:
|
||||
|
||||
```text
|
||||
agent_device_observations.mac
|
||||
-> device_identifiers(kind = 'mac', value = mac)
|
||||
-> known_devices.device_id
|
||||
```
|
||||
|
||||
Unknown observations are rows that do not match any manual `device_identifiers` row.
|
||||
|
||||
This enables:
|
||||
|
||||
- same known device observed by multiple agents;
|
||||
- same known device with multiple MACs;
|
||||
- UI flow to attach an unknown observed MAC to an existing known device;
|
||||
- wake flows that choose agent-local observed IP/MAC context for a known device.
|
||||
|
||||
## Step 5: UI/API Later
|
||||
|
||||
After storage and upload exist:
|
||||
|
||||
- show known devices with all matching observations grouped by agent;
|
||||
- show unknown observations;
|
||||
- add action: attach observation identifier to known device;
|
||||
- add action: create known device from observation;
|
||||
- add wake action from known device using a selected agent/observation.
|
||||
|
||||
## Defaults
|
||||
|
||||
- `wakey` remains the local router/debugging CLI.
|
||||
- `wakey-agent` is the sync bridge to the control plane.
|
||||
- `wakey-control-plane` is durable identity and multi-agent view.
|
||||
- Local observation store is not authoritative; live sources still matter.
|
||||
- Control-plane observations are not durable identity; only manual known-device identifiers are.
|
||||
@@ -1,149 +0,0 @@
|
||||
## Plan: wakey UI v1 (Device-First)
|
||||
|
||||
The Operator UI is not the end goal by itself.
|
||||
The goal is to make wakey excellent at its original purpose: quickly finding devices and waking them reliably.
|
||||
|
||||
Agent, audit, and token features remain important, but they should support the device workflow rather than dominate the navigation and development effort.
|
||||
|
||||
## Product North Star
|
||||
|
||||
An operator should be able to do this in under 10 seconds:
|
||||
1. Open the UI.
|
||||
2. Search for a device by name, IP, or MAC.
|
||||
3. See whether it looks online/reachable.
|
||||
4. Trigger wake.
|
||||
5. See immediate command result and short follow-up status.
|
||||
|
||||
## Scope Priorities
|
||||
|
||||
1. P0: Device discovery and wake UX.
|
||||
2. P1: Fast troubleshooting context around wake results.
|
||||
3. P2: Fleet/agent/admin operations.
|
||||
|
||||
This explicitly means pages and components for Agent, Audit, Alerts, and Tokens should be present but secondary in visual hierarchy and effort until P0 is complete.
|
||||
|
||||
## IA Direction (v1)
|
||||
|
||||
Primary top-level focus:
|
||||
1. Devices
|
||||
2. Wake Queue (or Recent Actions)
|
||||
|
||||
Secondary top-level focus:
|
||||
1. Fleet Health
|
||||
2. Audit
|
||||
3. Alerts
|
||||
4. Access/Tokens
|
||||
|
||||
If needed, keep current routes during transition, but adjust default landing and navigation emphasis so Devices is the home workflow.
|
||||
|
||||
## Phase Plan
|
||||
|
||||
### Phase 1: Device-Centric Foundation
|
||||
|
||||
1. Add a dedicated Devices page that merges existing status/leases/inventory signal into one operator list.
|
||||
2. Include searchable columns for name, IP, MAC, interface/dev, and recency indicators.
|
||||
3. Provide row-level wake action and bulk-safe interaction model (single-click row action, confirm for bulk).
|
||||
4. Define a compact "device confidence" heuristic from available data (for example: recent lease + reachable neighbor).
|
||||
5. Set the default route to Devices, with prominent search and wake controls above the fold.
|
||||
|
||||
Acceptance criteria:
|
||||
1. Search by hostname, IP, and MAC all work from one input.
|
||||
2. Wake action reachable in one click from list row.
|
||||
3. Response feedback shown immediately with clear success/error text.
|
||||
|
||||
### Phase 2: Wake Execution UX
|
||||
|
||||
1. Build a focused wake panel with explicit target preview before send.
|
||||
2. Provide quick presets: "wake by selected device", "wake by MAC", "wake by query".
|
||||
3. Persist recent wake targets locally for operator speed.
|
||||
4. Add post-wake verification loop (short timed refresh of status indicators).
|
||||
5. Surface request correlation id and a copy action for incident sharing.
|
||||
|
||||
Acceptance criteria:
|
||||
1. Operator can retry wake with one click.
|
||||
2. Operator can see last 20 wake attempts with outcome and timestamp.
|
||||
3. Error states differentiate validation, timeout, and execution failure.
|
||||
|
||||
### Phase 3: Context Without Workflow Drift
|
||||
|
||||
1. Keep Alerts and Audit accessible from device rows and wake outcomes.
|
||||
2. Add contextual deep links: device -> related alerts, device -> recent audit events.
|
||||
3. Improve filtering for alerts/audit with saved local filter presets.
|
||||
4. Add gentle live updates, keeping websocket optional with polling fallback.
|
||||
|
||||
Acceptance criteria:
|
||||
1. From any failed wake, operator can jump to relevant audit entries in one step.
|
||||
2. Alerts page can be filtered by kind/severity/agent and linked back to impacted devices.
|
||||
|
||||
### Phase 4: Fleet/Admin Hardening
|
||||
|
||||
1. Keep Agents page for connectivity and control routing visibility.
|
||||
2. Keep Tokens page for enrollment lifecycle operations.
|
||||
3. Keep Dashboard but reframe metrics around "device availability" and "wake success" first.
|
||||
4. Add audit-friendly confirmation flows for destructive actions.
|
||||
|
||||
Acceptance criteria:
|
||||
1. Admin flows do not block or slow P0 device workflows.
|
||||
2. All admin actions produce clear audit-visible outcomes.
|
||||
|
||||
### Phase 5: Validation and Production Readiness
|
||||
|
||||
1. Add smoke tests for P0 flow: find device -> wake -> observe result.
|
||||
2. Add contract checks for command payload/response shapes used by device and wake screens.
|
||||
3. Add scenario drills (offline agent, delayed command, websocket drop, expired token).
|
||||
4. Verify edge policy still protects control routes while preserving required public endpoints.
|
||||
|
||||
Acceptance criteria:
|
||||
1. P0 flow remains usable during partial degradation.
|
||||
2. Build/typecheck/test gates stay green in CI.
|
||||
|
||||
## Concrete UI Backlog (Ordered)
|
||||
|
||||
1. Create DevicesPage with unified searchable table.
|
||||
2. Wire wake action directly from device row.
|
||||
3. Add Recent Wake Actions panel with outcomes.
|
||||
4. Add post-wake short verification refresh.
|
||||
5. Rework Dashboard cards to device-first metrics.
|
||||
6. Add deep links from wake result to audit and alerts context.
|
||||
7. Add empty/loading/error skeleton patterns tuned for device list scale.
|
||||
|
||||
## Metrics of Success
|
||||
|
||||
1. Time-to-wake median under 10 seconds for known target.
|
||||
2. Wake success rate visible per time window.
|
||||
3. Fewer operator clicks for common tasks (device lookup + wake).
|
||||
4. Reduced navigation to agent-centric pages for everyday usage.
|
||||
|
||||
## Design and Interaction Principles
|
||||
|
||||
1. Device-first information density over generic admin dashboards.
|
||||
2. Search and action bar always visible on desktop and mobile.
|
||||
3. Action feedback must be immediate and explicit.
|
||||
4. Keep advanced infrastructure details available but visually de-emphasized.
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
1. Keep same-domain /ui serving and origin-relative API requests.
|
||||
2. Keep route and API contracts stable while iterating UX aggressively.
|
||||
3. Treat websocket as progressive enhancement; polling fallback required.
|
||||
4. Preserve Cloudflare Access boundary for all control endpoints.
|
||||
|
||||
## Relevant Files
|
||||
|
||||
1. [ui/src/App.tsx](ui/src/App.tsx)
|
||||
2. [ui/src/pages/CommandsPage.tsx](ui/src/pages/CommandsPage.tsx)
|
||||
3. [ui/src/pages/DashboardPage.tsx](ui/src/pages/DashboardPage.tsx)
|
||||
4. [ui/src/api.ts](ui/src/api.ts)
|
||||
5. [wakey-control-plane/src/api/commands.rs](wakey-control-plane/src/api/commands.rs)
|
||||
6. [wakey-control-plane/src/api/audit.rs](wakey-control-plane/src/api/audit.rs)
|
||||
7. [wakey-control-plane/src/api/alerts.rs](wakey-control-plane/src/api/alerts.rs)
|
||||
8. [wakey-control-plane/src/api/control.rs](wakey-control-plane/src/api/control.rs)
|
||||
9. [wakey-control-plane/src/runtime/mod.rs](wakey-control-plane/src/runtime/mod.rs)
|
||||
10. [README.md](README.md)
|
||||
|
||||
## Immediate Next Build Slice
|
||||
|
||||
1. Implement DevicesPage and make it default route.
|
||||
2. Add row-level wake action with in-place result feedback.
|
||||
3. Add Recent Wake Actions section backed by local state first, then audit correlation.
|
||||
4. Rebalance navigation labels/order to make device workflows primary.
|
||||
@@ -1,69 +0,0 @@
|
||||
# Plan: SQLx Query Macro Adoption
|
||||
|
||||
## Summary
|
||||
|
||||
Move control-plane SQL from unchecked `sqlx::query(...)` calls toward `sqlx::query!` / `query_as!` where the SQL shape is static.
|
||||
|
||||
This gives compile-time checking for table/column names and Rust value types. Dynamic filter builders can stay on `QueryBuilder`.
|
||||
|
||||
## Offline Setup
|
||||
|
||||
Normal builds should not need a live database:
|
||||
|
||||
```text
|
||||
SQLX_OFFLINE=true
|
||||
```
|
||||
|
||||
`.env` is ignored, so copy:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
SQLx query metadata should be generated into `.sqlx/` and committed.
|
||||
|
||||
Prepare metadata with:
|
||||
|
||||
```sh
|
||||
cargo install sqlx-cli --no-default-features --features sqlite
|
||||
./scripts/prepare_sqlx_sqlite.sh
|
||||
```
|
||||
|
||||
The script:
|
||||
|
||||
- creates a temporary SQLite database;
|
||||
- runs `wakey-control-plane/migrations`;
|
||||
- runs `cargo sqlx prepare --workspace -- -p wakey-control-plane --all-targets --all-features`;
|
||||
- writes `.sqlx/`.
|
||||
|
||||
## Conversion Rules
|
||||
|
||||
Use `query!` / `query_as!` for static SQL:
|
||||
|
||||
- inserts;
|
||||
- deletes;
|
||||
- simple selects by primary key;
|
||||
- fixed update statements;
|
||||
- count queries.
|
||||
|
||||
Keep non-macro SQL for genuinely dynamic SQL:
|
||||
|
||||
- audit event filters built with `QueryBuilder`;
|
||||
- observation listing with optional filters, unless split into fixed branches;
|
||||
- any SQL where table/column names are intentionally generated.
|
||||
|
||||
## Test/CI
|
||||
|
||||
After query macros are introduced, CI should add:
|
||||
|
||||
```sh
|
||||
cargo install sqlx-cli --no-default-features --features sqlite
|
||||
./scripts/prepare_sqlx_sqlite.sh
|
||||
cargo sqlx prepare --check --workspace -- --all-targets --all-features
|
||||
```
|
||||
|
||||
Do not add the CI check until the first `.sqlx/` metadata is committed, otherwise it adds dependency install cost without catching anything.
|
||||
|
||||
## Notes
|
||||
|
||||
The SQLx docs say offline mode needs `cargo sqlx prepare` output checked into version control, and that `DATABASE_URL` takes precedence unless `SQLX_OFFLINE=true` is set. Keep `.env` local; commit `.env.example` and `.sqlx/`.
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_device_observation_events\n (event_id, agent_id, kind, action, mac, ip, hostname, ts_unix)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 8
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "06c45563892b3d688153985aec411f588e80b5f17731f1fce97f9494a1155ffb"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", fact_json as \"fact_json!\"\n FROM agent_device_facts",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "fact_json!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "12e443ec0991c042cf527498b567bbbb6d02885f72eb3fa426c9493368f8a9e7"
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observations.observation_key as \"observation_key!\",\n observations.agent_id as \"agent_id!\",\n observations.kind as \"kind!\",\n observations.mac,\n observations.ip,\n observations.hostname,\n observations.first_seen_unix,\n observations.last_seen_unix,\n observations.last_action as \"last_action!\",\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observations observations\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN observations.mac IS NOT NULL THEN 'mac:' || observations.mac\n WHEN observations.ip IS NOT NULL THEN 'ip:' || observations.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE observations.agent_id = ?1\n ORDER BY observations.last_seen_unix DESC\n LIMIT ?2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 11,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "190ea5014566f84255a8655599e03695fb2f5ce9b720700f93d625c1ae2780e6"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO agents (agent_id, agent_token) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "1d4677e5e37a32a8c0f8ab29ec07986142a621c099a62d3c5973f368e664991c"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_device_observations\n WHERE agent_id = ?1\n AND kind = ?2\n AND observation_key NOT IN (\n SELECT observation_key\n FROM agent_observation_snapshot_keys\n WHERE agent_id = ?1 AND kind = ?2\n )",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "273bcf6b604fbb48cad93630a1485590b1039149d1dd856db674dcc5584947d0"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_observation_snapshot_keys WHERE agent_id = ?1 AND kind = ?2",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "29f24b83cf513758b6a546e86be8aa7ce4b1f66d799aabacaeac02ff84996d24"
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observation_key as \"observation_key!\", agent_id as \"agent_id!\",\n kind as \"kind!\", mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action as \"last_action!\"\n FROM agent_device_observations\n WHERE agent_id = ?1\n ORDER BY last_seen_unix DESC\n LIMIT ?2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "305f50ab2691e12c74e8a222ef12a16f14a65edd7b7c5400a196fd57a9788dcf"
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT mac, ip\n FROM agent_device_observations\n WHERE observation_key = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "3b06698566cea17eed9d10a389ee12a95cee2db6c3d450dca7a3b2d08e8fed7b"
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT events.event_id as \"event_id!\",\n ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) as \"observation_key!\",\n events.agent_id as \"agent_id!\",\n events.kind as \"kind!\",\n events.action as \"action!\",\n events.mac,\n events.ip,\n events.hostname,\n events.ts_unix,\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observation_events events\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE (?1 IS NULL OR events.agent_id = ?1)\n AND (?2 IS NULL OR events.kind = ?2)\n AND (?3 IS NULL OR events.mac = ?3)\n AND (?4 IS NULL OR events.ip = ?4)\n AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) = ?5)\n ORDER BY events.ts_unix DESC\n LIMIT ?6",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "event_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "action!",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ts_unix",
|
||||
"ordinal": 8,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 11,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 6
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "3bc141cecd0ba7c9ca937036b310728dff57c69ed7b74529fd81fa6a3c0e40cf"
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observations.observation_key as \"observation_key!\",\n observations.agent_id as \"agent_id!\",\n observations.kind as \"kind!\",\n observations.mac,\n observations.ip,\n observations.hostname,\n observations.first_seen_unix,\n observations.last_seen_unix,\n observations.last_action as \"last_action!\",\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observations observations\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN observations.mac IS NOT NULL THEN 'mac:' || observations.mac\n WHEN observations.ip IS NOT NULL THEN 'ip:' || observations.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n ORDER BY observations.last_seen_unix DESC\n LIMIT ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 11,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "409e1e7aa2d9bc46030001e5c522d7c2812b4583dceadfe5c535a866ac76489c"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", hostname as \"hostname!\"\n FROM agent_device_hostnames\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "4188fb9a0dac2e19fb1f83e023eb1e8d93f6ca896cd78a53668080639fc048d9"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", ip as \"ip!\"\n FROM agent_device_ips",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "4dd5e580826b0f6980bb8c2adecdc81ff95992ec337f93263463c5a4e357dc72"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", mac as \"mac!\"\n FROM agent_device_macs\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "580f6bc100d373137db6f853b8babd7633c700dbfaf17ded507b704fd98e46a5"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", mac as \"mac!\"\n FROM agent_device_macs",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5824c6cb841f7aaeb2a039f846effe17ba8038e35998b674136a19a4d42d8b88"
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observation_key as \"observation_key!\", agent_id as \"agent_id!\",\n kind as \"kind!\", mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action as \"last_action!\"\n FROM agent_device_observations\n ORDER BY last_seen_unix DESC\n LIMIT ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5a0f37b5da194e432c795972d5b3bf67c2d2a00f379143d1ae5871ea790d1bf2"
|
||||
}
|
||||
+13
-13
@@ -1,50 +1,50 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT mac, ip, hostname, first_seen_unix, last_seen_unix,\n last_action as \"last_action!\"\n FROM agent_device_observations\n WHERE observation_key = ?1",
|
||||
"query": "SELECT agent_id, device_key, presence, display_name,\n first_seen_unix, last_seen_unix\n FROM agent_devices\n WHERE agent_id = ?1\n ORDER BY device_key",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "mac",
|
||||
"name": "agent_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"name": "device_key",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"name": "presence",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"name": "display_name",
|
||||
"ordinal": 3,
|
||||
"type_info": "Integer"
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "92775bf2e3b9f772d108bb8d0cd1aebbe01357ed70dc2af7b50ee348e668b319"
|
||||
"hash": "5f7e043ca389f1431c7b3478ea506b0c9bb706d32c06871d1267068dbe9cb746"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO alert_transitions\n (transition_key, transition_id, ts_unix, alert_id, kind, agent_id,\n from_status, to_status, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "69601f4f2268a759f03a2d533a0a30dec5cf05797817fd8d2426714cd84d7ada"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_observation_snapshots\n (agent_id, kind, last_dump_unix)\n VALUES (?1, ?2, ?3)\n ON CONFLICT(agent_id, kind) DO UPDATE SET\n last_dump_unix = excluded.last_dump_unix",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "8e7964dee0a2c21d377923d83df23454a104b68fc08f334c6e576bee273bc73b"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_device_observations\n (observation_key, agent_id, kind, mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)\n ON CONFLICT(observation_key) DO UPDATE SET\n mac = excluded.mac,\n ip = excluded.ip,\n hostname = excluded.hostname,\n first_seen_unix = MIN(agent_device_observations.first_seen_unix, excluded.first_seen_unix),\n last_seen_unix = MAX(agent_device_observations.last_seen_unix, excluded.last_seen_unix),\n last_action = excluded.last_action",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 9
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a47ba9ef887f67a7715bd919871ddd76f4ee09aa6ac0ee2f36d32c27d8a756d4"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO active_alerts\n (alert_id, kind, severity, status, agent_id, message, value, threshold,\n last_seen_unix, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a69a1ea43b1a59254cb29b549b5cd3ebfcab8130941dc2d9a78814bc2072c0d5"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_observation_snapshot_keys (agent_id, kind, observation_key)\n VALUES (?1, ?2, ?3)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "aebbe573b428c0aa5ea79d493868c8d9ba06d7a919d955d4c3b96c5fd4b96598"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO agent_meta (agent_id, nickname) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "b69fb8f030b9745db1d8c9db8225426334b4d1edea5d8a8c9b289c17f194c153"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", ip as \"ip!\"\n FROM agent_device_ips\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "c423e005d85659547302f506380ad217cc31329262a1c0254ef532653b3a37bb"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO audit_events\n (event_key, event_id, ts_unix, actor_type, actor_id, agent_id, request_id,\n event_type, outcome, latency_ms, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 12
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "c496c7a8ada53d6d88ea1a29d9e7bf178fe5f3ee9067357dba05384fa1e2772c"
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id, device_key, presence, display_name,\n first_seen_unix, last_seen_unix\n FROM agent_devices\n ORDER BY agent_id, device_key",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "presence",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 5,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "cd8585b9431d223962c376a2d463f0ca8128e7759c8694631f41db0cbd8eb221"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_device_observations WHERE last_seen_unix < ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "cf1c3bedcc9538d7af97e3e59b705b54dd95e7f219c2a8097187eb386d051e83"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", hostname as \"hostname!\"\n FROM agent_device_hostnames",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "dba637bf03d53bf3394ead0f01466f9a72fafc54f9ce239d2e5ac7f76b63b168"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO alert_transitions\n (transition_key, transition_id, ts_unix, alert_id, kind, agent_id,\n from_status, to_status, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "e508aeb39a57b9defc7cec1bf854669150b8f3a02a7d8312e8fea5951391c1bb"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", fact_json as \"fact_json!\"\n FROM agent_device_facts\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "fact_json!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "e6be4d9782f66f98ebe4d4b6ec6e93ea9efe8e4c7f1147e1ff68d41a311d57f9"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_device_observation_events WHERE ts_unix < ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "edfcbcd3d530f59971e3e1c7c293321440dd9702ba6d6ac264fc9cf3d7cc7b5a"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO active_alerts\n (alert_id, kind, severity, status, agent_id, message, value, threshold,\n last_seen_unix, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "fa09ff199445b7bf689ef4426cbd20d89040230ffff977cc1b4c73b499b1b33f"
|
||||
}
|
||||
Generated
+7
-6
@@ -3677,7 +3677,6 @@ checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9"
|
||||
dependencies = [
|
||||
"getrandom 0.4.2",
|
||||
"js-sys",
|
||||
"serde_core",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -3701,7 +3700,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wakey"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
@@ -3722,7 +3721,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wakey-agent"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -3746,12 +3745,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wakey-control-plane"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"futures-util",
|
||||
"macaddr",
|
||||
"nix 0.31.2",
|
||||
"opentelemetry",
|
||||
"opentelemetry-otlp",
|
||||
@@ -3770,11 +3770,12 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"wakey-agent",
|
||||
"wakey-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wakey-core"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"macaddr",
|
||||
"serde",
|
||||
@@ -3785,7 +3786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wakey-linux"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"futures",
|
||||
|
||||
+17
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "wakey"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
@@ -32,6 +32,22 @@ strip = true
|
||||
[workspace]
|
||||
members = ["ipjs", "wakey-agent", "wakey-control-plane", "wakey-core", "wakey-linux"]
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
macaddr = { version = "1", features = ["serde", "serde_std"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = [
|
||||
"fs",
|
||||
"process",
|
||||
"rt-multi-thread",
|
||||
"io-util",
|
||||
"macros",
|
||||
"time",
|
||||
] }
|
||||
tracing = "0.1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
[dependencies.lda-ipjs]
|
||||
path = "ipjs"
|
||||
registry = "gitea"
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Report: Device State Rewrite
|
||||
|
||||
## What changed
|
||||
|
||||
The control plane now stores **complete per-agent Device snapshots** instead of flat observation rows. The agent sends `Vec<Device>` (merged from DHCP, neighbors, hooks). The control plane upserts per agent, deletes stale, fleet view merges across agents at read time.
|
||||
|
||||
## Architecture (before → after)
|
||||
|
||||
**Before**: Agent → raw hook observations → control plane flattens into rows → re-merges at fleet read → presence recomputed from flat actions
|
||||
|
||||
**After**: Agent → inventory → `Vec<Device>` with correct presence → control plane stores as-is → fleet merge at read time from typed rows
|
||||
|
||||
## Schema
|
||||
|
||||
Old tables dropped: `agent_device_observations`, `agent_device_observation_events`, `agent_observation_snapshots`, `agent_observation_snapshot_keys`
|
||||
|
||||
New tables:
|
||||
- `agent_devices` — per-agent device row (keyed by `DeviceId` serialization)
|
||||
- `agent_device_macs` — MACs per device, indexed for cross-agent merge
|
||||
- `agent_device_ips` — IPs per device, indexed for cross-agent merge
|
||||
- `agent_device_hostnames` — hostnames per device
|
||||
- `agent_device_facts` — debug/source material (JSON, not identity)
|
||||
|
||||
## Concrete types throughout
|
||||
|
||||
- `FleetDevice.macs`: `Vec<MacAddr>`, `ips`: `Vec<IpAddr>`, `presence`: `Presence`
|
||||
- `FleetWakeRoute.mac`: `Option<MacAddr>`, `ip`: `Option<IpAddr>`
|
||||
- `AgentDeviceWithChildren.macs`: `Vec<MacAddr>`, `ips`: `Vec<IpAddr>`
|
||||
- Row types (`AgentDeviceMacRow`, `AgentDeviceIpRow`) stay `String` from SQLite, convert via `TryFrom` impls
|
||||
- `AgentDeviceRow` has `.presence()`, `.first_seen()`, `.last_seen()` methods — no string matching in business code
|
||||
- `Presence` from wakey-core: `Ord`, `PartialOrd`, `From<&str>`, `.as_str()`
|
||||
|
||||
## Rust features used
|
||||
|
||||
- `TryFrom<&AgentDeviceMacRow> for MacAddr`, `TryFrom<&AgentDeviceIpRow> for IpAddr`
|
||||
- `From<&str> for Presence`
|
||||
- `#[allow(dead_code)]` where appropriate (test-only methods, debug fields)
|
||||
- Workspace dependencies for shared crates (`macaddr`, `serde`, `tokio`, etc.)
|
||||
- Shared `TestStore` with `Drop` guard for clean test teardown
|
||||
|
||||
## What was removed
|
||||
|
||||
- `AgentObservation` struct (replaced by `Device`)
|
||||
- `AgentDeviceObservation`, `AgentDeviceObservationView`, `AgentDeviceObservationEvent`, `AgentDeviceObservationInput` types
|
||||
- `inventory_result_to_observations()` — the flatten-then-rebuild function
|
||||
- `upload_agent_observations`, `list_agent_observations`, `list_agent_observation_history` API endpoints
|
||||
- `gc_stale_observations()` — no longer needed
|
||||
- `SyncObservations` CLI command from agent
|
||||
- `prune_removed_observations_from_path` calls from agent session
|
||||
- Observations page from UI
|
||||
|
||||
## What stayed
|
||||
|
||||
- Agent observation store (`/tmp/wakey_observations.json`) — agent-local memory, not forwarded
|
||||
- Hotplug hooks — still update agent-local store, feed next inventory
|
||||
- Known devices + identifiers — manual lifecycle, never auto-deleted
|
||||
- Audit events, alerts — unchanged
|
||||
- `observation_retention` config field — `#[allow(dead_code)]`, kept for config file compat
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
cargo fmt — clean
|
||||
cargo clippy-all — clean (0 warnings)
|
||||
cargo test-all — 89 tests pass, 6 ignored (on-device only)
|
||||
pnpm typecheck — clean
|
||||
```
|
||||
|
||||
## Remaining
|
||||
|
||||
- UI cleanup: remove observations page nav entry, observation API types from `api.ts`
|
||||
- Known device identifier UI controls (API exists, UI needs affordance)
|
||||
- The `observation_retention` config field could be removed in a future cleanup
|
||||
- `list_agent_device_rows_for_agent` is `#[allow(dead_code)]` — used in tests, could be `#[cfg(test)]`
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "wakey-agent"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
|
||||
@@ -32,9 +32,6 @@ pub enum Command {
|
||||
InitConfig(InitConfigArgs),
|
||||
/// Reload a running agent daemon by sending SIGHUP.
|
||||
Reload(ReloadArgs),
|
||||
/// Upload local observations to the control plane once and exit.
|
||||
#[command(visible_alias = "sync")]
|
||||
SyncObservations(SyncObservationsArgs),
|
||||
/// Pass local hotplug observations through to the wakey CLI.
|
||||
Observe(ObserveArgs),
|
||||
}
|
||||
@@ -115,13 +112,6 @@ pub struct ReloadArgs {
|
||||
pub pid_file: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct SyncObservationsArgs {
|
||||
/// Path to the agent config file.
|
||||
#[arg(long, short, default_value = config::DEFAULT_CONFIG_PATH)]
|
||||
pub config: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveArgs {
|
||||
/// Path to the agent config file. If present, local path settings are passed through.
|
||||
|
||||
@@ -101,15 +101,6 @@ async fn main() -> Result<()> {
|
||||
::tracing::info!(pid_file = %args.pid_file.display(), "wakey-agent command: reload");
|
||||
serve::reload_daemon(&args.pid_file)?
|
||||
}
|
||||
Command::SyncObservations(mut args) => {
|
||||
if let Some(config) = global_config {
|
||||
args.config = config.to_path_buf();
|
||||
}
|
||||
::tracing::info!(config = %args.config.display(), "wakey-agent command: sync-observations");
|
||||
let cfg = config::load_config(&args.config)?;
|
||||
let accepted = session::sync_observations_once(&cfg).await?;
|
||||
println!("observations_synced={accepted}");
|
||||
}
|
||||
Command::Observe(mut args) => {
|
||||
if let Some(config) = global_config {
|
||||
args.config = config.to_path_buf();
|
||||
|
||||
+10
-29
@@ -4,8 +4,8 @@ use std::fmt;
|
||||
use std::net::IpAddr;
|
||||
use wakey_core::parse::mac;
|
||||
use wakey_core::{
|
||||
DeviceInventory, DhcpLeaseWithState, InterfaceSummary, InventoryQuery, InventoryQueryBuilder,
|
||||
WakeResult,
|
||||
Device, DeviceInventory, DhcpLeaseWithState, InterfaceSummary, InventoryQuery,
|
||||
InventoryQueryBuilder, WakeResult,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -130,17 +130,6 @@ pub struct WakeRequest {
|
||||
pub ip: Option<IpAddr>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentObservation {
|
||||
pub kind: String,
|
||||
pub action: String,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<IpAddr>,
|
||||
pub hostname: Option<String>,
|
||||
pub first_seen_unix: u64,
|
||||
pub last_seen_unix: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum AgentCommand {
|
||||
@@ -172,9 +161,9 @@ pub enum ClientMessage {
|
||||
Heartbeat {
|
||||
agent_id: String,
|
||||
},
|
||||
Observations {
|
||||
DeviceSnapshot {
|
||||
agent_id: String,
|
||||
observations: Vec<AgentObservation>,
|
||||
devices: Vec<Device>,
|
||||
},
|
||||
Result {
|
||||
request_id: RequestId,
|
||||
@@ -193,7 +182,7 @@ pub enum ServerMessage {
|
||||
request_id: RequestId,
|
||||
command: AgentCommand,
|
||||
},
|
||||
SyncObservations,
|
||||
SyncDeviceSnapshot,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -233,22 +222,14 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observations_message_serializes() {
|
||||
let msg = ClientMessage::Observations {
|
||||
fn device_snapshot_serializes() {
|
||||
let msg = ClientMessage::DeviceSnapshot {
|
||||
agent_id: "agent-a".into(),
|
||||
observations: vec![AgentObservation {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("aa:bb:cc:dd:ee:ff".into()),
|
||||
ip: Some("192.168.1.10".parse().expect("ip")),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
}],
|
||||
devices: vec![],
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&msg).expect("serialize");
|
||||
assert!(json.contains("\"type\":\"observations\""));
|
||||
assert!(json.contains("\"kind\":\"dhcp\""));
|
||||
assert!(json.contains("\"type\":\"device_snapshot\""));
|
||||
assert!(json.contains("\"devices\""));
|
||||
}
|
||||
}
|
||||
|
||||
+23
-113
@@ -1,6 +1,5 @@
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::Serialize;
|
||||
use std::net::IpAddr;
|
||||
use std::time::Instant;
|
||||
use tokio::time::{Duration, MissedTickBehavior, interval, sleep};
|
||||
@@ -9,7 +8,7 @@ use tracing::{debug, error, info, info_span, warn};
|
||||
|
||||
use crate::config::AgentConfig;
|
||||
use crate::dispatch::dispatch_command;
|
||||
use crate::protocol::{AgentCommand, AgentObservation, ClientMessage, ErrorPayload, ServerMessage};
|
||||
use crate::protocol::{AgentCommand, ClientMessage, ErrorPayload, ServerMessage};
|
||||
|
||||
pub async fn run(config: AgentConfig) -> Result<()> {
|
||||
let mut backoff = config.reconnect_base_ms.max(100);
|
||||
@@ -87,11 +86,11 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
|
||||
let mut heartbeat = interval(Duration::from_secs(30));
|
||||
heartbeat.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut observation_sync = interval(Duration::from_secs(
|
||||
let mut snapshot_sync = interval(Duration::from_secs(
|
||||
config.observation_sync_interval_seconds.max(1),
|
||||
));
|
||||
observation_sync.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
observation_sync.reset();
|
||||
snapshot_sync.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
snapshot_sync.reset();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
@@ -101,9 +100,9 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
}).await?;
|
||||
debug!(agent_id = %config.agent_id, "heartbeat sent");
|
||||
}
|
||||
_ = observation_sync.tick() => {
|
||||
if let Err(err) = send_agent_observations_ws(&mut sink, config).await {
|
||||
warn!(agent_id = %config.agent_id, error = %err, "failed to sync local observations");
|
||||
_ = snapshot_sync.tick() => {
|
||||
if let Err(err) = send_device_snapshot_ws(&mut sink, config).await {
|
||||
warn!(agent_id = %config.agent_id, error = %err, "failed to sync device snapshot");
|
||||
}
|
||||
}
|
||||
maybe_msg = source.next() => {
|
||||
@@ -119,7 +118,7 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
Message::Text(text) => {
|
||||
match serde_json::from_str::<ServerMessage>(&text) {
|
||||
Ok(message) => {
|
||||
handle_server_message(config, &mut sink, &mut observation_sync, message).await?;
|
||||
handle_server_message(config, &mut sink, &mut snapshot_sync, message).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
// Allow the server to introduce extra frame types without
|
||||
@@ -146,109 +145,28 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct UploadAgentObservationsRequest {
|
||||
agent_id: String,
|
||||
agent_token: String,
|
||||
observations: Vec<AgentObservation>,
|
||||
}
|
||||
|
||||
pub async fn sync_observations_once(config: &AgentConfig) -> Result<usize> {
|
||||
let client = reqwest::Client::new();
|
||||
send_agent_observations(&client, config).await
|
||||
}
|
||||
|
||||
async fn send_agent_observations(client: &reqwest::Client, config: &AgentConfig) -> Result<usize> {
|
||||
let observations = load_agent_observations(config).await?;
|
||||
if observations.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let url = observations_url(&config.server_url)?;
|
||||
let payload = UploadAgentObservationsRequest {
|
||||
agent_id: config.agent_id.clone(),
|
||||
agent_token: config.agent_token.clone(),
|
||||
observations,
|
||||
};
|
||||
|
||||
let response = client
|
||||
.post(url.clone())
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("failed to call observation endpoint {url}"))?;
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.unwrap_or_else(|_| "<unreadable error body>".to_string());
|
||||
anyhow::bail!("observation upload failed with {status}: {body}");
|
||||
}
|
||||
if let Err(err) = wakey::wakey_linux::observations::prune_removed_observations_from_path(
|
||||
&config.observation_store_path,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(agent_id = %config.agent_id, error = %err, "failed to prune removed observations after upload");
|
||||
}
|
||||
debug!(
|
||||
agent_id = %config.agent_id,
|
||||
observations = payload.observations.len(),
|
||||
"synced local observations"
|
||||
);
|
||||
Ok(payload.observations.len())
|
||||
}
|
||||
|
||||
async fn send_agent_observations_ws<S>(sink: &mut S, config: &AgentConfig) -> Result<usize>
|
||||
async fn send_device_snapshot_ws<S>(sink: &mut S, config: &AgentConfig) -> Result<usize>
|
||||
where
|
||||
S: SinkExt<Message> + Unpin,
|
||||
<S as futures_util::Sink<Message>>::Error: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
let observations = load_agent_observations(config).await?;
|
||||
if observations.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let count = observations.len();
|
||||
let query = wakey_core::InventoryQueryBuilder::new().build();
|
||||
let inventory = wakey::inventory(query)
|
||||
.await
|
||||
.context("failed to run inventory for device snapshot")?;
|
||||
let count = inventory.devices.len();
|
||||
send_json(
|
||||
sink,
|
||||
&ClientMessage::Observations {
|
||||
&ClientMessage::DeviceSnapshot {
|
||||
agent_id: config.agent_id.clone(),
|
||||
observations,
|
||||
devices: inventory.devices,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
if let Err(err) = wakey::wakey_linux::observations::prune_removed_observations_from_path(
|
||||
&config.observation_store_path,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(agent_id = %config.agent_id, error = %err, "failed to prune removed observations after websocket send");
|
||||
}
|
||||
debug!(agent_id = %config.agent_id, observations = count, "sent observations over websocket");
|
||||
debug!(agent_id = %config.agent_id, devices = count, "sent device snapshot over websocket");
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
async fn load_agent_observations(config: &AgentConfig) -> Result<Vec<AgentObservation>> {
|
||||
let observations = wakey::wakey_linux::observations::list_local_observations_from_path(
|
||||
&config.observation_store_path,
|
||||
)
|
||||
.await
|
||||
.context("failed to read local observations")?;
|
||||
Ok(observations
|
||||
.into_iter()
|
||||
.map(|observation| AgentObservation {
|
||||
kind: observation.kind,
|
||||
action: observation.action,
|
||||
mac: observation.mac,
|
||||
ip: observation.ip,
|
||||
hostname: observation.hostname,
|
||||
first_seen_unix: observation.first_seen_unix,
|
||||
last_seen_unix: observation.last_seen_unix,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn next_backoff_ms(current_ms: u64, max_ms: u64) -> u64 {
|
||||
let cap = max_ms.max(current_ms);
|
||||
current_ms.saturating_mul(2).min(cap)
|
||||
@@ -257,7 +175,7 @@ pub fn next_backoff_ms(current_ms: u64, max_ms: u64) -> u64 {
|
||||
async fn handle_server_message<S>(
|
||||
config: &AgentConfig,
|
||||
sink: &mut S,
|
||||
observation_sync: &mut tokio::time::Interval,
|
||||
snapshot_sync: &mut tokio::time::Interval,
|
||||
message: ServerMessage,
|
||||
) -> Result<()>
|
||||
where
|
||||
@@ -293,10 +211,10 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerMessage::SyncObservations => {
|
||||
info!("received observation sync request from control-plane");
|
||||
send_agent_observations_ws(sink, config).await?;
|
||||
observation_sync.reset();
|
||||
ServerMessage::SyncDeviceSnapshot => {
|
||||
info!("received device snapshot sync request from control-plane");
|
||||
send_device_snapshot_ws(sink, config).await?;
|
||||
snapshot_sync.reset();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -373,7 +291,7 @@ fn client_message_kind(message: &ClientMessage) -> &'static str {
|
||||
ClientMessage::Hello { .. } => "hello",
|
||||
ClientMessage::Auth { .. } => "auth",
|
||||
ClientMessage::Heartbeat { .. } => "heartbeat",
|
||||
ClientMessage::Observations { .. } => "observations",
|
||||
ClientMessage::DeviceSnapshot { .. } => "device_snapshot",
|
||||
ClientMessage::Result { .. } => "result",
|
||||
ClientMessage::Error { .. } => "error",
|
||||
}
|
||||
@@ -398,14 +316,6 @@ pub fn websocket_url(server_url: &str) -> Result<url::Url> {
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
pub fn observations_url(server_url: &str) -> Result<url::Url> {
|
||||
let mut url = url::Url::parse(server_url).context("invalid server_url")?;
|
||||
url.set_path("/api/v1/agents/observations");
|
||||
url.set_query(None);
|
||||
url.set_fragment(None);
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
async fn dns_resolution_diagnostics(ws_url: &url::Url) -> Option<(u64, usize)> {
|
||||
let host = ws_url.host_str()?;
|
||||
if host.parse::<IpAddr>().is_ok() {
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_device_observation_events\n (event_id, agent_id, kind, action, mac, ip, hostname, ts_unix)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 8
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "06c45563892b3d688153985aec411f588e80b5f17731f1fce97f9494a1155ffb"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", fact_json as \"fact_json!\"\n FROM agent_device_facts",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "fact_json!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "12e443ec0991c042cf527498b567bbbb6d02885f72eb3fa426c9493368f8a9e7"
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observations.observation_key as \"observation_key!\",\n observations.agent_id as \"agent_id!\",\n observations.kind as \"kind!\",\n observations.mac,\n observations.ip,\n observations.hostname,\n observations.first_seen_unix,\n observations.last_seen_unix,\n observations.last_action as \"last_action!\",\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observations observations\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN observations.mac IS NOT NULL THEN 'mac:' || observations.mac\n WHEN observations.ip IS NOT NULL THEN 'ip:' || observations.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE observations.agent_id = ?1\n ORDER BY observations.last_seen_unix DESC\n LIMIT ?2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 11,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "190ea5014566f84255a8655599e03695fb2f5ce9b720700f93d625c1ae2780e6"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO agents (agent_id, agent_token) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "1d4677e5e37a32a8c0f8ab29ec07986142a621c099a62d3c5973f368e664991c"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_device_observations\n WHERE agent_id = ?1\n AND kind = ?2\n AND observation_key NOT IN (\n SELECT observation_key\n FROM agent_observation_snapshot_keys\n WHERE agent_id = ?1 AND kind = ?2\n )",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "273bcf6b604fbb48cad93630a1485590b1039149d1dd856db674dcc5584947d0"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_observation_snapshot_keys WHERE agent_id = ?1 AND kind = ?2",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "29f24b83cf513758b6a546e86be8aa7ce4b1f66d799aabacaeac02ff84996d24"
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observation_key as \"observation_key!\", agent_id as \"agent_id!\",\n kind as \"kind!\", mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action as \"last_action!\"\n FROM agent_device_observations\n WHERE agent_id = ?1\n ORDER BY last_seen_unix DESC\n LIMIT ?2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "305f50ab2691e12c74e8a222ef12a16f14a65edd7b7c5400a196fd57a9788dcf"
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT mac, ip\n FROM agent_device_observations\n WHERE observation_key = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "3b06698566cea17eed9d10a389ee12a95cee2db6c3d450dca7a3b2d08e8fed7b"
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT events.event_id as \"event_id!\",\n ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) as \"observation_key!\",\n events.agent_id as \"agent_id!\",\n events.kind as \"kind!\",\n events.action as \"action!\",\n events.mac,\n events.ip,\n events.hostname,\n events.ts_unix,\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observation_events events\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE (?1 IS NULL OR events.agent_id = ?1)\n AND (?2 IS NULL OR events.kind = ?2)\n AND (?3 IS NULL OR events.mac = ?3)\n AND (?4 IS NULL OR events.ip = ?4)\n AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) = ?5)\n ORDER BY events.ts_unix DESC\n LIMIT ?6",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "event_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "action!",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ts_unix",
|
||||
"ordinal": 8,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 11,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 6
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "3bc141cecd0ba7c9ca937036b310728dff57c69ed7b74529fd81fa6a3c0e40cf"
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observations.observation_key as \"observation_key!\",\n observations.agent_id as \"agent_id!\",\n observations.kind as \"kind!\",\n observations.mac,\n observations.ip,\n observations.hostname,\n observations.first_seen_unix,\n observations.last_seen_unix,\n observations.last_action as \"last_action!\",\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observations observations\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN observations.mac IS NOT NULL THEN 'mac:' || observations.mac\n WHEN observations.ip IS NOT NULL THEN 'ip:' || observations.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n ORDER BY observations.last_seen_unix DESC\n LIMIT ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 10,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 11,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "409e1e7aa2d9bc46030001e5c522d7c2812b4583dceadfe5c535a866ac76489c"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", hostname as \"hostname!\"\n FROM agent_device_hostnames\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "4188fb9a0dac2e19fb1f83e023eb1e8d93f6ca896cd78a53668080639fc048d9"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", ip as \"ip!\"\n FROM agent_device_ips",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "4dd5e580826b0f6980bb8c2adecdc81ff95992ec337f93263463c5a4e357dc72"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", mac as \"mac!\"\n FROM agent_device_macs\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "580f6bc100d373137db6f853b8babd7633c700dbfaf17ded507b704fd98e46a5"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", mac as \"mac!\"\n FROM agent_device_macs",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5824c6cb841f7aaeb2a039f846effe17ba8038e35998b674136a19a4d42d8b88"
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observation_key as \"observation_key!\", agent_id as \"agent_id!\",\n kind as \"kind!\", mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action as \"last_action!\"\n FROM agent_device_observations\n ORDER BY last_seen_unix DESC\n LIMIT ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5a0f37b5da194e432c795972d5b3bf67c2d2a00f379143d1ae5871ea790d1bf2"
|
||||
}
|
||||
+13
-13
@@ -1,50 +1,50 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT mac, ip, hostname, first_seen_unix, last_seen_unix,\n last_action as \"last_action!\"\n FROM agent_device_observations\n WHERE observation_key = ?1",
|
||||
"query": "SELECT agent_id, device_key, presence, display_name,\n first_seen_unix, last_seen_unix\n FROM agent_devices\n WHERE agent_id = ?1\n ORDER BY device_key",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "mac",
|
||||
"name": "agent_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"name": "device_key",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"name": "presence",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"name": "display_name",
|
||||
"ordinal": 3,
|
||||
"type_info": "Integer"
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "92775bf2e3b9f772d108bb8d0cd1aebbe01357ed70dc2af7b50ee348e668b319"
|
||||
"hash": "5f7e043ca389f1431c7b3478ea506b0c9bb706d32c06871d1267068dbe9cb746"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO alert_transitions\n (transition_key, transition_id, ts_unix, alert_id, kind, agent_id,\n from_status, to_status, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "69601f4f2268a759f03a2d533a0a30dec5cf05797817fd8d2426714cd84d7ada"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_observation_snapshots\n (agent_id, kind, last_dump_unix)\n VALUES (?1, ?2, ?3)\n ON CONFLICT(agent_id, kind) DO UPDATE SET\n last_dump_unix = excluded.last_dump_unix",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "8e7964dee0a2c21d377923d83df23454a104b68fc08f334c6e576bee273bc73b"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_device_observations\n (observation_key, agent_id, kind, mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)\n ON CONFLICT(observation_key) DO UPDATE SET\n mac = excluded.mac,\n ip = excluded.ip,\n hostname = excluded.hostname,\n first_seen_unix = MIN(agent_device_observations.first_seen_unix, excluded.first_seen_unix),\n last_seen_unix = MAX(agent_device_observations.last_seen_unix, excluded.last_seen_unix),\n last_action = excluded.last_action",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 9
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a47ba9ef887f67a7715bd919871ddd76f4ee09aa6ac0ee2f36d32c27d8a756d4"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO active_alerts\n (alert_id, kind, severity, status, agent_id, message, value, threshold,\n last_seen_unix, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a69a1ea43b1a59254cb29b549b5cd3ebfcab8130941dc2d9a78814bc2072c0d5"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_observation_snapshot_keys (agent_id, kind, observation_key)\n VALUES (?1, ?2, ?3)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "aebbe573b428c0aa5ea79d493868c8d9ba06d7a919d955d4c3b96c5fd4b96598"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO agent_meta (agent_id, nickname) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "b69fb8f030b9745db1d8c9db8225426334b4d1edea5d8a8c9b289c17f194c153"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", ip as \"ip!\"\n FROM agent_device_ips\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "c423e005d85659547302f506380ad217cc31329262a1c0254ef532653b3a37bb"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO audit_events\n (event_key, event_id, ts_unix, actor_type, actor_id, agent_id, request_id,\n event_type, outcome, latency_ms, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 12
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "c496c7a8ada53d6d88ea1a29d9e7bf178fe5f3ee9067357dba05384fa1e2772c"
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id, device_key, presence, display_name,\n first_seen_unix, last_seen_unix\n FROM agent_devices\n ORDER BY agent_id, device_key",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "presence",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 5,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "cd8585b9431d223962c376a2d463f0ca8128e7759c8694631f41db0cbd8eb221"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_device_observations WHERE last_seen_unix < ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "cf1c3bedcc9538d7af97e3e59b705b54dd95e7f219c2a8097187eb386d051e83"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", hostname as \"hostname!\"\n FROM agent_device_hostnames",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "dba637bf03d53bf3394ead0f01466f9a72fafc54f9ce239d2e5ac7f76b63b168"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO alert_transitions\n (transition_key, transition_id, ts_unix, alert_id, kind, agent_id,\n from_status, to_status, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "e508aeb39a57b9defc7cec1bf854669150b8f3a02a7d8312e8fea5951391c1bb"
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", fact_json as \"fact_json!\"\n FROM agent_device_facts\n WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_key!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "fact_json!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "e6be4d9782f66f98ebe4d4b6ec6e93ea9efe8e4c7f1147e1ff68d41a311d57f9"
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_device_observation_events WHERE ts_unix < ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "edfcbcd3d530f59971e3e1c7c293321440dd9702ba6d6ac264fc9cf3d7cc7b5a"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO active_alerts\n (alert_id, kind, severity, status, agent_id, message, value, threshold,\n last_seen_unix, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 10
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "fa09ff199445b7bf689ef4426cbd20d89040230ffff977cc1b4c73b499b1b33f"
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
[package]
|
||||
name = "wakey-control-plane"
|
||||
version = "0.2.3"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
anyhow = { workspace = true }
|
||||
axum = { version = "0.8", features = ["ws", "json"] }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
futures-util = "0.3"
|
||||
macaddr = { workspace = true }
|
||||
nix = { version = "0.31", default-features = false, features = [
|
||||
"signal",
|
||||
"process",
|
||||
@@ -17,8 +18,8 @@ reqwest = { version = "0.13", default-features = false, features = [
|
||||
"json",
|
||||
"rustls",
|
||||
] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sled = "0.34"
|
||||
sqlx = { version = "0.8", features = [
|
||||
"runtime-tokio",
|
||||
@@ -29,16 +30,9 @@ sqlx = { version = "0.8", features = [
|
||||
"json",
|
||||
] }
|
||||
toml = "1.1"
|
||||
tokio = { version = "1", features = [
|
||||
"macros",
|
||||
"rt-multi-thread",
|
||||
"fs",
|
||||
"sync",
|
||||
"time",
|
||||
"signal",
|
||||
] }
|
||||
tokio = { workspace = true }
|
||||
tower-http = { version = "0.6.8", features = ["fs"] }
|
||||
tracing = "0.1"
|
||||
tracing = { workspace = true }
|
||||
tracing-opentelemetry = "0.32"
|
||||
tracing-subscriber = { version = "0.3", features = [
|
||||
"env-filter",
|
||||
@@ -50,5 +44,6 @@ time = { version = "0.3", features = ["formatting", "local-offset"] }
|
||||
opentelemetry = "0.31"
|
||||
opentelemetry-otlp = { version = "0.31", features = ["grpc-tonic", "trace"] }
|
||||
opentelemetry_sdk = { version = "0.31", features = ["rt-tokio"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
uuid = { workspace = true }
|
||||
wakey-agent = { path = "../wakey-agent", registry = "gitea", version = "0" }
|
||||
wakey-core = { path = "../wakey-core", registry = "gitea", version = "0" }
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
CREATE TABLE agent_observation_snapshots (
|
||||
agent_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
last_dump_unix INTEGER NOT NULL,
|
||||
PRIMARY KEY(agent_id, kind)
|
||||
);
|
||||
|
||||
CREATE TABLE agent_observation_snapshot_keys (
|
||||
agent_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
observation_key TEXT NOT NULL,
|
||||
PRIMARY KEY(agent_id, kind, observation_key)
|
||||
);
|
||||
|
||||
CREATE INDEX agent_observation_snapshot_keys_observation_idx
|
||||
ON agent_observation_snapshot_keys(observation_key);
|
||||
+68
-32
@@ -18,6 +18,69 @@ CREATE TABLE agent_meta (
|
||||
nickname TEXT
|
||||
);
|
||||
|
||||
---------------------------------------------------------------------------
|
||||
-- Agent-reported complete device state
|
||||
---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE agent_devices (
|
||||
agent_id TEXT NOT NULL,
|
||||
device_key TEXT NOT NULL,
|
||||
presence TEXT NOT NULL,
|
||||
display_name TEXT,
|
||||
first_seen_unix INTEGER NOT NULL,
|
||||
last_seen_unix INTEGER NOT NULL,
|
||||
PRIMARY KEY (agent_id, device_key)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE INDEX agent_devices_agent_seen_idx
|
||||
ON agent_devices(agent_id, last_seen_unix);
|
||||
|
||||
CREATE TABLE agent_device_macs (
|
||||
agent_id TEXT NOT NULL,
|
||||
device_key TEXT NOT NULL,
|
||||
mac TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, device_key, mac),
|
||||
FOREIGN KEY (agent_id, device_key)
|
||||
REFERENCES agent_devices(agent_id, device_key) ON DELETE CASCADE
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE INDEX agent_device_macs_mac_idx
|
||||
ON agent_device_macs(mac);
|
||||
|
||||
CREATE TABLE agent_device_ips (
|
||||
agent_id TEXT NOT NULL,
|
||||
device_key TEXT NOT NULL,
|
||||
ip TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, device_key, ip),
|
||||
FOREIGN KEY (agent_id, device_key)
|
||||
REFERENCES agent_devices(agent_id, device_key) ON DELETE CASCADE
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE INDEX agent_device_ips_ip_idx
|
||||
ON agent_device_ips(ip);
|
||||
|
||||
CREATE TABLE agent_device_hostnames (
|
||||
agent_id TEXT NOT NULL,
|
||||
device_key TEXT NOT NULL,
|
||||
hostname TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, device_key, hostname),
|
||||
FOREIGN KEY (agent_id, device_key)
|
||||
REFERENCES agent_devices(agent_id, device_key) ON DELETE CASCADE
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE agent_device_facts (
|
||||
agent_id TEXT NOT NULL,
|
||||
device_key TEXT NOT NULL,
|
||||
fact_json TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, device_key, fact_json),
|
||||
FOREIGN KEY (agent_id, device_key)
|
||||
REFERENCES agent_devices(agent_id, device_key) ON DELETE CASCADE
|
||||
) WITHOUT ROWID;
|
||||
|
||||
---------------------------------------------------------------------------
|
||||
-- Operator-curated known devices
|
||||
---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE known_devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
@@ -36,39 +99,12 @@ CREATE TABLE device_identifiers (
|
||||
UNIQUE(kind, value)
|
||||
);
|
||||
|
||||
CREATE INDEX device_identifiers_device_id_idx ON device_identifiers(device_id);
|
||||
CREATE INDEX device_identifiers_device_id_idx
|
||||
ON device_identifiers(device_id);
|
||||
|
||||
CREATE TABLE agent_device_observations (
|
||||
observation_key TEXT PRIMARY KEY,
|
||||
agent_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
mac TEXT,
|
||||
ip TEXT,
|
||||
hostname TEXT,
|
||||
first_seen_unix INTEGER NOT NULL,
|
||||
last_seen_unix INTEGER NOT NULL,
|
||||
last_action TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX agent_device_observations_agent_id_idx ON agent_device_observations(agent_id);
|
||||
CREATE INDEX agent_device_observations_mac_idx ON agent_device_observations(mac);
|
||||
CREATE INDEX agent_device_observations_ip_idx ON agent_device_observations(ip);
|
||||
CREATE INDEX agent_device_observations_hostname_idx ON agent_device_observations(hostname);
|
||||
CREATE INDEX agent_device_observations_last_seen_unix_idx ON agent_device_observations(last_seen_unix);
|
||||
|
||||
CREATE TABLE agent_device_observation_events (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
agent_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
mac TEXT,
|
||||
ip TEXT,
|
||||
hostname TEXT,
|
||||
ts_unix INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX agent_device_observation_events_agent_ts_idx ON agent_device_observation_events(agent_id, ts_unix);
|
||||
CREATE INDEX agent_device_observation_events_mac_idx ON agent_device_observation_events(mac);
|
||||
---------------------------------------------------------------------------
|
||||
-- Audit + alerts
|
||||
---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE audit_events (
|
||||
event_key TEXT PRIMARY KEY,
|
||||
@@ -1,12 +1,11 @@
|
||||
mod devices;
|
||||
mod enroll;
|
||||
mod fleet;
|
||||
mod observations;
|
||||
mod stats;
|
||||
|
||||
pub use devices::{
|
||||
attach_device_identifier, attach_observation_identifier, create_known_device,
|
||||
detach_device_identifier, forget_known_device, list_known_devices, merge_known_device,
|
||||
attach_device_identifier, create_known_device, detach_device_identifier, forget_known_device,
|
||||
list_known_devices, merge_known_device,
|
||||
};
|
||||
pub use enroll::{
|
||||
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
||||
@@ -14,8 +13,4 @@ pub use enroll::{
|
||||
set_agent_nickname,
|
||||
};
|
||||
pub use fleet::{list_fleet_devices, refresh_fleet_devices, wake_fleet_device};
|
||||
pub use observations::{
|
||||
list_agent_observation_history, list_agent_observations, request_agent_observation_sync,
|
||||
upload_agent_observations,
|
||||
};
|
||||
pub use stats::{StateStatsResponse, state_stats};
|
||||
|
||||
@@ -25,11 +25,6 @@ pub struct DeviceIdentifierRequest {
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AttachObservationIdentifierRequest {
|
||||
pub observation_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct KnownDeviceResponse {
|
||||
pub device_id: String,
|
||||
@@ -171,33 +166,6 @@ pub async fn attach_device_identifier(
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn attach_observation_identifier(
|
||||
State(state): State<AppState>,
|
||||
AxumPath(device_id): AxumPath<String>,
|
||||
Json(req): Json<AttachObservationIdentifierRequest>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
match state
|
||||
.store
|
||||
.attach_observation_identifier(&device_id, &req.observation_key)
|
||||
.await
|
||||
{
|
||||
Ok(Some(device)) => Ok((StatusCode::OK, Json(known_device_response(device)))),
|
||||
Ok(None) => Err(json_error(
|
||||
StatusCode::NOT_FOUND,
|
||||
"known_device_not_found",
|
||||
"known device not found",
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to attach observation identifier");
|
||||
Err(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"attach_observation_identifier_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn detach_device_identifier(
|
||||
State(state): State<AppState>,
|
||||
AxumPath((device_id, identifier_key)): AxumPath<(String, String)>,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::state::{AgentDeviceObservation, DeviceIdentifier, KnownDevice, KnownDeviceSummary};
|
||||
use macaddr::MacAddr;
|
||||
use wakey_core::Presence;
|
||||
|
||||
use crate::state::{AgentDeviceWithChildren, DeviceIdentifier, KnownDevice, KnownDeviceSummary};
|
||||
|
||||
use super::types::{FleetDevice, FleetDeviceAgent, FleetWakeRoute, ListFleetDevicesQuery};
|
||||
|
||||
@@ -22,20 +26,20 @@ struct FleetAccumulator {
|
||||
display_name: Option<String>,
|
||||
known_device: Option<KnownDeviceSummary>,
|
||||
pinned: bool,
|
||||
ips: BTreeSet<String>,
|
||||
macs: BTreeSet<String>,
|
||||
ips: BTreeSet<IpAddr>,
|
||||
macs: BTreeSet<MacAddr>,
|
||||
hostnames: BTreeSet<String>,
|
||||
sources: BTreeSet<String>,
|
||||
agents: BTreeMap<String, FleetDeviceAgent>,
|
||||
first_seen_unix: Option<u64>,
|
||||
last_seen_unix: Option<u64>,
|
||||
presence_rank: u8,
|
||||
presence: Presence,
|
||||
routes: BTreeMap<String, FleetWakeRoute>,
|
||||
}
|
||||
|
||||
pub(crate) fn build_fleet_devices(
|
||||
known_devices: Vec<KnownDevice>,
|
||||
observations: Vec<AgentDeviceObservation>,
|
||||
agent_devices: Vec<AgentDeviceWithChildren>,
|
||||
context: &FleetBuildContext,
|
||||
) -> Vec<FleetDevice> {
|
||||
let mut by_key = BTreeMap::<String, FleetAccumulator>::new();
|
||||
@@ -49,23 +53,22 @@ pub(crate) fn build_fleet_devices(
|
||||
display_name: Some(device.display_name.clone()),
|
||||
known_device: Some(known_device_summary(&device)),
|
||||
pinned: device.pinned,
|
||||
presence_rank: 1,
|
||||
..Default::default()
|
||||
});
|
||||
for identifier in device.identifiers {
|
||||
add_identifier_to_entry(entry, &identifier);
|
||||
for identifier in &device.identifiers {
|
||||
add_identifier_to_entry(entry, identifier);
|
||||
}
|
||||
}
|
||||
|
||||
for observation in observations {
|
||||
let key = observation_group_key(&observation, context);
|
||||
for agent_device in agent_devices {
|
||||
let key = device_group_key(&agent_device, context);
|
||||
let entry = by_key
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| FleetAccumulator {
|
||||
device_key: key,
|
||||
..Default::default()
|
||||
});
|
||||
add_observation_to_entry(entry, observation, context);
|
||||
add_agent_device_to_entry(entry, agent_device, context);
|
||||
}
|
||||
|
||||
let mut devices = by_key
|
||||
@@ -76,7 +79,7 @@ pub(crate) fn build_fleet_devices(
|
||||
b.pinned
|
||||
.cmp(&a.pinned)
|
||||
.then_with(|| b.known_device.is_some().cmp(&a.known_device.is_some()))
|
||||
.then_with(|| presence_rank(&b.presence).cmp(&presence_rank(&a.presence)))
|
||||
.then_with(|| b.presence.cmp(&a.presence))
|
||||
.then_with(|| b.last_seen_unix.cmp(&a.last_seen_unix))
|
||||
.then_with(|| a.display_name.cmp(&b.display_name))
|
||||
});
|
||||
@@ -98,7 +101,7 @@ pub(crate) fn filter_fleet_devices(devices: &mut Vec<FleetDevice>, query: &ListF
|
||||
}
|
||||
if let Some(presence) = presence.as_deref()
|
||||
&& presence != "all"
|
||||
&& device.presence != presence
|
||||
&& device.presence.as_str() != presence
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -118,18 +121,18 @@ pub(crate) fn filter_fleet_devices(devices: &mut Vec<FleetDevice>, query: &ListF
|
||||
return false;
|
||||
}
|
||||
if let Some(search) = search.as_deref() {
|
||||
let mut haystack = vec![
|
||||
device.device_key.as_str(),
|
||||
device.display_name.as_str(),
|
||||
device.presence.as_str(),
|
||||
let mut haystack: Vec<String> = vec![
|
||||
device.device_key.clone(),
|
||||
device.display_name.clone(),
|
||||
device.presence.as_str().to_string(),
|
||||
];
|
||||
haystack.extend(device.ips.iter().map(String::as_str));
|
||||
haystack.extend(device.macs.iter().map(String::as_str));
|
||||
haystack.extend(device.hostnames.iter().map(String::as_str));
|
||||
haystack.extend(device.sources.iter().map(String::as_str));
|
||||
haystack.extend(device.agents.iter().map(|agent| agent.agent_id.as_str()));
|
||||
haystack.extend(device.ips.iter().map(|ip| ip.to_string()));
|
||||
haystack.extend(device.macs.iter().map(|mac| mac.to_string()));
|
||||
haystack.extend(device.hostnames.clone());
|
||||
haystack.extend(device.sources.clone());
|
||||
haystack.extend(device.agents.iter().map(|a| a.agent_id.clone()));
|
||||
if !haystack
|
||||
.into_iter()
|
||||
.iter()
|
||||
.any(|value| value.to_ascii_lowercase().contains(search))
|
||||
{
|
||||
return false;
|
||||
@@ -145,70 +148,73 @@ fn fleet_device_is_operator_noise(device: &FleetDevice) -> bool {
|
||||
&& device.hostnames.is_empty()
|
||||
&& device.recommended_route.is_none()
|
||||
&& device.ips.is_empty()
|
||||
&& device.presence == "offline"
|
||||
&& device.presence == Presence::Offline
|
||||
}
|
||||
|
||||
fn observation_group_key(
|
||||
observation: &AgentDeviceObservation,
|
||||
context: &FleetBuildContext,
|
||||
) -> String {
|
||||
if let Some(summary) = observation_known_device(observation, context) {
|
||||
fn device_group_key(agent_device: &AgentDeviceWithChildren, context: &FleetBuildContext) -> String {
|
||||
if let Some(summary) = device_known_device(agent_device, context) {
|
||||
return format!("known:{}", summary.device_id);
|
||||
}
|
||||
if let Some(mac) = observation.mac.as_deref() {
|
||||
if let Some(mac) = agent_device.macs.first() {
|
||||
return format!("mac:{mac}");
|
||||
}
|
||||
if let Some(ip) = observation.ip.as_deref() {
|
||||
if let Some(ip) = agent_device.ips.first() {
|
||||
return format!("ip:{ip}");
|
||||
}
|
||||
observation.observation_key.clone()
|
||||
agent_device.device.device_key.clone()
|
||||
}
|
||||
|
||||
fn add_observation_to_entry(
|
||||
fn add_agent_device_to_entry(
|
||||
entry: &mut FleetAccumulator,
|
||||
observation: AgentDeviceObservation,
|
||||
agent_device: AgentDeviceWithChildren,
|
||||
context: &FleetBuildContext,
|
||||
) {
|
||||
let observation_offline = observation_is_offline(&observation);
|
||||
if let Some(summary) = observation_known_device(&observation, context)
|
||||
let device_offline = agent_device.device.presence() == Presence::Offline;
|
||||
if let Some(summary) = device_known_device(&agent_device, context)
|
||||
&& entry.known_device.is_none()
|
||||
{
|
||||
entry.display_name = Some(summary.display_name.clone());
|
||||
if let Some(ref name) = agent_device.device.display_name {
|
||||
entry.display_name = Some(name.clone());
|
||||
}
|
||||
entry.pinned = summary.pinned;
|
||||
entry.known_device = Some(summary);
|
||||
}
|
||||
if let Some(mac) = observation.mac.as_deref() {
|
||||
entry.macs.insert(mac.to_string());
|
||||
for mac in &agent_device.macs {
|
||||
entry.macs.insert(*mac);
|
||||
}
|
||||
if !observation_offline && let Some(ip) = observation.ip.as_deref() {
|
||||
entry.ips.insert(ip.to_string());
|
||||
}
|
||||
if let Some(hostname) = observation.hostname.as_deref() {
|
||||
if entry.display_name.is_none() {
|
||||
entry.display_name = Some(hostname.to_string());
|
||||
if !device_offline {
|
||||
for ip in &agent_device.ips {
|
||||
entry.ips.insert(*ip);
|
||||
}
|
||||
entry.hostnames.insert(hostname.to_string());
|
||||
}
|
||||
entry.sources.insert(observation.kind.clone());
|
||||
for hostname in &agent_device.hostnames {
|
||||
if entry.display_name.is_none() {
|
||||
entry.display_name = Some(hostname.clone());
|
||||
}
|
||||
entry.hostnames.insert(hostname.clone());
|
||||
}
|
||||
entry.sources.insert("device".to_string());
|
||||
let first_seen = agent_device.device.first_seen();
|
||||
let last_seen = agent_device.device.last_seen();
|
||||
entry.first_seen_unix = Some(
|
||||
entry
|
||||
.first_seen_unix
|
||||
.map(|current| current.min(observation.first_seen_unix))
|
||||
.unwrap_or(observation.first_seen_unix),
|
||||
.map(|current| current.min(first_seen))
|
||||
.unwrap_or(first_seen),
|
||||
);
|
||||
entry.last_seen_unix = Some(
|
||||
entry
|
||||
.last_seen_unix
|
||||
.map(|current| current.max(observation.last_seen_unix))
|
||||
.unwrap_or(observation.last_seen_unix),
|
||||
.map(|current| current.max(last_seen))
|
||||
.unwrap_or(last_seen),
|
||||
);
|
||||
entry.presence_rank = entry
|
||||
.presence_rank
|
||||
.max(observation_presence_rank(&observation));
|
||||
let device_presence = agent_device.device.presence();
|
||||
entry.presence = std::cmp::max(entry.presence, device_presence);
|
||||
|
||||
let agent_id = agent_device.device.agent_id.clone();
|
||||
let status = context
|
||||
.agent_status
|
||||
.get(&observation.agent_id)
|
||||
.get(&agent_id)
|
||||
.cloned()
|
||||
.unwrap_or(AgentRuntimeStatus {
|
||||
nickname: None,
|
||||
@@ -216,71 +222,95 @@ fn add_observation_to_entry(
|
||||
});
|
||||
entry
|
||||
.agents
|
||||
.entry(observation.agent_id.clone())
|
||||
.entry(agent_id.clone())
|
||||
.and_modify(|agent| {
|
||||
agent.last_seen_unix = agent.last_seen_unix.max(observation.last_seen_unix);
|
||||
agent.last_seen_unix = agent.last_seen_unix.max(last_seen);
|
||||
agent.connected = status.connected;
|
||||
agent.nickname = status.nickname.clone();
|
||||
})
|
||||
.or_insert(FleetDeviceAgent {
|
||||
agent_id: observation.agent_id.clone(),
|
||||
agent_id: agent_id.clone(),
|
||||
nickname: status.nickname.clone(),
|
||||
connected: status.connected,
|
||||
last_seen_unix: observation.last_seen_unix,
|
||||
last_seen_unix: last_seen,
|
||||
});
|
||||
|
||||
let route_id = route_id(
|
||||
&observation.agent_id,
|
||||
observation.mac.as_deref(),
|
||||
observation.ip.as_deref(),
|
||||
&observation.kind,
|
||||
);
|
||||
let wakeable = status.connected && observation.mac.is_some() && !observation_offline;
|
||||
entry.routes.insert(
|
||||
route_id.clone(),
|
||||
FleetWakeRoute {
|
||||
route_id: route_id.clone(),
|
||||
agent_id: observation.agent_id,
|
||||
nickname: status.nickname,
|
||||
connected: status.connected,
|
||||
mac: observation.mac,
|
||||
ip: observation.ip,
|
||||
hostname: observation.hostname,
|
||||
source: observation.kind,
|
||||
last_seen_unix: observation.last_seen_unix,
|
||||
wakeable,
|
||||
},
|
||||
);
|
||||
if let Some(route) = entry.routes.get_mut(&route_id) {
|
||||
route.wakeable = route.connected && route.mac.is_some() && !observation_offline;
|
||||
for mac in &agent_device.macs {
|
||||
let ip_for_mac = agent_device.ips.first().copied();
|
||||
let hostname_for_mac = agent_device.hostnames.first().cloned();
|
||||
let rid = route_id(&agent_id, Some(mac), ip_for_mac.as_ref(), "device");
|
||||
let wakeable = status.connected && !device_offline;
|
||||
entry.routes.insert(
|
||||
rid.clone(),
|
||||
FleetWakeRoute {
|
||||
route_id: rid,
|
||||
agent_id: agent_id.clone(),
|
||||
nickname: status.nickname.clone(),
|
||||
connected: status.connected,
|
||||
mac: Some(*mac),
|
||||
ip: ip_for_mac,
|
||||
hostname: hostname_for_mac,
|
||||
source: "device".to_string(),
|
||||
last_seen_unix: last_seen,
|
||||
wakeable,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if agent_device.macs.is_empty()
|
||||
&& let Some(ip) = agent_device.ips.first()
|
||||
{
|
||||
let hostname = agent_device.hostnames.first().cloned();
|
||||
let rid = route_id(&agent_id, None, Some(ip), "device");
|
||||
entry.routes.insert(
|
||||
rid.clone(),
|
||||
FleetWakeRoute {
|
||||
route_id: rid,
|
||||
agent_id: agent_id.clone(),
|
||||
nickname: status.nickname.clone(),
|
||||
connected: status.connected,
|
||||
mac: None,
|
||||
ip: Some(*ip),
|
||||
hostname,
|
||||
source: "device".to_string(),
|
||||
last_seen_unix: last_seen,
|
||||
wakeable: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_identifier_to_entry(entry: &mut FleetAccumulator, identifier: &DeviceIdentifier) {
|
||||
match identifier.kind.as_str() {
|
||||
"mac" => {
|
||||
entry.macs.insert(identifier.value.clone());
|
||||
if let Ok(mac) = identifier.value.parse::<MacAddr>() {
|
||||
entry.macs.insert(mac);
|
||||
}
|
||||
}
|
||||
"ip" => {
|
||||
entry.ips.insert(identifier.value.clone());
|
||||
if let Ok(ip) = identifier.value.parse::<IpAddr>() {
|
||||
entry.ips.insert(ip);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn observation_known_device(
|
||||
observation: &AgentDeviceObservation,
|
||||
fn device_known_device(
|
||||
agent_device: &AgentDeviceWithChildren,
|
||||
context: &FleetBuildContext,
|
||||
) -> Option<KnownDeviceSummary> {
|
||||
observation
|
||||
.mac
|
||||
.as_deref()
|
||||
.and_then(|mac| context.identifier_map.get(&format!("mac:{mac}")).cloned())
|
||||
agent_device
|
||||
.macs
|
||||
.first()
|
||||
.map(|mac| format!("mac:{}", mac.to_string().to_ascii_lowercase()))
|
||||
.and_then(|key| context.identifier_map.get(&key).cloned())
|
||||
.or_else(|| {
|
||||
observation
|
||||
.ip
|
||||
.as_deref()
|
||||
.and_then(|ip| context.identifier_map.get(&format!("ip:{ip}")).cloned())
|
||||
agent_device
|
||||
.ips
|
||||
.first()
|
||||
.map(|ip| format!("ip:{ip}"))
|
||||
.and_then(|key| context.identifier_map.get(&key).cloned())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -309,8 +339,8 @@ impl FleetAccumulator {
|
||||
let display_name = self
|
||||
.display_name
|
||||
.or_else(|| self.hostnames.iter().next().cloned())
|
||||
.or_else(|| self.macs.iter().next().cloned())
|
||||
.or_else(|| self.ips.iter().next().cloned())
|
||||
.or_else(|| self.macs.iter().next().map(|mac| mac.to_string()))
|
||||
.or_else(|| self.ips.iter().next().map(|ip| ip.to_string()))
|
||||
.unwrap_or_else(|| "(unknown device)".to_string());
|
||||
|
||||
FleetDevice {
|
||||
@@ -325,50 +355,20 @@ impl FleetAccumulator {
|
||||
sources: self.sources.into_iter().collect(),
|
||||
first_seen_unix: self.first_seen_unix,
|
||||
last_seen_unix: self.last_seen_unix,
|
||||
presence: rank_presence(self.presence_rank).to_string(),
|
||||
presence: self.presence,
|
||||
route_candidates,
|
||||
recommended_route,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn observation_presence_rank(observation: &AgentDeviceObservation) -> u8 {
|
||||
match observation.last_action.as_str() {
|
||||
"remove" => 0,
|
||||
"add" | "old" | "update" => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn observation_is_offline(observation: &AgentDeviceObservation) -> bool {
|
||||
observation.last_action == "remove"
|
||||
}
|
||||
|
||||
fn rank_presence(rank: u8) -> &'static str {
|
||||
match rank {
|
||||
3 => "online",
|
||||
2 => "likely_online",
|
||||
0 => "offline",
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
fn presence_rank(presence: &str) -> u8 {
|
||||
match presence {
|
||||
"online" => 3,
|
||||
"likely_online" => 2,
|
||||
"offline" => 0,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn route_id(agent_id: &str, mac: Option<&str>, ip: Option<&str>, source: &str) -> String {
|
||||
fn route_id(agent_id: &str, mac: Option<&MacAddr>, ip: Option<&IpAddr>, source: &str) -> String {
|
||||
format!(
|
||||
"{}|{}|{}|{}",
|
||||
agent_id,
|
||||
source,
|
||||
mac.unwrap_or(""),
|
||||
ip.unwrap_or("")
|
||||
mac.map(|m| m.to_string()).unwrap_or_default(),
|
||||
ip.map(|i| i.to_string()).unwrap_or_default()
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::net::IpAddr;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::state::AgentDeviceObservationInput;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InventoryEnvelope {
|
||||
kind: String,
|
||||
devices: Vec<InventoryDevice>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InventoryDevice {
|
||||
#[serde(default)]
|
||||
names: Vec<String>,
|
||||
#[serde(default)]
|
||||
ips: Vec<IpAddr>,
|
||||
#[serde(default)]
|
||||
macs: Vec<String>,
|
||||
#[serde(default)]
|
||||
neighbors: Vec<InventoryNeighbor>,
|
||||
#[serde(default)]
|
||||
leases: Vec<InventoryLease>,
|
||||
#[serde(default)]
|
||||
observations: Vec<InventoryObservationFact>,
|
||||
#[serde(default)]
|
||||
presence: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InventoryNeighbor {
|
||||
ip: IpAddr,
|
||||
#[serde(default)]
|
||||
mac: Option<String>,
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InventoryLease {
|
||||
ip: IpAddr,
|
||||
mac: String,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InventoryObservationFact {
|
||||
kind: String,
|
||||
action: String,
|
||||
#[serde(default)]
|
||||
mac: Option<String>,
|
||||
#[serde(default)]
|
||||
ip: Option<IpAddr>,
|
||||
#[serde(default)]
|
||||
hostname: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn inventory_result_to_observations(
|
||||
result: serde_json::Value,
|
||||
) -> anyhow::Result<Vec<AgentDeviceObservationInput>> {
|
||||
let envelope: InventoryEnvelope = serde_json::from_value(result)?;
|
||||
if envelope.kind != "inventory" {
|
||||
anyhow::bail!("expected inventory result, got {}", envelope.kind);
|
||||
}
|
||||
|
||||
let now = now_unix();
|
||||
let mut out = Vec::new();
|
||||
for device in envelope.devices {
|
||||
let hostname = device
|
||||
.names
|
||||
.iter()
|
||||
.find(|name| !name.trim().is_empty())
|
||||
.cloned();
|
||||
let mut wrote_source_observation = false;
|
||||
for neighbor in &device.neighbors {
|
||||
if neighbor.mac.is_none() && device.macs.is_empty() {
|
||||
out.push(inventory_observation(
|
||||
inventory_action_for_neighbor(neighbor),
|
||||
None,
|
||||
Some(neighbor.ip.to_string()),
|
||||
hostname.clone(),
|
||||
now,
|
||||
));
|
||||
wrote_source_observation = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let macs = neighbor
|
||||
.mac
|
||||
.iter()
|
||||
.chain(device.macs.iter())
|
||||
.collect::<BTreeSet<_>>();
|
||||
for mac in macs {
|
||||
out.push(inventory_observation(
|
||||
inventory_action_for_neighbor(neighbor),
|
||||
Some(mac.clone()),
|
||||
Some(neighbor.ip.to_string()),
|
||||
hostname.clone(),
|
||||
now,
|
||||
));
|
||||
wrote_source_observation = true;
|
||||
}
|
||||
}
|
||||
for observation in &device.observations {
|
||||
if observation.mac.is_none() && observation.ip.is_none() {
|
||||
continue;
|
||||
}
|
||||
out.push(inventory_observation(
|
||||
inventory_action_for_observation(observation),
|
||||
observation.mac.clone(),
|
||||
observation.ip.map(|ip| ip.to_string()),
|
||||
observation.hostname.clone().or_else(|| hostname.clone()),
|
||||
now,
|
||||
));
|
||||
wrote_source_observation = true;
|
||||
}
|
||||
for lease in &device.leases {
|
||||
out.push(inventory_observation(
|
||||
"update",
|
||||
Some(lease.mac.clone()),
|
||||
Some(lease.ip.to_string()),
|
||||
lease.name.clone().or_else(|| hostname.clone()),
|
||||
now,
|
||||
));
|
||||
wrote_source_observation = true;
|
||||
}
|
||||
if wrote_source_observation {
|
||||
continue;
|
||||
}
|
||||
|
||||
let action = if device.presence == "offline" {
|
||||
"remove"
|
||||
} else {
|
||||
"update"
|
||||
};
|
||||
if !device.macs.is_empty() {
|
||||
for mac in device.macs {
|
||||
out.push(inventory_observation(
|
||||
action,
|
||||
Some(mac),
|
||||
device.ips.first().map(ToString::to_string),
|
||||
hostname.clone(),
|
||||
now,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
for ip in &device.ips {
|
||||
out.push(inventory_observation(
|
||||
action,
|
||||
None,
|
||||
Some(ip.to_string()),
|
||||
hostname.clone(),
|
||||
now,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn inventory_observation(
|
||||
action: &str,
|
||||
mac: Option<String>,
|
||||
ip: Option<String>,
|
||||
hostname: Option<String>,
|
||||
now: u64,
|
||||
) -> AgentDeviceObservationInput {
|
||||
AgentDeviceObservationInput {
|
||||
kind: "inventory".into(),
|
||||
action: action.into(),
|
||||
mac,
|
||||
ip,
|
||||
hostname,
|
||||
first_seen_unix: now,
|
||||
last_seen_unix: now,
|
||||
}
|
||||
}
|
||||
|
||||
fn inventory_action_for_neighbor(neighbor: &InventoryNeighbor) -> &'static str {
|
||||
if neighbor
|
||||
.state
|
||||
.as_deref()
|
||||
.is_some_and(|state| state.eq_ignore_ascii_case("FAILED"))
|
||||
{
|
||||
"remove"
|
||||
} else {
|
||||
"update"
|
||||
}
|
||||
}
|
||||
|
||||
fn inventory_action_for_observation(observation: &InventoryObservationFact) -> &str {
|
||||
match observation.action.as_str() {
|
||||
"add" | "old" | "update" => "update",
|
||||
"remove" | "del" => "remove",
|
||||
_ if observation.kind == "neigh" => "update",
|
||||
_ => "update",
|
||||
}
|
||||
}
|
||||
|
||||
fn now_unix() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -12,7 +12,6 @@ use crate::api::json_error;
|
||||
use crate::runtime::AppState;
|
||||
|
||||
mod build;
|
||||
mod inventory;
|
||||
mod types;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -22,7 +21,6 @@ use build::{
|
||||
AgentRuntimeStatus, FleetBuildContext, build_fleet_devices, filter_fleet_devices,
|
||||
known_device_summary,
|
||||
};
|
||||
use inventory::inventory_result_to_observations;
|
||||
use types::{
|
||||
FleetDevice, ListFleetDevicesQuery, RefreshFleetAgentResult, RefreshFleetDevicesRequest,
|
||||
RefreshFleetDevicesResponse, WakeFleetDeviceRequest, WakeFleetDeviceResponse,
|
||||
@@ -87,28 +85,35 @@ pub async fn refresh_fleet_devices(
|
||||
});
|
||||
continue;
|
||||
};
|
||||
match inventory_result_to_observations(result) {
|
||||
Ok(observations) => match state
|
||||
.store
|
||||
.upsert_agent_observations_snapshot(&agent_id, "inventory", observations)
|
||||
.await
|
||||
{
|
||||
Ok(accepted) => {
|
||||
total_accepted = total_accepted.saturating_add(accepted);
|
||||
results.push(RefreshFleetAgentResult {
|
||||
match serde_json::from_value::<Vec<wakey_core::Device>>(
|
||||
result
|
||||
.get("devices")
|
||||
.cloned()
|
||||
.unwrap_or(serde_json::Value::Array(vec![])),
|
||||
) {
|
||||
Ok(devices) => {
|
||||
match state
|
||||
.store
|
||||
.replace_agent_device_snapshot(&agent_id, &devices)
|
||||
.await
|
||||
{
|
||||
Ok(accepted) => {
|
||||
total_accepted = total_accepted.saturating_add(accepted);
|
||||
results.push(RefreshFleetAgentResult {
|
||||
agent_id,
|
||||
status: "ok".into(),
|
||||
accepted,
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
Err(err) => results.push(RefreshFleetAgentResult {
|
||||
agent_id,
|
||||
status: "ok".into(),
|
||||
accepted,
|
||||
error: None,
|
||||
});
|
||||
status: "error".into(),
|
||||
accepted: 0,
|
||||
error: Some(err.to_string()),
|
||||
}),
|
||||
}
|
||||
Err(err) => results.push(RefreshFleetAgentResult {
|
||||
agent_id,
|
||||
status: "error".into(),
|
||||
accepted: 0,
|
||||
error: Some(err.to_string()),
|
||||
}),
|
||||
},
|
||||
}
|
||||
Err(err) => results.push(RefreshFleetAgentResult {
|
||||
agent_id,
|
||||
status: "error".into(),
|
||||
@@ -191,7 +196,7 @@ pub async fn wake_fleet_device(
|
||||
)
|
||||
})?;
|
||||
|
||||
let Some(mac) = route.mac.as_deref() else {
|
||||
let Some(mac) = route.mac else {
|
||||
return Err(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"wake_route_unavailable",
|
||||
@@ -213,33 +218,13 @@ pub async fn wake_fleet_device(
|
||||
));
|
||||
}
|
||||
|
||||
let mac = mac.parse().map_err(|err| {
|
||||
json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_wake_route",
|
||||
&format!("invalid route MAC: {err}"),
|
||||
)
|
||||
})?;
|
||||
let ip = route
|
||||
.ip
|
||||
.as_deref()
|
||||
.map(str::parse)
|
||||
.transpose()
|
||||
.map_err(|err| {
|
||||
json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_wake_route",
|
||||
&format!("invalid route IP: {err}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let command = relay_agent_command(
|
||||
&state,
|
||||
&route.agent_id,
|
||||
AgentCommand::Wake(WakeRequest {
|
||||
query: None,
|
||||
mac: Some(mac),
|
||||
ip,
|
||||
ip: route.ip,
|
||||
}),
|
||||
req.timeout_ms,
|
||||
)
|
||||
@@ -256,10 +241,7 @@ async fn load_fleet_devices(
|
||||
query: &ListFleetDevicesQuery,
|
||||
) -> anyhow::Result<Vec<FleetDevice>> {
|
||||
let known_devices = state.store.list_known_devices().await?;
|
||||
let observations = state
|
||||
.store
|
||||
.list_agent_observations(None, query.limit.unwrap_or(1000).max(1))
|
||||
.await?;
|
||||
let agent_devices = state.store.list_agent_device_rows().await?;
|
||||
let connected = {
|
||||
let sessions = state.sessions.read().await;
|
||||
sessions.keys().cloned().collect::<BTreeSet<_>>()
|
||||
@@ -291,7 +273,7 @@ async fn load_fleet_devices(
|
||||
agent_status,
|
||||
identifier_map,
|
||||
};
|
||||
let mut devices = build_fleet_devices(known_devices, observations, &context);
|
||||
let mut devices = build_fleet_devices(known_devices, agent_devices, &context);
|
||||
filter_fleet_devices(&mut devices, query);
|
||||
let limit = query.limit.unwrap_or(500).clamp(1, 1000);
|
||||
devices.truncate(limit);
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
|
||||
use macaddr::MacAddr;
|
||||
use wakey_core::Presence;
|
||||
|
||||
use super::build::{
|
||||
AgentRuntimeStatus, FleetBuildContext, build_fleet_devices, filter_fleet_devices,
|
||||
known_device_summary,
|
||||
};
|
||||
use super::inventory::inventory_result_to_observations;
|
||||
use super::types::ListFleetDevicesQuery;
|
||||
use crate::state::{AgentDeviceObservation, DeviceIdentifier, KnownDevice};
|
||||
use crate::state::{AgentDeviceRow, AgentDeviceWithChildren, DeviceIdentifier, KnownDevice};
|
||||
|
||||
fn context(connected: &[&str]) -> FleetBuildContext {
|
||||
FleetBuildContext {
|
||||
@@ -26,27 +29,83 @@ fn context(connected: &[&str]) -> FleetBuildContext {
|
||||
}
|
||||
}
|
||||
|
||||
fn observation(
|
||||
fn agent_device(
|
||||
agent_id: &str,
|
||||
device_key: &str,
|
||||
mac: Option<&str>,
|
||||
ip: Option<&str>,
|
||||
last_seen_unix: u64,
|
||||
) -> AgentDeviceObservation {
|
||||
AgentDeviceObservation {
|
||||
observation_key: format!(
|
||||
"agent:{agent_id}:dhcp:{}",
|
||||
mac.map(|mac| format!("mac:{mac}"))
|
||||
.or_else(|| ip.map(|ip| format!("ip:{ip}")))
|
||||
.unwrap_or_default()
|
||||
),
|
||||
agent_id: agent_id.into(),
|
||||
kind: "dhcp".into(),
|
||||
mac: mac.map(str::to_string),
|
||||
ip: ip.map(str::to_string),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 1,
|
||||
last_seen_unix,
|
||||
last_action: "update".into(),
|
||||
last_seen_unix: i64,
|
||||
) -> AgentDeviceWithChildren {
|
||||
AgentDeviceWithChildren {
|
||||
device: AgentDeviceRow {
|
||||
agent_id: agent_id.into(),
|
||||
device_key: device_key.into(),
|
||||
presence: "likely_online".into(),
|
||||
display_name: Some("lda".into()),
|
||||
first_seen_unix: 1,
|
||||
last_seen_unix,
|
||||
},
|
||||
macs: mac
|
||||
.map(|m| m.parse::<MacAddr>().unwrap())
|
||||
.into_iter()
|
||||
.collect(),
|
||||
ips: ip
|
||||
.map(|i| i.parse::<IpAddr>().unwrap())
|
||||
.into_iter()
|
||||
.collect(),
|
||||
hostnames: vec!["lda".to_string()],
|
||||
facts: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn offline_agent_device(
|
||||
agent_id: &str,
|
||||
device_key: &str,
|
||||
mac: Option<&str>,
|
||||
ip: Option<&str>,
|
||||
last_seen_unix: i64,
|
||||
) -> AgentDeviceWithChildren {
|
||||
AgentDeviceWithChildren {
|
||||
device: AgentDeviceRow {
|
||||
agent_id: agent_id.into(),
|
||||
device_key: device_key.into(),
|
||||
presence: "offline".into(),
|
||||
display_name: Some("lda".into()),
|
||||
first_seen_unix: 1,
|
||||
last_seen_unix,
|
||||
},
|
||||
macs: mac
|
||||
.map(|m| m.parse::<MacAddr>().unwrap())
|
||||
.into_iter()
|
||||
.collect(),
|
||||
ips: ip
|
||||
.map(|i| i.parse::<IpAddr>().unwrap())
|
||||
.into_iter()
|
||||
.collect(),
|
||||
hostnames: vec!["lda".to_string()],
|
||||
facts: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn offline_ip_only_unknown(
|
||||
agent_id: &str,
|
||||
device_key: &str,
|
||||
ip: &str,
|
||||
last_seen_unix: i64,
|
||||
) -> AgentDeviceWithChildren {
|
||||
AgentDeviceWithChildren {
|
||||
device: AgentDeviceRow {
|
||||
agent_id: agent_id.into(),
|
||||
device_key: device_key.into(),
|
||||
presence: "offline".into(),
|
||||
display_name: None,
|
||||
first_seen_unix: 1,
|
||||
last_seen_unix,
|
||||
},
|
||||
macs: vec![],
|
||||
ips: vec![ip.parse().unwrap()],
|
||||
hostnames: vec![],
|
||||
facts: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,14 +114,16 @@ fn fleet_grouping_combines_same_mac_across_agents() {
|
||||
let devices = build_fleet_devices(
|
||||
Vec::new(),
|
||||
vec![
|
||||
observation(
|
||||
agent_device(
|
||||
"agent-a",
|
||||
"mac:aa:bb:cc:dd:ee:ff",
|
||||
Some("aa:bb:cc:dd:ee:ff"),
|
||||
Some("192.168.1.2"),
|
||||
10,
|
||||
),
|
||||
observation(
|
||||
agent_device(
|
||||
"agent-b",
|
||||
"mac:aa:bb:cc:dd:ee:ff",
|
||||
Some("aa:bb:cc:dd:ee:ff"),
|
||||
Some("192.168.2.2"),
|
||||
20,
|
||||
@@ -71,8 +132,9 @@ fn fleet_grouping_combines_same_mac_across_agents() {
|
||||
&context(&["agent-a", "agent-b"]),
|
||||
);
|
||||
|
||||
let expected_mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap();
|
||||
assert_eq!(devices.len(), 1);
|
||||
assert_eq!(devices[0].macs, vec!["aa:bb:cc:dd:ee:ff"]);
|
||||
assert_eq!(devices[0].macs, vec![expected_mac]);
|
||||
assert_eq!(devices[0].agents.len(), 2);
|
||||
assert_eq!(
|
||||
devices[0]
|
||||
@@ -84,7 +146,7 @@ fn fleet_grouping_combines_same_mac_across_agents() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_device_with_two_macs_absorbs_both_observation_groups() {
|
||||
fn known_device_with_two_macs_absorbs_both_device_groups() {
|
||||
let known = KnownDevice {
|
||||
device_id: "dev-1".into(),
|
||||
display_name: "lda".into(),
|
||||
@@ -120,8 +182,20 @@ fn known_device_with_two_macs_absorbs_both_observation_groups() {
|
||||
let devices = build_fleet_devices(
|
||||
vec![known],
|
||||
vec![
|
||||
observation("agent-a", Some("aa:bb:cc:dd:ee:01"), None, 10),
|
||||
observation("agent-a", Some("aa:bb:cc:dd:ee:02"), None, 20),
|
||||
agent_device(
|
||||
"agent-a",
|
||||
"mac:aa:bb:cc:dd:ee:01",
|
||||
Some("aa:bb:cc:dd:ee:01"),
|
||||
None,
|
||||
10,
|
||||
),
|
||||
agent_device(
|
||||
"agent-a",
|
||||
"mac:aa:bb:cc:dd:ee:02",
|
||||
Some("aa:bb:cc:dd:ee:02"),
|
||||
None,
|
||||
20,
|
||||
),
|
||||
],
|
||||
&ctx,
|
||||
);
|
||||
@@ -135,44 +209,54 @@ fn known_device_with_two_macs_absorbs_both_observation_groups() {
|
||||
fn ip_only_unknown_is_visible_but_not_wakeable() {
|
||||
let devices = build_fleet_devices(
|
||||
Vec::new(),
|
||||
vec![observation("agent-a", None, Some("192.168.1.2"), 10)],
|
||||
vec![agent_device(
|
||||
"agent-a",
|
||||
"ip:192.168.1.2",
|
||||
None,
|
||||
Some("192.168.1.2"),
|
||||
10,
|
||||
)],
|
||||
&context(&["agent-a"]),
|
||||
);
|
||||
|
||||
let expected_ip: IpAddr = "192.168.1.2".parse().unwrap();
|
||||
assert_eq!(devices.len(), 1);
|
||||
assert_eq!(devices[0].ips, vec![expected_ip]);
|
||||
assert!(devices[0].recommended_route.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_device_has_offline_presence() {
|
||||
let devices = build_fleet_devices(
|
||||
Vec::new(),
|
||||
vec![offline_agent_device(
|
||||
"agent-a",
|
||||
"mac:aa:bb:cc:dd:ee:ff",
|
||||
Some("aa:bb:cc:dd:ee:ff"),
|
||||
Some("192.168.1.2"),
|
||||
20,
|
||||
)],
|
||||
&context(&["agent-a"]),
|
||||
);
|
||||
|
||||
assert_eq!(devices.len(), 1);
|
||||
assert_eq!(devices[0].ips, vec!["192.168.1.2"]);
|
||||
assert!(devices[0].recommended_route.is_none());
|
||||
assert!(!devices[0].route_candidates[0].wakeable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_observation_does_not_advertise_current_ip_or_wake_route() {
|
||||
let mut offline = observation(
|
||||
"agent-a",
|
||||
Some("aa:bb:cc:dd:ee:ff"),
|
||||
Some("192.168.1.2"),
|
||||
20,
|
||||
);
|
||||
offline.kind = "neigh".into();
|
||||
offline.last_action = "remove".into();
|
||||
|
||||
let devices = build_fleet_devices(Vec::new(), vec![offline], &context(&["agent-a"]));
|
||||
|
||||
assert_eq!(devices.len(), 1);
|
||||
assert!(devices[0].ips.is_empty());
|
||||
assert_eq!(devices[0].presence, "offline");
|
||||
assert_eq!(devices[0].presence, Presence::Offline);
|
||||
assert!(devices[0].recommended_route.is_none());
|
||||
assert!(!devices[0].route_candidates[0].wakeable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_ip_only_remove_observation_is_hidden() {
|
||||
let mut offline = observation("agent-a", None, Some("192.168.1.2"), 20);
|
||||
offline.kind = "neigh".into();
|
||||
offline.hostname = None;
|
||||
offline.last_action = "remove".into();
|
||||
|
||||
let mut devices = build_fleet_devices(Vec::new(), vec![offline], &context(&["agent-a"]));
|
||||
fn unknown_ip_only_offline_device_is_hidden_by_default() {
|
||||
let mut devices = build_fleet_devices(
|
||||
Vec::new(),
|
||||
vec![offline_ip_only_unknown(
|
||||
"agent-a",
|
||||
"ip:192.168.1.2",
|
||||
"192.168.1.2",
|
||||
20,
|
||||
)],
|
||||
&context(&["agent-a"]),
|
||||
);
|
||||
|
||||
assert_eq!(devices.len(), 1);
|
||||
assert_eq!(devices[0].display_name, "(unknown device)");
|
||||
@@ -181,13 +265,17 @@ fn unknown_ip_only_remove_observation_is_hidden() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_all_keeps_unknown_ip_only_remove_observation() {
|
||||
let mut offline = observation("agent-a", None, Some("192.168.1.2"), 20);
|
||||
offline.kind = "neigh".into();
|
||||
offline.hostname = None;
|
||||
offline.last_action = "remove".into();
|
||||
|
||||
let mut devices = build_fleet_devices(Vec::new(), vec![offline], &context(&["agent-a"]));
|
||||
fn visibility_all_keeps_unknown_ip_only_offline_device() {
|
||||
let mut devices = build_fleet_devices(
|
||||
Vec::new(),
|
||||
vec![offline_ip_only_unknown(
|
||||
"agent-a",
|
||||
"ip:192.168.1.2",
|
||||
"192.168.1.2",
|
||||
20,
|
||||
)],
|
||||
&context(&["agent-a"]),
|
||||
);
|
||||
|
||||
filter_fleet_devices(
|
||||
&mut devices,
|
||||
@@ -201,7 +289,7 @@ fn visibility_all_keeps_unknown_ip_only_remove_observation() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_ip_only_remove_observation_is_kept() {
|
||||
fn known_ip_only_offline_device_is_kept() {
|
||||
let known = KnownDevice {
|
||||
device_id: "dev-1".into(),
|
||||
display_name: "lda".into(),
|
||||
@@ -220,114 +308,22 @@ fn known_ip_only_remove_observation_is_kept() {
|
||||
let mut ctx = context(&["agent-a"]);
|
||||
ctx.identifier_map
|
||||
.insert("ip:192.168.1.2".into(), known_device_summary(&known));
|
||||
let mut offline = observation("agent-a", None, Some("192.168.1.2"), 20);
|
||||
offline.kind = "neigh".into();
|
||||
offline.hostname = None;
|
||||
offline.last_action = "remove".into();
|
||||
|
||||
let devices = build_fleet_devices(vec![known], vec![offline], &ctx);
|
||||
let devices = build_fleet_devices(
|
||||
vec![known],
|
||||
vec![offline_agent_device(
|
||||
"agent-a",
|
||||
"ip:192.168.1.2",
|
||||
None,
|
||||
Some("192.168.1.2"),
|
||||
20,
|
||||
)],
|
||||
&ctx,
|
||||
);
|
||||
|
||||
let expected_ip: IpAddr = "192.168.1.2".parse().unwrap();
|
||||
assert_eq!(devices.len(), 1);
|
||||
assert_eq!(devices[0].device_key, "known:dev-1");
|
||||
assert_eq!(devices[0].display_name, "lda");
|
||||
assert!(devices[0].ips.contains(&"192.168.1.2".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_result_maps_to_stored_observations() {
|
||||
let observations = inventory_result_to_observations(serde_json::json!({
|
||||
"kind": "inventory",
|
||||
"devices": [{
|
||||
"names": ["lda"],
|
||||
"ips": ["192.168.1.2"],
|
||||
"macs": ["aa:bb:cc:dd:ee:ff"],
|
||||
"presence": "likely_online"
|
||||
}]
|
||||
}))
|
||||
.expect("inventory should map");
|
||||
|
||||
assert_eq!(observations.len(), 1);
|
||||
assert_eq!(observations[0].kind, "inventory");
|
||||
assert_eq!(observations[0].action, "update");
|
||||
assert_eq!(observations[0].mac.as_deref(), Some("aa:bb:cc:dd:ee:ff"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_result_preserves_neighbor_failed_ip_as_remove() {
|
||||
let observations = inventory_result_to_observations(serde_json::json!({
|
||||
"kind": "inventory",
|
||||
"devices": [{
|
||||
"names": ["lda"],
|
||||
"ips": ["192.168.1.2", "192.168.1.3"],
|
||||
"macs": ["aa:bb:cc:dd:ee:ff"],
|
||||
"neighbors": [
|
||||
{
|
||||
"ip": "192.168.1.2",
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"state": "FAILED"
|
||||
},
|
||||
{
|
||||
"ip": "192.168.1.3",
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"state": "REACHABLE"
|
||||
}
|
||||
],
|
||||
"presence": "online"
|
||||
}]
|
||||
}))
|
||||
.expect("inventory should map");
|
||||
|
||||
assert_eq!(observations.len(), 2);
|
||||
let removed = observations
|
||||
.iter()
|
||||
.find(|observation| observation.ip.as_deref() == Some("192.168.1.2"))
|
||||
.expect("failed neighbor observation should exist");
|
||||
assert_eq!(removed.action, "remove");
|
||||
assert_eq!(removed.mac.as_deref(), Some("aa:bb:cc:dd:ee:ff"));
|
||||
|
||||
let current = observations
|
||||
.iter()
|
||||
.find(|observation| observation.ip.as_deref() == Some("192.168.1.3"))
|
||||
.expect("reachable neighbor observation should exist");
|
||||
assert_eq!(current.action, "update");
|
||||
assert_eq!(current.mac.as_deref(), Some("aa:bb:cc:dd:ee:ff"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_result_preserves_hook_observations_and_leases() {
|
||||
let observations = inventory_result_to_observations(serde_json::json!({
|
||||
"kind": "inventory",
|
||||
"devices": [{
|
||||
"names": ["lda"],
|
||||
"ips": ["192.168.1.2", "192.168.1.3"],
|
||||
"macs": ["aa:bb:cc:dd:ee:ff"],
|
||||
"observations": [{
|
||||
"kind": "neigh",
|
||||
"action": "remove",
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"ip": "192.168.1.2"
|
||||
}],
|
||||
"leases": [{
|
||||
"expires_epoch": 1893456000_u64,
|
||||
"ip": "192.168.1.3",
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"name": "lda"
|
||||
}],
|
||||
"presence": "likely_online"
|
||||
}]
|
||||
}))
|
||||
.expect("inventory should map");
|
||||
|
||||
assert_eq!(observations.len(), 2);
|
||||
assert!(observations.iter().any(|observation| {
|
||||
observation.action == "remove"
|
||||
&& observation.mac.as_deref() == Some("aa:bb:cc:dd:ee:ff")
|
||||
&& observation.ip.as_deref() == Some("192.168.1.2")
|
||||
}));
|
||||
assert!(observations.iter().any(|observation| {
|
||||
observation.action == "update"
|
||||
&& observation.mac.as_deref() == Some("aa:bb:cc:dd:ee:ff")
|
||||
&& observation.ip.as_deref() == Some("192.168.1.3")
|
||||
&& observation.hostname.as_deref() == Some("lda")
|
||||
}));
|
||||
assert!(devices[0].ips.contains(&expected_ip));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
use macaddr::MacAddr;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::IpAddr;
|
||||
|
||||
use wakey_core::Presence;
|
||||
|
||||
use crate::api::commands::RelayCommandResponse;
|
||||
use crate::state::KnownDeviceSummary;
|
||||
use wakey_core::parse::mac;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct ListFleetDevicesQuery {
|
||||
@@ -53,14 +58,15 @@ pub struct FleetDevice {
|
||||
pub display_name: String,
|
||||
pub known_device: Option<KnownDeviceSummary>,
|
||||
pub pinned: bool,
|
||||
pub ips: Vec<String>,
|
||||
pub macs: Vec<String>,
|
||||
pub ips: Vec<IpAddr>,
|
||||
#[serde(with = "mac::vec_mac")]
|
||||
pub macs: Vec<MacAddr>,
|
||||
pub hostnames: Vec<String>,
|
||||
pub agents: Vec<FleetDeviceAgent>,
|
||||
pub sources: Vec<String>,
|
||||
pub first_seen_unix: Option<u64>,
|
||||
pub last_seen_unix: Option<u64>,
|
||||
pub presence: String,
|
||||
pub presence: Presence,
|
||||
pub route_candidates: Vec<FleetWakeRoute>,
|
||||
pub recommended_route: Option<FleetWakeRoute>,
|
||||
}
|
||||
@@ -79,8 +85,9 @@ pub struct FleetWakeRoute {
|
||||
pub agent_id: String,
|
||||
pub nickname: Option<String>,
|
||||
pub connected: bool,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<String>,
|
||||
#[serde(with = "mac::option_mac")]
|
||||
pub mac: Option<MacAddr>,
|
||||
pub ip: Option<IpAddr>,
|
||||
pub hostname: Option<String>,
|
||||
pub source: String,
|
||||
pub last_seen_unix: u64,
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path as AxumPath, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use serde::Deserialize;
|
||||
use tracing::warn;
|
||||
use wakey_agent::protocol::ServerMessage;
|
||||
|
||||
use crate::api::json_error;
|
||||
use crate::runtime::{AppState, SessionEvent};
|
||||
use crate::state::{
|
||||
AgentDeviceObservationEvent, AgentDeviceObservationInput, AgentDeviceObservationView,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UploadAgentObservationsRequest {
|
||||
pub agent_id: String,
|
||||
pub agent_token: String,
|
||||
#[serde(default)]
|
||||
pub observations: Vec<AgentObservationRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AgentObservationRequest {
|
||||
pub kind: String,
|
||||
pub action: String,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
pub first_seen_unix: u64,
|
||||
pub last_seen_unix: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct UploadAgentObservationsResponse {
|
||||
pub accepted: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RequestAgentObservationSyncResponse {
|
||||
pub agent_id: String,
|
||||
pub requested: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ListObservationsQuery {
|
||||
pub agent_id: Option<String>,
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ListObservationHistoryQuery {
|
||||
pub agent_id: Option<String>,
|
||||
pub kind: Option<String>,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<String>,
|
||||
pub observation_key: Option<String>,
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
pub async fn upload_agent_observations(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<UploadAgentObservationsRequest>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
if !state
|
||||
.store
|
||||
.verify_agent_token(&req.agent_id, &req.agent_token)
|
||||
.await
|
||||
{
|
||||
return Err(json_error(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"agent_auth_rejected",
|
||||
"agent credentials rejected",
|
||||
));
|
||||
}
|
||||
|
||||
let mut by_kind: BTreeMap<String, Vec<AgentDeviceObservationInput>> = BTreeMap::new();
|
||||
for observation in req.observations {
|
||||
let kind = observation.kind.trim().to_ascii_lowercase();
|
||||
let entry = by_kind.entry(kind.clone()).or_default();
|
||||
entry.push(AgentDeviceObservationInput {
|
||||
kind,
|
||||
action: observation.action,
|
||||
mac: observation.mac,
|
||||
ip: observation.ip,
|
||||
hostname: observation.hostname,
|
||||
first_seen_unix: observation.first_seen_unix,
|
||||
last_seen_unix: observation.last_seen_unix,
|
||||
});
|
||||
}
|
||||
|
||||
let mut accepted = 0usize;
|
||||
for (kind, observations) in by_kind {
|
||||
match state
|
||||
.store
|
||||
.upsert_agent_observations_snapshot(&req.agent_id, &kind, observations)
|
||||
.await
|
||||
{
|
||||
Ok(written) => {
|
||||
accepted = accepted.saturating_add(written);
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(error = %err, agent_id = %req.agent_id, kind = %kind, "failed to upload agent observations");
|
||||
return Err(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"upload_observations_failed",
|
||||
&err.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((
|
||||
StatusCode::OK,
|
||||
Json(UploadAgentObservationsResponse { accepted }),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn list_agent_observations(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<ListObservationsQuery>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
match state
|
||||
.store
|
||||
.list_agent_observation_views(query.agent_id.as_deref(), query.limit.unwrap_or(500))
|
||||
.await
|
||||
{
|
||||
Ok(observations) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(
|
||||
observations
|
||||
.into_iter()
|
||||
.map(agent_observation_response)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to list agent observations");
|
||||
Err(json_error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"list_observations_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn request_agent_observation_sync(
|
||||
State(state): State<AppState>,
|
||||
AxumPath(agent_id): AxumPath<String>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
let tx = {
|
||||
let sessions = state.sessions.read().await;
|
||||
sessions.get(&agent_id).map(|session| session.tx.clone())
|
||||
};
|
||||
let Some(tx) = tx else {
|
||||
return Ok((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(RequestAgentObservationSyncResponse {
|
||||
agent_id,
|
||||
requested: false,
|
||||
}),
|
||||
));
|
||||
};
|
||||
|
||||
match tx.send(SessionEvent::Message(ServerMessage::SyncObservations)) {
|
||||
Ok(()) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(RequestAgentObservationSyncResponse {
|
||||
agent_id,
|
||||
requested: true,
|
||||
}),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to request agent observation sync");
|
||||
Err(json_error(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"agent_observation_sync_request_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_agent_observation_history(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<ListObservationHistoryQuery>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
let kind = normalized_query_value(query.kind).map(|value| value.to_ascii_lowercase());
|
||||
let mac = normalized_query_value(query.mac).map(|value| value.to_ascii_lowercase());
|
||||
let ip = normalized_query_value(query.ip);
|
||||
let observation_key = normalized_query_value(query.observation_key);
|
||||
match state
|
||||
.store
|
||||
.list_agent_observation_events(
|
||||
query.agent_id.as_deref(),
|
||||
kind.as_deref(),
|
||||
mac.as_deref(),
|
||||
ip.as_deref(),
|
||||
observation_key.as_deref(),
|
||||
query.limit.unwrap_or(500),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(events) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(
|
||||
events
|
||||
.into_iter()
|
||||
.map(agent_observation_event_response)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to list agent observation history");
|
||||
Err(json_error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"list_observation_history_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn agent_observation_response(
|
||||
observation: AgentDeviceObservationView,
|
||||
) -> AgentDeviceObservationView {
|
||||
observation
|
||||
}
|
||||
|
||||
fn agent_observation_event_response(
|
||||
event: AgentDeviceObservationEvent,
|
||||
) -> AgentDeviceObservationEvent {
|
||||
event
|
||||
}
|
||||
|
||||
fn normalized_query_value(value: Option<String>) -> Option<String> {
|
||||
value
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
@@ -11,12 +11,10 @@ pub use audit::list_audit_events;
|
||||
pub use commands::{list_agents, run_command};
|
||||
pub use control::{
|
||||
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
||||
StateStatsResponse, attach_device_identifier, attach_observation_identifier,
|
||||
create_known_device, detach_device_identifier, enroll, forget_known_device, healthz,
|
||||
issue_enroll_token, list_agent_observation_history, list_agent_observations,
|
||||
list_enroll_tokens, list_fleet_devices, list_known_devices, merge_known_device,
|
||||
refresh_fleet_devices, request_agent_observation_sync, revoke_agent, revoke_enroll_token,
|
||||
set_agent_nickname, state_stats, upload_agent_observations, wake_fleet_device,
|
||||
StateStatsResponse, attach_device_identifier, create_known_device, detach_device_identifier,
|
||||
enroll, forget_known_device, healthz, issue_enroll_token, list_enroll_tokens,
|
||||
list_fleet_devices, list_known_devices, merge_known_device, refresh_fleet_devices,
|
||||
revoke_agent, revoke_enroll_token, set_agent_nickname, state_stats, wake_fleet_device,
|
||||
};
|
||||
|
||||
pub fn json_error(
|
||||
|
||||
@@ -12,6 +12,7 @@ pub struct DaemonConfig {
|
||||
pub state_file: PathBuf,
|
||||
pub command_timeout: Duration,
|
||||
pub enroll_token_ttl: Duration,
|
||||
#[allow(dead_code)]
|
||||
pub observation_retention: Duration,
|
||||
pub pid_file: PathBuf,
|
||||
pub ui_dist_dir: PathBuf,
|
||||
|
||||
@@ -71,10 +71,6 @@ fn public_api_routes(ui_dist_dir: std::path::PathBuf) -> Router<AppState> {
|
||||
)
|
||||
.route("/healthz", get(api::healthz))
|
||||
.route("/api/v1/agents/enroll", post(api::enroll))
|
||||
.route(
|
||||
"/api/v1/agents/observations",
|
||||
post(api::upload_agent_observations),
|
||||
)
|
||||
.route("/api/v1/agent/ws", get(ws::agent_ws))
|
||||
}
|
||||
|
||||
@@ -102,18 +98,6 @@ fn control_api_routes() -> Router<AppState> {
|
||||
post(api::refresh_fleet_devices),
|
||||
)
|
||||
.route("/api/v1/control/fleet/wake", post(api::wake_fleet_device))
|
||||
.route(
|
||||
"/api/v1/control/observations",
|
||||
get(api::list_agent_observations),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/observations/history",
|
||||
get(api::list_agent_observation_history),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/agents/{agent_id}/observations/sync",
|
||||
post(api::request_agent_observation_sync),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/devices",
|
||||
get(api::list_known_devices).post(api::create_known_device),
|
||||
@@ -134,10 +118,6 @@ fn control_api_routes() -> Router<AppState> {
|
||||
"/api/v1/control/devices/{device_id}/identifiers/{identifier_key}",
|
||||
axum::routing::delete(api::detach_device_identifier),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/devices/{device_id}/identifiers/from-observation",
|
||||
post(api::attach_observation_identifier),
|
||||
)
|
||||
.route("/api/v1/control/audit/events", get(api::list_audit_events))
|
||||
.route("/api/v1/control/alerts", get(api::active_alerts))
|
||||
.route("/api/v1/control/alerts/history", get(api::alert_history))
|
||||
@@ -226,18 +206,6 @@ pub async fn serve(daemon: config::DaemonConfig) -> Result<()> {
|
||||
}
|
||||
Err(err) => warn!(error = %err, "periodic gc failed"),
|
||||
}
|
||||
match app_state
|
||||
.store
|
||||
.gc_stale_observations(daemon.observation_retention)
|
||||
.await
|
||||
{
|
||||
Ok(removed) => {
|
||||
if removed > 0 {
|
||||
info!(removed, "periodic gc removed stale observations");
|
||||
}
|
||||
}
|
||||
Err(err) => warn!(error = %err, "periodic observation gc failed"),
|
||||
}
|
||||
}
|
||||
join = &mut server => {
|
||||
let _ = remove_pid_file(&daemon.pid_file);
|
||||
|
||||
@@ -2,8 +2,9 @@ mod store;
|
||||
mod types;
|
||||
|
||||
pub use store::Store;
|
||||
#[cfg(test)]
|
||||
pub use types::AgentDeviceRow;
|
||||
pub use types::{
|
||||
AgentDeviceObservation, AgentDeviceObservationEvent, AgentDeviceObservationInput,
|
||||
AgentDeviceObservationView, AlertState, AuditEvent, AuditEventFilter, AuditEventInput,
|
||||
AgentDeviceWithChildren, AlertState, AuditEvent, AuditEventFilter, AuditEventInput,
|
||||
DeviceIdentifier, DeviceIdentifierInput, KnownDevice, KnownDeviceInput, KnownDeviceSummary,
|
||||
};
|
||||
|
||||
@@ -8,10 +8,9 @@ use tracing::{info, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::state::types::{
|
||||
AgentDeviceObservation, AgentDeviceObservationEvent, AgentDeviceObservationInput,
|
||||
AgentDeviceObservationView, AlertState, AlertTransition, AuditEvent, AuditEventFilter,
|
||||
AuditEventInput, DeviceIdentifier, DeviceIdentifierInput, EnrollTokenInfo, IssuedAgent,
|
||||
IssuedEnrollToken, KnownDevice, KnownDeviceInput, KnownDeviceSummary, StateStats,
|
||||
AlertState, AlertTransition, AuditEvent, AuditEventFilter, AuditEventInput, DeviceIdentifier,
|
||||
DeviceIdentifierInput, EnrollTokenInfo, IssuedAgent, IssuedEnrollToken, KnownDevice,
|
||||
KnownDeviceInput, StateStats,
|
||||
};
|
||||
|
||||
pub struct Store {
|
||||
@@ -21,8 +20,9 @@ pub struct Store {
|
||||
|
||||
const SCHEMA_VERSION_KEY: &str = "schema_version";
|
||||
const SEEDED_ENROLL_TOKEN_PREFIX: &str = "seeded_enroll_token:";
|
||||
const SCHEMA_VERSION: u32 = 1;
|
||||
const SCHEMA_VERSION: u32 = 2;
|
||||
|
||||
pub(crate) mod agent_devices;
|
||||
mod alerts;
|
||||
mod audit;
|
||||
mod db;
|
||||
@@ -30,7 +30,6 @@ mod devices;
|
||||
mod enrollment;
|
||||
mod helpers;
|
||||
mod import_sled;
|
||||
mod observations;
|
||||
|
||||
use helpers::alerts_audit::*;
|
||||
use helpers::core::*;
|
||||
@@ -45,20 +44,7 @@ mod tests {
|
||||
use crate::state::{DeviceIdentifierInput, KnownDeviceInput};
|
||||
|
||||
use super::Store;
|
||||
|
||||
async fn make_store() -> (Store, std::path::PathBuf) {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("wakey-cp-store-test-{}", uuid::Uuid::new_v4()));
|
||||
let db_path = dir.join("state.sqlite3");
|
||||
let store = Store::load_or_init(&db_path, Vec::new(), Duration::from_secs(60))
|
||||
.await
|
||||
.expect("store should initialize");
|
||||
(store, dir)
|
||||
}
|
||||
|
||||
fn cleanup_dir(path: &std::path::Path) {
|
||||
let _ = fs::remove_dir_all(path);
|
||||
}
|
||||
use super::helpers::test_helpers::TestStore;
|
||||
|
||||
async fn insert_token(store: &Store, token: &str, expires_at_unix: u64) {
|
||||
sqlx::query(
|
||||
@@ -81,15 +67,16 @@ mod tests {
|
||||
Err(err) => err,
|
||||
};
|
||||
assert!(err.to_string().contains("legacy sled store"));
|
||||
cleanup_dir(&dir);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gc_removes_expired_tokens() {
|
||||
let (store, dir) = make_store().await;
|
||||
insert_token(&store, "enr-expired-gc-test", 1).await;
|
||||
let ts = TestStore::new().await;
|
||||
insert_token(ts.store(), "enr-expired-gc-test", 1).await;
|
||||
|
||||
let removed = store
|
||||
let removed = ts
|
||||
.store()
|
||||
.gc_expired_enroll_tokens()
|
||||
.await
|
||||
.expect("gc should succeed");
|
||||
@@ -98,19 +85,19 @@ mod tests {
|
||||
let exists =
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM enroll_tokens WHERE token = ?1")
|
||||
.bind("enr-expired-gc-test")
|
||||
.fetch_one(&store.pool)
|
||||
.fetch_one(&ts.store().pool)
|
||||
.await
|
||||
.expect("read should succeed");
|
||||
assert_eq!(exists, 0);
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enroll_rejects_expired_token() {
|
||||
let (store, dir) = make_store().await;
|
||||
insert_token(&store, "enr-expired-enroll-test", 1).await;
|
||||
let ts = TestStore::new().await;
|
||||
insert_token(ts.store(), "enr-expired-enroll-test", 1).await;
|
||||
|
||||
let err = store
|
||||
let err = ts
|
||||
.store()
|
||||
.enroll("enr-expired-enroll-test")
|
||||
.await
|
||||
.expect_err("expired token should be rejected");
|
||||
@@ -119,119 +106,122 @@ mod tests {
|
||||
let exists =
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM enroll_tokens WHERE token = ?1")
|
||||
.bind("enr-expired-enroll-test")
|
||||
.fetch_one(&store.pool)
|
||||
.fetch_one(&ts.store().pool)
|
||||
.await
|
||||
.expect("read should succeed");
|
||||
assert_eq!(exists, 0);
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stats_counts_agents_and_expired_tokens() {
|
||||
let (store, dir) = make_store().await;
|
||||
insert_token(&store, "enr-valid-test", i64::MAX as u64).await;
|
||||
let ts = TestStore::new().await;
|
||||
insert_token(ts.store(), "enr-valid-test", i64::MAX as u64).await;
|
||||
|
||||
let _issued = store
|
||||
let _issued = ts
|
||||
.store()
|
||||
.issue_enroll_token(Duration::from_secs(60))
|
||||
.await
|
||||
.expect("issue should succeed");
|
||||
|
||||
insert_token(&store, "enr-expired-stats-test", 1).await;
|
||||
insert_token(ts.store(), "enr-expired-stats-test", 1).await;
|
||||
|
||||
let issued_agent = store
|
||||
let issued_agent = ts
|
||||
.store()
|
||||
.enroll("enr-valid-test")
|
||||
.await
|
||||
.expect("enroll should succeed for valid token");
|
||||
assert!(!issued_agent.agent_id.is_empty());
|
||||
|
||||
let stats = store.stats().await.expect("stats should succeed");
|
||||
let stats = ts.store().stats().await.expect("stats should succeed");
|
||||
|
||||
assert_eq!(stats.agent_count, 1);
|
||||
assert_eq!(stats.enroll_token_count, 2);
|
||||
assert_eq!(stats.expired_enroll_token_count, 1);
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoke_agent_removes_credentials() {
|
||||
let (store, dir) = make_store().await;
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
insert_token(&store, "enr-revoke-agent-test", i64::MAX as u64).await;
|
||||
insert_token(ts.store(), "enr-revoke-agent-test", i64::MAX as u64).await;
|
||||
|
||||
let issued = store
|
||||
let issued = ts
|
||||
.store()
|
||||
.enroll("enr-revoke-agent-test")
|
||||
.await
|
||||
.expect("enroll should succeed");
|
||||
|
||||
assert!(
|
||||
store
|
||||
ts.store()
|
||||
.verify_agent_token(&issued.agent_id, &issued.agent_token)
|
||||
.await
|
||||
);
|
||||
|
||||
let removed = store
|
||||
let removed = ts
|
||||
.store()
|
||||
.revoke_agent(&issued.agent_id)
|
||||
.await
|
||||
.expect("revoke should succeed");
|
||||
assert!(removed);
|
||||
assert!(
|
||||
!store
|
||||
!ts.store()
|
||||
.verify_agent_token(&issued.agent_id, &issued.agent_token)
|
||||
.await
|
||||
);
|
||||
|
||||
let removed_again = store
|
||||
let removed_again = ts
|
||||
.store()
|
||||
.revoke_agent(&issued.agent_id)
|
||||
.await
|
||||
.expect("second revoke should succeed");
|
||||
assert!(!removed_again);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nickname_set_and_clear_roundtrip() {
|
||||
let (store, dir) = make_store().await;
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
insert_token(&store, "enr-nickname-test", i64::MAX as u64).await;
|
||||
insert_token(ts.store(), "enr-nickname-test", i64::MAX as u64).await;
|
||||
|
||||
let issued = store
|
||||
let issued = ts
|
||||
.store()
|
||||
.enroll("enr-nickname-test")
|
||||
.await
|
||||
.expect("enroll should succeed");
|
||||
|
||||
let updated = store
|
||||
let updated = ts
|
||||
.store()
|
||||
.set_agent_nickname(&issued.agent_id, Some("kitchen-router"))
|
||||
.await
|
||||
.expect("nickname set should succeed");
|
||||
assert!(updated);
|
||||
|
||||
let listed = store.list_agents_with_nicknames().await;
|
||||
let listed = ts.store().list_agents_with_nicknames().await;
|
||||
assert!(listed.iter().any(|(id, name)| {
|
||||
id == &issued.agent_id && name.as_deref() == Some("kitchen-router")
|
||||
}));
|
||||
|
||||
let cleared = store
|
||||
let cleared = ts
|
||||
.store()
|
||||
.set_agent_nickname(&issued.agent_id, None)
|
||||
.await
|
||||
.expect("nickname clear should succeed");
|
||||
assert!(cleared);
|
||||
|
||||
let listed = store.list_agents_with_nicknames().await;
|
||||
let listed = ts.store().list_agents_with_nicknames().await;
|
||||
assert!(
|
||||
listed
|
||||
.iter()
|
||||
.any(|(id, name)| id == &issued.agent_id && name.is_none())
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn known_device_can_hold_multiple_manual_mac_identifiers() {
|
||||
let (store, dir) = make_store().await;
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let created = store
|
||||
let created = ts
|
||||
.store()
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda".into(),
|
||||
pinned: true,
|
||||
@@ -249,7 +239,8 @@ mod tests {
|
||||
assert_eq!(created.identifiers.len(), 1);
|
||||
assert_eq!(created.identifiers[0].value, "aa:bb:cc:dd:ee:01");
|
||||
|
||||
let updated = store
|
||||
let updated = ts
|
||||
.store()
|
||||
.attach_device_identifier(
|
||||
&created.device_id,
|
||||
DeviceIdentifierInput {
|
||||
@@ -269,7 +260,8 @@ mod tests {
|
||||
.any(|identifier| identifier.value == "aa:bb:cc:dd:ee:02")
|
||||
);
|
||||
|
||||
let matched = store
|
||||
let matched = ts
|
||||
.store()
|
||||
.lookup_known_device_by_identifier(DeviceIdentifierInput {
|
||||
kind: "mac".into(),
|
||||
value: "aa:bb:cc:dd:ee:02".into(),
|
||||
@@ -278,14 +270,13 @@ mod tests {
|
||||
.expect("lookup should succeed")
|
||||
.expect("identifier should match");
|
||||
assert_eq!(matched.device_id, created.device_id);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn known_device_identifier_is_unique_across_devices() {
|
||||
let (store, dir) = make_store().await;
|
||||
let first = store
|
||||
let ts = TestStore::new().await;
|
||||
let first = ts
|
||||
.store()
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda".into(),
|
||||
pinned: true,
|
||||
@@ -297,7 +288,8 @@ mod tests {
|
||||
})
|
||||
.await
|
||||
.expect("first device should create");
|
||||
let second = store
|
||||
let second = ts
|
||||
.store()
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "other".into(),
|
||||
pinned: false,
|
||||
@@ -307,7 +299,8 @@ mod tests {
|
||||
.await
|
||||
.expect("second device should create");
|
||||
|
||||
let err = store
|
||||
let err = ts
|
||||
.store()
|
||||
.attach_device_identifier(
|
||||
&second.device_id,
|
||||
DeviceIdentifierInput {
|
||||
@@ -322,7 +315,11 @@ mod tests {
|
||||
.contains("failed attaching device identifier")
|
||||
);
|
||||
|
||||
let listed = store.list_known_devices().await.expect("list should work");
|
||||
let listed = ts
|
||||
.store()
|
||||
.list_known_devices()
|
||||
.await
|
||||
.expect("list should work");
|
||||
assert_eq!(listed.len(), 2);
|
||||
assert!(
|
||||
listed
|
||||
@@ -333,14 +330,13 @@ mod tests {
|
||||
.len()
|
||||
== 1
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn device_identifier_can_be_detached_manually() {
|
||||
let (store, dir) = make_store().await;
|
||||
let created = store
|
||||
let ts = TestStore::new().await;
|
||||
let created = ts
|
||||
.store()
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda".into(),
|
||||
pinned: true,
|
||||
@@ -359,7 +355,8 @@ mod tests {
|
||||
.await
|
||||
.expect("known device should create");
|
||||
|
||||
let updated = store
|
||||
let updated = ts
|
||||
.store()
|
||||
.detach_device_identifier(&created.device_id, "ip:192.168.1.2")
|
||||
.await
|
||||
.expect("identifier detach should succeed")
|
||||
@@ -371,7 +368,8 @@ mod tests {
|
||||
"mac:aa:bb:cc:dd:ee:ff"
|
||||
);
|
||||
|
||||
let unmatched = store
|
||||
let unmatched = ts
|
||||
.store()
|
||||
.lookup_known_device_by_identifier(DeviceIdentifierInput {
|
||||
kind: "ip".into(),
|
||||
value: "192.168.1.2".into(),
|
||||
@@ -379,14 +377,13 @@ mod tests {
|
||||
.await
|
||||
.expect("lookup should succeed");
|
||||
assert!(unmatched.is_none());
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn merge_known_devices_moves_identifiers_and_deletes_source() {
|
||||
let (store, dir) = make_store().await;
|
||||
let target = store
|
||||
let ts = TestStore::new().await;
|
||||
let target = ts
|
||||
.store()
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda".into(),
|
||||
pinned: true,
|
||||
@@ -398,7 +395,8 @@ mod tests {
|
||||
})
|
||||
.await
|
||||
.expect("target should create");
|
||||
let source = store
|
||||
let source = ts
|
||||
.store()
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda duplicate".into(),
|
||||
pinned: false,
|
||||
@@ -411,7 +409,8 @@ mod tests {
|
||||
.await
|
||||
.expect("source should create");
|
||||
|
||||
let merged = store
|
||||
let merged = ts
|
||||
.store()
|
||||
.merge_known_devices(&target.device_id, &source.device_id)
|
||||
.await
|
||||
.expect("merge should succeed")
|
||||
@@ -426,362 +425,19 @@ mod tests {
|
||||
.any(|identifier| identifier.value == "aa:bb:cc:dd:ee:02")
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
ts.store()
|
||||
.get_known_device(&source.device_id)
|
||||
.await
|
||||
.expect("source lookup should work")
|
||||
.is_none()
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_observations_upsert_current_state_and_events() {
|
||||
let (store, dir) = make_store().await;
|
||||
|
||||
let accepted = store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:FF".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("observation upsert should succeed");
|
||||
assert_eq!(accepted, 1);
|
||||
|
||||
let rows = store
|
||||
.list_agent_observations(Some("agent-a"), 10)
|
||||
.await
|
||||
.expect("observations should list");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].mac.as_deref(), Some("aa:bb:cc:dd:ee:ff"));
|
||||
assert_eq!(rows[0].hostname.as_deref(), Some("lda"));
|
||||
|
||||
let event_count =
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM agent_device_observation_events")
|
||||
.fetch_one(&store.pool)
|
||||
.await
|
||||
.expect("event count should read");
|
||||
assert_eq!(event_count, 1);
|
||||
|
||||
let accepted = store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:FF".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("duplicate observation upsert should succeed");
|
||||
assert_eq!(accepted, 1);
|
||||
|
||||
let event_count =
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM agent_device_observation_events")
|
||||
.fetch_one(&store.pool)
|
||||
.await
|
||||
.expect("event count should read");
|
||||
assert_eq!(event_count, 1);
|
||||
|
||||
store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "remove".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:FF".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 30,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("changed observation upsert should succeed");
|
||||
|
||||
let events = store
|
||||
.list_agent_observation_events(
|
||||
Some("agent-a"),
|
||||
None,
|
||||
Some("aa:bb:cc:dd:ee:ff"),
|
||||
None,
|
||||
None,
|
||||
10,
|
||||
)
|
||||
.await
|
||||
.expect("observation events should list");
|
||||
assert_eq!(events.len(), 2);
|
||||
assert_eq!(events[0].action, "remove");
|
||||
assert_eq!(
|
||||
events[0].observation_key,
|
||||
"agent:agent-a:dhcp:mac:aa:bb:cc:dd:ee:ff"
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observation_snapshot_prunes_missing_keys() {
|
||||
let (store, dir) = make_store().await;
|
||||
|
||||
store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![
|
||||
crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:01".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("first".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
},
|
||||
crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:02".into()),
|
||||
ip: Some("192.168.1.11".into()),
|
||||
hostname: Some("second".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("initial observations should upsert");
|
||||
|
||||
store
|
||||
.upsert_agent_observations_snapshot(
|
||||
"agent-a",
|
||||
"dhcp",
|
||||
vec![crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:01".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("first".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 30,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("snapshot upsert should succeed");
|
||||
|
||||
let rows = store
|
||||
.list_agent_observations(Some("agent-a"), 10)
|
||||
.await
|
||||
.expect("observations should list");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].mac.as_deref(), Some("aa:bb:cc:dd:ee:01"));
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observation_gc_removes_stale_rows() {
|
||||
let (store, dir) = make_store().await;
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("time should be monotonic")
|
||||
.as_secs();
|
||||
let old = now.saturating_sub(10);
|
||||
|
||||
store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![
|
||||
crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:10".into()),
|
||||
ip: Some("192.168.1.20".into()),
|
||||
hostname: Some("old".into()),
|
||||
first_seen_unix: old,
|
||||
last_seen_unix: old,
|
||||
},
|
||||
crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:11".into()),
|
||||
ip: Some("192.168.1.21".into()),
|
||||
hostname: Some("fresh".into()),
|
||||
first_seen_unix: now,
|
||||
last_seen_unix: now,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("observations should upsert");
|
||||
|
||||
let removed = store
|
||||
.gc_stale_observations(Duration::from_secs(5))
|
||||
.await
|
||||
.expect("gc should succeed");
|
||||
assert!(removed >= 1);
|
||||
|
||||
let rows = store
|
||||
.list_agent_observations(Some("agent-a"), 10)
|
||||
.await
|
||||
.expect("observations should list");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].hostname.as_deref(), Some("fresh"));
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_observation_views_include_matching_known_device() {
|
||||
let (store, dir) = make_store().await;
|
||||
|
||||
let device = store
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda".into(),
|
||||
pinned: true,
|
||||
notes: None,
|
||||
identifiers: vec![DeviceIdentifierInput {
|
||||
kind: "mac".into(),
|
||||
value: "aa:bb:cc:dd:ee:ff".into(),
|
||||
}],
|
||||
})
|
||||
.await
|
||||
.expect("known device should create");
|
||||
|
||||
store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![
|
||||
crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:FF".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
},
|
||||
crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("00:11:22:33:44:55".into()),
|
||||
ip: Some("192.168.1.11".into()),
|
||||
hostname: Some("guest".into()),
|
||||
first_seen_unix: 11,
|
||||
last_seen_unix: 21,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("observation upsert should succeed");
|
||||
|
||||
let rows = store
|
||||
.list_agent_observation_views(Some("agent-a"), 10)
|
||||
.await
|
||||
.expect("observation views should list");
|
||||
assert_eq!(rows.len(), 2);
|
||||
|
||||
let known = rows
|
||||
.iter()
|
||||
.find(|row| row.mac.as_deref() == Some("aa:bb:cc:dd:ee:ff"))
|
||||
.expect("known observation should be present");
|
||||
let known_device = known
|
||||
.known_device
|
||||
.as_ref()
|
||||
.expect("known observation should join device");
|
||||
assert_eq!(known_device.device_id, device.device_id);
|
||||
assert_eq!(known_device.display_name, "lda");
|
||||
assert!(known_device.pinned);
|
||||
|
||||
let unknown = rows
|
||||
.iter()
|
||||
.find(|row| row.mac.as_deref() == Some("00:11:22:33:44:55"))
|
||||
.expect("unknown observation should be present");
|
||||
assert!(unknown.known_device.is_none());
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observation_identifier_can_be_attached_to_known_device() {
|
||||
let (store, dir) = make_store().await;
|
||||
|
||||
let device = store
|
||||
.create_known_device(KnownDeviceInput {
|
||||
display_name: "lda".into(),
|
||||
pinned: true,
|
||||
notes: None,
|
||||
identifiers: Vec::new(),
|
||||
})
|
||||
.await
|
||||
.expect("known device should create");
|
||||
|
||||
store
|
||||
.upsert_agent_observations(
|
||||
"agent-a",
|
||||
vec![crate::state::AgentDeviceObservationInput {
|
||||
kind: "dhcp".into(),
|
||||
action: "update".into(),
|
||||
mac: Some("AA:BB:CC:DD:EE:FF".into()),
|
||||
ip: Some("192.168.1.10".into()),
|
||||
hostname: Some("lda".into()),
|
||||
first_seen_unix: 10,
|
||||
last_seen_unix: 20,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("observation upsert should succeed");
|
||||
|
||||
let observation = store
|
||||
.list_agent_observations(Some("agent-a"), 10)
|
||||
.await
|
||||
.expect("observations should list")
|
||||
.pop()
|
||||
.expect("observation should exist");
|
||||
|
||||
let updated = store
|
||||
.attach_observation_identifier(&device.device_id, &observation.observation_key)
|
||||
.await
|
||||
.expect("observation identifier should attach")
|
||||
.expect("device should exist");
|
||||
|
||||
assert_eq!(updated.identifiers.len(), 1);
|
||||
assert_eq!(updated.identifiers[0].kind, "mac");
|
||||
assert_eq!(updated.identifiers[0].value, "aa:bb:cc:dd:ee:ff");
|
||||
|
||||
let views = store
|
||||
.list_agent_observation_views(Some("agent-a"), 10)
|
||||
.await
|
||||
.expect("observation views should list");
|
||||
assert_eq!(
|
||||
views[0]
|
||||
.known_device
|
||||
.as_ref()
|
||||
.map(|device| device.device_id.as_str()),
|
||||
Some(device.device_id.as_str())
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn audit_events_append_and_filter() {
|
||||
let (store, dir) = make_store().await;
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
store
|
||||
ts.store()
|
||||
.append_audit_event(crate::state::AuditEventInput {
|
||||
actor_type: "admin_api".into(),
|
||||
actor_id: None,
|
||||
@@ -796,7 +452,7 @@ mod tests {
|
||||
.await
|
||||
.expect("append first event should succeed");
|
||||
|
||||
store
|
||||
ts.store()
|
||||
.append_audit_event(crate::state::AuditEventInput {
|
||||
actor_type: "agent".into(),
|
||||
actor_id: Some("agent-2".into()),
|
||||
@@ -811,7 +467,8 @@ mod tests {
|
||||
.await
|
||||
.expect("append second event should succeed");
|
||||
|
||||
let all = store
|
||||
let all = ts
|
||||
.store()
|
||||
.list_audit_events(crate::state::AuditEventFilter {
|
||||
limit: 10,
|
||||
..Default::default()
|
||||
@@ -820,7 +477,8 @@ mod tests {
|
||||
.expect("list all should succeed");
|
||||
assert_eq!(all.len(), 2);
|
||||
|
||||
let filtered = store
|
||||
let filtered = ts
|
||||
.store()
|
||||
.list_audit_events(crate::state::AuditEventFilter {
|
||||
agent_id: Some("agent-1".into()),
|
||||
event_type: Some("command_result".into()),
|
||||
@@ -833,7 +491,8 @@ mod tests {
|
||||
assert_eq!(filtered.len(), 1);
|
||||
assert_eq!(filtered[0].request_id.as_deref(), Some("req-1"));
|
||||
|
||||
let rejected = store
|
||||
let rejected = ts
|
||||
.store()
|
||||
.list_audit_events(crate::state::AuditEventFilter {
|
||||
outcome: Some("rejected".into()),
|
||||
limit: 10,
|
||||
@@ -843,12 +502,11 @@ mod tests {
|
||||
.expect("rejected list should succeed");
|
||||
assert_eq!(rejected.len(), 1);
|
||||
assert_eq!(rejected[0].latency_ms, None);
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn alert_transitions_track_open_and_resolve() {
|
||||
let (store, dir) = make_store().await;
|
||||
let ts = TestStore::new().await;
|
||||
let alert = crate::state::AlertState {
|
||||
alert_id: "agent_offline:agent-a".into(),
|
||||
kind: "agent_offline".into(),
|
||||
@@ -862,26 +520,28 @@ mod tests {
|
||||
metadata: serde_json::json!({}),
|
||||
};
|
||||
|
||||
let opened = store
|
||||
let opened = ts
|
||||
.store()
|
||||
.sync_alert_transitions(std::slice::from_ref(&alert))
|
||||
.await
|
||||
.expect("open transition should succeed");
|
||||
assert_eq!(opened.len(), 1);
|
||||
assert_eq!(opened[0].to_status, "active");
|
||||
|
||||
let resolved = store
|
||||
let resolved = ts
|
||||
.store()
|
||||
.sync_alert_transitions(&[])
|
||||
.await
|
||||
.expect("resolve transition should succeed");
|
||||
assert_eq!(resolved.len(), 1);
|
||||
assert_eq!(resolved[0].to_status, "resolved");
|
||||
|
||||
let history = store
|
||||
let history = ts
|
||||
.store()
|
||||
.list_alert_transitions(None, 10)
|
||||
.await
|
||||
.expect("history should load");
|
||||
assert!(history.len() >= 2);
|
||||
cleanup_dir(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -923,7 +583,7 @@ mod tests {
|
||||
.contains("invalid or already-used enroll token")
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -984,6 +644,6 @@ mod tests {
|
||||
.any(|token| token.enroll_token == "enr-import-test")
|
||||
);
|
||||
|
||||
cleanup_dir(&dir);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,608 @@
|
||||
use anyhow::{Context, Result};
|
||||
use wakey_core::{Device, DeviceId};
|
||||
|
||||
use super::Store;
|
||||
use super::helpers::core::*;
|
||||
use crate::state::types::*;
|
||||
|
||||
impl Store {
|
||||
/// Replace the complete device snapshot for an agent.
|
||||
///
|
||||
/// This is the only write path for agent device state. Every sync source
|
||||
/// (WebSocket snapshot, fleet refresh, HTTP upload) must go through here.
|
||||
pub async fn replace_agent_device_snapshot(
|
||||
&self,
|
||||
agent_id: &str,
|
||||
devices: &[Device],
|
||||
) -> Result<usize> {
|
||||
let mut tx = self
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.context("failed starting device snapshot transaction")?;
|
||||
|
||||
let mut incoming_keys = std::collections::HashSet::with_capacity(devices.len());
|
||||
let snapshot_time = now_unix();
|
||||
let snapshot_time_i64 = i64::try_from(snapshot_time).context("snapshot time overflow")?;
|
||||
|
||||
let existing_keys: Vec<String> =
|
||||
sqlx::query_scalar("SELECT device_key FROM agent_devices WHERE agent_id = ?1")
|
||||
.bind(agent_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await
|
||||
.context("failed fetching existing keys")?;
|
||||
|
||||
for device in devices {
|
||||
let Some(device_id) = &device.id else {
|
||||
continue;
|
||||
};
|
||||
let device_key = device_key_from_id(device_id);
|
||||
incoming_keys.insert(device_key.clone());
|
||||
|
||||
let presence = presence_to_str(device.presence);
|
||||
let display_name: Option<String> = None;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_devices (agent_id, device_key, presence, display_name, first_seen_unix, last_seen_unix)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
||||
ON CONFLICT (agent_id, device_key) DO UPDATE SET
|
||||
presence = excluded.presence,
|
||||
last_seen_unix = excluded.last_seen_unix",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.bind(presence)
|
||||
.bind(&display_name)
|
||||
.bind(snapshot_time_i64)
|
||||
.bind(snapshot_time_i64)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed upserting agent device")?;
|
||||
|
||||
// Replace child rows.
|
||||
sqlx::query("DELETE FROM agent_device_macs WHERE agent_id = ?1 AND device_key = ?2")
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed deleting device macs")?;
|
||||
|
||||
for mac in &device.macs {
|
||||
let mac_str = mac.to_string().to_ascii_lowercase();
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_device_macs (agent_id, device_key, mac) VALUES (?1, ?2, ?3)",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.bind(&mac_str)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed inserting device mac")?;
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM agent_device_ips WHERE agent_id = ?1 AND device_key = ?2")
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed deleting device ips")?;
|
||||
|
||||
for ip in &device.ips {
|
||||
let ip_str = ip.to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_device_ips (agent_id, device_key, ip) VALUES (?1, ?2, ?3)",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.bind(&ip_str)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed inserting device ip")?;
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"DELETE FROM agent_device_hostnames WHERE agent_id = ?1 AND device_key = ?2",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed deleting device hostnames")?;
|
||||
|
||||
for hostname in &device.names {
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_device_hostnames (agent_id, device_key, hostname) VALUES (?1, ?2, ?3)",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.bind(hostname)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed inserting device hostname")?;
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM agent_device_facts WHERE agent_id = ?1 AND device_key = ?2")
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed deleting device facts")?;
|
||||
|
||||
for observation in &device.observations {
|
||||
let fact_json =
|
||||
serde_json::to_string(observation).context("failed serializing fact")?;
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_device_facts (agent_id, device_key, fact_json) VALUES (?1, ?2, ?3)",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(&device_key)
|
||||
.bind(&fact_json)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed inserting device fact")?;
|
||||
}
|
||||
}
|
||||
|
||||
for old_key in existing_keys {
|
||||
if !incoming_keys.contains(&old_key) {
|
||||
sqlx::query("DELETE FROM agent_devices WHERE agent_id = ?1 AND device_key = ?2")
|
||||
.bind(agent_id)
|
||||
.bind(&old_key)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("failed pruning old agent device")?;
|
||||
}
|
||||
}
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.context("failed committing device snapshot")?;
|
||||
|
||||
Ok(incoming_keys.len())
|
||||
}
|
||||
|
||||
/// List all agent device rows with their child MAC/IP/hostname/fact rows.
|
||||
pub async fn list_agent_device_rows(&self) -> Result<Vec<AgentDeviceWithChildren>> {
|
||||
let devices = sqlx::query_as!(
|
||||
AgentDeviceRow,
|
||||
r#"SELECT agent_id, device_key, presence, display_name,
|
||||
first_seen_unix, last_seen_unix
|
||||
FROM agent_devices
|
||||
ORDER BY agent_id, device_key"#,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent devices")?;
|
||||
|
||||
let macs = sqlx::query_as!(
|
||||
AgentDeviceMacRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", mac as "mac!"
|
||||
FROM agent_device_macs"#,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device macs")?;
|
||||
|
||||
let ips = sqlx::query_as!(
|
||||
AgentDeviceIpRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", ip as "ip!"
|
||||
FROM agent_device_ips"#,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device ips")?;
|
||||
|
||||
let hostnames = sqlx::query_as!(
|
||||
AgentDeviceHostnameRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", hostname as "hostname!"
|
||||
FROM agent_device_hostnames"#,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device hostnames")?;
|
||||
|
||||
let facts = sqlx::query_as!(
|
||||
AgentDeviceFactRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", fact_json as "fact_json!"
|
||||
FROM agent_device_facts"#,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device facts")?;
|
||||
|
||||
Ok(assemble_device_rows(devices, macs, ips, hostnames, facts))
|
||||
}
|
||||
|
||||
/// List agent device rows for a single agent.
|
||||
#[allow(dead_code)]
|
||||
pub async fn list_agent_device_rows_for_agent(
|
||||
&self,
|
||||
agent_id: &str,
|
||||
) -> Result<Vec<AgentDeviceWithChildren>> {
|
||||
let devices = sqlx::query_as!(
|
||||
AgentDeviceRow,
|
||||
r#"SELECT agent_id, device_key, presence, display_name,
|
||||
first_seen_unix, last_seen_unix
|
||||
FROM agent_devices
|
||||
WHERE agent_id = ?1
|
||||
ORDER BY device_key"#,
|
||||
agent_id,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent devices for agent")?;
|
||||
|
||||
let macs = sqlx::query_as!(
|
||||
AgentDeviceMacRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", mac as "mac!"
|
||||
FROM agent_device_macs
|
||||
WHERE agent_id = ?1"#,
|
||||
agent_id,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device macs for agent")?;
|
||||
|
||||
let ips = sqlx::query_as!(
|
||||
AgentDeviceIpRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", ip as "ip!"
|
||||
FROM agent_device_ips
|
||||
WHERE agent_id = ?1"#,
|
||||
agent_id,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device ips for agent")?;
|
||||
|
||||
let hostnames = sqlx::query_as!(
|
||||
AgentDeviceHostnameRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", hostname as "hostname!"
|
||||
FROM agent_device_hostnames
|
||||
WHERE agent_id = ?1"#,
|
||||
agent_id,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device hostnames for agent")?;
|
||||
|
||||
let facts = sqlx::query_as!(
|
||||
AgentDeviceFactRow,
|
||||
r#"SELECT agent_id as "agent_id!", device_key as "device_key!", fact_json as "fact_json!"
|
||||
FROM agent_device_facts
|
||||
WHERE agent_id = ?1"#,
|
||||
agent_id,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.context("failed listing agent device facts for agent")?;
|
||||
|
||||
Ok(assemble_device_rows(devices, macs, ips, hostnames, facts))
|
||||
}
|
||||
}
|
||||
|
||||
fn assemble_device_rows(
|
||||
devices: Vec<AgentDeviceRow>,
|
||||
macs: Vec<AgentDeviceMacRow>,
|
||||
ips: Vec<AgentDeviceIpRow>,
|
||||
hostnames: Vec<AgentDeviceHostnameRow>,
|
||||
facts: Vec<AgentDeviceFactRow>,
|
||||
) -> Vec<AgentDeviceWithChildren> {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
let mut mac_map: BTreeMap<(&str, &str), Vec<&AgentDeviceMacRow>> = BTreeMap::new();
|
||||
for row in &macs {
|
||||
mac_map
|
||||
.entry((row.agent_id.as_str(), row.device_key.as_str()))
|
||||
.or_default()
|
||||
.push(row);
|
||||
}
|
||||
let mut ip_map: BTreeMap<(&str, &str), Vec<&AgentDeviceIpRow>> = BTreeMap::new();
|
||||
for row in &ips {
|
||||
ip_map
|
||||
.entry((row.agent_id.as_str(), row.device_key.as_str()))
|
||||
.or_default()
|
||||
.push(row);
|
||||
}
|
||||
let mut hostname_map: BTreeMap<(&str, &str), Vec<String>> = BTreeMap::new();
|
||||
for row in &hostnames {
|
||||
hostname_map
|
||||
.entry((row.agent_id.as_str(), row.device_key.as_str()))
|
||||
.or_default()
|
||||
.push(row.hostname.clone());
|
||||
}
|
||||
let mut fact_map: BTreeMap<(&str, &str), Vec<String>> = BTreeMap::new();
|
||||
for row in &facts {
|
||||
fact_map
|
||||
.entry((row.agent_id.as_str(), row.device_key.as_str()))
|
||||
.or_default()
|
||||
.push(row.fact_json.clone());
|
||||
}
|
||||
|
||||
devices
|
||||
.into_iter()
|
||||
.map(|device| {
|
||||
let key = (device.agent_id.as_str(), device.device_key.as_str());
|
||||
let macs: Vec<macaddr::MacAddr> = mac_map
|
||||
.get(&key)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|row| macaddr::MacAddr::try_from(*row).ok())
|
||||
.collect();
|
||||
let ips: Vec<std::net::IpAddr> = ip_map
|
||||
.get(&key)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|row| std::net::IpAddr::try_from(*row).ok())
|
||||
.collect();
|
||||
let hostnames = hostname_map.get(&key).cloned().unwrap_or_default();
|
||||
let facts = fact_map.get(&key).cloned().unwrap_or_default();
|
||||
AgentDeviceWithChildren {
|
||||
macs,
|
||||
ips,
|
||||
hostnames,
|
||||
facts,
|
||||
device,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn device_key_from_id(device_id: &DeviceId) -> String {
|
||||
match device_id {
|
||||
DeviceId::Mac(mac) => format!("mac:{}", mac.to_string().to_ascii_lowercase()),
|
||||
DeviceId::Ip(ip) => format!("ip:{ip}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn presence_to_str(presence: wakey_core::Presence) -> &'static str {
|
||||
match presence {
|
||||
wakey_core::Presence::Online => "online",
|
||||
wakey_core::Presence::LikelyOnline => "likely_online",
|
||||
wakey_core::Presence::Unknown => "unknown",
|
||||
wakey_core::Presence::Offline => "offline",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::helpers::test_helpers::TestStore;
|
||||
use std::time::Duration;
|
||||
use wakey_core::{
|
||||
Device, DeviceId, DeviceObservationFact, NeighborEntry, NeighborState, Presence,
|
||||
};
|
||||
|
||||
fn sample_device(mac: &str, ip: &str, name: &str) -> Device {
|
||||
Device {
|
||||
id: Some(DeviceId::Mac(mac.parse().expect("mac"))),
|
||||
names: vec![name.to_string()],
|
||||
ips: vec![ip.parse().expect("ip")],
|
||||
macs: vec![mac.parse().expect("mac")],
|
||||
interfaces: vec!["br-lan".to_string()],
|
||||
neighbors: vec![NeighborEntry {
|
||||
ip: ip.parse().expect("ip"),
|
||||
dev: Some("br-lan".to_string()),
|
||||
mac: Some(mac.parse().expect("mac")),
|
||||
state: NeighborState::Reachable,
|
||||
}],
|
||||
leases: vec![],
|
||||
observations: vec![],
|
||||
presence: Presence::Online,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_inserts_devices_and_children() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let devices = vec![sample_device(
|
||||
"aa:bb:cc:dd:ee:01",
|
||||
"192.168.1.10",
|
||||
"first-pc",
|
||||
)];
|
||||
let count = ts
|
||||
.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices)
|
||||
.await
|
||||
.expect("snapshot should succeed");
|
||||
assert_eq!(count, 1);
|
||||
|
||||
let rows = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].device.device_key, "mac:aa:bb:cc:dd:ee:01");
|
||||
assert_eq!(rows[0].device.presence, "online");
|
||||
assert_eq!(
|
||||
rows[0].macs,
|
||||
vec!["aa:bb:cc:dd:ee:01".parse::<macaddr::MacAddr>().unwrap()]
|
||||
);
|
||||
assert_eq!(
|
||||
rows[0].ips,
|
||||
vec!["192.168.1.10".parse::<std::net::IpAddr>().unwrap()]
|
||||
);
|
||||
assert_eq!(rows[0].hostnames, vec!["first-pc"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn second_snapshot_prunes_missing_devices() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let first = vec![
|
||||
sample_device("aa:bb:cc:dd:ee:01", "192.168.1.10", "first"),
|
||||
sample_device("aa:bb:cc:dd:ee:02", "192.168.1.11", "second"),
|
||||
];
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &first)
|
||||
.await
|
||||
.expect("first snapshot should succeed");
|
||||
|
||||
let second = vec![sample_device("aa:bb:cc:dd:ee:01", "192.168.1.10", "first")];
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &second)
|
||||
.await
|
||||
.expect("second snapshot should succeed");
|
||||
|
||||
let rows = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].device.device_key, "mac:aa:bb:cc:dd:ee:01");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_snapshot_clears_devices() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let devices = vec![sample_device("aa:bb:cc:dd:ee:01", "192.168.1.10", "first")];
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices)
|
||||
.await
|
||||
.expect("snapshot should succeed");
|
||||
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &[])
|
||||
.await
|
||||
.expect("empty snapshot should succeed");
|
||||
|
||||
let rows = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(rows.len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_seen_survives_snapshot_update() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let devices = vec![sample_device("aa:bb:cc:dd:ee:01", "192.168.1.10", "first")];
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices)
|
||||
.await
|
||||
.expect("first snapshot should succeed");
|
||||
|
||||
let first_seen = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed")[0]
|
||||
.device
|
||||
.first_seen_unix;
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices)
|
||||
.await
|
||||
.expect("second snapshot should succeed");
|
||||
|
||||
let rows = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(rows[0].device.first_seen_unix, first_seen);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_does_not_prune_other_agents() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let devices_a = vec![sample_device("aa:bb:cc:dd:ee:01", "192.168.1.10", "first")];
|
||||
let devices_b = vec![sample_device("aa:bb:cc:dd:ee:02", "192.168.1.11", "second")];
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices_a)
|
||||
.await
|
||||
.expect("snapshot a should succeed");
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-b", &devices_b)
|
||||
.await
|
||||
.expect("snapshot b should succeed");
|
||||
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &[])
|
||||
.await
|
||||
.expect("clear a should succeed");
|
||||
|
||||
let rows_b = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-b")
|
||||
.await
|
||||
.expect("list b should succeed");
|
||||
assert_eq!(rows_b.len(), 1);
|
||||
assert_eq!(rows_b[0].device.device_key, "mac:aa:bb:cc:dd:ee:02");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn device_without_id_is_skipped() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let devices = vec![Device {
|
||||
id: None,
|
||||
names: vec!["no-id".to_string()],
|
||||
ips: vec![],
|
||||
macs: vec![],
|
||||
interfaces: vec![],
|
||||
neighbors: vec![],
|
||||
leases: vec![],
|
||||
observations: vec![],
|
||||
presence: Presence::Unknown,
|
||||
}];
|
||||
let count = ts
|
||||
.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices)
|
||||
.await
|
||||
.expect("snapshot should succeed");
|
||||
assert_eq!(count, 0);
|
||||
|
||||
let rows = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(rows.len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn facts_are_stored_as_json() {
|
||||
let ts = TestStore::new().await;
|
||||
|
||||
let devices = vec![Device {
|
||||
id: Some(DeviceId::Mac("aa:bb:cc:dd:ee:01".parse().expect("mac"))),
|
||||
names: vec!["pc".to_string()],
|
||||
ips: vec!["192.168.1.10".parse().expect("ip")],
|
||||
macs: vec!["aa:bb:cc:dd:ee:01".parse().expect("mac")],
|
||||
interfaces: vec![],
|
||||
neighbors: vec![],
|
||||
leases: vec![],
|
||||
observations: vec![DeviceObservationFact {
|
||||
kind: "dhcp".to_string(),
|
||||
action: "update".to_string(),
|
||||
mac: Some("aa:bb:cc:dd:ee:01".parse().expect("mac")),
|
||||
ip: Some("192.168.1.10".parse().expect("ip")),
|
||||
hostname: Some("pc".to_string()),
|
||||
first_seen_unix: Some(10),
|
||||
last_seen_unix: Some(20),
|
||||
}],
|
||||
presence: Presence::LikelyOnline,
|
||||
}];
|
||||
ts.store()
|
||||
.replace_agent_device_snapshot("agent-a", &devices)
|
||||
.await
|
||||
.expect("snapshot should succeed");
|
||||
|
||||
let rows = ts
|
||||
.store()
|
||||
.list_agent_device_rows_for_agent("agent-a")
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].facts.len(), 1);
|
||||
assert!(rows[0].facts[0].contains("dhcp"));
|
||||
}
|
||||
}
|
||||
@@ -181,21 +181,6 @@ impl Store {
|
||||
self.get_known_device(device_id).await
|
||||
}
|
||||
|
||||
pub async fn attach_observation_identifier(
|
||||
&self,
|
||||
device_id: &str,
|
||||
observation_key: &str,
|
||||
) -> Result<Option<KnownDevice>> {
|
||||
let observation = get_observation_identifier_row(&self.pool, observation_key).await?;
|
||||
|
||||
let Some(observation) = observation else {
|
||||
anyhow::bail!("observation not found");
|
||||
};
|
||||
let input = observation_identifier_to_input(observation)?;
|
||||
|
||||
self.attach_device_identifier(device_id, input).await
|
||||
}
|
||||
|
||||
pub async fn detach_device_identifier(
|
||||
&self,
|
||||
device_id: &str,
|
||||
|
||||
@@ -4,3 +4,5 @@ pub(super) mod alerts_audit;
|
||||
pub(super) mod core;
|
||||
pub(super) mod legacy;
|
||||
pub(super) mod rows;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_helpers;
|
||||
|
||||
@@ -1,159 +1,162 @@
|
||||
use super::*;
|
||||
|
||||
pub(in crate::state::store) async fn insert_audit_event(
|
||||
pool: &SqlitePool,
|
||||
key: &str,
|
||||
event: &AuditEvent,
|
||||
) -> Result<()> {
|
||||
pub async fn insert_audit_event(pool: &SqlitePool, key: &str, event: &AuditEvent) -> Result<()> {
|
||||
let metadata_json =
|
||||
serde_json::to_string(&event.metadata).context("failed to encode audit metadata")?;
|
||||
sqlx::query(
|
||||
let ts_unix = i64::try_from(event.ts_unix).context("audit timestamp overflow")?;
|
||||
let latency_ms = event
|
||||
.latency_ms
|
||||
.map(i64::try_from)
|
||||
.transpose()
|
||||
.context("audit latency overflow")?;
|
||||
sqlx::query!(
|
||||
"INSERT OR REPLACE INTO audit_events
|
||||
(event_key, event_id, ts_unix, actor_type, actor_id, agent_id, request_id,
|
||||
event_type, outcome, latency_ms, message, metadata_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
key,
|
||||
event.event_id,
|
||||
ts_unix,
|
||||
event.actor_type,
|
||||
event.actor_id,
|
||||
event.agent_id,
|
||||
event.request_id,
|
||||
event.event_type,
|
||||
event.outcome,
|
||||
latency_ms,
|
||||
event.message,
|
||||
metadata_json
|
||||
)
|
||||
.bind(key)
|
||||
.bind(&event.event_id)
|
||||
.bind(i64::try_from(event.ts_unix).context("audit timestamp overflow")?)
|
||||
.bind(&event.actor_type)
|
||||
.bind(&event.actor_id)
|
||||
.bind(&event.agent_id)
|
||||
.bind(&event.request_id)
|
||||
.bind(&event.event_type)
|
||||
.bind(&event.outcome)
|
||||
.bind(
|
||||
event
|
||||
.latency_ms
|
||||
.map(i64::try_from)
|
||||
.transpose()
|
||||
.context("audit latency overflow")?,
|
||||
)
|
||||
.bind(&event.message)
|
||||
.bind(metadata_json)
|
||||
.execute(pool)
|
||||
.await
|
||||
.context("failed persisting audit event")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn insert_active_alert(
|
||||
pub async fn insert_active_alert(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
alert: &AlertState,
|
||||
) -> Result<()> {
|
||||
let metadata_json =
|
||||
serde_json::to_string(&alert.metadata).context("failed to encode active alert metadata")?;
|
||||
sqlx::query(
|
||||
let alert_value = i64::try_from(alert.value).context("active alert value overflow")?;
|
||||
let alert_threshold =
|
||||
i64::try_from(alert.threshold).context("active alert threshold overflow")?;
|
||||
let last_seen_unix =
|
||||
i64::try_from(alert.last_seen_unix).context("active alert timestamp overflow")?;
|
||||
sqlx::query!(
|
||||
"INSERT INTO active_alerts
|
||||
(alert_id, kind, severity, status, agent_id, message, value, threshold,
|
||||
last_seen_unix, metadata_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
alert.alert_id,
|
||||
alert.kind,
|
||||
alert.severity,
|
||||
alert.status,
|
||||
alert.agent_id,
|
||||
alert.message,
|
||||
alert_value,
|
||||
alert_threshold,
|
||||
last_seen_unix,
|
||||
metadata_json
|
||||
)
|
||||
.bind(&alert.alert_id)
|
||||
.bind(&alert.kind)
|
||||
.bind(&alert.severity)
|
||||
.bind(&alert.status)
|
||||
.bind(&alert.agent_id)
|
||||
.bind(&alert.message)
|
||||
.bind(i64::try_from(alert.value).context("active alert value overflow")?)
|
||||
.bind(i64::try_from(alert.threshold).context("active alert threshold overflow")?)
|
||||
.bind(i64::try_from(alert.last_seen_unix).context("active alert timestamp overflow")?)
|
||||
.bind(metadata_json)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.context("failed writing active alert snapshot")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn insert_active_alert_pool(
|
||||
pool: &SqlitePool,
|
||||
alert: &AlertState,
|
||||
) -> Result<()> {
|
||||
pub async fn insert_active_alert_pool(pool: &SqlitePool, alert: &AlertState) -> Result<()> {
|
||||
let metadata_json =
|
||||
serde_json::to_string(&alert.metadata).context("failed to encode active alert metadata")?;
|
||||
sqlx::query(
|
||||
let alert_value = i64::try_from(alert.value).context("active alert value overflow")?;
|
||||
let alert_threshold =
|
||||
i64::try_from(alert.threshold).context("active alert threshold overflow")?;
|
||||
let last_seen_unix =
|
||||
i64::try_from(alert.last_seen_unix).context("active alert timestamp overflow")?;
|
||||
sqlx::query!(
|
||||
"INSERT OR REPLACE INTO active_alerts
|
||||
(alert_id, kind, severity, status, agent_id, message, value, threshold,
|
||||
last_seen_unix, metadata_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
alert.alert_id,
|
||||
alert.kind,
|
||||
alert.severity,
|
||||
alert.status,
|
||||
alert.agent_id,
|
||||
alert.message,
|
||||
alert_value,
|
||||
alert_threshold,
|
||||
last_seen_unix,
|
||||
metadata_json
|
||||
)
|
||||
.bind(&alert.alert_id)
|
||||
.bind(&alert.kind)
|
||||
.bind(&alert.severity)
|
||||
.bind(&alert.status)
|
||||
.bind(&alert.agent_id)
|
||||
.bind(&alert.message)
|
||||
.bind(i64::try_from(alert.value).context("active alert value overflow")?)
|
||||
.bind(i64::try_from(alert.threshold).context("active alert threshold overflow")?)
|
||||
.bind(i64::try_from(alert.last_seen_unix).context("active alert timestamp overflow")?)
|
||||
.bind(metadata_json)
|
||||
.execute(pool)
|
||||
.await
|
||||
.context("failed writing active alert snapshot")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn insert_alert_transition(
|
||||
pub async fn insert_alert_transition(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
key: &str,
|
||||
transition: &AlertTransition,
|
||||
) -> Result<()> {
|
||||
let metadata_json = serde_json::to_string(&transition.metadata)
|
||||
.context("failed to encode alert transition metadata")?;
|
||||
sqlx::query(
|
||||
let ts_unix = i64::try_from(transition.ts_unix).context("alert timestamp overflow")?;
|
||||
sqlx::query!(
|
||||
"INSERT INTO alert_transitions
|
||||
(transition_key, transition_id, ts_unix, alert_id, kind, agent_id,
|
||||
from_status, to_status, message, metadata_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
key,
|
||||
transition.transition_id,
|
||||
ts_unix,
|
||||
transition.alert_id,
|
||||
transition.kind,
|
||||
transition.agent_id,
|
||||
transition.from_status,
|
||||
transition.to_status,
|
||||
transition.message,
|
||||
metadata_json
|
||||
)
|
||||
.bind(key)
|
||||
.bind(&transition.transition_id)
|
||||
.bind(i64::try_from(transition.ts_unix).context("alert timestamp overflow")?)
|
||||
.bind(&transition.alert_id)
|
||||
.bind(&transition.kind)
|
||||
.bind(&transition.agent_id)
|
||||
.bind(&transition.from_status)
|
||||
.bind(&transition.to_status)
|
||||
.bind(&transition.message)
|
||||
.bind(metadata_json)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.context("failed persisting alert transition")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn insert_alert_transition_pool(
|
||||
pub async fn insert_alert_transition_pool(
|
||||
pool: &SqlitePool,
|
||||
key: &str,
|
||||
transition: &AlertTransition,
|
||||
) -> Result<()> {
|
||||
let metadata_json = serde_json::to_string(&transition.metadata)
|
||||
.context("failed to encode alert transition metadata")?;
|
||||
sqlx::query(
|
||||
let ts_unix = i64::try_from(transition.ts_unix).context("alert timestamp overflow")?;
|
||||
sqlx::query!(
|
||||
"INSERT OR REPLACE INTO alert_transitions
|
||||
(transition_key, transition_id, ts_unix, alert_id, kind, agent_id,
|
||||
from_status, to_status, message, metadata_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
key,
|
||||
transition.transition_id,
|
||||
ts_unix,
|
||||
transition.alert_id,
|
||||
transition.kind,
|
||||
transition.agent_id,
|
||||
transition.from_status,
|
||||
transition.to_status,
|
||||
transition.message,
|
||||
metadata_json
|
||||
)
|
||||
.bind(key)
|
||||
.bind(&transition.transition_id)
|
||||
.bind(i64::try_from(transition.ts_unix).context("alert timestamp overflow")?)
|
||||
.bind(&transition.alert_id)
|
||||
.bind(&transition.kind)
|
||||
.bind(&transition.agent_id)
|
||||
.bind(&transition.from_status)
|
||||
.bind(&transition.to_status)
|
||||
.bind(&transition.message)
|
||||
.bind(metadata_json)
|
||||
.execute(pool)
|
||||
.await
|
||||
.context("failed persisting alert transition")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn audit_event_from_row(
|
||||
row: sqlx::sqlite::SqliteRow,
|
||||
) -> Result<AuditEvent> {
|
||||
pub fn audit_event_from_row(row: sqlx::sqlite::SqliteRow) -> Result<AuditEvent> {
|
||||
let ts_unix: i64 = row.try_get("ts_unix")?;
|
||||
let latency_ms: Option<i64> = row.try_get("latency_ms")?;
|
||||
let metadata_json: String = row.try_get("metadata_json")?;
|
||||
@@ -175,7 +178,7 @@ pub(in crate::state::store) fn audit_event_from_row(
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn alert_state_from_row(row: AlertStateRow) -> Result<AlertState> {
|
||||
pub fn alert_state_from_row(row: AlertStateRow) -> Result<AlertState> {
|
||||
Ok(AlertState {
|
||||
alert_id: row.alert_id,
|
||||
kind: row.kind,
|
||||
@@ -193,9 +196,7 @@ pub(in crate::state::store) fn alert_state_from_row(row: AlertStateRow) -> Resul
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn alert_transition_from_row(
|
||||
row: AlertTransitionRow,
|
||||
) -> Result<AlertTransition> {
|
||||
pub fn alert_transition_from_row(row: AlertTransitionRow) -> Result<AlertTransition> {
|
||||
Ok(AlertTransition {
|
||||
transition_id: row.transition_id,
|
||||
ts_unix: u64::try_from(row.ts_unix).context("negative alert timestamp in state db")?,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
pub(in crate::state::store) async fn open_sqlite_pool(path: &Path) -> Result<SqlitePool> {
|
||||
pub async fn open_sqlite_pool(path: &Path) -> Result<SqlitePool> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.create_if_missing(true)
|
||||
@@ -14,7 +14,7 @@ pub(in crate::state::store) async fn open_sqlite_pool(path: &Path) -> Result<Sql
|
||||
.with_context(|| format!("failed to open SQLite state db {}", path.display()))
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn sql_count(pool: &SqlitePool, table: &str) -> Result<i64> {
|
||||
pub async fn sql_count(pool: &SqlitePool, table: &str) -> Result<i64> {
|
||||
let sql = format!("SELECT COUNT(*) FROM {table}");
|
||||
sqlx::query_scalar::<_, i64>(&sql)
|
||||
.fetch_one(pool)
|
||||
@@ -22,14 +22,14 @@ pub(in crate::state::store) async fn sql_count(pool: &SqlitePool, table: &str) -
|
||||
.with_context(|| format!("failed counting {table}"))
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn now_unix() -> u64 {
|
||||
pub fn now_unix() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn decode_expiry(raw: &[u8]) -> Result<u64> {
|
||||
pub fn decode_expiry(raw: &[u8]) -> Result<u64> {
|
||||
if raw.len() != 8 {
|
||||
anyhow::bail!("invalid token expiry length {}", raw.len());
|
||||
}
|
||||
@@ -38,7 +38,7 @@ pub(in crate::state::store) fn decode_expiry(raw: &[u8]) -> Result<u64> {
|
||||
Ok(u64::from_le_bytes(arr))
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn decode_schema(raw: &[u8]) -> Result<u32> {
|
||||
pub fn decode_schema(raw: &[u8]) -> Result<u32> {
|
||||
if raw.len() != 4 {
|
||||
anyhow::bail!("invalid schema version length {}", raw.len());
|
||||
}
|
||||
@@ -47,11 +47,11 @@ pub(in crate::state::store) fn decode_schema(raw: &[u8]) -> Result<u32> {
|
||||
Ok(u32::from_le_bytes(arr))
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn seeded_enroll_token_key(token: &str) -> String {
|
||||
pub fn seeded_enroll_token_key(token: &str) -> String {
|
||||
format!("{SEEDED_ENROLL_TOKEN_PREFIX}{token}")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn normalize_required_text(value: &str, field: &str) -> Result<String> {
|
||||
pub fn normalize_required_text(value: &str, field: &str) -> Result<String> {
|
||||
let normalized = value.trim();
|
||||
if normalized.is_empty() {
|
||||
anyhow::bail!("{field} must not be empty");
|
||||
@@ -59,14 +59,14 @@ pub(in crate::state::store) fn normalize_required_text(value: &str, field: &str)
|
||||
Ok(normalized.to_string())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn normalize_optional_text(value: Option<&str>) -> Option<String> {
|
||||
pub fn normalize_optional_text(value: Option<&str>) -> Option<String> {
|
||||
value
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn normalize_device_identifier(
|
||||
pub fn normalize_device_identifier(
|
||||
input: DeviceIdentifierInput,
|
||||
) -> Result<NormalizedDeviceIdentifier> {
|
||||
let kind = normalize_required_text(&input.kind, "identifier kind")?.to_ascii_lowercase();
|
||||
@@ -80,15 +80,11 @@ pub(in crate::state::store) fn normalize_device_identifier(
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(in crate::state::store) fn normalized_identifier_key_owned(
|
||||
identifier: NormalizedDeviceIdentifier,
|
||||
) -> String {
|
||||
pub fn normalized_identifier_key_owned(identifier: NormalizedDeviceIdentifier) -> String {
|
||||
identifier.identifier_key
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn list_enroll_token_rows(
|
||||
pool: &SqlitePool,
|
||||
) -> Result<Vec<EnrollTokenRow>> {
|
||||
pub async fn list_enroll_token_rows(pool: &SqlitePool) -> Result<Vec<EnrollTokenRow>> {
|
||||
sqlx::query_as!(
|
||||
EnrollTokenRow,
|
||||
r#"SELECT token as "token!", expires_at_unix FROM enroll_tokens ORDER BY expires_at_unix, token"#,
|
||||
@@ -98,10 +94,7 @@ pub(in crate::state::store) async fn list_enroll_token_rows(
|
||||
.context("failed listing enroll tokens")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn enroll_token_info_from_row(
|
||||
row: EnrollTokenRow,
|
||||
now: u64,
|
||||
) -> Result<EnrollTokenInfo> {
|
||||
pub fn enroll_token_info_from_row(row: EnrollTokenRow, now: u64) -> Result<EnrollTokenInfo> {
|
||||
let expires_at_unix =
|
||||
u64::try_from(row.expires_at_unix).context("negative token expiry in state db")?;
|
||||
Ok(EnrollTokenInfo {
|
||||
@@ -111,9 +104,7 @@ pub(in crate::state::store) fn enroll_token_info_from_row(
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn list_known_device_rows(
|
||||
pool: &SqlitePool,
|
||||
) -> Result<Vec<KnownDeviceRow>> {
|
||||
pub async fn list_known_device_rows(pool: &SqlitePool) -> Result<Vec<KnownDeviceRow>> {
|
||||
sqlx::query_as!(
|
||||
KnownDeviceRow,
|
||||
r#"SELECT device_id as "device_id!", display_name as "display_name!",
|
||||
@@ -126,7 +117,7 @@ pub(in crate::state::store) async fn list_known_device_rows(
|
||||
.context("failed listing known devices")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn get_known_device_row(
|
||||
pub async fn get_known_device_row(
|
||||
pool: &SqlitePool,
|
||||
device_id: &str,
|
||||
) -> Result<Option<KnownDeviceRow>> {
|
||||
@@ -143,11 +134,11 @@ pub(in crate::state::store) async fn get_known_device_row(
|
||||
.context("failed reading known device")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn known_device_row_device_id(row: &KnownDeviceRow) -> &str {
|
||||
pub fn known_device_row_device_id(row: &KnownDeviceRow) -> &str {
|
||||
&row.device_id
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn known_device_from_row_and_identifiers(
|
||||
pub fn known_device_from_row_and_identifiers(
|
||||
row: KnownDeviceRow,
|
||||
identifiers: Vec<DeviceIdentifier>,
|
||||
) -> Result<KnownDevice> {
|
||||
@@ -164,7 +155,7 @@ pub(in crate::state::store) fn known_device_from_row_and_identifiers(
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn list_device_identifier_rows(
|
||||
pub async fn list_device_identifier_rows(
|
||||
pool: &SqlitePool,
|
||||
device_id: &str,
|
||||
) -> Result<Vec<DeviceIdentifierRow>> {
|
||||
@@ -182,109 +173,7 @@ pub(in crate::state::store) async fn list_device_identifier_rows(
|
||||
.context("failed listing device identifiers")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn get_observation_identifier_row(
|
||||
pool: &SqlitePool,
|
||||
observation_key: &str,
|
||||
) -> Result<Option<ObservationIdentifierRow>> {
|
||||
sqlx::query_as!(
|
||||
ObservationIdentifierRow,
|
||||
r#"SELECT mac, ip
|
||||
FROM agent_device_observations
|
||||
WHERE observation_key = ?1"#,
|
||||
observation_key
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.context("failed reading observation identifier")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn get_observation_current_row(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
observation_key: &str,
|
||||
) -> Result<Option<ObservationCurrentRow>> {
|
||||
sqlx::query_as!(
|
||||
ObservationCurrentRow,
|
||||
r#"SELECT mac, ip, hostname, first_seen_unix, last_seen_unix,
|
||||
last_action as "last_action!"
|
||||
FROM agent_device_observations
|
||||
WHERE observation_key = ?1"#,
|
||||
observation_key
|
||||
)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.context("failed reading current observation")
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn observation_current_changed(
|
||||
current: Option<&ObservationCurrentRow>,
|
||||
next: &AgentDeviceObservation,
|
||||
first_seen_unix: i64,
|
||||
last_seen_unix: i64,
|
||||
) -> bool {
|
||||
let Some(current) = current else {
|
||||
return true;
|
||||
};
|
||||
current.mac != next.mac
|
||||
|| current.ip != next.ip
|
||||
|| current.hostname != next.hostname
|
||||
|| current.first_seen_unix != first_seen_unix
|
||||
|| current.last_seen_unix != last_seen_unix
|
||||
|| current.last_action != next.last_action
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn observation_identifier_to_input(
|
||||
observation: ObservationIdentifierRow,
|
||||
) -> Result<DeviceIdentifierInput> {
|
||||
observation
|
||||
.mac
|
||||
.map(|value| DeviceIdentifierInput {
|
||||
kind: "mac".into(),
|
||||
value,
|
||||
})
|
||||
.or_else(|| {
|
||||
observation.ip.map(|value| DeviceIdentifierInput {
|
||||
kind: "ip".into(),
|
||||
value,
|
||||
})
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("observation has no attachable mac or ip"))
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn normalize_agent_observation(
|
||||
agent_id: &str,
|
||||
input: AgentDeviceObservationInput,
|
||||
) -> Result<AgentDeviceObservation> {
|
||||
let kind = normalize_required_text(&input.kind, "observation kind")?.to_ascii_lowercase();
|
||||
let action = normalize_required_text(&input.action, "observation action")?.to_ascii_lowercase();
|
||||
let mac = normalize_optional_text(input.mac.as_deref()).map(|value| value.to_ascii_lowercase());
|
||||
let ip = normalize_optional_text(input.ip.as_deref());
|
||||
let hostname = normalize_optional_text(input.hostname.as_deref());
|
||||
let identifier = observation_identifier(&kind, mac.as_deref(), ip.as_deref())
|
||||
.ok_or_else(|| anyhow::anyhow!("observation requires mac or ip"))?;
|
||||
let observation_key = format!("agent:{agent_id}:{kind}:{identifier}");
|
||||
Ok(AgentDeviceObservation {
|
||||
observation_key,
|
||||
agent_id: agent_id.to_string(),
|
||||
kind,
|
||||
mac,
|
||||
ip,
|
||||
hostname,
|
||||
first_seen_unix: input.first_seen_unix,
|
||||
last_seen_unix: input.last_seen_unix,
|
||||
last_action: action,
|
||||
})
|
||||
}
|
||||
|
||||
fn observation_identifier(kind: &str, mac: Option<&str>, ip: Option<&str>) -> Option<String> {
|
||||
match (kind, mac, ip) {
|
||||
("neigh" | "inventory", Some(mac), Some(ip)) => Some(format!("mac:{mac}:ip:{ip}")),
|
||||
(_, Some(mac), _) => Some(format!("mac:{mac}")),
|
||||
(_, None, Some(ip)) => Some(format!("ip:{ip}")),
|
||||
(_, None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::state::store) async fn insert_device_identifier_tx(
|
||||
pub async fn insert_device_identifier_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
device_id: &str,
|
||||
identifier: &NormalizedDeviceIdentifier,
|
||||
@@ -313,9 +202,7 @@ pub(in crate::state::store) async fn insert_device_identifier_tx(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn device_identifier_from_row(
|
||||
row: DeviceIdentifierRow,
|
||||
) -> Result<DeviceIdentifier> {
|
||||
pub fn device_identifier_from_row(row: DeviceIdentifierRow) -> Result<DeviceIdentifier> {
|
||||
Ok(DeviceIdentifier {
|
||||
identifier_key: row.identifier_key,
|
||||
device_id: row.device_id,
|
||||
@@ -325,75 +212,3 @@ pub(in crate::state::store) fn device_identifier_from_row(
|
||||
.context("negative device identifier timestamp in state db")?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(in crate::state::store) fn agent_observation_from_row(
|
||||
row: AgentObservationRow,
|
||||
) -> Result<AgentDeviceObservation> {
|
||||
Ok(AgentDeviceObservation {
|
||||
observation_key: row.observation_key,
|
||||
agent_id: row.agent_id,
|
||||
kind: row.kind,
|
||||
mac: row.mac,
|
||||
ip: row.ip,
|
||||
hostname: row.hostname,
|
||||
first_seen_unix: u64::try_from(row.first_seen_unix)
|
||||
.context("negative observation first_seen timestamp in state db")?,
|
||||
last_seen_unix: u64::try_from(row.last_seen_unix)
|
||||
.context("negative observation last_seen timestamp in state db")?,
|
||||
last_action: row.last_action,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn agent_observation_view_from_row(
|
||||
row: AgentObservationViewRow,
|
||||
) -> Result<AgentDeviceObservationView> {
|
||||
let known_device = match (row.device_id, row.display_name, row.pinned) {
|
||||
(Some(device_id), Some(display_name), Some(pinned)) => Some(KnownDeviceSummary {
|
||||
device_id,
|
||||
display_name,
|
||||
pinned: pinned != 0,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(AgentDeviceObservationView {
|
||||
observation_key: row.observation_key,
|
||||
agent_id: row.agent_id,
|
||||
kind: row.kind,
|
||||
mac: row.mac,
|
||||
ip: row.ip,
|
||||
hostname: row.hostname,
|
||||
first_seen_unix: u64::try_from(row.first_seen_unix)
|
||||
.context("negative observation first_seen timestamp in state db")?,
|
||||
last_seen_unix: u64::try_from(row.last_seen_unix)
|
||||
.context("negative observation last_seen timestamp in state db")?,
|
||||
last_action: row.last_action,
|
||||
known_device,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::state::store) fn agent_observation_event_from_row(
|
||||
row: AgentObservationEventRow,
|
||||
) -> Result<AgentDeviceObservationEvent> {
|
||||
let known_device = match (row.device_id, row.display_name, row.pinned) {
|
||||
(Some(device_id), Some(display_name), Some(pinned)) => Some(KnownDeviceSummary {
|
||||
device_id,
|
||||
display_name,
|
||||
pinned: pinned != 0,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(AgentDeviceObservationEvent {
|
||||
event_id: row.event_id,
|
||||
observation_key: row.observation_key,
|
||||
agent_id: row.agent_id,
|
||||
kind: row.kind,
|
||||
action: row.action,
|
||||
mac: row.mac,
|
||||
ip: row.ip,
|
||||
hostname: row.hostname,
|
||||
ts_unix: u64::try_from(row.ts_unix)
|
||||
.context("negative observation event timestamp in state db")?,
|
||||
known_device,
|
||||
})
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user