16 Commits

Author SHA256 Message Date
Alphaeus Mote bfbd9b1d4f fix(messaging): a fleet reconnecting at once gets every settings answer [skip ci]
A 10,000-device connect storm answered 1,526 settings pulls on SQLite and
4,365 on PostgreSQL; the rest came after the agent's 20 s. Measured (a
probe in the lanes): every pull queued in the 8 agent-event lanes behind
every device's ready event, and each event's replay id was one database
insert (19 to 36 ms under the storm's write contention) before anything
else; the lanes' wait reached 61 s on SQLite (41 s on PostgreSQL), 8,312
of 9,845 SQLite answers left after the agent had stopped waiting, and 155
more failed to publish. Nothing was dropped by a subscription.

- Requests on the event subject (anything with an inbox: settings pulls,
  CLI runs, uploads, restarts) leave the lanes for a request path of their
  own: up to 256 at a time opened side by side, their ids remembered for
  every replica in one insert (ServerReceipt.EventBatch, RememberEventsAsync;
  a replay is refused as before), settings pulls answered together.
- AgentSettingsAnswers: the enabled profiles (and every device's groups when
  a profile names groups) kept as a snapshot until AgentSettingsSignal fires
  (profile, group, member, tag changes) or 30 s; a batch's devices and
  stored sets in one query each. A stored set that is what the snapshot
  decides, not pending and not behind the agent, is the answer with no
  write; everything else goes through ReconcileDeviceAsync, read afresh.
- The lanes take what has queued (up to 64) and write it together:
  inventory reports in one transaction (one at a time when that fails),
  ready and logon events' device rows in one, event ids in one insert;
  order per device is kept. These writes, settings rows and replay ids
  take SqliteWriteGate on SQLite.
- Presence, inventory, events and requests read the keys of devices not
  cached a query per 500 (DeviceKeyCache.LoadAsync) and open side by side.
- The server's ECDH key is held in up to 8 instances: one instance under
  one lock made every first message of every device (after a server start)
  wait its turn, which starved the thread pool once opening ran in
  parallel (833 answers in that run).
- Subscriptions hold 65,536 messages (NATS.Net's default is 16,384); what
  a full one drops is counted by kind and logged every 10 s at most. An
  answer sent after the agent's 20 s is counted and logged too.
- An upgrade's key check reads the keys the command was just sealed with.

After: 10,000/10,000 first-try answers on SQLite (p50 0.5 s, p95 1.8 s,
max 2.1 s) and on PostgreSQL (p50 0.1 s, p95 0.3 s, max 0.9 s); every
inventory, presence and ready event stored by the end of the 20 s ramp.

Replies are sealed and signed for the asking device and bound to its inbox
as before; pulls and other requests are still replay-checked in the
database for every replica.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 10:56:23 -05:00
Alphaeus Mote 084f569c31 perf(jobs): parallel dispatch for large runs, job rows written in batches [skip ci]
A run without a stagger now writes its jobs 500 per transaction and seals and
publishes each batch's commands JOB_DISPATCH_PARALLELISM at a time (default 16,
at most 128) while the next batch is written and the last one's Dispatched
states and history pruning are stored. A batch's rows commit before any of its
commands goes out, and a batch is sent only once the one before has been, so an
agent's first state always finds its job and a device's jobs leave in order.
The job dispatcher (staggered slots, retries) sends a pass's due jobs the same
way: only what is due, so Spread Over and Devices at a Time hold as before.

- A device's failed send stays with that device: it is left queued for the
  dispatcher, and its later jobs in the batch wait behind it.
- A script command carries its job id as the JetStream message id, so a resend
  inside the stream's duplicate window (a publish that was not confirmed, a run
  stopped part way) is dropped by the stream: a job is never delivered twice.
- A run stopped part way hands what was written but not sent to the dispatcher.
- Staggered runs write their rows a batch per transaction after the snapshot.
- History pruning for a batch: one grouped count, deletes in one transaction.
- On SQLite, new rows go through one prepared INSERT (BulkInsert): SaveChanges
  cost about 0.4 ms a row there. PostgreSQL and SQL Server keep SaveChanges.
- SqliteWriteGate: the batch writers (a run's rows and states, and the
  messaging workers' in the next commit) take SQLite's one writer in turn,
  awaited, instead of meeting at its lock, where Microsoft.Data.Sqlite retries
  after 150 ms sleeps. It does nothing on PostgreSQL and SQL Server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 06:49:02 -05:00
Alphaeus Mote 94bccc1235 Merge main; sealed tests keep the shared NATS in memory storage
Merges local main (its job pipeline test starts the command stream over
in memory storage when the server holds an incompatible one; taken as
it is). The sealed tests' fixture now makes the command and job event
streams itself in memory storage, as the pipeline test does, with the
backend's job event consumer, starting a stream over when another run
left it with settings that cannot be updated, and again before each test
agent (another run may have reset them). The backend's own file-storage
provisioning then only logs that it cannot change them. Each test agent
deletes its consumer when it stops.

The load benchmark switches the streams to file storage for a run (as in
production) and its cleanup, run after each run, puts memory-storage
streams back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 22:53:07 -05:00
Alphaeus Mote c277010007 test(integration): start the command stream over when a test server holds an incompatible one
CI / build-test (push) Failing after 6m58s
CI / images (push) Has been skipped
Release / release (push) Failing after 1m21s
Release / images (push) Has been skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 22:39:36 -05:00
Alphaeus Mote 19f6b48a79 fix(files): a cancelled transfer's slot is not refused as busy; close after answers
ACancelledDownloadReleasesTheDevice failed most runs on unmodified main
over a real NATS server (5 of 6 here), two ways:

- "busy": a download stopped from the server frees its slot only once the
  agent hears the abort, and a request arriving just before that was
  refused at once. A request now waits up to 3 s for a slot before it is
  answered busy.
- the listener's session ended while the requests it had handed to the
  thread pool were still writing frames, and the connection was closed
  under them. It now waits (up to 10 s) for them to stop first.

Left: NATS.Net now and then times out writing an unsubscribe on close
after a large publish was cancelled part way; the test's teardown
tolerates that one exception (the connection closes anyway).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 22:33:10 -05:00
Alphaeus Mote c1a5200ca3 test(security): sealed messaging end to end over a real NATS server
The real backend (messaging workers, command dispatcher, message security,
enrollment) hosted against the live NATS with its own SQLite database, and
agents enrolled through the real bootstrap endpoint running the agent's own
command processor, publisher, file listener and request link. A raw client
watches the wire and replays, tampers with and injects messages:

- a queued script sealed and signed by the server runs; its output and
  states come back sealed and signed by the device and are stored
- a replayed command runs once, an expired one and four tampered copies are
  refused (the untampered copy then runs)
- tampered, forged, foreign and replayed job states and output are refused
  by the server
- the CLI run and the Agent Settings pull are sealed both ways; a captured
  request sent again gets no answer
- a sealed file transfer round-trips intact while duplicated, reordered and
  forged frames are injected both ways
- a key rotation reaches the agent as a queued command; both keys work
- Require Sealed Agents refuses a v1 agent's presence, job states and
  requests, and sends it nothing
- a script at the library's limit: sent sealed, or refused with the sizes
  when the NATS server is at its 1 MB default

The unsealed pipeline test now makes the command stream as the backend does
(file storage), so both can share one server. All skip without NATS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:55:39 -05:00
Alphaeus Mote cf2c83fb56 feat(agent): file downloads follow server paths, with the server's trust
A delivery's URL can now be a path, resolved against the server URL the agent
already reaches, as upgrades do. Both downloaders also use enrollment's trust,
so a self-signed server's links work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:50:36 -05:00
Alphaeus Mote bcc44038f8 feat(server): device file routes, and browsing and searching S3
files.browse reads and files.manage changes, in device scope and on the audit
trail. Nothing is stored: transfers stream through the node holding the browser's
request. System roles now follow what their version grants, so Operator picks up
new permissions on upgrade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:17:51 -05:00
Alphaeus Mote 98fca000e1 feat(agent): browse, change, upload and download files on the device
Uploads land only once complete, text saves keep their encoding and refuse a
file that moved on, and folders stream as zips. AllowFileAccess turns all of it
off locally, whatever the server asks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:17:51 -05:00
Alphaeus Mote 1fc4569910 feat(agent): renew the credential over HTTPS and remove the agent on command or 410
A background service renews at every start and at half life, NATS connected or not; NATS reads the current credential at each connect. Nothing is replaced while an upgrade could roll back, and a 410 from an unverified server uninstalls nothing. The remove command checks its enrollment and refuses foreground runs and upgrades in progress; a device with no watchdog runs the same runner from a copy of the agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:09:50 -04:00
Alphaeus Mote 7fc8154935 test: build the command processor with its upgrade handler; run the watchdog tests in CI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:47:41 -04:00
gsadmin a675ef4d69 System proxy support with default credentials, agent and server
All outbound traffic honors the system/environment proxy
(HTTP_PROXY/HTTPS_PROXY/NO_PROXY or the Windows system proxy) and
authenticates to it with the process account's default credentials, so
corporate NTLM/Negotiate proxies work unattended. The agent applies it
at host startup and explicitly hands HttpClient.DefaultProxy to the
NATS WebSocket (ClientWebSocket does not inherit it); a new ProxyUrl
setting forces an explicit proxy via GPO (ADMX included), registry,
MSI PROXYURL or configure --proxy. The server sets the same default
ahead of everything, covering S3, OIDC, secrets providers and the
nats-server download. No-op when no proxy is configured.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 21:08:45 -04:00
gsadmin b2aa8a1a13 Agents follow self-signed servers: skip-verify via registry/GPO
CI / build-test (push) Successful in 15m39s
CI / images (push) Successful in 3m27s
CI / build-test (pull_request) Successful in 3m54s
CI / images (pull_request) Has been skipped
New TlsSkipVerify agent setting (DWORD, GPO policy key beats local
registry, ADMX template included) accepts the server certificate
without validation on both the enrollment HTTP call and the NATS
websocket — for servers on the managed self-signed chain with no proxy
in front; the connection stays fully TLS-encrypted. Set it via
configure --skip-tls-verify, the agent MSI SKIPTLSVERIFY=1 property
(remember-pattern like the rest), GPO, or the registry directly.

The server detects direct self-signed serving (HTTPS + no forwarded
headers) and the UI one-liners plus all generated install scripts pick
the correct scheme and add the skip-verify bits automatically —
PS5-safe callback on Windows, curl -k on unix — and configure the
agent to match. Proxied deployments are untouched: agents validate the
edge certificate normally.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 17:18:41 -04:00
gsadmin 05afb16076 Device orphaning toggle with re-enrollment recovery, and S3 download caching
Device lifecycle (DEVICE_ORPHAN_AFTER_DAYS, default 0 = off):
- Default behaviour is unchanged and needs no operator action: a silent device
  ages Online -> Stale -> Offline, keeps its credentials, and reconnects by
  itself whenever it returns
- With a positive window, the sweeper orphans devices silent for that long.
  An orphaned device is refused credential refresh (401) and job creation
  (409), and presence from it is logged and ignored rather than resurrecting it
- Recovery is deliberate: pushing a fresh bootstrap token makes the agent
  re-enroll, which clears the flag and reuses the same device record
- Agent needed no new mode: a bootstrap token is erased after each successful
  enrollment, so finding one on an already-enrolled agent is by definition an
  instruction to re-enroll

S3 download caching (skip work when nothing changed):
- If the destination exists and the caller supplied sha256, the agent hashes
  the local file and skips entirely on a match - no request at all
- Otherwise it sends the previously stored ETag as If-None-Match and treats
  304 Not Modified as "already up to date", letting S3 make the call
- Local cache (destination -> ETag, SHA-256, size) lives in the agent's SQLite
  store so it survives restarts; every completed download is hashed to verify
  the transfer and seed the cache
- 5 download-cache tests (39 agent tests)

Migrations added for all three providers. README documents both flows with
diagrams, plus the deploy script and Gitea secrets bootstrap.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 22:18:11 -04:00
gsadmin 9470116e40 M8: Gitea CI/CD workflows, release publishing, end-to-end integration test
- .gitea/workflows/ci.yml: PR->main builds + unit/integration tests + svelte
  check; push to dev/main also builds (and pushes) backend/webui images with
  dev / <version>-dev or <version> / latest tags
- .gitea/workflows/release.yml + scripts/Publish-Release.ps1: on main, generate
  icon, package agent (exe zip + MSI + checksums) and create a Gitea release
  with assets via the REST API (no-ops without GITEA_TOKEN; never prints it)
- Integration test: real NATS+JetStream durable dispatch -> in-process
  PowerShell execution -> live output/progress/state, and duplicate delivery
  runs exactly once. Verified passing against nats-server 2.14 (JetStream);
  skips cleanly when NATS_URL is unreachable
- Icon generation wired into the agent build (ApplicationIcon)

Full suite: 95 unit tests + 1 integration test green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 20:32:07 -04:00
gsadmin d4dbf35711 Foundation: solution, shared contracts/infrastructure, backend and agent skeletons
- Central package management pinned for .NET 10; unified yyyy.MM.dd.HHmm versioning
- Shared.Contracts: ApiRoutes, message envelope, payload/DTO records, JSON defaults
- Shared.Infrastructure: branding constants, protocol defaults, NATS subject map
  with central identifier validation, JetStream definitions, ServerURL normalization,
  token hashing, MSI version transform
- Backend: health/ready endpoints, trusted-proxy forwarded headers plumbing
- Agent: CLI dispatcher, Generic Host worker, Windows service lifecycle via
  advapi32/ServiceController (no sc.exe)
- Shared.Tests: 42 tests covering routes, subjects, ServerURL, envelope, versioning

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 18:38:00 -04:00