The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
sentinel: a managed Vector forwarder to Microsoft Sentinel, on every platform
shukieshah5216e22e7e70
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 77c6a7a4..40ea6935 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -471,6 +471,14 @@ jobs:- name: Test endpoint packages with the race detectorworking-directory: cli/beaconrun: go test -race ./internal/endpoint/...+ # The Sentinel forwarder's config run by the Vector the packages ship, against a mock of+ # Entra ID and the Logs Ingestion API: retried 403s, a rotation, a restart, the log copy.+ - name: Run the Sentinel forwarder against real Vector+ run: |+ sh packaging/linux/fetch-vector.sh "$RUNNER_TEMP/vector" amd64+ cd cli/beacon+ BEACON_TEST_VECTOR_BIN="$RUNNER_TEMP/vector/linux_amd64/beacon-vector" \+ go test -count=1 -run TestForwarderConfigDeliversThroughRealVector -v ./internal/endpoint/sentinel/- name: Test hook adapter on Linuxworking-directory: cli/beacon-hooksrun: go test ./...@@ -620,6 +628,17 @@ jobs:./internal/endpoint/writer/... `./internal/endpoint/inventory/... `./internal/endpoint/service/...+ # The same real-Vector run as on Linux. The mock's CA goes into LocalMachine\Root, which is+ # where Vector's token client looks on Windows; the test removes it again.+ - name: Run the Sentinel forwarder against real Vector+ run: |+ $vector = pwsh -NoProfile -File packaging\windows\fetch-vector.ps1 -OutDir "$env:RUNNER_TEMP\vector" | Select-Object -Last 1+ if ($LASTEXITCODE -ne 0) { throw "fetch-vector.ps1 failed" }+ Set-Location cli\beacon+ $env:BEACON_TEST_VECTOR_BIN = $vector+ $env:BEACON_TEST_SENTINEL_TRUST_STORE = '1'+ go test -count=1 -run TestForwarderConfigDeliversThroughRealVector -v ./internal/endpoint/sentinel/+ if ($LASTEXITCODE -ne 0) { throw "the Sentinel forwarder end-to-end test failed" }- name: Test hook adapter on Windowsworking-directory: cli/beacon-hooksrun: go test -count=1 ./...@@ -827,6 +846,9 @@ jobs:Set-Location ..\beacongo build -o beacon.exe .if ($LASTEXITCODE -ne 0) { throw "beacon build failed" }+ # Stands in for Entra ID and the Logs Ingestion API in the Sentinel forwarder smoke.+ go build -o sentinel-mock.exe ./internal/endpoint/sentinel/sentinelmock/cmd/sentinel-mock+ if ($LASTEXITCODE -ne 0) { throw "sentinel-mock build failed" }- name: Build the collectorrun: |@@ -941,6 +963,12 @@ jobs:Write-Output "installed, running, backend=windows-service"exit 0+ # The managed Sentinel forwarder the way a fleet sets it up: as SYSTEM, with a certificate,+ # against a mock of Entra ID and the Logs Ingestion API that refuses the first batches with 403.+ - name: The Sentinel forwarder must deliver, keeping its credential private+ timeout-minutes: 6+ run: pwsh -NoProfile -File packaging/windows/smoke-sentinel-forwarder.ps1 -Phase setup -MockExe cli\beacon\sentinel-mock.exe+- name: Upgrading must replace the payload and leave it runningtimeout-minutes: 20run: |@@ -1017,10 +1045,19 @@ jobs:# The restricted log access mode against a real ordinary account on the installed endpoint: its# hook reaches the log only through the collector's pipe, stamped as itself; it can neither read# nor append to the log; it spools while the collector is stopped; and shared puts it all back.+ - name: The Sentinel forwarder must come back after the upgrade+ timeout-minutes: 4+ run: pwsh -NoProfile -File packaging/windows/smoke-sentinel-forwarder.ps1 -Phase after-upgrade+- name: Restricted log access must hold against an ordinary accounttimeout-minutes: 8run: pwsh -NoProfile -File packaging/windows/smoke-restricted-log.ps1+ # Switching log access replaces the log with a copy, which Vector follows only once restarted.+ - name: The Sentinel forwarder must have sent every event exactly once+ timeout-minutes: 5+ run: pwsh -NoProfile -File packaging/windows/smoke-sentinel-forwarder.ps1 -Phase verify+- name: Uninstall must remove the service and keep the datatimeout-minutes: 5run: |@@ -1095,6 +1132,14 @@ jobs:# bound (packaging/windows/package-common.ps1), so a hang no longer wedges the MSI -- which also# means it no longer fails a step on its own. Each script leaves a package log in SYSTEM's# temporary directory, and a TIMEOUT line there is a hang this job must not pass over.+ - name: Uninstall must remove the Sentinel forwarder service and keep its settings+ timeout-minutes: 2+ run: pwsh -NoProfile -File packaging/windows/smoke-sentinel-forwarder.ps1 -Phase after-uninstall++ - name: Stop the Sentinel mock and remove its certificates+ if: always()+ run: pwsh -NoProfile -File packaging/windows/smoke-sentinel-forwarder.ps1 -Phase cleanup+- name: Every package action must finish within its boundif: always()run: |@@ -1130,6 +1175,12 @@ jobs:Write-Output '--- BeaconCollector ---'& sc.exe queryex BeaconCollector 2>&1 | Write-Output& sc.exe qc BeaconCollector 2>&1 | Write-Output+ Write-Output '--- BeaconSentinelForwarder ---'+ & sc.exe queryex BeaconSentinelForwarder 2>&1 | Write-Output+ $forwarderLogs = Join-Path $env:ProgramData 'Beacon\Endpoint\forwarders\sentinel\logs'+ Get-ChildItem $forwarderLogs -Filter 'vector-*.log' -ErrorAction SilentlyContinue |+ ForEach-Object { Write-Output "--- $($_.Name) (tail) ---"; Get-Content -LiteralPath $_.FullName -Tail 40 | Write-Output }+ Get-Content (Join-Path $env:RUNNER_TEMP 'sentinel-smoke\mock.err') -Tail 40 -ErrorAction SilentlyContinue | Write-OutputWrite-Output '--- Windows Installer, collector and service control events ---'foreach ($filter in @(@{ LogName = 'Application'; ProviderName = 'MsiInstaller' },diff --git a/CLAUDE.md b/CLAUDE.mdindex f7bf6b0b..c635e957 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -66,6 +66,7 @@ Supported runtime surfaces today:- Browser chat telemetry through an optional MV3 extension (`browser-extension/`; Chrome, with a beta Firefox build) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser-identity.ts` from UA Client Hints brands, with a UA-string fallback that also names Firefox. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented. Per-browser differences live only in `browser-extension/tools/targets.mjs` (one entry per target, deriving its manifest from `src/manifest.json`; Chrome ships that file verbatim to `dist/`, Firefox gets `dist-firefox/`), and every extension API call goes through the `src/shared/browser.ts` shim (a unit test fails on direct `chrome.*` use). The Firefox Gecko ID `[email protected]` is pinned and must never change.- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.- OTLP forward (`beacon endpoint install|repair --otlp-forward-endpoint`, `--otlp-forward-protocol grpc|http/protobuf`, `--otlp-forward-harness`, repeatable `--otlp-forward-header`, `--no-otlp-forward`; `config.json` `destinations.otlp_forward`): for machines whose runtimes already exported OTLP to another backend before Beacon pointed them at its collector. The collector renders an `otlp/forward` or `otlphttp/forward` exporter (both in `collector-builder/builder.yaml`) on `logs/forward`, `traces/forward` and `metrics/forward` pipelines fed by the same receiver: `memory_limiter`, `beacon_forward_filter` (`forwardfilterprocessor`; keeps only resources whose harness, resolved like beaconjson resolves it, is listed, default Claude Code and Codex, so browser-extension chats and other runtimes never leave), `claude_api_body` on logs, `beacon_privacy`, `batch`. The exporter's queue and retries are bounded so a down backend sheds data instead of pushing `memory_limiter` into refusing Beacon's own pipelines. It is a customer-chosen destination like the HEC exporters, not a Beacon network channel, and carries no hook or session-store data. Install and repair carry it over (`buildConfig`) until `--no-otlp-forward` removes it. Header values never go in `config.json` (ordinary accounts read the system one to find the system log): they live in `OTLPForwardSecretsPath` (`otlp-forward-headers.json`, 0600) and the 0600 collector config, `config.json` keeps `header_names`, and status, doctor and `config show` show names only. Guide: `docs/guides/kandji-otlp-forward-mdm.mdx`.+- Managed Microsoft Sentinel forwarder (`beacon endpoint sentinel forwarder install|status|remove --system`, hidden `reconcile`; `cli/beacon/internal/endpoint/sentinel/forwarder.go`, `cli/beacon/cmd/endpoint_sentinel_forwarder.go`; docs in `docs/log-forwarding/microsoft-sentinel.mdx#vector-and-the-logs-ingestion-api` and `docs/cli/sentinel.mdx`): the bundled Vector (the MSI ships `vector.exe` beside `beacon.exe`, checked against the pinned `packaging/vector/` checksums by `packaging/windows/fetch-vector.ps1`) run as a system service (`BeaconSentinelForwarder`, `beacon-sentinel-forwarder.service`, `com.beacon.endpoint.sentinel-forwarder`) through `service.ForwarderManager` with a `ForwarderSpec`; the Asymptote forwarder's spec is the zero value, byte-identical units, and has no Windows service, so `connect` stays refused there. System mode only. Its state is `<SystemBaseDir>/forwarders/sentinel/` (`forwarder.json` non-secret settings, `secrets.json` read by Vector's `file` secret backend, optional `client.pfx`, `vector.toml` with literal values, `data/` checkpoints, `logs/vector-<date>.log` warnings), `sysacl.SecureSecretDir`/`WriteSecretFile` (root-only 0700/0600 on POSIX), apart from `config.json` so repair never touches it. The credential is never a flag value (env or stdin). Install validates a scratch copy with Vector before writing anything, so a rejected install leaves the old forwarder. The config (`pack/vector.toml.tmpl`, shared with the manual env-var pack via `manualVectorConfig`) reads `runtime.jsonl` and `.1` with the default checksum fingerprint, acknowledgements on, a custom `retry_strategy` (401/403/408/429/5xx, unlimited), 512 KB batches. Vector recognizes a file by its first line, so after the log is replaced with a copy (the log-access switch) it keeps reading the old file until restarted: `lifecycle.Install` therefore reconciles with `Restart` on every install, repair and package upgrade (the macOS postinstall runs the hidden `reconcile`), which is also how the MSI upgrade re-registers the service its uninstall step removed. `lifecycle.Uninstall` always removes the service (so `vector.exe` can be replaced) and keeps the state under `KeepConfig`; repair keeps it running (`KeepForwarders`). `AZURE_AUTHORITY_HOST` (`--authority-host`) goes into the service environment. `sentinelmock` (and `cmd/sentinel-mock`) stands in for Entra ID and the Logs Ingestion API; `TestForwarderConfigDeliversThroughRealVector` runs real Vector against it in `linux-test` and `windows-test` (`BEACON_TEST_VECTOR_BIN`, `BEACON_TEST_SENTINEL_TRUST_STORE=1` on Windows), and `packaging/windows/smoke-sentinel-forwarder.ps1` drives the installed MSI through setup, upgrade, log-access switches and uninstall in `windows-package-smoke`.- Scheduled session sync (`beacon endpoint install|repair --session-sync`, `--no-session-sync`; `config.json` `session_sync.enabled`, opt-in; docs in `docs/cli/endpoint-install.mdx#scheduled-session-sync`): a one-shot job, `com.beacon.endpoint.session-sync` / `beacon-session-sync.timer` (`service.SessionSyncManager`), every 15 minutes starting one interval after load (`jobSpec.runAtLoad` false, unlike inventory: a run fired at load would take the sweep lock ahead of the install backfill that follows it), running the hidden-flagged `beacon endpoint sessions sync --scheduled` (`cli/beacon/cmd/endpoint_session_sync.go`), which is `runEndpointBackfill`: the install backfill's sweep, window, budget and system-mode confinement, with cursors so each run reads only what is new. `lifecycle.ReconcileSessionSyncJob` installs it when on and removes it when off on every install, repair and package upgrade (`beacon endpoint sessions install-daemon`), and `buildConfig` carries the setting. It and the inventory job share `service.scheduledJob` (`jobSpec` per job). The scheduled run reports failures and exits 0 so the scheduler keeps it; a manual run fails on them. Every sweep (install, connect, manual and scheduled) and every writing `beacon endpoint <runtime> sync` (through `collectUnderSweepLock`, once or per `--watch` tick; a test fails on a collector called directly from `cmd`) holds `<BaseDir>/state/session-sweep.lock` for its whole run, because collectors load cursors at the start and save them at the end; the scheduled run and watch ticks skip when it is held, `--print` takes no lock, and the scheduled run returns early unless `session_sync.enabled` is on. An install or connect that skips its backfill (`--no-backfill`, `BEACON_BACKFILL=0`) records per-runtime floors in `session-sync-floor.json` beside the lock (`recordSkippedBackfill`), and a session sync then reads only that runtime's sessions active since (`sessionwindow.Recent` is per session, so an ongoing one is read whole); only a runtime with none of its own cursor files (`endpointBackfillRunner.State`, resolved in the console user's home for a system endpoint) gets one, an existing floor is never moved later, and a backfill that runs removes them all. A scheduled system run copies each `SQLite` runner's store at most every `endpointSnapshotInterval` (an hour; times in `session-sync-snapshots.json`), because the confined copy can approach `sessionfs.MaxSnapshotBytes`. Tests point `endpointSweepLockPath` at a temp dir in `TestMain`. `beacon endpoint sessions enable|disable` (`lifecycle.SetSessionSync`) changes only that key of config.json (`setConfigFileKey`) and reconciles the job, because a repair rebuilds the config from its flags and resets harnesses, ports and HEC destinations it is not given. Package installs set it with `BEACON_SESSION_SYNC=1|0` (unset keeps it) in `install-endpoint.sh` (macOS and Linux). A user-mode job carries `sessionSyncJobEnv` (the inventory job's variables plus `sessionSyncJobPathEnv`/`sessionSyncJobNameEnv`), and a test fails when a session-store collector reads a variable it does not carry.- Endpoint inventory (`inventory.heartbeat` / `inventory.snapshot` in `inventory_state.jsonl`) is written by a scheduled job, `com.beacon.endpoint.inventory` (`service.InventoryManager`, user LaunchAgent or system LaunchDaemon, `beacon-inventory.timer` on systemd), every six hours and once at load, on by default and reconciled by `lifecycle.ReconcileInventoryJob` on every install, repair and package upgrade (`beacon endpoint inventory install-daemon`). Agent hooks do not trigger inventory any more; the hook binary's `--cli` flag and `inventory-heartbeat` subcommand survive only as no-ops for hook commands written by older versions, and `beacon endpoint inventory heartbeat --trigger hook` is likewise retired. A system-mode run inventories the active console user's home and still writes the liveness heartbeat when nobody is logged in; the scheduled scan has no working directory, so project-scoped config is only in `beacon endpoint inventory`.- Beacon Cloud forwarding, the one Beacon-hosted network channel for endpoint telemetry: user-mode `beacon endpoint connect` authorizes device enrollment with the signed-in CLI account; system mode uses browser PKCE at `/cli/enroll`. Both store only the per-device key in `<BaseDir>/asymptote/vector-secrets.json` (0600, 0700 dir), render the selected privacy mode into `vector.toml` (re-rendered in place by install, repair and package upgrades, see above), validate it, and run Vector as `com.beacon.endpoint.asymptote-forwarder` / `beacon-asymptote-forwarder.service` through `service.ForwarderManager` (refused in supervised mode). `enrollment.json` and `config.json`'s `managed_ingest` block carry only non-secret identity and privacy mode; `beacon endpoint status` reports forwarder state and a live credential check (`GET /v1/ingest/health`, 3 s timeout); `disconnect` and `uninstall` remove the forwarder and credentials but never revoke server-side.diff --git a/cli/beacon/cmd/endpoint_destinations.go b/cli/beacon/cmd/endpoint_destinations.goindex f053ada6..5bbf04de 100644--- a/cli/beacon/cmd/endpoint_destinations.go+++ b/cli/beacon/cmd/endpoint_destinations.go@@ -373,7 +373,11 @@ var siemDestinations = []siemDestination{func buildDestinationCommands() []*cobra.Command {groups := make([]*cobra.Command, 0, len(siemDestinations))for _, d := range siemDestinations {- groups = append(groups, buildDestinationGroup(d))+ group := buildDestinationGroup(d)+ if d.name == "sentinel" {+ group.AddCommand(newSentinelForwarderCommand())+ }+ groups = append(groups, group)}return groups}diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.goindex 567840ad..2094d045 100644--- a/cli/beacon/cmd/endpoint_install.go+++ b/cli/beacon/cmd/endpoint_install.go@@ -261,6 +261,7 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {reportSessionSyncJob(details, result)reportLogAccess(details, result)reportManagedForwarder(details, cmd.ErrOrStderr(), result.ManagedForwarder)+ reportSentinelForwarder(details, cmd.ErrOrStderr(), result.SentinelForwarder)printLingerGap(cmd.ErrOrStderr(), result)installHookTargetsFromEndpointInstall(details, cmd.ErrOrStderr(), selection.Hooks)refreshAgentSkills(cmd.ErrOrStderr())@@ -431,7 +432,11 @@ func runEndpointStatus(cmd *cobra.Command, args []string) error {for _, forwarder := range status.ScriptForwarders {fmt.Println(scriptForwarderStatusLine(forwarder))}- if line := cloudStatusLine(status.ManagedIngest, endpointUserMode(), len(status.ScriptForwarders) > 0); line != "" {+ if status.SentinelForwarder != nil {+ fmt.Println(sentinelForwarderStatusLine(*status.SentinelForwarder))+ }+ otherForwarders := len(status.ScriptForwarders) > 0 || status.SentinelForwarder != nil+ if line := cloudStatusLine(status.ManagedIngest, endpointUserMode(), otherForwarders); line != "" {fmt.Println(line)}fmt.Println(inventoryHeartbeatStatusLine(status.InventoryHeartbeat))@@ -533,6 +538,7 @@ func runEndpointRepair(cmd *cobra.Command, args []string) error {reportSessionSyncJob(os.Stdout, result)reportLogAccess(os.Stdout, result)reportManagedForwarder(os.Stdout, cmd.ErrOrStderr(), result.ManagedForwarder)+ reportSentinelForwarder(os.Stdout, cmd.ErrOrStderr(), result.SentinelForwarder)printLingerGap(cmd.ErrOrStderr(), result)installHookTargetsFromEndpointInstall(os.Stdout, cmd.ErrOrStderr(), selection.Hooks)refreshAgentSkills(cmd.ErrOrStderr())diff --git a/cli/beacon/cmd/endpoint_sentinel_forwarder.go b/cli/beacon/cmd/endpoint_sentinel_forwarder.gonew file mode 100644index 00000000..dd75a946--- /dev/null+++ b/cli/beacon/cmd/endpoint_sentinel_forwarder.go@@ -0,0 +1,265 @@+package cmd++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "strings"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sentinel"+)++// Seams so the commands can be tested without a service manager, Vector or root.+var (+ installSentinelForwarder = sentinel.Install+ removeSentinelForwarder = sentinel.Remove+ reconcileSentinelForwarder = sentinel.Reconcile+ readSentinelForwarder = sentinel.ReadStatus+ sentinelHasPrivileges = lifecycle.HasSystemPrivileges+)++var sentinelForwarderOpts struct {+ endpoint string+ dcr string+ tenant string+ client string+ certificate string+ authority string+ readFrom string+ vectorBin string+ secretStdin bool+ passwordStdin bool+}++// newSentinelForwarderCommand is `beacon endpoint sentinel forwarder`: Vector running the Logs+// Ingestion config as a system service, managed by Beacon.+func newSentinelForwarderCommand() *cobra.Command {+ group := &cobra.Command{+ Use: "forwarder",+ Short: "Run Vector as a system service that sends the runtime log to Microsoft Sentinel",+ Long: `Run the Vector bundled with Beacon as a system service that sends every runtime log line+to Microsoft Sentinel through the Azure Monitor Logs Ingestion API, using a Microsoft Entra+app registration. The service survives reboots, repair and package upgrades, and uninstall+removes it. System installs only.`,+ }++ install := &cobra.Command{+ Use: "install",+ Short: "Set up the Sentinel forwarder, or replace its settings",+ Long: `Set up the Sentinel forwarder, or replace the settings of one already set up.++The credential never goes on the command line. Give a client secret in AZURE_CLIENT_SECRET+(or on stdin with --client-secret-stdin), or a certificate with --client-certificate and its+password, if it has one, in AZURE_CLIENT_CERTIFICATE_PASSWORD (or --certificate-password-stdin).+Both are stored where only root, or SYSTEM and Administrators on Windows, can read them.++Vector checks the config before anything changes, so a rejected install leaves a working+forwarder as it was.`,+ Example: ` printf '%s' "$CLIENT_SECRET" | sudo beacon endpoint sentinel forwarder install --system \+ --endpoint https://beacon-dcr-abcd.eastus-1.ingest.monitor.azure.com \+ --dcr-immutable-id dcr-0123456789abcdef0123456789abcdef \+ --tenant-id <tenant GUID> --client-id <app GUID> --client-secret-stdin++ sudo beacon endpoint sentinel forwarder install --system --client-certificate app.pfx \+ --endpoint ... --dcr-immutable-id ... --tenant-id ... --client-id ...`,+ SilenceUsage: true,+ RunE: runSentinelForwarderInstall,+ }+ addEndpointPathFlags(install)+ flags := install.Flags()+ flags.StringVar(&sentinelForwarderOpts.endpoint, "endpoint", "", "The DCR's logs ingestion URL (or a Data Collection Endpoint's)")+ flags.StringVar(&sentinelForwarderOpts.dcr, "dcr-immutable-id", "", "The DCR's immutable ID (dcr-...)")+ flags.StringVar(&sentinelForwarderOpts.tenant, "tenant-id", "", "Microsoft Entra tenant ID")+ flags.StringVar(&sentinelForwarderOpts.client, "client-id", "", "App registration (client) ID")+ flags.BoolVar(&sentinelForwarderOpts.secretStdin, "client-secret-stdin", false, "Read the client secret from stdin instead of AZURE_CLIENT_SECRET")+ flags.StringVar(&sentinelForwarderOpts.certificate, "client-certificate", "", "Authenticate with this PFX certificate instead of a client secret")+ flags.BoolVar(&sentinelForwarderOpts.passwordStdin, "certificate-password-stdin", false, "Read the certificate password from stdin instead of AZURE_CLIENT_CERTIFICATE_PASSWORD")+ flags.StringVar(&sentinelForwarderOpts.authority, "authority-host", "", "Entra authority for a sovereign cloud, such as https://login.microsoftonline.us")+ flags.StringVar(&sentinelForwarderOpts.readFrom, "read-from", "beginning", "Where to start in a log not read before: beginning (send the current log once) or end")+ flags.StringVar(&sentinelForwarderOpts.vectorBin, "vector", "", "Vector binary to run (default: the one Beacon's package installed)")+ flags.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print output as JSON")+ for _, name := range []string{"endpoint", "dcr-immutable-id", "tenant-id", "client-id"} {+ _ = install.MarkFlagRequired(name)+ }+ install.MarkFlagsMutuallyExclusive("client-secret-stdin", "client-certificate")++ status := &cobra.Command{+ Use: "status",+ Short: "Show the Sentinel forwarder's settings and service state",+ SilenceUsage: true,+ RunE: runSentinelForwarderStatus,+ }+ addEndpointPathFlags(status)+ status.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print output as JSON")++ remove := &cobra.Command{+ Use: "remove",+ Short: "Stop the Sentinel forwarder and delete its settings and credential",+ SilenceUsage: true,+ RunE: runSentinelForwarderRemove,+ }+ addEndpointPathFlags(remove)++ reconcile := &cobra.Command{+ Use: "reconcile",+ Short: "Internal: bring the Sentinel forwarder's config and service up to date",+ Long: `Re-render the Sentinel forwarder's config from its recorded settings and the pack this+version carries, have Vector validate it, and restart the service. Install and repair do+this on their own; the macOS package runs it after an upgrade.`,+ Hidden: true,+ SilenceUsage: true,+ RunE: runSentinelForwarderReconcile,+ }+ addEndpointPathFlags(reconcile)++ group.AddCommand(install, status, remove, reconcile)+ return group+}++// requireSystemForwarder refuses user mode and an unprivileged system run.+func requireSystemForwarder(action string) error {+ if endpointUserMode() {+ return errors.New("the Sentinel forwarder runs only with a system install; pass --system")+ }+ if !sentinelHasPrivileges() {+ return fmt.Errorf("%s the Sentinel forwarder needs elevated privileges; %s", action, lifecycle.SystemPrivilegeHint())+ }+ return nil+}++func runSentinelForwarderInstall(cmd *cobra.Command, args []string) error {+ if err := requireSystemForwarder("installing"); err != nil {+ return err+ }+ opts := sentinel.InstallOptions{+ Endpoint: sentinelForwarderOpts.endpoint,+ DCRImmutableID: sentinelForwarderOpts.dcr,+ TenantID: sentinelForwarderOpts.tenant,+ ClientID: sentinelForwarderOpts.client,+ CertificatePath: sentinelForwarderOpts.certificate,+ AuthorityHost: sentinelForwarderOpts.authority,+ ReadFrom: sentinelForwarderOpts.readFrom,+ LogPath: loadOrDefaultConfig().LogPath,+ VectorBin: sentinelForwarderOpts.vectorBin,+ ClientSecret: os.Getenv("AZURE_CLIENT_SECRET"),+ CertificatePassword: os.Getenv("AZURE_CLIENT_CERTIFICATE_PASSWORD"),+ }+ if sentinelForwarderOpts.secretStdin || sentinelForwarderOpts.passwordStdin {+ value, err := readStdinSecret(cmd.InOrStdin())+ if err != nil {+ return err+ }+ if sentinelForwarderOpts.secretStdin {+ opts.ClientSecret = value+ } else {+ opts.CertificatePassword = value+ }+ }+ if opts.CertificatePath != "" {+ // A secret left in the environment is not a reason to refuse a certificate install.+ opts.ClientSecret = ""+ }+ result, err := installSentinelForwarder(opts)+ if err != nil {+ return err+ }+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(result)+ }+ out := cmd.OutOrStdout()+ fmt.Fprintln(out, "Sentinel forwarder installed.")+ fmt.Fprintf(out, " Service: %s (running=%t)\n", result.Service.Label, result.Service.Running)+ fmt.Fprintf(out, " Config: %s\n", result.Config)+ fmt.Fprintf(out, " Vector: %s\n", result.Vector)+ fmt.Fprintln(out, "Check delivery: write a validation event with `beacon endpoint sentinel validate --system`, then run in Log Analytics:")+ fmt.Fprintln(out, ` BeaconRuntime_CL | where Message has "Beacon endpoint Sentinel validation event"`)+ return nil+}++// readStdinSecret reads one value from stdin, without its trailing newline.+func readStdinSecret(in io.Reader) (string, error) {+ data, err := io.ReadAll(io.LimitReader(in, 64*1024))+ if err != nil {+ return "", fmt.Errorf("read stdin: %w", err)+ }+ value := strings.TrimRight(string(data), "\r\n")+ if value == "" {+ return "", errors.New("nothing on stdin")+ }+ return value, nil+}++func runSentinelForwarderStatus(cmd *cobra.Command, args []string) error {+ if endpointUserMode() {+ return errors.New("the Sentinel forwarder runs only with a system install; pass --system")+ }+ status := readSentinelForwarder()+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(status)+ }+ out := cmd.OutOrStdout()+ if !status.Installed {+ fmt.Fprintln(out, "Sentinel forwarder: not installed (or this account cannot read its settings; "+lifecycle.SystemPrivilegeHint()+")")+ return nil+ }+ fmt.Fprintln(out, sentinelForwarderStatusLine(status))+ fmt.Fprintf(out, " Endpoint: %s\n", status.Settings.Endpoint)+ fmt.Fprintf(out, " DCR: %s\n", status.Settings.DCRImmutableID)+ fmt.Fprintf(out, " Credential: %s (app %s)\n", status.Settings.Credential, status.Settings.ClientID)+ fmt.Fprintf(out, " Log: %s\n", status.Settings.LogPath)+ return nil+}++// sentinelForwarderStatusLine is the one line `beacon endpoint status` prints for it.+func sentinelForwarderStatusLine(status sentinel.Status) string {+ line := fmt.Sprintf("Sentinel forwarder: loaded=%t running=%t", status.Service.Loaded, status.Service.Running)+ if !status.Service.Loaded && status.Service.Message != "" {+ line += " (" + status.Service.Message + ")"+ }+ if status.LastProblem != "" {+ line += "; Vector last reported: " + status.LastProblem+ }+ return line+}++func runSentinelForwarderRemove(cmd *cobra.Command, args []string) error {+ if err := requireSystemForwarder("removing"); err != nil {+ return err+ }+ if err := removeSentinelForwarder(false); err != nil {+ return err+ }+ fmt.Fprintln(cmd.OutOrStdout(), "Sentinel forwarder removed, with its settings and credential.")+ return nil+}++func runSentinelForwarderReconcile(cmd *cobra.Command, args []string) error {+ if err := requireSystemForwarder("reconciling"); err != nil {+ return err+ }+ result, err := reconcileSentinelForwarder(sentinel.ReconcileOptions{LogPath: loadOrDefaultConfig().LogPath, Restart: true})+ if err != nil {+ return err+ }+ if result.Skipped == "" {+ fmt.Fprintln(cmd.OutOrStdout(), result.Message())+ }+ return nil+}++// reportSentinelForwarder prints the install or repair reconcile outcome when one is set up.+func reportSentinelForwarder(out, errOut io.Writer, result *sentinel.ReconcileResult) {+ if result == nil || result.Skipped != "" {+ return+ }+ if result.Warning != "" {+ fmt.Fprintln(errOut, "Warning: "+result.Message())+ return+ }+ fmt.Fprintln(out, result.Message())+}diff --git a/cli/beacon/cmd/endpoint_sentinel_forwarder_test.go b/cli/beacon/cmd/endpoint_sentinel_forwarder_test.gonew file mode 100644index 00000000..f014d98d--- /dev/null+++ b/cli/beacon/cmd/endpoint_sentinel_forwarder_test.go@@ -0,0 +1,84 @@+package cmd++import (+ "bytes"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sentinel"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+)++func stubSentinelForwarder(t *testing.T, privileged bool) *sentinel.InstallOptions {+ t.Helper()+ var got sentinel.InstallOptions+ oldInstall, oldPriv := installSentinelForwarder, sentinelHasPrivileges+ installSentinelForwarder = func(o sentinel.InstallOptions) (sentinel.InstallResult, error) {+ got = o+ return sentinel.InstallResult{Config: "/x/vector.toml", Vector: "/opt/beacon/bin/vector",+ Service: service.Status{Label: "BeaconSentinelForwarder", Running: true}}, nil+ }+ sentinelHasPrivileges = func() bool { return privileged }+ t.Cleanup(func() { installSentinelForwarder, sentinelHasPrivileges = oldInstall, oldPriv })+ return &got+}++func runSentinelForwarderCmd(t *testing.T, stdin string, args ...string) (string, error) {+ t.Helper()+ saved := endpointOpts+ t.Cleanup(func() { endpointOpts = saved })+ sentinelForwarderOpts = struct {+ endpoint, dcr, tenant, client, certificate, authority, readFrom, vectorBin string+ secretStdin, passwordStdin bool+ }{}+ cmd := newSentinelForwarderCommand()+ var out bytes.Buffer+ cmd.SetOut(&out)+ cmd.SetErr(&out)+ cmd.SetIn(strings.NewReader(stdin))+ cmd.SetArgs(args)+ err := cmd.Execute()+ return out.String(), err+}++var forwarderArgs = []string{"install", "--system", "--endpoint", "https://dcr.example", "--dcr-immutable-id", "dcr-x", "--tenant-id", "t", "--client-id", "c"}++func TestSentinelForwarderInstallTakesTheSecretFromStdinOrTheEnvironment(t *testing.T) {+ got := stubSentinelForwarder(t, true)+ t.Setenv("AZURE_CLIENT_SECRET", "from-env")+ out, err := runSentinelForwarderCmd(t, "", forwarderArgs...)+ if err != nil || got.ClientSecret != "from-env" || !strings.Contains(out, "Sentinel forwarder installed") {+ t.Fatalf("env secret: %v %+v\n%s", err, *got, out)+ }+ if _, err := runSentinelForwarderCmd(t, "from-stdin\n", append(forwarderArgs, "--client-secret-stdin")...); err != nil || got.ClientSecret != "from-stdin" {+ t.Fatalf("stdin secret: %v %q", err, got.ClientSecret)+ }+ // A certificate install ignores a secret left in the environment.+ if _, err := runSentinelForwarderCmd(t, "", append(forwarderArgs, "--client-certificate", "app.pfx")...); err != nil ||+ got.ClientSecret != "" || got.CertificatePath != "app.pfx" {+ t.Fatalf("certificate: %v %+v", err, *got)+ }+}++func TestSentinelForwarderRefusesUserModeAndUnprivilegedRuns(t *testing.T) {+ stubSentinelForwarder(t, true)+ userArgs := []string{"install", "--endpoint", "https://dcr.example", "--dcr-immutable-id", "dcr-x", "--tenant-id", "t", "--client-id", "c"}+ if _, err := runSentinelForwarderCmd(t, "", userArgs...); err == nil || !strings.Contains(err.Error(), "--system") {+ t.Fatalf("user mode: %v", err)+ }+ stubSentinelForwarder(t, false)+ if _, err := runSentinelForwarderCmd(t, "", forwarderArgs...); err == nil || !strings.Contains(err.Error(), "elevated") {+ t.Fatalf("unprivileged: %v", err)+ }+}++func TestSentinelForwarderStatusLine(t *testing.T) {+ line := sentinelForwarderStatusLine(sentinel.Status{+ Installed: true,+ Service: service.Status{Loaded: true, Running: true},+ LastProblem: "2026-11-04T11:00:00Z WARN Retrying after response.",+ })+ if line != "Sentinel forwarder: loaded=true running=true; Vector last reported: 2026-11-04T11:00:00Z WARN Retrying after response." {+ t.Fatalf("line = %q", line)+ }+}diff --git a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.goindex 594a5036..81d98010 100644--- a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go@@ -413,16 +413,20 @@ func TestStableProgramPathPrefersTheLinkedHomebrewBinary(t *testing.T) {// with them, and must not reach for /Library.func TestUserUninstallLeavesScriptForwardersAlone(t *testing.T) {testenv.SetHome(t, t.TempDir())- old := removeScriptForwarders- called := false+ old, oldSentinel := removeScriptForwarders, removeSentinelForwarder+ called, sentinelCalled := false, falseremoveScriptForwarders = func(bool) error { called = true; return nil }- t.Cleanup(func() { removeScriptForwarders = old })+ removeSentinelForwarder = func(bool) error { sentinelCalled = true; return nil }+ t.Cleanup(func() { removeScriptForwarders, removeSentinelForwarder = old, oldSentinel })if err := Uninstall(UninstallOptions{UserMode: true}); err != nil {t.Fatal(err)}if called {t.Fatal("a user-mode uninstall removed the system S3/GCS/Falcon forwarders")}+ if sentinelCalled {+ t.Fatal("a user-mode uninstall removed the system Sentinel forwarder")+ }}// Repair tears the endpoint down and installs it again, and Install never recreates the S3, GCS ordiff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 6e59497b..8ce30f65 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -20,6 +20,7 @@ import (endpointinventory "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sentinel""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"@@ -65,6 +66,14 @@ var (reconcileManagedForwarder = func(userMode bool, logPath string) (asymptote.ReconcileResult, error) {return asymptote.ReconcileForwarder(asymptote.ReconcileOptions{UserMode: userMode, LogPath: logPath})}+ // reconcileSentinelForwarder and removeSentinelForwarder are the seams for the managed Sentinel+ // forwarder. Install always restarts it: an install or repair may have replaced the log with a+ // copy (switching log access does), which Vector only notices when it restarts.+ reconcileSentinelForwarder = func(logPath string) (sentinel.ReconcileResult, error) {+ return sentinel.Reconcile(sentinel.ReconcileOptions{LogPath: logPath, Restart: true})+ }+ removeSentinelForwarder = sentinel.Remove+ sentinelForwarderStatus = sentinel.ReadStatus)// inventoryJobController is what lifecycle needs from service.InventoryManager.@@ -379,6 +388,9 @@ type InstallResult struct {// ManagedForwarder reports the Beacon Cloud forwarder reconcile. It never fails the install:// a config Vector rejects leaves the running forwarder on its old one and is reported here.ManagedForwarder *asymptote.ReconcileResult `json:"managed_forwarder,omitempty"`+ // SentinelForwarder reports the managed Sentinel forwarder reconcile on a system install. Like+ // ManagedForwarder it never fails the install.+ SentinelForwarder *sentinel.ReconcileResult `json:"sentinel_forwarder,omitempty"`}type Status struct {@@ -402,6 +414,9 @@ type Status struct {// ScriptForwarders are the S3, GCS and Falcon forwarders the package helpers install, one entry// per forwarder that is set up on this machine.ScriptForwarders []service.Status `json:"script_forwarders,omitempty"`+ // SentinelForwarder is the managed Sentinel forwarder, on a system endpoint where one is set up+ // and this account can read its settings.+ SentinelForwarder *sentinel.Status `json:"sentinel_forwarder,omitempty"`// LogAccess is the system log's access mode, "shared" or "restricted"; empty in user mode.LogAccess string `json:"log_access,omitempty"`}@@ -836,8 +851,17 @@ func Install(opts InstallOptions) (InstallResult, error) {}managedForwarder = &reconciled}+ var sentinelForwarder *sentinel.ReconcileResult+ if opts.StartService && !cfg.UserMode {+ reconciled, err := reconcileSentinelForwarder(cfg.LogPath)+ if err != nil && reconciled.Warning == "" {+ reconciled.Warning = err.Error()+ }+ sentinelForwarder = &reconciled+ }return InstallResult{ManagedForwarder: managedForwarder,+ SentinelForwarder: sentinelForwarder,ConfigPath: configPath,CollectorConfigPath: cfg.Collector.ConfigPath,PlistPath: plistPath,@@ -901,6 +925,10 @@ func Uninstall(opts UninstallOptions) error {// from their env files, so they go with the endpoint the same way the managed forwarder does.if !cfg.UserMode && !opts.KeepForwarders {fail("remove package forwarders", removeScriptForwarders(opts.KeepConfig))+ // The service always goes, so a package upgrade can replace Vector's binary; its settings,+ // credential and read positions stay with --keep-config, which is how the MSI upgrade runs+ // the old package's uninstall, so the install that follows brings it back where it was.+ fail("remove the Sentinel forwarder", removeSentinelForwarder(opts.KeepConfig))}// The managed-ingest forwarder and its credentials go with the endpoint; server-side the// device stays registered until it is revoked from the dashboard. Repair keeps all of it.@@ -1158,10 +1186,22 @@ func buildStatus(requestedUserMode bool, effectiveCfg endpointconfig.Config, runInventoryHeartbeat: inventoryHeartbeatStatus(requestedUserMode, runtimeLog.RequestedLogPath),SessionSync: sessionSyncStatus(requestedUserMode, runtimeLog.RequestedLogPath),ScriptForwarders: scriptForwarderStatuses(),+ SentinelForwarder: sentinelForwarderStatusFor(requestedUserMode),LogAccess: logAccessOf(effectiveCfg),}}+func sentinelForwarderStatusFor(userMode bool) *sentinel.Status {+ if userMode {+ return nil+ }+ status := sentinelForwarderStatus()+ if !status.Installed {+ return nil+ }+ return &status+}+func ResolveRuntimeLog(userMode bool, logPath string) RuntimeLogSource {cfg := loadOrDefault(userMode, logPath)source := RuntimeLogSource{diff --git a/cli/beacon/internal/endpoint/lifecycle/main_test.go b/cli/beacon/internal/endpoint/lifecycle/main_test.goindex 59f7f886..bbc0051a 100644--- a/cli/beacon/internal/endpoint/lifecycle/main_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/main_test.go@@ -6,6 +6,8 @@ import ("path/filepath""runtime""testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sentinel")// TestMain puts stand-ins for the service managers first on PATH for the whole package.@@ -26,6 +28,13 @@ func TestMain(m *testing.M) {for _, name := range append(append([]string{}, inventoryJobPathEnv...), inventoryJobNameEnv...) {_ = os.Unsetenv(name)}+ // Tests that run a system install or uninstall must not reach a real Sentinel forwarder under+ // the machine's system directory; the ones about it set these themselves.+ reconcileSentinelForwarder = func(string) (sentinel.ReconcileResult, error) {+ return sentinel.ReconcileResult{Skipped: "not installed"}, nil+ }+ removeSentinelForwarder = func(bool) error { return nil }+ sentinelForwarderStatus = func() sentinel.Status { return sentinel.Status{} }os.Exit(runWithServiceManagerStandIns(m))}diff --git a/cli/beacon/internal/endpoint/lifecycle/managed_forwarder_test.go b/cli/beacon/internal/endpoint/lifecycle/managed_forwarder_test.goindex 5fcb4704..5e674eac 100644--- a/cli/beacon/internal/endpoint/lifecycle/managed_forwarder_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/managed_forwarder_test.go@@ -112,7 +112,7 @@ func TestInstallWithoutStartingServicesLeavesTheForwarderToTheCaller(t *testing.if err != nil {t.Fatalf("Install: %v", err)}- if called || result.ManagedForwarder != nil {+ if called || result.ManagedForwarder != nil || result.SentinelForwarder != nil {t.Fatal("a --no-start install reconciled the forwarder")}}diff --git a/cli/beacon/internal/endpoint/sentinel/forwarder.go b/cli/beacon/internal/endpoint/sentinel/forwarder.gonew file mode 100644index 00000000..f79afd73--- /dev/null+++ b/cli/beacon/internal/endpoint/sentinel/forwarder.go@@ -0,0 +1,688 @@+package sentinel++import (+ "bufio"+ "encoding/json"+ "errors"+ "fmt"+ "net/url"+ "os"+ "path/filepath"+ "regexp"+ "sort"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/atomicfile"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/siempack"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl"+)++// The managed forwarder: Vector running the Logs Ingestion config as a system service, set up by+// `beacon endpoint sentinel forwarder install --system`. Its state lives in one directory under the+// system base directory, apart from config.json, so a repair, which rebuilds config.json from its+// flags, never touches it. The directory is root-only (POSIX) or SYSTEM and Administrators only+// (Windows), because it holds the Entra credential.++const (+ // CredentialClientSecret and CredentialCertificate are the two app registration credentials.+ CredentialClientSecret = "client_secret"+ CredentialCertificate = "client_certificate"++ settingsFileName = "forwarder.json"+ secretsFileName = "secrets.json"+ certificateFileName = "client.pfx"+ configFileName = "vector.toml"+ dataDirName = "data"+ logDirName = "logs"++ // secretBackend is the Vector secret backend the config reads the credential through.+ secretBackend = "beacon_sentinel"++ settingsVersion = 1++ // vectorLogRetention is how long Vector's own daily warning logs are kept.+ vectorLogRetention = 7 * 24 * time.Hour+)++// ForwarderSpec is how the forwarder runs under each service manager. Vector drains for at most+// ten seconds on stop, and the Windows stop budget outlasts that, so a stop never gives up on a+// Vector that is still flushing. AZURE_AUTHORITY_HOST moves the Entra token authority, for a+// sovereign cloud.+func ForwarderSpec(authorityHost string) service.ForwarderSpec {+ spec := service.ForwarderSpec{+ Label: "com.beacon.endpoint.sentinel-forwarder",+ SystemdUnit: "beacon-sentinel-forwarder.service",+ WindowsService: "BeaconSentinelForwarder",+ Description: "Beacon endpoint forwarder to Microsoft Sentinel",+ Documentation: "https://docs.beacon.sh/log-forwarding/microsoft-sentinel",+ Args: []string{"--graceful-shutdown-limit-secs", "10"},+ StopTimeout: 30 * time.Second,+ }+ if authorityHost != "" {+ spec.Env = []string{"AZURE_AUTHORITY_HOST=" + authorityHost}+ }+ return spec+}++// Settings is forwarder.json: everything needed to render the config again, and nothing secret.+type Settings struct {+ Version int `json:"version"`+ Endpoint string `json:"endpoint"`+ DCRImmutableID string `json:"dcr_immutable_id"`+ TenantID string `json:"tenant_id"`+ ClientID string `json:"client_id"`+ Credential string `json:"credential"`+ AuthorityHost string `json:"authority_host,omitempty"`+ ReadFrom string `json:"read_from"`+ LogPath string `json:"log_path"`+ InstalledAt string `json:"installed_at"`+}++// InstallOptions is what `forwarder install` was given.+type InstallOptions struct {+ Endpoint string+ DCRImmutableID string+ TenantID string+ ClientID string+ // ClientSecret, or CertificatePath (a PFX file, copied into the forwarder's directory) with an+ // optional CertificatePassword. Exactly one of ClientSecret and CertificatePath.+ ClientSecret string+ CertificatePath string+ CertificatePassword string+ AuthorityHost string+ // ReadFrom is where Vector starts in a log it has no checkpoint for: "beginning" (the default)+ // sends the current log once, "end" only what is written from now on.+ ReadFrom string+ LogPath string+ // VectorBin names a Vector binary ahead of the usual search.+ VectorBin string+}++// InstallResult reports what install set up.+type InstallResult struct {+ Dir string `json:"dir"`+ Config string `json:"config"`+ Unit string `json:"unit"`+ Vector string `json:"vector"`+ Service service.Status `json:"service"`+}++// forwarderService is what the forwarder needs from service.ForwarderManager.+type forwarderService interface {+ Supported() bool+ UnsupportedReason() string+ WriteUnit(vectorBin, configPath string) (string, error)+ UnitCurrent(vectorBin, configPath string) (bool, error)+ Load() error+ Unload() error+ RemoveUnits()+ Status() service.Status+}++// Seams for tests: no service manager, no real Vector, no system directory.+var (+ newForwarderService = func(spec service.ForwarderSpec) forwarderService {+ return service.ForwarderManager{Spec: spec}+ }+ findVector = asymptote.FindVector+ validateVector = asymptote.ValidateVectorConfig+ ForwarderDir = func() string {+ return filepath.Join(endpointconfig.SystemBaseDir(), "forwarders", "sentinel")+ }+ now = time.Now+)++var (+ dcrIDPattern = regexp.MustCompile(`^dcr-[0-9a-f]{32}$`)+ guidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$`)+)++// ErrNotInstalled is returned by Remove and Status when no forwarder was set up.+var ErrNotInstalled = errors.New("the Sentinel forwarder is not installed; set it up with `beacon endpoint sentinel forwarder install --system`")++func (o InstallOptions) settings() (Settings, error) {+ s := Settings{+ Version: settingsVersion,+ Endpoint: strings.TrimRight(strings.TrimSpace(o.Endpoint), "/"),+ DCRImmutableID: strings.TrimSpace(o.DCRImmutableID),+ TenantID: strings.TrimSpace(o.TenantID),+ ClientID: strings.TrimSpace(o.ClientID),+ AuthorityHost: strings.TrimRight(strings.TrimSpace(o.AuthorityHost), "/"),+ ReadFrom: strings.TrimSpace(o.ReadFrom),+ LogPath: o.LogPath,+ }+ if err := httpsURL("--endpoint", s.Endpoint, true); err != nil {+ return s, err+ }+ if !dcrIDPattern.MatchString(s.DCRImmutableID) {+ return s, fmt.Errorf("--dcr-immutable-id %q is not a DCR immutable ID (dcr- followed by 32 hex digits)", s.DCRImmutableID)+ }+ if !guidPattern.MatchString(s.TenantID) {+ return s, fmt.Errorf("--tenant-id %q is not a GUID", s.TenantID)+ }+ if !guidPattern.MatchString(s.ClientID) {+ return s, fmt.Errorf("--client-id %q is not a GUID", s.ClientID)+ }+ if s.AuthorityHost != "" {+ if err := httpsURL("--authority-host", s.AuthorityHost, false); err != nil {+ return s, err+ }+ }+ switch s.ReadFrom {+ case "":+ s.ReadFrom = "beginning"+ case "beginning", "end":+ default:+ return s, fmt.Errorf("--read-from must be beginning or end, not %q", s.ReadFrom)+ }+ switch {+ case o.ClientSecret != "" && o.CertificatePath != "":+ return s, errors.New("give a client secret or a certificate, not both")+ case o.ClientSecret != "":+ s.Credential = CredentialClientSecret+ case o.CertificatePath != "":+ s.Credential = CredentialCertificate+ default:+ return s, errors.New("no credential: set AZURE_CLIENT_SECRET (or pass --client-secret-stdin), or pass --client-certificate with a PFX file")+ }+ if strings.TrimSpace(s.LogPath) == "" {+ return s, errors.New("no runtime log path")+ }+ return s, nil+}++// httpsURL accepts an https URL with a host, and with a path only where one makes sense.+func httpsURL(flag, raw string, bare bool) error {+ u, err := url.Parse(raw)+ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {+ return fmt.Errorf("%s %q must be an https URL", flag, raw)+ }+ if bare && u.Path != "" {+ return fmt.Errorf("%s %q must be the DCR's logs ingestion URL alone, with no path", flag, raw)+ }+ return nil+}++type renderOptions struct {+ Settings Settings+ DataDir string+ SecretsPath string+ CertificatePath string+ LogDir string+ HasCertificatePassword bool+}++// renderForwarderConfig fills the pack's template with literal values, the credential read through+// Vector's file secret backend, and Vector's own warnings sent to a daily log.+func renderForwarderConfig(o renderOptions) string {+ s := o.Settings+ q := func(v string) string { return `"` + siempack.TOMLEscape(v) + `"` }+ var auth strings.Builder+ switch s.Credential {+ case CredentialCertificate:+ auth.WriteString("azure_credential_kind = \"client_certificate_credential\"\n")+ fmt.Fprintf(&auth, "azure_tenant_id = %s\nazure_client_id = %s\n", q(s.TenantID), q(s.ClientID))+ fmt.Fprintf(&auth, "certificate_path = %s\n", q(o.CertificatePath))+ if o.HasCertificatePassword {+ fmt.Fprintf(&auth, "certificate_password = \"SECRET[%s.certificate_password]\"\n", secretBackend)+ }+ default:+ auth.WriteString("azure_credential_kind = \"client_secret_credential\"\n")+ fmt.Fprintf(&auth, "azure_tenant_id = %s\nazure_client_id = %s\n", q(s.TenantID), q(s.ClientID))+ fmt.Fprintf(&auth, "azure_client_secret = \"SECRET[%s.client_secret]\"\n", secretBackend)+ }+ var secrets string+ if s.Credential == CredentialClientSecret || o.HasCertificatePassword {+ secrets = fmt.Sprintf("\n[secret.%s]\ntype = \"file\"\npath = %s\n", secretBackend, q(o.SecretsPath))+ }+ vectorLog := fmt.Sprintf(`+# Vector's own warnings and errors, one file a day, kept for a week. A Windows service has nowhere+# else to write them.+[sources.beacon_vector_logs]+type = "internal_logs"++[transforms.beacon_vector_problems]+type = "filter"+inputs = ["beacon_vector_logs"]+condition = '.metadata.level == "WARN" || .metadata.level == "ERROR"'++[sinks.beacon_vector_log]+type = "file"+inputs = ["beacon_vector_problems"]+path = %s++[sinks.beacon_vector_log.encoding]+codec = "json"+`, q(filepath.Join(o.LogDir, "vector-%Y-%m-%d.log")))+ note := "# Written by `beacon endpoint sentinel forwarder install`, which also runs it as a service.\n" ++ "# Run that again to change a setting: install, repair and upgrades replace edits made here."+ return fillTemplate(mustRead("pack/vector.toml.tmpl"), map[string]string{+ "{{SETTINGS_NOTE}}": note,+ "{{DATA_DIR}}": siempack.TOMLEscape(o.DataDir),+ "{{SECRET_BACKEND}}": secrets,+ "{{READ_FROM}}": s.ReadFrom,+ "{{ENDPOINT}}": siempack.TOMLEscape(s.Endpoint),+ "{{DCR_IMMUTABLE_ID}}": siempack.TOMLEscape(s.DCRImmutableID),+ "{{AUTH}}": auth.String(),+ "{{VECTOR_LOG}}": vectorLog,+ }, s.LogPath)+}++// manualVectorConfig is the pack's vector.toml for running Vector by hand: values come from the+// Vector service environment, and {{LOG_PATH}} is left for the pack installer.+func manualVectorConfig() string {+ note := `# Set in the Vector service environment, not in Beacon config:+# BEACON_SENTINEL_DCE_ENDPOINT https://<dcr>.<region>-1.ingest.monitor.azure.com (the DCR's+# logs ingestion URL, or a Data Collection Endpoint's)+# BEACON_SENTINEL_DCR_IMMUTABLE_ID dcr-... (the DCR's immutableId)+# AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET+# Or let ` + "`beacon endpoint sentinel forwarder install --system`" + ` write this config with the values+# in it and run Vector as a service.`+ auth := `azure_credential_kind = "client_secret_credential"+azure_tenant_id = "${AZURE_TENANT_ID}"+azure_client_id = "${AZURE_CLIENT_ID}"+azure_client_secret = "${AZURE_CLIENT_SECRET}"+`+ return fillTemplate(mustRead("pack/vector.toml.tmpl"), map[string]string{+ "{{SETTINGS_NOTE}}": note,+ "{{DATA_DIR}}": "/var/lib/vector/beacon-sentinel",+ "{{SECRET_BACKEND}}": "",+ "{{READ_FROM}}": "end",+ "{{ENDPOINT}}": "${BEACON_SENTINEL_DCE_ENDPOINT}",+ "{{DCR_IMMUTABLE_ID}}": "${BEACON_SENTINEL_DCR_IMMUTABLE_ID}",+ "{{AUTH}}": auth,+ "{{VECTOR_LOG}}": "",+ }, "")+}++func fillTemplate(tmpl string, values map[string]string, logPath string) string {+ keys := make([]string, 0, len(values))+ for key := range values {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ pairs := make([]string, 0, 2*len(keys))+ for _, key := range keys {+ pairs = append(pairs, key, values[key])+ }+ out := strings.NewReplacer(pairs...).Replace(tmpl)+ if logPath != "" {+ out = siempack.RenderLogPath(configFileName, out, logPath)+ }+ return out+}++func paths(dir string) (settings, secrets, certificate, config, data, logs string) {+ return filepath.Join(dir, settingsFileName), filepath.Join(dir, secretsFileName),+ filepath.Join(dir, certificateFileName), filepath.Join(dir, configFileName),+ filepath.Join(dir, dataDirName), filepath.Join(dir, logDirName)+}++// Install sets up the forwarder, or replaces one already set up. Nothing on disk or in the service+// manager changes until Vector has accepted the new config, so a rejected install leaves a working+// forwarder as it was. The caller has checked for system privileges.+func Install(o InstallOptions) (InstallResult, error) {+ settings, err := o.settings()+ if err != nil {+ return InstallResult{}, err+ }+ manager := newForwarderService(ForwarderSpec(settings.AuthorityHost))+ if !manager.Supported() {+ return InstallResult{}, errors.New(manager.UnsupportedReason())+ }+ vector, err := findVector(o.VectorBin)+ if err != nil {+ return InstallResult{}, err+ }+ var certificate []byte+ if settings.Credential == CredentialCertificate {+ if certificate, err = readCertificate(o.CertificatePath); err != nil {+ return InstallResult{}, err+ }+ }+ secrets := map[string]string{}+ switch {+ case settings.Credential == CredentialClientSecret:+ secrets["client_secret"] = o.ClientSecret+ case o.CertificatePassword != "":+ secrets["certificate_password"] = o.CertificatePassword+ }+ secretsJSON, err := json.Marshal(secrets)+ if err != nil {+ return InstallResult{}, err+ }++ dir := ForwarderDir()+ if err := ensurePrivateDir(dir); err != nil {+ return InstallResult{}, err+ }+ settingsPath, secretsPath, certificatePath, configPath, dataDir, logDir := paths(dir)++ // Proved in a scratch directory first, with the real credential so the secret backend is+ // exercised too, and nothing outside it touched.+ scratch, err := os.MkdirTemp(dir, ".preflight-*")+ if err != nil {+ return InstallResult{}, err+ }+ defer os.RemoveAll(scratch)+ preflight := renderOptions{+ Settings: settings,+ DataDir: filepath.Join(scratch, dataDirName),+ SecretsPath: filepath.Join(scratch, secretsFileName),+ CertificatePath: filepath.Join(scratch, certificateFileName),+ LogDir: filepath.Join(scratch, logDirName),+ HasCertificatePassword: o.CertificatePassword != "",+ }+ if err := writeFiles(preflight, secretsJSON, certificate); err != nil {+ return InstallResult{}, err+ }+ preflightConfig := filepath.Join(scratch, configFileName)+ if err := atomicfile.Write(preflightConfig, []byte(renderForwarderConfig(preflight)), 0o600); err != nil {+ return InstallResult{}, err+ }+ if err := validateVector(vector.Path, preflightConfig); err != nil {+ return InstallResult{}, err+ }++ final := renderOptions{+ Settings: settings,+ DataDir: dataDir,+ SecretsPath: secretsPath,+ CertificatePath: certificatePath,+ LogDir: logDir,+ HasCertificatePassword: o.CertificatePassword != "",+ }+ if err := writeFiles(final, secretsJSON, certificate); err != nil {+ return InstallResult{}, err+ }+ if settings.Credential != CredentialCertificate {+ _ = os.Remove(certificatePath)+ }+ if err := atomicfile.Write(configPath, []byte(renderForwarderConfig(final)), 0o600); err != nil {+ return InstallResult{}, err+ }+ settings.InstalledAt = now().UTC().Format(time.RFC3339)+ settingsJSON, err := json.MarshalIndent(settings, "", " ")+ if err != nil {+ return InstallResult{}, err+ }+ if err := atomicfile.Write(settingsPath, append(settingsJSON, '\n'), 0o600); err != nil {+ return InstallResult{}, err+ }+ unit, err := manager.WriteUnit(vector.Path, configPath)+ if err != nil {+ return InstallResult{}, err+ }+ if err := manager.Load(); err != nil {+ return InstallResult{}, fmt.Errorf("%w; Vector's own log is in %s", err, logDir)+ }+ return InstallResult{Dir: dir, Config: configPath, Unit: unit, Vector: vector.Path, Service: manager.Status()}, nil+}++// writeFiles writes the credential files and the directories the config points at.+func writeFiles(o renderOptions, secretsJSON, certificate []byte) error {+ for _, dir := range []string{o.DataDir, o.LogDir} {+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return err+ }+ }+ if o.Settings.Credential == CredentialClientSecret || o.HasCertificatePassword {+ if err := sysacl.WriteSecretFile(o.SecretsPath, secretsJSON); err != nil {+ return fmt.Errorf("write %s: %w", o.SecretsPath, err)+ }+ } else {+ _ = os.Remove(o.SecretsPath)+ }+ if certificate != nil {+ if err := sysacl.WriteSecretFile(o.CertificatePath, certificate); err != nil {+ return fmt.Errorf("write %s: %w", o.CertificatePath, err)+ }+ }+ return nil+}++func readCertificate(path string) ([]byte, error) {+ info, err := os.Stat(path)+ if err != nil {+ return nil, fmt.Errorf("--client-certificate: %w", err)+ }+ if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 1<<20 {+ return nil, fmt.Errorf("--client-certificate %s must be a PFX file of at most 1 MB", path)+ }+ return os.ReadFile(path)+}++// ensurePrivateDir creates dir readable only by root, or by SYSTEM and Administrators.+func ensurePrivateDir(dir string) error {+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return err+ }+ if err := os.Chmod(dir, 0o700); err != nil {+ return err+ }+ return sysacl.SecureSecretDir(dir)+}++// ReadSettings returns forwarder.json, or ErrNotInstalled.+func ReadSettings() (Settings, error) {+ settingsPath, _, _, _, _, _ := paths(ForwarderDir())+ data, err := os.ReadFile(settingsPath)+ if errors.Is(err, os.ErrNotExist) {+ return Settings{}, ErrNotInstalled+ }+ if err != nil {+ return Settings{}, err+ }+ var s Settings+ if err := json.Unmarshal(data, &s); err != nil {+ return Settings{}, fmt.Errorf("%s is not valid JSON: %w", settingsPath, err)+ }+ return s, nil+}++// Remove stops and deletes the service. keepState leaves the directory, so a later install or+// upgrade brings the forwarder back with its credential and read positions: the MSI upgrade+// removes the old package this way before installing the new one.+func Remove(keepState bool) error {+ settings, err := ReadSettings()+ if err != nil && !errors.Is(err, ErrNotInstalled) {+ // Unreadable settings must not keep the service running; remove it with the default name.+ settings = Settings{}+ }+ manager := newForwarderService(ForwarderSpec(settings.AuthorityHost))+ unloadErr := manager.Unload()+ manager.RemoveUnits()+ if keepState {+ return unloadErr+ }+ if err := os.RemoveAll(ForwarderDir()); err != nil {+ return errors.Join(unloadErr, err)+ }+ return unloadErr+}++// ReconcileResult reports what Reconcile did.+type ReconcileResult struct {+ Skipped string `json:"skipped,omitempty"`+ Unchanged bool `json:"unchanged,omitempty"`+ Restarted bool `json:"restarted,omitempty"`+ Warning string `json:"warning,omitempty"`+}++// Message is a one-line summary for install, repair and the reconcile command.+func (r ReconcileResult) Message() string {+ switch {+ case r.Skipped != "":+ return "Sentinel forwarder: " + r.Skipped+ case r.Warning != "":+ return "Sentinel forwarder: " + r.Warning+ case r.Unchanged:+ return "Sentinel forwarder: running, unchanged"+ default:+ return "Sentinel forwarder: restarted"+ }+}++// ReconcileOptions drives Reconcile.+type ReconcileOptions struct {+ // LogPath is the endpoint's runtime log; empty keeps the one recorded at install.+ LogPath string+ // Restart restarts a running forwarder even when nothing about it changed. Install and repair+ // set it, because they may have replaced the log with a copy under the same name (switching+ // log access does), and Vector, which recognizes a file by its first line, keeps reading the+ // replaced file until it restarts. After a restart it resumes in the copy where it left off.+ Restart bool+}++// Reconcile brings an installed forwarder up to date with this version: it re-renders the config+// from the stored settings and the pack this binary carries, has Vector validate it, rewrites the+// service definition if it changed, and makes sure the service is running. Install, repair and+// package upgrades run it, which is also how the MSI upgrade puts back the service its uninstall+// step removed. A config Vector rejects is a warning that keeps the old one.+func Reconcile(opts ReconcileOptions) (ReconcileResult, error) {+ logPath := opts.LogPath+ settings, err := ReadSettings()+ if errors.Is(err, ErrNotInstalled) {+ return ReconcileResult{Skipped: "not installed"}, nil+ }+ if err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ manager := newForwarderService(ForwarderSpec(settings.AuthorityHost))+ if !manager.Supported() {+ return ReconcileResult{Skipped: manager.UnsupportedReason()}, nil+ }+ vector, err := findVector("")+ if err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ dir := ForwarderDir()+ if err := ensurePrivateDir(dir); err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ pruneVectorLogs(filepath.Join(dir, logDirName))+ if logPath != "" {+ settings.LogPath = logPath+ }+ _, secretsPath, certificatePath, configPath, dataDir, logDir := paths(dir)+ hasPassword := false+ if settings.Credential == CredentialCertificate {+ if _, err := os.Stat(secretsPath); err == nil {+ hasPassword = true+ }+ }+ for _, d := range []string{dataDir, logDir} {+ if err := os.MkdirAll(d, 0o700); err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ }+ rendered := renderForwarderConfig(renderOptions{+ Settings: settings,+ DataDir: dataDir,+ SecretsPath: secretsPath,+ CertificatePath: certificatePath,+ LogDir: logDir,+ HasCertificatePassword: hasPassword,+ })+ current, _ := os.ReadFile(configPath)+ configChanged := string(current) != rendered+ if configChanged {+ candidate := configPath + ".new"+ if err := atomicfile.Write(candidate, []byte(rendered), 0o600); err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ if err := validateVector(vector.Path, candidate); err != nil {+ _ = os.Remove(candidate)+ return ReconcileResult{Warning: "kept the previous config: " + err.Error()}, nil+ }+ if err := os.Rename(candidate, configPath); err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ }+ unitCurrent, _ := manager.UnitCurrent(vector.Path, configPath)+ if !unitCurrent {+ if _, err := manager.WriteUnit(vector.Path, configPath); err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ }+ if !opts.Restart && !configChanged && unitCurrent && manager.Status().Running {+ return ReconcileResult{Unchanged: true}, nil+ }+ if err := manager.Load(); err != nil {+ return ReconcileResult{Warning: err.Error()}, err+ }+ return ReconcileResult{Restarted: true}, nil+}++// Status is what `forwarder status` and `endpoint status` show.+type Status struct {+ Installed bool `json:"installed"`+ Settings *Settings `json:"settings,omitempty"`+ Service service.Status `json:"service"`+ // LastProblem is the newest warning or error in Vector's own log, if any.+ LastProblem string `json:"last_problem,omitempty"`+}++// ReadStatus reports the forwarder's settings, service state and Vector's latest complaint.+func ReadStatus() Status {+ settings, err := ReadSettings()+ if err != nil {+ manager := newForwarderService(ForwarderSpec(""))+ status := Status{Service: manager.Status()}+ return status+ }+ manager := newForwarderService(ForwarderSpec(settings.AuthorityHost))+ return Status{+ Installed: true,+ Settings: &settings,+ Service: manager.Status(),+ LastProblem: lastVectorProblem(filepath.Join(ForwarderDir(), logDirName)),+ }+}++// lastVectorProblem reads the last line of the newest daily log.+func lastVectorProblem(logDir string) string {+ matches, _ := filepath.Glob(filepath.Join(logDir, "vector-*.log"))+ if len(matches) == 0 {+ return ""+ }+ sort.Strings(matches)+ f, err := os.Open(matches[len(matches)-1])+ if err != nil {+ return ""+ }+ defer f.Close()+ var last string+ scanner := bufio.NewScanner(f)+ scanner.Buffer(make([]byte, 64*1024), 1<<20)+ for scanner.Scan() {+ if line := strings.TrimSpace(scanner.Text()); line != "" {+ last = line+ }+ }+ var entry struct {+ Timestamp string `json:"timestamp"`+ Message string `json:"message"`+ Metadata struct {+ Level string `json:"level"`+ } `json:"metadata"`+ }+ if json.Unmarshal([]byte(last), &entry) != nil || entry.Message == "" {+ return last+ }+ return strings.TrimSpace(fmt.Sprintf("%s %s %s", entry.Timestamp, entry.Metadata.Level, entry.Message))+}++func pruneVectorLogs(logDir string) {+ matches, _ := filepath.Glob(filepath.Join(logDir, "vector-*.log"))+ cutoff := now().Add(-vectorLogRetention)+ for _, path := range matches {+ if info, err := os.Stat(path); err == nil && info.ModTime().Before(cutoff) {+ _ = os.Remove(path)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/sentinel/forwarder_e2e_test.go b/cli/beacon/internal/endpoint/sentinel/forwarder_e2e_test.gonew file mode 100644index 00000000..35f19a56--- /dev/null+++ b/cli/beacon/internal/endpoint/sentinel/forwarder_e2e_test.go@@ -0,0 +1,290 @@+package sentinel++import (+ "bufio"+ "encoding/json"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sentinel/sentinelmock"+)++// The forwarder's real config, run by real Vector against a mock of Entra ID and the Logs Ingestion+// API. It proves what no unit test can: that Vector 0.56 accepts the config, authenticates, posts+// the rows the DCR expects, survives a stretch of 403s, follows a rotation, does not resend after a+// restart or after the restricted-mode switch replaces the log with a copy, and never loses a line.+//+// Needs BEACON_TEST_VECTOR_BIN. Vector's token client trusts only the operating system's store, so+// the mock's CA has to be trusted there: on Linux through SSL_CERT_FILE, which this test sets; on+// Windows by importing it into LocalMachine\Root, which this test does only when+// BEACON_TEST_SENTINEL_TRUST_STORE=1 (CI) because it changes the machine. macOS has no switch for it,+// so the test skips there.+func TestForwarderConfigDeliversThroughRealVector(t *testing.T) {+ vectorBin := os.Getenv("BEACON_TEST_VECTOR_BIN")+ if vectorBin == "" {+ t.Skip("set BEACON_TEST_VECTOR_BIN to run the forwarder against real Vector")+ }+ switch runtime.GOOS {+ case "darwin":+ t.Skip("Vector's token client on macOS trusts only the keychain; run this on Linux or Windows")+ case "windows":+ if os.Getenv("BEACON_TEST_SENTINEL_TRUST_STORE") != "1" {+ t.Skip("set BEACON_TEST_SENTINEL_TRUST_STORE=1 to let this test trust the mock's CA in LocalMachine\\Root")+ }+ }++ dir := t.TempDir()+ caFile := filepath.Join(dir, "mock-ca.pem")+ settings := Settings{+ Endpoint: "",+ DCRImmutableID: "dcr-0123456789abcdef0123456789abcdef",+ TenantID: "11111111-2222-3333-4444-555555555555",+ ClientID: "66666666-7777-8888-9999-000000000000",+ Credential: CredentialClientSecret,+ ReadFrom: "beginning",+ LogPath: filepath.Join(dir, "logs", "runtime.jsonl"),+ }+ mock, err := sentinelmock.Start(sentinelmock.Options{+ TenantID: settings.TenantID, ClientID: settings.ClientID, ClientSecret: "s3cret",+ DCRImmutableID: settings.DCRImmutableID, Stream: "Custom-BeaconRuntimeRaw", CAFile: caFile,+ // A role assignment that has not propagated yet.+ IngestStatuses: []int{403, 403, 403},+ })+ if err != nil {+ t.Fatal(err)+ }+ defer mock.Close()+ settings.Endpoint = mock.URL+ trustCA(t, caFile)++ state := filepath.Join(dir, "forwarder")+ render := renderOptions{+ Settings: settings,+ DataDir: filepath.Join(state, dataDirName),+ SecretsPath: filepath.Join(state, secretsFileName),+ LogDir: filepath.Join(state, logDirName),+ }+ if err := writeFiles(render, []byte(`{"client_secret":"s3cret"}`), nil); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(filepath.Dir(settings.LogPath), 0o755); err != nil {+ t.Fatal(err)+ }+ configPath := filepath.Join(state, configFileName)+ if err := os.WriteFile(configPath, []byte(renderForwarderConfig(render)), 0o600); err != nil {+ t.Fatal(err)+ }+ if out, err := exec.Command(vectorBin, "validate", "--skip-healthchecks", configPath).CombinedOutput(); err != nil {+ t.Fatalf("vector validate: %v\n%s", err, out)+ }++ log := &testLog{t: t, path: settings.LogPath}+ log.append(5) // written before Vector starts, like the install backfill++ vector := startVector(t, vectorBin, configPath, mock.URL, caFile)+ log.append(20)+ waitForRows(t, mock, log.ids, 90*time.Second)+ if _, _, rejected := mock.Counts(); rejected != 3 {+ t.Fatalf("the mock refused %d requests, want the 3 injected 403s to have been retried", rejected)+ }++ // A rotation: lines appended just before it land in runtime.jsonl.1.+ log.append(10)+ if err := os.Rename(settings.LogPath, settings.LogPath+".1"); err != nil {+ t.Fatal(err)+ }+ log.append(10)+ waitForRows(t, mock, log.ids, 60*time.Second)++ graceful := vector.stop()+ log.append(5) // written while Vector is down+ vector = startVector(t, vectorBin, configPath, mock.URL, caFile)+ log.append(5)+ waitForRows(t, mock, log.ids, 60*time.Second)++ // The restricted-mode switch replaces the log with a copy under the same name. Vector recognizes+ // a file by its first line, so it keeps reading the replaced one; install and repair, which make+ // the switch, then restart the forwarder (Reconcile with Restart), and it resumes in the copy.+ data, err := os.ReadFile(settings.LogPath)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(settings.LogPath+".copy", data, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Rename(settings.LogPath+".copy", settings.LogPath); err != nil {+ t.Fatal(err)+ }+ log.append(5) // between the switch and the restart+ if !vector.stop() {+ graceful = false+ }+ vector = startVector(t, vectorBin, configPath, mock.URL, caFile)+ log.append(5)+ waitForRows(t, mock, log.ids, 60*time.Second)+ time.Sleep(3 * time.Second) // let anything resent arrive before counting+ vector.stop()++ seen := map[string]int{}+ for _, row := range mock.Rows() {+ var event struct {+ Event struct {+ ID string `json:"id"`+ } `json:"event"`+ }+ if err := json.Unmarshal([]byte(row.RawData), &event); err != nil {+ t.Fatalf("RawData is not the Beacon line: %v: %s", err, row.RawData)+ }+ if row.TimeGenerated == "" {+ t.Fatalf("a row has no TimeGenerated: %+v", row)+ }+ seen[event.Event.ID]+++ }+ for _, id := range log.ids {+ if seen[id] == 0 {+ t.Errorf("event %s never reached the mock", id)+ }+ // Vector saves read positions on a graceful stop. Without one (Windows has no console signal+ // to send it here) a resend is allowed; a loss never is.+ if seen[id] > 1 && graceful {+ t.Errorf("event %s was sent %d times", id, seen[id])+ }+ }+ if !t.Failed() {+ tokens, ingests, _ := mock.Counts()+ t.Logf("%d events delivered exactly once across a rotation, a restart and a log copy; %d token requests, %d ingest requests", len(log.ids), tokens, ingests)+ }+}++type testLog struct {+ t *testing.T+ path string+ ids []string+}++func (l *testLog) append(n int) {+ f, err := os.OpenFile(l.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)+ if err != nil {+ l.t.Fatal(err)+ }+ defer f.Close()+ w := bufio.NewWriter(f)+ for i := 0; i < n; i++ {+ id := fmt.Sprintf("00000000-0000-4000-8000-%012d", len(l.ids))+ l.ids = append(l.ids, id)+ line, _ := json.Marshal(map[string]any{+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),+ "vendor": "Asymptote Labs",+ "product": "Beacon Endpoint Agent",+ "schema_version": "1.0",+ "event": map[string]any{"id": id, "action": "tool.invoked", "category": "agent"},+ "user": map[string]any{"name": "tester", "uid": "1000"},+ })+ w.Write(append(line, '\n'))+ }+ if err := w.Flush(); err != nil {+ l.t.Fatal(err)+ }+}++type vectorProcess struct {+ t *testing.T+ cmd *exec.Cmd+ out *strings.Builder+}++func startVector(t *testing.T, bin, config, authority, caFile string) *vectorProcess {+ t.Helper()+ cmd := exec.Command(bin, "--config", config, "--graceful-shutdown-limit-secs", "10")+ cmd.Env = append(os.Environ(), "AZURE_AUTHORITY_HOST="+authority, "VECTOR_LOG=info")+ if runtime.GOOS == "linux" {+ cmd.Env = append(cmd.Env, "SSL_CERT_FILE="+caFile)+ }+ out := &strings.Builder{}+ cmd.Stdout, cmd.Stderr = out, out+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ p := &vectorProcess{t: t, cmd: cmd, out: out}+ t.Cleanup(func() {+ if cmd.ProcessState == nil {+ _ = cmd.Process.Kill()+ _ = cmd.Wait()+ }+ if t.Failed() {+ t.Logf("vector output:\n%s", out.String())+ }+ })+ return p+}++// stop ends Vector, gracefully where the platform allows it, and reports whether it did.+func (p *vectorProcess) stop() bool {+ graceful := runtime.GOOS != "windows"+ if graceful {+ _ = p.cmd.Process.Signal(os.Interrupt)+ } else {+ _ = p.cmd.Process.Kill()+ }+ done := make(chan struct{})+ go func() { _ = p.cmd.Wait(); close(done) }()+ select {+ case <-done:+ case <-time.After(30 * time.Second):+ _ = p.cmd.Process.Kill()+ <-done+ graceful = false+ }+ return graceful+}++func waitForRows(t *testing.T, mock *sentinelmock.Server, ids []string, timeout time.Duration) {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for {+ seen := map[string]bool{}+ for _, row := range mock.Rows() {+ for _, id := range ids {+ if strings.Contains(row.RawData, id) {+ seen[id] = true+ }+ }+ }+ if len(seen) == len(ids) {+ return+ }+ if time.Now().After(deadline) {+ tokens, ingests, rejected := mock.Counts()+ t.Fatalf("%d of %d events reached the mock in %s (token requests %d, ingest requests %d, refused %d)",+ len(seen), len(ids), timeout, tokens, ingests, rejected)+ }+ time.Sleep(500 * time.Millisecond)+ }+}++// trustCA puts the mock's CA where Vector's token client looks. Linux needs nothing here:+// startVector points SSL_CERT_FILE at it.+func trustCA(t *testing.T, caFile string) {+ t.Helper()+ if runtime.GOOS != "windows" {+ return+ }+ if out, err := exec.Command("certutil", "-addstore", "-f", "Root", caFile).CombinedOutput(); err != nil {+ t.Fatalf("certutil -addstore Root: %v\n%s", err, out)+ }+ t.Cleanup(func() {+ // The mock's CA has its own random name; delete exactly that certificate.+ out, _ := exec.Command("powershell", "-NoProfile", "-Command",+ `$c = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2('`+caFile+`'); `++ `Get-ChildItem Cert:\LocalMachine\Root | Where-Object Thumbprint -eq $c.Thumbprint | Remove-Item`).CombinedOutput()+ if len(out) > 0 {+ t.Logf("removing the mock CA: %s", out)+ }+ })+}diff --git a/cli/beacon/internal/endpoint/sentinel/forwarder_test.go b/cli/beacon/internal/endpoint/sentinel/forwarder_test.gonew file mode 100644index 00000000..ac3c9048--- /dev/null+++ b/cli/beacon/internal/endpoint/sentinel/forwarder_test.go@@ -0,0 +1,367 @@+package sentinel++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/siempack"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++type fakeService struct {+ spec service.ForwarderSpec+ unsupported string+ units []string+ loads int+ unloads int+ removed int+ running bool+ current bool+}++func (f *fakeService) Supported() bool { return f.unsupported == "" }+func (f *fakeService) UnsupportedReason() string { return f.unsupported }+func (f *fakeService) WriteUnit(vectorBin, configPath string) (string, error) {+ f.units = append(f.units, vectorBin+" "+configPath)+ f.current = true+ return "unit:" + f.spec.Label, nil+}+func (f *fakeService) UnitCurrent(string, string) (bool, error) { return f.current, nil }+func (f *fakeService) Load() error { f.loads++; f.running = true; return nil }+func (f *fakeService) Unload() error { f.unloads++; f.running = false; return nil }+func (f *fakeService) RemoveUnits() { f.removed++ }+func (f *fakeService) Status() service.Status {+ return service.Status{Label: f.spec.Label, Loaded: f.running, Running: f.running}+}++type forwarderFixture struct {+ dir string+ svc *fakeService+ validated []string+ reject error+}++func newForwarderFixture(t *testing.T) *forwarderFixture {+ t.Helper()+ f := &forwarderFixture{dir: filepath.Join(t.TempDir(), "forwarders", "sentinel"), svc: &fakeService{}}+ oldService, oldFind, oldValidate, oldDir, oldNow := newForwarderService, findVector, validateVector, ForwarderDir, now+ newForwarderService = func(spec service.ForwarderSpec) forwarderService { f.svc.spec = spec; return f.svc }+ findVector = func(string) (asymptote.VectorInfo, error) {+ return asymptote.VectorInfo{Path: "/opt/beacon/bin/vector", Version: "0.56.0"}, nil+ }+ validateVector = func(_, config string) error {+ f.validated = append(f.validated, config)+ return f.reject+ }+ ForwarderDir = func() string { return f.dir }+ now = func() time.Time { return time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) }+ t.Cleanup(func() {+ newForwarderService, findVector, validateVector, ForwarderDir, now = oldService, oldFind, oldValidate, oldDir, oldNow+ })+ return f+}++func validInstall() InstallOptions {+ return InstallOptions{+ Endpoint: "https://beacon-dcr-abcd.eastus-1.ingest.monitor.azure.com/",+ DCRImmutableID: "dcr-0123456789abcdef0123456789abcdef",+ TenantID: "11111111-2222-3333-4444-555555555555",+ ClientID: "66666666-7777-8888-9999-000000000000",+ ClientSecret: "the-client-secret",+ LogPath: "/var/log/beacon-agent/runtime.jsonl",+ }+}++func readFile(t *testing.T, path string) string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ return string(data)+}++func TestForwarderInstallWritesStateValidatesThenRunsTheService(t *testing.T) {+ f := newForwarderFixture(t)+ result, err := Install(validInstall())+ if err != nil {+ t.Fatalf("Install: %v", err)+ }+ config := readFile(t, filepath.Join(f.dir, configFileName))+ for _, want := range []string{+ `endpoint = "https://beacon-dcr-abcd.eastus-1.ingest.monitor.azure.com"`,+ `dcr_immutable_id = "dcr-0123456789abcdef0123456789abcdef"`,+ `azure_tenant_id = "11111111-2222-3333-4444-555555555555"`,+ `azure_client_secret = "SECRET[beacon_sentinel.client_secret]"`,+ `[secret.beacon_sentinel]`,+ `read_from = "beginning"`,+ `include = ["/var/log/beacon-agent/runtime.jsonl", "/var/log/beacon-agent/runtime.jsonl.1"]`,+ `data_dir = "` + siempack.TOMLEscape(filepath.Join(f.dir, dataDirName)) + `"`,+ `type = "internal_logs"`,+ } {+ if !strings.Contains(config, want) {+ t.Errorf("vector.toml is missing %q", want)+ }+ }+ if strings.Contains(config, "the-client-secret") || strings.Contains(config, "${") {+ t.Fatalf("vector.toml must hold no secret and no environment reference:\n%s", config)+ }+ settings := readFile(t, filepath.Join(f.dir, settingsFileName))+ if strings.Contains(settings, "the-client-secret") {+ t.Fatal("forwarder.json must not hold the secret")+ }+ var secrets map[string]string+ if err := json.Unmarshal([]byte(readFile(t, filepath.Join(f.dir, secretsFileName))), &secrets); err != nil || secrets["client_secret"] != "the-client-secret" {+ t.Fatalf("secrets.json = %v (%v)", secrets, err)+ }+ if testenv.HasPOSIXFileModes() {+ for _, path := range []string{f.dir, filepath.Join(f.dir, secretsFileName), filepath.Join(f.dir, configFileName)} {+ info, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ if info.Mode().Perm()&0o077 != 0 {+ t.Errorf("%s has mode %v; only its owner may read it", path, info.Mode().Perm())+ }+ }+ }+ // Vector validated a scratch copy before anything real was written.+ if len(f.validated) != 1 || !strings.Contains(f.validated[0], ".preflight-") {+ t.Fatalf("validated %v, want one preflight config", f.validated)+ }+ if _, err := os.Stat(filepath.Dir(f.validated[0])); !os.IsNotExist(err) {+ t.Fatal("the preflight directory must be removed")+ }+ if len(f.svc.units) != 1 || f.svc.loads != 1 || !result.Service.Running {+ t.Fatalf("units=%v loads=%d result=%+v", f.svc.units, f.svc.loads, result)+ }+ if f.svc.spec.WindowsService != "BeaconSentinelForwarder" || len(f.svc.spec.Env) != 0 {+ t.Fatalf("spec = %+v", f.svc.spec)+ }+}++func TestForwarderInstallRefusesBadInput(t *testing.T) {+ newForwarderFixture(t)+ cases := map[string]func(*InstallOptions){+ "plain http endpoint": func(o *InstallOptions) { o.Endpoint = "http://dcr.example.com" },+ "endpoint with path": func(o *InstallOptions) { o.Endpoint = "https://dcr.example.com/dataCollectionRules/x" },+ "bad DCR id": func(o *InstallOptions) { o.DCRImmutableID = "my-dcr" },+ "bad tenant": func(o *InstallOptions) { o.TenantID = "contoso.onmicrosoft.com" },+ "bad client": func(o *InstallOptions) { o.ClientID = "app" },+ "no credential": func(o *InstallOptions) { o.ClientSecret = "" },+ "both credentials": func(o *InstallOptions) { o.CertificatePath = "x.pfx" },+ "bad read_from": func(o *InstallOptions) { o.ReadFrom = "middle" },+ "http authority": func(o *InstallOptions) { o.AuthorityHost = "http://login.example.com" },+ }+ for name, mutate := range cases {+ o := validInstall()+ mutate(&o)+ if _, err := Install(o); err == nil {+ t.Errorf("%s: Install accepted it", name)+ }+ }+}++// A config Vector rejects changes nothing: an existing forwarder keeps running as it was.+func TestForwarderInstallRejectedByVectorLeavesTheOldForwarder(t *testing.T) {+ f := newForwarderFixture(t)+ if _, err := Install(validInstall()); err != nil {+ t.Fatal(err)+ }+ before := readFile(t, filepath.Join(f.dir, configFileName))+ beforeSecrets := readFile(t, filepath.Join(f.dir, secretsFileName))+ f.reject = errors.New("vector validate failed")+ changed := validInstall()+ changed.ClientSecret = "a-new-secret"+ changed.DCRImmutableID = "dcr-ffffffffffffffffffffffffffffffff"+ if _, err := Install(changed); err == nil {+ t.Fatal("Install must fail when Vector rejects the config")+ }+ if readFile(t, filepath.Join(f.dir, configFileName)) != before || readFile(t, filepath.Join(f.dir, secretsFileName)) != beforeSecrets {+ t.Fatal("a rejected install changed the installed config or credential")+ }+ if f.svc.loads != 1 || len(f.svc.units) != 1 {+ t.Fatalf("a rejected install touched the service: loads=%d units=%d", f.svc.loads, len(f.svc.units))+ }+}++func TestForwarderInstallWithACertificate(t *testing.T) {+ f := newForwarderFixture(t)+ pfx := filepath.Join(t.TempDir(), "app.pfx")+ if err := os.WriteFile(pfx, []byte("pfx bytes"), 0o600); err != nil {+ t.Fatal(err)+ }+ o := validInstall()+ o.ClientSecret, o.CertificatePath = "", pfx+ if _, err := Install(o); err != nil {+ t.Fatal(err)+ }+ config := readFile(t, filepath.Join(f.dir, configFileName))+ if !strings.Contains(config, `azure_credential_kind = "client_certificate_credential"`) ||+ !strings.Contains(config, `certificate_path = "`+siempack.TOMLEscape(filepath.Join(f.dir, certificateFileName))+`"`) ||+ strings.Contains(config, "certificate_password") || strings.Contains(config, "[secret.") {+ t.Fatalf("certificate config without a password:\n%s", config)+ }+ if readFile(t, filepath.Join(f.dir, certificateFileName)) != "pfx bytes" {+ t.Fatal("the certificate was not copied into the forwarder's directory")+ }+ if _, err := os.Stat(filepath.Join(f.dir, secretsFileName)); !os.IsNotExist(err) {+ t.Fatal("a certificate without a password needs no secrets file")+ }++ o.CertificatePassword = "pfx-password"+ if _, err := Install(o); err != nil {+ t.Fatal(err)+ }+ config = readFile(t, filepath.Join(f.dir, configFileName))+ if !strings.Contains(config, `certificate_password = "SECRET[beacon_sentinel.certificate_password]"`) || strings.Contains(config, "pfx-password") {+ t.Fatalf("certificate config with a password:\n%s", config)+ }+ if !strings.Contains(readFile(t, filepath.Join(f.dir, secretsFileName)), "pfx-password") {+ t.Fatal("the certificate password belongs in secrets.json")+ }+}++func TestForwarderAuthorityHostReachesTheServiceEnvironment(t *testing.T) {+ f := newForwarderFixture(t)+ o := validInstall()+ o.AuthorityHost = "https://login.microsoftonline.us/"+ if _, err := Install(o); err != nil {+ t.Fatal(err)+ }+ if got := f.svc.spec.Env; len(got) != 1 || got[0] != "AZURE_AUTHORITY_HOST=https://login.microsoftonline.us" {+ t.Fatalf("service environment = %v", got)+ }+}++func TestForwarderRemoveKeepsStateOnlyWhenAsked(t *testing.T) {+ f := newForwarderFixture(t)+ if _, err := Install(validInstall()); err != nil {+ t.Fatal(err)+ }+ if err := Remove(true); err != nil {+ t.Fatal(err)+ }+ if f.svc.unloads != 1 || f.svc.removed != 1 {+ t.Fatalf("unloads=%d removed=%d", f.svc.unloads, f.svc.removed)+ }+ if _, err := ReadSettings(); err != nil {+ t.Fatalf("keepState removed the state: %v", err)+ }+ if err := Remove(false); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(f.dir); !os.IsNotExist(err) {+ t.Fatal("Remove(false) must delete the forwarder's directory")+ }+ if _, err := ReadSettings(); !errors.Is(err, ErrNotInstalled) {+ t.Fatalf("ReadSettings after removal: %v", err)+ }+}++func TestForwarderReconcile(t *testing.T) {+ f := newForwarderFixture(t)+ if got, err := Reconcile(ReconcileOptions{}); err != nil || got.Skipped == "" {+ t.Fatalf("not installed: %+v %v", got, err)+ }+ if _, err := Install(validInstall()); err != nil {+ t.Fatal(err)+ }+ if got, err := Reconcile(ReconcileOptions{}); err != nil || !got.Unchanged || f.svc.loads != 1 {+ t.Fatalf("unchanged: %+v %v loads=%d", got, err, f.svc.loads)+ }+ // Install and repair restart it even when nothing changed: they may have replaced the log.+ if got, err := Reconcile(ReconcileOptions{Restart: true}); err != nil || !got.Restarted || f.svc.loads != 2 {+ t.Fatalf("restart: %+v %v loads=%d", got, err, f.svc.loads)+ }+ // A config an older version wrote is replaced and the service restarted.+ configPath := filepath.Join(f.dir, configFileName)+ if err := os.WriteFile(configPath, []byte("# old\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if got, err := Reconcile(ReconcileOptions{}); err != nil || !got.Restarted || f.svc.loads != 3 {+ t.Fatalf("changed: %+v %v loads=%d", got, err, f.svc.loads)+ }+ if strings.HasPrefix(readFile(t, configPath), "# old") {+ t.Fatal("Reconcile did not rewrite the config")+ }+ // One Vector rejects is a warning that keeps what is there.+ if err := os.WriteFile(configPath, []byte("# old\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ f.reject = errors.New("vector validate failed")+ if got, err := Reconcile(ReconcileOptions{}); err != nil || got.Warning == "" || f.svc.loads != 3 {+ t.Fatalf("rejected: %+v %v loads=%d", got, err, f.svc.loads)+ }+ if readFile(t, configPath) != "# old\n" {+ t.Fatal("a rejected reconcile replaced the config")+ }+ f.reject = nil+ // The MSI upgrade removes the service and keeps the state; the install that follows puts the+ // service back.+ if err := Remove(true); err != nil {+ t.Fatal(err)+ }+ f.svc.current = false+ if got, err := Reconcile(ReconcileOptions{Restart: true}); err != nil || !got.Restarted || !f.svc.running {+ t.Fatalf("after upgrade: %+v %v running=%t", got, err, f.svc.running)+ }+}++func TestForwarderOnAnUnsupportedHost(t *testing.T) {+ f := newForwarderFixture(t)+ f.svc.unsupported = "Windows has no per-user service manager"+ if _, err := Install(validInstall()); err == nil || !strings.Contains(err.Error(), "per-user") {+ t.Fatalf("Install on an unsupported host: %v", err)+ }+ if _, err := os.Stat(f.dir); !os.IsNotExist(err) {+ t.Fatal("an unsupported install must write nothing")+ }+}++func TestLastVectorProblemReadsTheNewestDailyLog(t *testing.T) {+ dir := t.TempDir()+ if lastVectorProblem(dir) != "" {+ t.Fatal("no logs means no problem")+ }+ write := func(name, content string) {+ if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ write("vector-2026-11-03.log", `{"timestamp":"2026-11-03T10:00:00Z","message":"old","metadata":{"level":"WARN"}}`+"\n")+ write("vector-2026-11-04.log", `{"timestamp":"2026-11-04T10:00:00Z","message":"first","metadata":{"level":"WARN"}}`+"\n"++ `{"timestamp":"2026-11-04T11:00:00Z","message":"Retrying after response.","metadata":{"level":"WARN"}}`+"\n")+ if got := lastVectorProblem(dir); got != "2026-11-04T11:00:00Z WARN Retrying after response." {+ t.Fatalf("lastVectorProblem = %q", got)+ }+}++// The manual pack's config is still for running Vector by hand with the values in its environment.+func TestManualVectorConfigKeepsItsEnvironmentContract(t *testing.T) {+ manual := manualVectorConfig()+ for _, want := range []string{+ `endpoint = "${BEACON_SENTINEL_DCE_ENDPOINT}"`,+ `azure_client_secret = "${AZURE_CLIENT_SECRET}"`,+ `data_dir = "/var/lib/vector/beacon-sentinel"`,+ `read_from = "end"`,+ `[sinks.beacon_sentinel.retry_strategy]`,+ `[sinks.beacon_sentinel.acknowledgements]`,+ } {+ if !strings.Contains(manual, want) {+ t.Errorf("manual vector.toml is missing %q", want)+ }+ }+ for _, unwanted := range []string{"{{", "SECRET[", "internal_logs"} {+ if strings.Contains(strings.ReplaceAll(manual, "{{LOG_PATH}}", ""), unwanted) {+ t.Errorf("manual vector.toml contains %q", unwanted)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/sentinel/pack/README.md b/cli/beacon/internal/endpoint/sentinel/pack/README.mdindex b4280c36..4750f2a8 100644--- a/cli/beacon/internal/endpoint/sentinel/pack/README.md+++ b/cli/beacon/internal/endpoint/sentinel/pack/README.md@@ -86,22 +86,34 @@ fields. Flattening those events into CEF loses useful context.## Without Azure Monitor Agent: Vector and the Logs Ingestion APIOn a machine outside Azure, Azure Monitor Agent needs Azure Arc first, and it-does not run on macOS at all. `vector.toml` is the alternative. The Vector that-ships with Beacon (`/opt/beacon/bin/vector`) posts each line to the Logs-Ingestion API with a Microsoft Entra app registration. It needs no Arc and no-agent extension.--1. Deploy `dcr-logs-ingestion-template.json` with your workspace and Data- Collection Endpoint resource IDs, and note the `dcrImmutableId` output. It- runs the same transform into the same `BeaconRuntime_CL` table.+does not run on macOS at all. The Vector that ships with Beacon (`/opt/beacon/bin/vector`+on macOS and Linux, `vector.exe` beside `beacon.exe` on Windows) posts each line+to the Logs Ingestion API with a Microsoft Entra app registration instead. It+needs no Arc and no agent extension.++1. Deploy `dcr-logs-ingestion-template.json` with your workspace's resource ID,+ and note the `dcrImmutableId` output. It runs the same transform into the same+ `BeaconRuntime_CL` table. The DCR gets its own logs ingestion URL+ (`az monitor data-collection rule show ... --query endpoints.logsIngestion`);+ pass a Data Collection Endpoint only if you use Private Link.2. Grant your app registration the Monitoring Metrics Publisher role on that DCR.-3. Run Vector with `vector.toml`, setting `BEACON_SENTINEL_DCE_ENDPOINT`,- `BEACON_SENTINEL_DCR_IMMUTABLE_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and- `AZURE_CLIENT_SECRET` in the Vector service's environment.--The host needs outbound HTTPS to `login.microsoftonline.com` and the DCE's-`*.ingest.monitor.azure.com` hostname. The Azure credentials live only in the-Vector service's environment, never in Beacon config.+3. On each host, as root or an administrator:++ ```+ beacon endpoint sentinel forwarder install --system \+ --endpoint <logs ingestion URL> --dcr-immutable-id <dcr-...> \+ --tenant-id <tenant> --client-id <app> --client-certificate app.pfx+ ```++ It runs Vector as a system service with this config, the values written in+ and the credential readable only by root (SYSTEM and Administrators on+ Windows). `vector.toml` in this pack is the same config for running Vector+ yourself, with the values in the Vector service's environment:+ `BEACON_SENTINEL_DCE_ENDPOINT`, `BEACON_SENTINEL_DCR_IMMUTABLE_ID`,+ `AZURE_TENANT_ID`, `AZURE_CLIENT_ID` and `AZURE_CLIENT_SECRET`.++The host needs outbound HTTPS to `login.microsoftonline.com` and the+`*.ingest.monitor.azure.com` hostname of the logs ingestion URL.## Content Handlingdiff --git a/cli/beacon/internal/endpoint/sentinel/pack/dcr-logs-ingestion-template.json b/cli/beacon/internal/endpoint/sentinel/pack/dcr-logs-ingestion-template.jsonindex b6e45857..74380dcb 100644--- a/cli/beacon/internal/endpoint/sentinel/pack/dcr-logs-ingestion-template.json+++ b/cli/beacon/internal/endpoint/sentinel/pack/dcr-logs-ingestion-template.json@@ -14,8 +14,9 @@},"dataCollectionEndpointResourceId": {"type": "string",+ "defaultValue": "","metadata": {- "description": "Resource ID of a Data Collection Endpoint in the workspace's region."+ "description": "Optional. Resource ID of a Data Collection Endpoint in the workspace's region, for Private Link. Without one the DCR gets its own logs ingestion URL (properties.endpoints.logsIngestion)."}},"location": {@@ -31,7 +32,7 @@"location": "[parameters('location')]","kind": "Direct","properties": {- "dataCollectionEndpointId": "[parameters('dataCollectionEndpointResourceId')]",+ "dataCollectionEndpointId": "[if(empty(parameters('dataCollectionEndpointResourceId')), null(), parameters('dataCollectionEndpointResourceId'))]","streamDeclarations": {"Custom-BeaconRuntimeRaw": {"columns": [diff --git a/cli/beacon/internal/endpoint/sentinel/pack/vector.toml.tmpl b/cli/beacon/internal/endpoint/sentinel/pack/vector.toml.tmplindex 970602fc..42301577 100644--- a/cli/beacon/internal/endpoint/sentinel/pack/vector.toml.tmpl+++ b/cli/beacon/internal/endpoint/sentinel/pack/vector.toml.tmpl@@ -1,26 +1,26 @@# Beacon Endpoint Agent -> Microsoft Sentinel, through the Azure Monitor Logs Ingestion API## For hosts that cannot run Azure Monitor Agent, which on a machine outside Azure means-# onboarding it to Azure Arc first. Vector posts to a Data Collection Endpoint with a-# Microsoft Entra app registration instead, so no Arc and no agent extension are needed.-# Beacon's Linux packages ship Vector at /opt/beacon/bin/vector.+# onboarding it to Azure Arc first. Vector posts to a data collection rule with a Microsoft+# Entra app registration instead, so no Arc and no agent extension are needed. Beacon's+# packages ship Vector: /opt/beacon/bin/vector on macOS and Linux, and vector.exe beside+# beacon.exe on Windows.## Each record carries the original Beacon line as RawData. The DCR in# dcr-logs-ingestion-template.json runs the same transform as the Azure Monitor Agent# path, so both paths produce identical BeaconRuntime_CL rows.#-# Set in the Vector service environment, not in Beacon config:-# BEACON_SENTINEL_DCE_ENDPOINT https://<dce>.<region>.ingest.monitor.azure.com-# BEACON_SENTINEL_DCR_IMMUTABLE_ID dcr-... (the DCR's immutableId)-# AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET+{{SETTINGS_NOTE}}# The app registration needs the Monitoring Metrics Publisher role on the DCR.-data_dir = "/var/lib/vector/beacon-sentinel"-+data_dir = "{{DATA_DIR}}"+{{SECRET_BACKEND}}[sources.beacon_runtime]type = "file"-include = ["{{LOG_PATH}}"]-read_from = "end"+# The active log and the file a rotation renamed it to, so lines written just before a rotation+# are still sent when Vector was behind or stopped. Checkpoints keep either from being read twice.+include = ["{{LOG_PATH}}", "{{LOG_PATH}}.1"]+read_from = "{{READ_FROM}}"[transforms.beacon_raw_record]type = "remap"@@ -39,16 +39,17 @@ if err == null && is_object(parsed) {[sinks.beacon_sentinel]type = "azure_logs_ingestion"inputs = ["beacon_raw_record"]-endpoint = "${BEACON_SENTINEL_DCE_ENDPOINT}"-dcr_immutable_id = "${BEACON_SENTINEL_DCR_IMMUTABLE_ID}"+endpoint = "{{ENDPOINT}}"+dcr_immutable_id = "{{DCR_IMMUTABLE_ID}}"stream_name = "Custom-BeaconRuntimeRaw"timestamp_field = "TimeGenerated"[sinks.beacon_sentinel.auth]-azure_credential_kind = "client_secret_credential"-azure_tenant_id = "${AZURE_TENANT_ID}"-azure_client_id = "${AZURE_CLIENT_ID}"-azure_client_secret = "${AZURE_CLIENT_SECRET}"+{{AUTH}}+# A line's read position is saved only once Azure has accepted it, so a restart or a stretch of+# failures resends rather than skips.+[sinks.beacon_sentinel.acknowledgements]+enabled = true# The Logs Ingestion API rejects a request over 1 MB with 413, and the sink's own default is 10 MB.# 512 KB leaves room for the JSON escaping of RawData; one Beacon event is at most 64 KB.@@ -57,7 +58,16 @@ max_bytes = 524288max_events = 1000timeout_secs = 30+# Retried without a limit, backing off to five minutes, so an outage or a credential that is not+# yet accepted holds the log back instead of dropping it.[sinks.beacon_sentinel.request]-retry_attempts = 10retry_initial_backoff_secs = 1retry_max_duration_secs = 300++# The sink's default retries only 408, 429 and 5xx, and drops a batch on any other error. A new+# role assignment on the DCR answers 403 for up to 30 minutes, so 401 and 403 are retried too.+# 400 and 413 are not: resending the same request cannot fix them.+[sinks.beacon_sentinel.retry_strategy]+type = "custom"+status_codes = [401, 403, 408, 429, 500, 502, 503, 504]+{{VECTOR_LOG}}\ No newline at end of filediff --git a/cli/beacon/internal/endpoint/sentinel/sentinel.go b/cli/beacon/internal/endpoint/sentinel/sentinel.goindex 1432741f..3d62153d 100644--- a/cli/beacon/internal/endpoint/sentinel/sentinel.go+++ b/cli/beacon/internal/endpoint/sentinel/sentinel.go@@ -3,9 +3,9 @@ package sentinelimport ("embed""fmt"- endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""strings"+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/siempack")@@ -28,7 +28,7 @@ func Files() []siempack.File {{Name: "dcr-template.json", Content: renderDCRTemplate("pack/dcr-template.json"), TemplateLogPath: true},// The Logs Ingestion API path, for hosts without Azure Monitor Agent: Vector sends each line// as RawData to a DCR that runs the same transform, so both paths fill the same table.- {Name: "vector.toml", Content: mustRead("pack/vector.toml.tmpl"), TemplateLogPath: true},+ {Name: "vector.toml", Content: manualVectorConfig(), TemplateLogPath: true},{Name: "dcr-logs-ingestion-template.json", Content: renderDCRTemplate("pack/dcr-logs-ingestion-template.json")},{Name: "queries.kql", Content: mustRead("pack/queries.kql")},{Name: "detections.kql", Content: mustRead("pack/detections.kql")},diff --git a/cli/beacon/internal/endpoint/sentinel/sentinel_test.go b/cli/beacon/internal/endpoint/sentinel/sentinel_test.goindex 390a4d37..6edf7261 100644--- a/cli/beacon/internal/endpoint/sentinel/sentinel_test.go+++ b/cli/beacon/internal/endpoint/sentinel/sentinel_test.go@@ -141,7 +141,7 @@ func parseDCR(t *testing.T, path string) dcrRule {// columns the shared transform reads, and the DCR writes to the same table as the Azure Monitor// Agent path. Nothing in Azure checks any of that until the first record is rejected.func TestLogsIngestionPathMatchesTheDCRAndTheAgentPath(t *testing.T) {- vector := mustRead("pack/vector.toml.tmpl")+ vector := manualVectorConfig()ingest := parseDCR(t, "pack/dcr-logs-ingestion-template.json").Resources[0].Propertiesagent := parseDCR(t, "pack/dcr-template.json").Resources[0].Properties@@ -181,7 +181,7 @@ func TestLogsIngestionPathMatchesTheDCRAndTheAgentPath(t *testing.T) {// Credentials come from the Vector service environment, never from the pack.func TestVectorConfigTakesAzureCredentialsFromTheEnvironment(t *testing.T) {- vector := mustRead("pack/vector.toml.tmpl")+ vector := manualVectorConfig()for _, key := range []string{"azure_tenant_id", "azure_client_id", "azure_client_secret", "endpoint", "dcr_immutable_id"} {found := falsefor _, line := range strings.Split(vector, "\n") {@@ -248,7 +248,7 @@ func TestKQLAssetsMentionSentinelTableAndValidation(t *testing.T) {// The Logs Ingestion API rejects requests over 1 MB, and the azure_logs_ingestion sink batches up to// 10 MB by default, so a busy flush would lose a whole batch to 413s.func TestVectorBatchesFitTheLogsIngestionLimit(t *testing.T) {- vector := mustRead("pack/vector.toml.tmpl")+ vector := manualVectorConfig()// \r? because Windows checkouts carry CRLF, and (?m)$ matches only before \n.match := regexp.MustCompile(`(?m)^max_bytes = (\d+)\r?$`).FindStringSubmatch(vector)if match == nil {diff --git a/cli/beacon/internal/endpoint/sentinel/sentinelmock/cmd/sentinel-mock/main.go b/cli/beacon/internal/endpoint/sentinel/sentinelmock/cmd/sentinel-mock/main.gonew file mode 100644index 00000000..5a98e9da--- /dev/null+++ b/cli/beacon/internal/endpoint/sentinel/sentinelmock/cmd/sentinel-mock/main.go@@ -0,0 +1,58 @@+// Command sentinel-mock runs sentinelmock until it is stopped, for package smoke tests that drive+// an installed forwarder. It prints the server URL on its first line.+package main++import (+ "flag"+ "fmt"+ "os"+ "os/signal"+ "strconv"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sentinel/sentinelmock"+)++func main() {+ var opts sentinelmock.Options+ var statuses, urlFile string+ flag.StringVar(&opts.Addr, "listen", "127.0.0.1:0", "listen address")+ flag.StringVar(&opts.CAFile, "ca-out", "", "write the CA certificate (PEM) here")+ flag.StringVar(&opts.RowsFile, "rows-out", "", "append accepted rows here, one JSON line each")+ flag.StringVar(&urlFile, "url-out", "", "also write the server URL here")+ flag.StringVar(&opts.TenantID, "tenant", "", "tenant ID")+ flag.StringVar(&opts.ClientID, "client-id", "", "app registration client ID")+ flag.StringVar(&opts.ClientSecret, "client-secret", "", "client secret; empty accepts a certificate assertion")+ flag.StringVar(&opts.DCRImmutableID, "dcr", "", "DCR immutable ID")+ flag.StringVar(&opts.Stream, "stream", "Custom-BeaconRuntimeRaw", "stream name")+ flag.IntVar(&opts.FailTokens, "fail-tokens", 0, "answer the first N token requests with 500")+ flag.StringVar(&statuses, "ingest-statuses", "", "comma-separated statuses for the first non-empty ingest requests")+ flag.Parse()+ for _, field := range strings.Split(statuses, ",") {+ if field = strings.TrimSpace(field); field == "" {+ continue+ }+ code, err := strconv.Atoi(field)+ if err != nil {+ fmt.Fprintln(os.Stderr, "sentinel-mock: bad --ingest-statuses:", err)+ os.Exit(2)+ }+ opts.IngestStatuses = append(opts.IngestStatuses, code)+ }+ server, err := sentinelmock.Start(opts)+ if err != nil {+ fmt.Fprintln(os.Stderr, "sentinel-mock:", err)+ os.Exit(1)+ }+ defer server.Close()+ fmt.Println(server.URL)+ if urlFile != "" {+ if err := os.WriteFile(urlFile, []byte(server.URL+"\n"), 0o644); err != nil {+ fmt.Fprintln(os.Stderr, "sentinel-mock:", err)+ os.Exit(1)+ }+ }+ stop := make(chan os.Signal, 1)+ signal.Notify(stop, os.Interrupt)+ <-stop+}diff --git a/cli/beacon/internal/endpoint/sentinel/sentinelmock/sentinelmock.go b/cli/beacon/internal/endpoint/sentinel/sentinelmock/sentinelmock.gonew file mode 100644index 00000000..673a5456--- /dev/null+++ b/cli/beacon/internal/endpoint/sentinel/sentinelmock/sentinelmock.go@@ -0,0 +1,286 @@+// Package sentinelmock stands in for Microsoft Entra ID and the Azure Monitor Logs Ingestion API,+// so the Sentinel forwarder can be tested end to end without an Azure tenant.+//+// One HTTPS server answers both: POST /{tenant}/oauth2/v2.0/token issues a bearer token for the+// configured app registration, and POST /dataCollectionRules/{id}/streams/{stream} accepts rows the+// way the real API does (a JSON array, at most 1 MB, with that token). Point Vector's endpoint at+// URL and AZURE_AUTHORITY_HOST at URL, and trust the CA written to CAFile.+package sentinelmock++import (+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/tls"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/hex"+ "encoding/json"+ "encoding/pem"+ "fmt"+ "io"+ "math/big"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "sync"+ "time"+)++// MaxBodyBytes is the Logs Ingestion API's request limit.+const MaxBodyBytes = 1 << 20++// Options configures the app registration and DCR the mock accepts, and the faults it injects.+type Options struct {+ TenantID string+ ClientID string+ ClientSecret string // empty accepts a certificate assertion instead+ DCRImmutableID string+ Stream string+ // CAFile receives the PEM CA certificate to trust. Required.+ CAFile string+ // RowsFile, when set, receives every accepted row as one JSON line.+ RowsFile string+ // Addr is the listen address; empty is 127.0.0.1 on a free port.+ Addr string+ // FailTokens answers the first N token requests with 500.+ FailTokens int+ // IngestStatuses answers the first non-empty ingest requests with these statuses, in order.+ IngestStatuses []int+}++// Row is one record the API accepted.+type Row struct {+ TimeGenerated string `json:"TimeGenerated"`+ RawData string `json:"RawData"`+}++// Server is a running mock.+type Server struct {+ URL string++ opts Options+ srv *httptest.Server+ mu sync.Mutex+ token string+ rows []Row+ tokens int+ ingests int+ rejected int+ rowsOut *os.File+}++// Start runs a mock until Close.+func Start(opts Options) (*Server, error) {+ if opts.CAFile == "" {+ return nil, fmt.Errorf("sentinelmock: CAFile is required")+ }+ tlsConfig, err := selfSigned(opts.CAFile)+ if err != nil {+ return nil, err+ }+ s := &Server{opts: opts, token: randomHex(24)}+ if opts.RowsFile != "" {+ if s.rowsOut, err = os.OpenFile(opts.RowsFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); err != nil {+ return nil, err+ }+ }+ s.srv = httptest.NewUnstartedServer(http.HandlerFunc(s.serve))+ if opts.Addr != "" {+ listener, err := net.Listen("tcp", opts.Addr)+ if err != nil {+ return nil, err+ }+ s.srv.Listener.Close()+ s.srv.Listener = listener+ }+ s.srv.TLS = tlsConfig+ s.srv.StartTLS()+ s.URL = s.srv.URL+ return s, nil+}++// Close stops the server.+func (s *Server) Close() {+ s.srv.Close()+ if s.rowsOut != nil {+ s.rowsOut.Close()+ }+}++// Rows returns every row accepted so far.+func (s *Server) Rows() []Row {+ s.mu.Lock()+ defer s.mu.Unlock()+ return append([]Row(nil), s.rows...)+}++// Counts reports token requests, non-empty ingest requests, and requests refused by injected faults.+func (s *Server) Counts() (tokens, ingests, rejected int) {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.tokens, s.ingests, s.rejected+}++func (s *Server) serve(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/oauth2/v2.0/token"):+ s.serveToken(w, r)+ case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/dataCollectionRules/"):+ s.serveIngest(w, r)+ default:+ http.Error(w, "not found", http.StatusNotFound)+ }+}++func (s *Server) serveToken(w http.ResponseWriter, r *http.Request) {+ s.mu.Lock()+ s.tokens+++ fail := s.tokens <= s.opts.FailTokens+ s.mu.Unlock()+ if fail {+ http.Error(w, `{"error":"temporarily_unavailable"}`, http.StatusInternalServerError)+ return+ }+ tenant := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/oauth2/v2.0/token")+ if err := r.ParseForm(); err != nil || tenant != s.opts.TenantID ||+ r.PostForm.Get("grant_type") != "client_credentials" || r.PostForm.Get("client_id") != s.opts.ClientID {+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_request"})+ return+ }+ if s.opts.ClientSecret != "" {+ if r.PostForm.Get("client_secret") != s.opts.ClientSecret {+ writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid_client"})+ return+ }+ } else if r.PostForm.Get("client_assertion") == "" ||+ r.PostForm.Get("client_assertion_type") != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" {+ writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid_client"})+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "token_type": "Bearer", "expires_in": 3599, "ext_expires_in": 3599, "access_token": s.token,+ })+}++func (s *Server) serveIngest(w http.ResponseWriter, r *http.Request) {+ want := "/dataCollectionRules/" + s.opts.DCRImmutableID + "/streams/" + s.opts.Stream+ if r.URL.Path != want || r.URL.Query().Get("api-version") == "" {+ writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such DCR or stream: " + r.URL.Path})+ return+ }+ if r.Header.Get("Authorization") != "Bearer "+s.token {+ writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "bad token"})+ return+ }+ if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {+ writeJSON(w, http.StatusUnsupportedMediaType, map[string]string{"error": "not JSON"})+ return+ }+ body, err := io.ReadAll(io.LimitReader(r.Body, MaxBodyBytes+1))+ if err != nil {+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})+ return+ }+ if len(body) > MaxBodyBytes {+ writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "over 1 MB"})+ return+ }+ var rows []Row+ if err := json.Unmarshal(body, &rows); err != nil {+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "not a JSON array of rows: " + err.Error()})+ return+ }+ if len(rows) == 0 {+ w.WriteHeader(http.StatusNoContent) // the sink's healthcheck+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ s.ingests+++ if s.ingests <= len(s.opts.IngestStatuses) {+ s.rejected+++ writeJSON(w, s.opts.IngestStatuses[s.ingests-1], map[string]string{"error": "injected"})+ return+ }+ for _, row := range rows {+ if row.TimeGenerated == "" || row.RawData == "" {+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "a row without TimeGenerated or RawData"})+ return+ }+ }+ s.rows = append(s.rows, rows...)+ if s.rowsOut != nil {+ for _, row := range rows {+ line, _ := json.Marshal(row)+ s.rowsOut.Write(append(line, '\n'))+ }+ }+ w.WriteHeader(http.StatusNoContent)+}++func writeJSON(w http.ResponseWriter, status int, v any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(v)+}++// selfSigned makes a CA, writes it to caFile, and returns a server config with a leaf for+// 127.0.0.1 and localhost signed by it.+func selfSigned(caFile string) (*tls.Config, error) {+ caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ return nil, err+ }+ notBefore := time.Now().Add(-time.Hour)+ ca := &x509.Certificate{+ SerialNumber: big.NewInt(1),+ Subject: pkix.Name{CommonName: "Beacon Sentinel mock CA " + randomHex(4)},+ NotBefore: notBefore,+ NotAfter: notBefore.Add(48 * time.Hour),+ IsCA: true,+ BasicConstraintsValid: true,+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,+ }+ caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &caKey.PublicKey, caKey)+ if err != nil {+ return nil, err+ }+ caCert, err := x509.ParseCertificate(caDER)+ if err != nil {+ return nil, err+ }+ leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ return nil, err+ }+ leaf := &x509.Certificate{+ SerialNumber: big.NewInt(2),+ Subject: pkix.Name{CommonName: "127.0.0.1"},+ NotBefore: notBefore,+ NotAfter: notBefore.Add(48 * time.Hour),+ KeyUsage: x509.KeyUsageDigitalSignature,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},+ IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},+ DNSNames: []string{"localhost"},+ }+ leafDER, err := x509.CreateCertificate(rand.Reader, leaf, caCert, &leafKey.PublicKey, caKey)+ if err != nil {+ return nil, err+ }+ if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0o644); err != nil {+ return nil, err+ }+ return &tls.Config{+ MinVersion: tls.VersionTLS12,+ Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER, caDER}, PrivateKey: leafKey}},+ }, nil+}++func randomHex(n int) string {+ b := make([]byte, n)+ _, _ = rand.Read(b)+ return hex.EncodeToString(b)+}diff --git a/cli/beacon/internal/endpoint/siempack/log_paths_test.go b/cli/beacon/internal/endpoint/siempack/log_paths_test.goindex ccd0df40..08ad8705 100644--- a/cli/beacon/internal/endpoint/siempack/log_paths_test.go+++ b/cli/beacon/internal/endpoint/siempack/log_paths_test.go@@ -48,6 +48,8 @@ func TestTOMLLogPathsRoundTrip(t *testing.T) {render func(string) (string, error)inventory boolbackfill bool+ // rotated packs also read the file a rotation renamed the log to.+ rotated bool}{{name: "asymptote", install: asymptote.InstallPack, render: asymptote.VectorConfig, inventory: true, backfill: true},{name: "cloudwatch", install: cloudwatch.InstallPack, render: cloudwatch.ConfigSnippet},@@ -55,13 +57,16 @@ func TestTOMLLogPathsRoundTrip(t *testing.T) {{name: "gcs", install: gcs.InstallPack, inventory: true},{name: "rapid7", install: rapid7.InstallPack},{name: "s3", install: s3.InstallPack, inventory: true},- {name: "sentinel", install: sentinel.InstallPack},+ {name: "sentinel", install: sentinel.InstallPack, rotated: true},{name: "sumo", install: sumo.InstallPack},}for _, pack := range packs {for _, path := range logPaths {t.Run(pack.name+"/"+path.name, func(t *testing.T) {want := map[string][]string{"beacon_runtime": {path.path}}+ if pack.rotated {+ want["beacon_runtime"] = append(want["beacon_runtime"], path.path+".1")+ }if pack.inventory {want["beacon_inventory"] = []string{siempack.InventoryLogPath(path.path)}}diff --git a/cli/beacon/internal/endpoint/siempack/siempack.go b/cli/beacon/internal/endpoint/siempack/siempack.goindex 427bf9a8..61f9e51e 100644--- a/cli/beacon/internal/endpoint/siempack/siempack.go+++ b/cli/beacon/internal/endpoint/siempack/siempack.go@@ -66,6 +66,9 @@ func logPathEscaper(name string) func(string) string {func verbatim(value string) string { return value }+// TOMLEscape escapes value for a TOML basic string, as pack templates render paths.+func TOMLEscape(value string) string { return tomlEscape(value) }+// tomlEscape takes JSON string escapes, which TOML basic strings share, plus DEL, which TOML forbids.func tomlEscape(value string) string {return strings.ReplaceAll(JSONEscapeForString(value), "\x7f", `\u007f`)diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdxindex 5f92455c..56f02768 100644--- a/docs/changelog/cli.mdx+++ b/docs/changelog/cli.mdx@@ -11,6 +11,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.## Unreleased+- **Microsoft Sentinel forwarding with one command, on macOS, Linux and Windows** · `beacon endpoint sentinel forwarder install --system` runs the Vector bundled with Beacon as a system service that sends the runtime log to Microsoft Sentinel through the Logs Ingestion API, with a Microsoft Entra app registration (certificate or client secret). The credential is stored where only root can read it, or SYSTEM and Administrators on Windows, and is never a command-line argument. Vector checks the config before anything changes. Repair and package upgrades keep the forwarder and restart it on the new Vector; uninstall removes the service. Throttling, server errors and `401`/`403` answers are retried without a limit, and a line counts as sent only once Azure has accepted it. `status` and `remove` complete the commands. The pack's Logs Ingestion DCR template no longer needs a Data Collection Endpoint. See [Vector and the Logs Ingestion API](/log-forwarding/microsoft-sentinel#vector-and-the-logs-ingestion-api).- **The Windows MSI carries Vector** · The MSI now installs Vector 0.56.0 as `vector.exe` beside `beacon.exe` in `%ProgramFiles%\Beacon\bin`, as the macOS and Linux packages already carry it, checked against the same pinned checksums. Beacon finds it there. The package only installs it; nothing runs it until a forwarder is set up. Allow it alongside the other three programs if you run AppLocker or WDAC.- **Scheduled session sync** · `beacon endpoint install|repair --session-sync` turns on a job that runs every 15 minutes and reads new records from the agent runtimes' local session stores into the runtime log. It runs the same bounded, confined sweep install already runs once, so session-store data keeps reaching the log, and any forwarder reading it, after install. Off by default; repair and upgrades keep the setting, and `--no-session-sync` removes the job. See [Scheduled session sync](/cli/endpoint-install#scheduled-session-sync).- **Turn session sync on or off without a repair** · `beacon endpoint sessions enable|disable` changes only the scheduled session sync setting and installs or removes its job. `beacon endpoint repair --session-sync` rebuilds the endpoint from its flags, so run without the ones an endpoint was set up with it reset harnesses and OTLP ports and dropped Splunk or Falcon HEC destinations. For package and MDM installs, `BEACON_SESSION_SYNC=1` in the environment of `/opt/beacon/scripts/install-endpoint.sh` (macOS and Linux) turns it on, and `0` turns it off; unset keeps the endpoint's own setting, so package upgrades never change it.diff --git a/docs/cli/sentinel.mdx b/docs/cli/sentinel.mdxindex 43aeac5f..a45abfe2 100644--- a/docs/cli/sentinel.mdx+++ b/docs/cli/sentinel.mdx@@ -7,7 +7,7 @@ description: "Generate Microsoft Sentinel forwarding content and validation evenUse `beacon endpoint sentinel` to generate Microsoft Sentinel forwarding content for Beacon endpoint events. The generated pack keeps Beacon as a local JSONL producer and gets `runtime.jsonl` into a Log Analytics custom table through a Data Collection Rule, either with Azure Monitor Agent or with the Vector that ships with Beacon and the Logs Ingestion API. The Vector path needs no Azure Arc.-Beacon does not store Azure tenant IDs, client secrets, workspace IDs, DCR identifiers, ingestion endpoints, or Azure Monitor Agent configuration. Keep those values in Azure, endpoint-management policy, or deployment tooling.+`beacon endpoint sentinel forwarder` runs that Vector as a system service on macOS, Linux and Windows. Its settings and Entra credential stay in a directory of its own that only root can read (SYSTEM and Administrators on Windows), never in Beacon's `config.json`.```bash title="Command syntax"beacon endpoint sentinel [command]@@ -25,6 +25,9 @@ beacon endpoint sentinel [command]<Card title="beacon endpoint sentinel validate" icon="check" href="#beacon-endpoint-sentinel-validate">Write and describe a Beacon Microsoft Sentinel validation event.</Card>+ <Card title="beacon endpoint sentinel forwarder" icon="paper-plane" href="#beacon-endpoint-sentinel-forwarder">+ Run Vector as a system service that sends the runtime log to Sentinel.+ </Card></Columns>## Runtime log paths@@ -32,7 +35,8 @@ beacon endpoint sentinel [command]| Mode | Path ||------|------|| User mode | `~/.beacon/endpoint/logs/runtime.jsonl` |-| System mode | `/var/log/beacon-agent/runtime.jsonl` |+| System mode, macOS and Linux | `/var/log/beacon-agent/runtime.jsonl` |+| System mode, Windows | `C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl` |## beacon endpoint sentinel print-config@@ -158,6 +162,50 @@ Expected validation query: BeaconRuntime_CL | where Message has "Beacon endpoint| `--system` | Use system endpoint paths and launch daemon || `--log-path <path>` | Runtime JSONL log path |+## beacon endpoint sentinel forwarder++`beacon endpoint sentinel forwarder install` runs the Vector bundled with Beacon as a system service that sends every runtime log line to Microsoft Sentinel through the Logs Ingestion API. It works the same on macOS, Linux and Windows, and needs a system install and root (an elevated shell, or `LocalSystem`, on Windows). See [Vector and the Logs Ingestion API](/log-forwarding/microsoft-sentinel#vector-and-the-logs-ingestion-api) for the Azure side.++```bash title="Set up the forwarder with a certificate"+sudo /opt/beacon/bin/beacon endpoint sentinel forwarder install --system \+ --endpoint https://<dcr>.<region>-1.ingest.monitor.azure.com \+ --dcr-immutable-id dcr-<32 hex digits> \+ --tenant-id <tenant ID> --client-id <app ID> \+ --client-certificate /path/to/app.pfx+```++```bash title="Set up the forwarder with a client secret"+printf '%s' "$CLIENT_SECRET" | sudo /opt/beacon/bin/beacon endpoint sentinel forwarder install --system \+ --endpoint https://<dcr>.<region>-1.ingest.monitor.azure.com \+ --dcr-immutable-id dcr-<32 hex digits> \+ --tenant-id <tenant ID> --client-id <app ID> --client-secret-stdin+```++The credential is never a command-line argument. Vector checks the config before anything changes, so a rejected install leaves a running forwarder as it was. Run `install` again to change a setting or rotate the credential.++```bash title="Check and remove it"+sudo /opt/beacon/bin/beacon endpoint sentinel forwarder status --system+sudo /opt/beacon/bin/beacon endpoint sentinel forwarder remove --system+```++`status` shows the settings, the service state and Vector's latest warning. `remove` stops the service and deletes the settings and credential. Repair and package upgrades keep the forwarder; uninstall removes the service, and keeps the settings with `--keep-config`.++### Flags++| Flag | Description |+|------|-------------|+| `--system` | Required. The forwarder runs only with a system install |+| `--endpoint <url>` | The DCR's logs ingestion URL, or a Data Collection Endpoint's |+| `--dcr-immutable-id <id>` | The DCR's immutable ID (`dcr-` and 32 hex digits) |+| `--tenant-id <id>` | Microsoft Entra tenant ID |+| `--client-id <id>` | App registration (client) ID |+| `--client-certificate <path>` | Authenticate with this PFX certificate. Its password, if any, comes from `AZURE_CLIENT_CERTIFICATE_PASSWORD` or stdin with `--certificate-password-stdin` |+| `--client-secret-stdin` | Read the client secret from stdin. Without it the secret comes from `AZURE_CLIENT_SECRET` |+| `--authority-host <url>` | Entra authority for a sovereign cloud, such as `https://login.microsoftonline.us` |+| `--read-from beginning\|end` | Where to start in a log not read before. `beginning`, the default, sends the current log once |+| `--vector <path>` | Vector binary to run. Defaults to the one Beacon's package installed |+| `--json` | Print the result as JSON |+## Related<Columns cols={2}>diff --git a/docs/log-forwarding/microsoft-sentinel.mdx b/docs/log-forwarding/microsoft-sentinel.mdxindex 73f15f21..a0ad8200 100644--- a/docs/log-forwarding/microsoft-sentinel.mdx+++ b/docs/log-forwarding/microsoft-sentinel.mdx@@ -14,14 +14,15 @@ Beacon `v0.0.32` added the [Microsoft Sentinel content pack](/concepts/core-concOn a desktop or server outside Azure, the Vector path is usually simpler.-Use this path when you want Sentinel ingestion without storing Azure tenant IDs, client secrets, workspace IDs, DCR identifiers, or ingestion endpoints in Beacon endpoint configuration.+Beacon's `config.json` never holds Azure values. On the Vector path, the forwarder keeps its settings and credential in a directory only root can read (SYSTEM and Administrators on Windows).## Runtime log paths| Mode | Runtime log ||------|-------------|| User mode | `~/.beacon/endpoint/logs/runtime.jsonl` |-| System mode | `/var/log/beacon-agent/runtime.jsonl` |+| System mode, macOS and Linux | `/var/log/beacon-agent/runtime.jsonl` |+| System mode, Windows | `C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl` |Use system mode for MDM deployments so Azure Monitor Agent can tail `/var/log/beacon-agent/runtime.jsonl` without per-user home directory permissions.@@ -31,7 +32,7 @@ Use system mode for MDM deployments so Azure Monitor Agent can tail `/var/log/be- A Log Analytics workspace, with Microsoft Sentinel enabled if you want Sentinel hunting and analytics workflows.- A custom Log Analytics table named `BeaconRuntime_CL`.- For the Azure Monitor Agent path: AMA on the endpoint (Azure Arc first, outside Azure) and a DCR associated with it.-- For the Vector path: an Entra app registration, a Data Collection Endpoint, and the Logs Ingestion DCR from the pack.+- For the Vector path: an Entra app registration and the Logs Ingestion DCR from the pack, and a system install of Beacon.## Install the Sentinel pack@@ -153,61 +154,81 @@ A host that cannot reach Azure at all cannot use either path.## Vector and the Logs Ingestion API-Vector reads `runtime.jsonl` and posts each line to the [Logs Ingestion API](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview) with an Entra app registration. It needs no Arc, no AMA, and no Azure resource per machine. Vector ships with Beacon: the `.deb`, `.rpm`, and macOS package install it at `/opt/beacon/bin/vector`, and the Linux archive carries it as `beacon-vector`.+Vector reads `runtime.jsonl` and posts each line to the [Logs Ingestion API](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview) with a Microsoft Entra app registration. It needs no Arc, no AMA, and no Azure resource per machine. Vector ships with Beacon on all three platforms: the macOS package and the Linux `.deb` and `.rpm` install it at `/opt/beacon/bin/vector`, and the Windows MSI installs `vector.exe` beside `beacon.exe`. `beacon endpoint sentinel forwarder install` runs it as a system service, so one command sets up forwarding the same way on every machine.Each record carries the original Beacon line as `RawData`. The Logs Ingestion DCR runs the same transform as the AMA path, so the rows are identical either way.### 1. Azure side, once-1. Create the `BeaconRuntime_CL` table and a Data Collection Endpoint in the workspace's region, as in steps 2 and 3 above.-2. Deploy `dcr-logs-ingestion-template.json` with the workspace and DCE resource IDs. Note the `dcrImmutableId` output.-3. Register an app in Microsoft Entra ID and create a client secret for it.-4. On the DCR, grant the app the **Monitoring Metrics Publisher** role.+1. Create the `BeaconRuntime_CL` table as in step 3 above.+2. Deploy `dcr-logs-ingestion-template.json` from the pack with the workspace resource ID, and note the `dcrImmutableId` output. Then read the DCR's logs ingestion URL:++ ```bash title="Read the DCR's logs ingestion URL"+ az monitor data-collection rule show \+ --resource-group <resource group> --name dcr-beacon-runtime-ingestion \+ --query endpoints.logsIngestion --output tsv+ ```++ You need a Data Collection Endpoint only for Private Link. Pass its resource ID as `dataCollectionEndpointResourceId` and use its logs ingestion URL instead.+3. Register an app in Microsoft Entra ID and give it a certificate. A client secret also works, but Microsoft recommends a certificate for production.+4. On the DCR, grant the app the **Monitoring Metrics Publisher** role. A new role assignment can take up to 30 minutes to apply; the forwarder keeps retrying until it does.### 2. Each host-The host needs outbound HTTPS to `login.microsoftonline.com` and to your DCE's `*.ingest.monitor.azure.com` hostname. Nothing else.--```bash title="Install the config and credentials"-sudo mkdir -p /etc/beacon-sentinel-sudo cp beacon-sentinel-pack/vector.toml /etc/beacon-sentinel/vector.toml-sudo install -m 0600 /dev/null /etc/beacon-sentinel/azure.env-sudo tee /etc/beacon-sentinel/azure.env >/dev/null <<'ENV'-BEACON_SENTINEL_DCE_ENDPOINT=https://<dce>.<region>.ingest.monitor.azure.com-BEACON_SENTINEL_DCR_IMMUTABLE_ID=dcr-...-AZURE_TENANT_ID=...-AZURE_CLIENT_ID=...-AZURE_CLIENT_SECRET=...-ENV+Run this as root, or from an elevated shell on Windows. A fleet tool running as `LocalSystem` works too.++<CodeGroup>+```bash title="macOS and Linux"+sudo AZURE_CLIENT_CERTIFICATE_PASSWORD='<pfx password>' \+ /opt/beacon/bin/beacon endpoint sentinel forwarder install --system \+ --endpoint https://<dcr>.<region>-1.ingest.monitor.azure.com \+ --dcr-immutable-id dcr-<32 hex digits> \+ --tenant-id <tenant ID> --client-id <app ID> \+ --client-certificate /path/to/app.pfx```-```ini title="/etc/systemd/system/beacon-sentinel.service"-[Unit]-Description=Vector: Beacon events to Microsoft Sentinel-After=network-online.target-Wants=network-online.target--[Service]-ExecStart=/opt/beacon/bin/vector --config /etc/beacon-sentinel/vector.toml-EnvironmentFile=/etc/beacon-sentinel/azure.env-DynamicUser=yes-StateDirectory=vector/beacon-sentinel-Restart=always--[Install]-WantedBy=multi-user.target+```powershell title="Windows"+$env:AZURE_CLIENT_CERTIFICATE_PASSWORD = '<pfx password>'+& "$env:ProgramFiles\Beacon\bin\beacon.exe" endpoint sentinel forwarder install --system `+ --endpoint https://<dcr>.<region>-1.ingest.monitor.azure.com `+ --dcr-immutable-id dcr-<32 hex digits> `+ --tenant-id <tenant ID> --client-id <app ID> `+ --client-certificate C:\path\to\app.pfx```+</CodeGroup>++Leave out the password variable for a certificate without one. To use a client secret instead of a certificate, drop `--client-certificate` and pass the secret on stdin with `--client-secret-stdin`, or in `AZURE_CLIENT_SECRET`. The credential is never a command-line argument.++The command:++1. Copies the certificate, its password or the secret into `forwarders/sentinel` under the endpoint's system directory (`/etc/beacon/endpoint` on Linux, `/Library/Application Support/Beacon/Endpoint` on macOS, `C:\ProgramData\Beacon\Endpoint` on Windows). Only root can read that directory, or SYSTEM and Administrators on Windows. You can delete your own copy of the certificate afterwards.+2. Writes Vector's config with the values in it and has Vector check it. If Vector rejects it, nothing changes, and a forwarder that was already running keeps running as it was.+3. Starts Vector as a service that restarts on failure and after a reboot: `BeaconSentinelForwarder` on Windows, `beacon-sentinel-forwarder.service` on Linux, and `com.beacon.endpoint.sentinel-forwarder` on macOS.-```bash title="Start it"-sudo systemctl daemon-reload-sudo systemctl enable --now beacon-sentinel+On its first start the forwarder sends the current runtime log once, including the sessions the install backfilled, then only new lines. Pass `--read-from end` to skip what is already in the log.++The host needs outbound HTTPS to `login.microsoftonline.com` and to the DCR's `*.ingest.monitor.azure.com` hostname. For Azure Government or another sovereign cloud, pass its Entra authority with `--authority-host`, such as `https://login.microsoftonline.us`.++### Operate the forwarder++```bash title="Check it"+sudo /opt/beacon/bin/beacon endpoint sentinel forwarder status --system```-`DynamicUser` runs Vector as an unprivileged user. It can read the runtime log because the default shared log is world-readable, and systemd reads `azure.env` as root before dropping privileges. If the endpoint uses [restricted log access](/security/restricted-log-access), add `SupplementaryGroups=beacon-log` under `[Service]` so Vector can still read it. `StateDirectory` creates `/var/lib/vector/beacon-sentinel`, where Vector keeps its read position.+`beacon endpoint status --system` shows the same service state. Vector's own warnings and errors are in `forwarders/sentinel/logs/vector-<date>.log` under the endpoint's system directory, kept for a week.++- To change a setting or rotate the credential, run `forwarder install` again with the new values.+- Repair and package upgrades keep the forwarder. An upgrade restarts it on the new package's Vector.+- Uninstall removes the service. A non-purge uninstall (`--keep-config`, or a Windows MSI removal without `BEACON_PURGE=1`) keeps its settings, so installing Beacon again brings it back. `beacon endpoint sentinel forwarder remove --system` deletes the settings and credential too.+- With [restricted log access](/security/restricted-log-access), nothing changes: the forwarder runs as root or SYSTEM and can read the log.++Vector saves its place in the log only after Azure has accepted a batch, and retries throttling, server errors and `401`/`403` answers without a limit. An outage or a role assignment that has not applied yet holds lines back rather than dropping them. After a crash some lines can be sent twice. Every row's `RawData` carries the event's `event.id`, so you can remove duplicates in a query.++### Run Vector yourself-The pack ships a client secret config. Vector also supports a certificate (`azure_credential_kind = "client_certificate_credential"` with `certificate_path`); see the [`azure_logs_ingestion` sink](https://vector.dev/docs/reference/configuration/sinks/azure_logs_ingestion/).+`vector.toml` in the pack is the same config for running Vector under your own service manager, with the values taken from its environment: `BEACON_SENTINEL_DCE_ENDPOINT` (the logs ingestion URL), `BEACON_SENTINEL_DCR_IMMUTABLE_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID` and `AZURE_CLIENT_SECRET`. If you already run it that way, stop that service before you install the managed forwarder, or every line is sent twice.-The generated table schema includes columns such as `Vendor`, `Product`, `EventAction`, `Severity`, `HostName`, `UserName`, `HarnessName`, `SessionId`, `ToolName`, `CommandLine`, `Repository`, `Branch`, `Message`, `ContentRetention`, and `RawData`.+The generated table schema includes columns such as `Vendor`, `Product`, `EventAction`, `Severity`, `HostName`, `UserName`, `HarnessName`, `SessionId`, `ToolName`, `CommandLine`, `Repository`, `Branch`, `Message`, and `RawData`.## Validate forwarding@@ -233,7 +254,7 @@ BeaconRuntime_CL| order by TimeGenerated desc```-If the validation query does not return data, check the DCR association, Azure Monitor Agent health state, configured file path, and table schema. On the Vector path, check `journalctl -u beacon-sentinel` for authentication errors and confirm the app has Monitoring Metrics Publisher on the DCR. Role assignments can take several minutes to apply. The target table must exist before the DCR can route transformed records to it.+If the validation query does not return data, check the DCR association, Azure Monitor Agent health state, configured file path, and table schema. On the Vector path, run `beacon endpoint sentinel forwarder status --system`, which shows Vector's last warning, and confirm the app has Monitoring Metrics Publisher on the DCR. Role assignments can take several minutes to apply. The target table must exist before the DCR can route transformed records to it.## Hunting content@@ -245,7 +266,7 @@ Use `detections.kql` as example analytics rule logic. Review and tune thresholdsMicrosoft Sentinel can also collect CEF and Syslog through Azure Monitor Agent, but the generated Beacon pack uses custom logs because Beacon events are rich structured JSON with prompts, tool calls, commands, files, runtime metadata, and optional raw fields. Flattening those events into CEF loses useful context.-Beacon's own endpoint config never holds Azure credentials. On the Vector path, the Entra secret, DCR ID, and ingestion endpoint live only in the Vector service's environment file. Vector does the batching and retries.+Beacon's `config.json` never holds Azure values. The managed forwarder keeps its settings and credential in its own directory, readable only by root, or by SYSTEM and Administrators on Windows. Vector does the batching and retries.## Content handlingdiff --git a/packaging/macos/scripts/postinstall b/packaging/macos/scripts/postinstallindex e7adac93..ff56bdea 100755--- a/packaging/macos/scripts/postinstall+++ b/packaging/macos/scripts/postinstall@@ -141,6 +141,11 @@ if command -v launchctl >/dev/null 2>&1; then# a no-op on an endpoint that is not connected. Non-fatal: a rejected config keeps the old one."${BEACON_BIN:-/opt/beacon/bin/beacon}" endpoint asymptote reconcile --system || \echo "Warning: Beacon Cloud forwarder config not reconciled (endpoint is installed and running)" >&2+ # A Sentinel forwarder set up with `beacon endpoint sentinel forwarder install` gets this version's+ # config and is restarted, so it runs the Vector this package just installed. A no-op where none+ # is set up. Non-fatal: a rejected config keeps the old one.+ "${BEACON_BIN:-/opt/beacon/bin/beacon}" endpoint sentinel forwarder reconcile --system || \+ echo "Warning: Sentinel forwarder not reconciled (endpoint is installed and running)" >&2fiexit 0diff --git a/packaging/macos/test-endpoint-scripts.sh b/packaging/macos/test-endpoint-scripts.shindex 11786d41..26fa7dd9 100644--- a/packaging/macos/test-endpoint-scripts.sh+++ b/packaging/macos/test-endpoint-scripts.sh@@ -1414,7 +1414,8 @@ for expected in \'endpoint update install-daemon' \'endpoint inventory install-daemon --system' \'endpoint sessions install-daemon --system' \- 'endpoint asymptote reconcile --system'+ 'endpoint asymptote reconcile --system' \+ 'endpoint sentinel forwarder reconcile --system'doif ! grep -qxF "$expected" "$POSTINSTALL_BEACON_LOG"; thenecho "postinstall should run: $expected" >&2diff --git a/packaging/windows/smoke-sentinel-forwarder.ps1 b/packaging/windows/smoke-sentinel-forwarder.ps1new file mode 100644index 00000000..54593fe2--- /dev/null+++ b/packaging/windows/smoke-sentinel-forwarder.ps1@@ -0,0 +1,248 @@+# End-to-end check of the managed Sentinel forwarder on an installed Windows endpoint, against a mock+# of Microsoft Entra ID and the Azure Monitor Logs Ingestion API (sentinel-mock.exe). It replays what+# a fleet does: install the MSI, set up the forwarder as SYSTEM with a certificate, upgrade, switch log+# access, uninstall. Run elevated, which the CI runner is; each phase runs at its point in the job.+#+# -Phase setup after the first install: mock up, forwarder installed, first rows arrive,+# and nobody but SYSTEM and Administrators can read the credential+# -Phase after-upgrade after the MSI upgrade: the service is back, on the new package's Vector+# -Phase verify after the log access switches: every event in the runtime log reached the+# mock, and none twice+# -Phase after-uninstall after a non-purge uninstall: the service is gone, its state kept+# -Phase cleanup always: stop the mock, remove its CA and the test certificate+[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)]+ [ValidateSet('setup', 'after-upgrade', 'verify', 'after-uninstall', 'cleanup')]+ [string]$Phase,+ [string]$MockExe+)++$ErrorActionPreference = 'Stop'++$beacon = Join-Path $env:ProgramFiles 'Beacon\bin\beacon.exe'+$service = 'BeaconSentinelForwarder'+$forwarderDir = Join-Path $env:ProgramData 'Beacon\Endpoint\forwarders\sentinel'+$logDir = Join-Path $env:ProgramData 'Beacon\Endpoint\logs'+$work = Join-Path $env:RUNNER_TEMP 'sentinel-smoke'+$rowsFile = Join-Path $work 'rows.jsonl'+$urlFile = Join-Path $work 'url'+$caFile = Join-Path $work 'mock-ca.pem'+$pfx = Join-Path $work 'app.pfx'+$tenant = '11111111-2222-3333-4444-555555555555'+$client = '66666666-7777-8888-9999-000000000000'+$dcr = 'dcr-0123456789abcdef0123456789abcdef'+$pfxPassword = 'smoke-pfx-password'++function Invoke-Beacon {+ param([string[]]$Arguments)+ $out = & $beacon @Arguments 2>&1 | Out-String+ if ($LASTEXITCODE -ne 0) {+ Write-Output $out+ throw "beacon $($Arguments -join ' ') exited $LASTEXITCODE"+ }+ return $out+}++function Get-Rows {+ if (-not (Test-Path -LiteralPath $rowsFile)) { return @() }+ $rows = @()+ # The mock appends while this reads; open allowing that.+ $stream = [System.IO.File]::Open($rowsFile, 'Open', 'Read', 'ReadWrite')+ try {+ $reader = New-Object System.IO.StreamReader($stream)+ while ($null -ne ($line = $reader.ReadLine())) {+ if ($line.Trim()) { $rows += ($line | ConvertFrom-Json) }+ }+ } finally {+ $stream.Dispose()+ }+ return $rows+}++function Get-RowIds {+ $ids = @{}+ foreach ($row in Get-Rows) {+ $id = ($row.RawData | ConvertFrom-Json).event.id+ $ids[$id] = 1 + [int]$ids[$id]+ }+ return $ids+}++# Every event id in the runtime log and the archive a rotation made, read as this elevated account.+function Get-LogIds {+ $ids = @()+ foreach ($name in @('runtime.jsonl.1', 'runtime.jsonl')) {+ $path = Join-Path $logDir $name+ if (-not (Test-Path -LiteralPath $path)) { continue }+ $stream = [System.IO.File]::Open($path, 'Open', 'Read', 'ReadWrite, Delete')+ try {+ $reader = New-Object System.IO.StreamReader($stream)+ while ($null -ne ($line = $reader.ReadLine())) {+ if ($line.Trim()) { $ids += ($line | ConvertFrom-Json).event.id }+ }+ } finally {+ $stream.Dispose()+ }+ }+ return $ids+}++function Wait-Validation {+ param([int]$Count, [int]$Seconds = 120)+ $deadline = (Get-Date).AddSeconds($Seconds)+ while ($true) {+ $found = @(Get-Rows | Where-Object { $_.RawData -like '*Beacon endpoint Sentinel validation event*' }).Count+ if ($found -ge $Count) { return }+ if ((Get-Date) -gt $deadline) {+ Show-Forwarder+ throw "$found of $Count Sentinel validation events reached the mock in ${Seconds}s"+ }+ Start-Sleep -Seconds 2+ }+}++function Assert-Running {+ $state = (& sc.exe query $service 2>&1 | Out-String)+ $global:LASTEXITCODE = 0+ if ($state -notmatch 'RUNNING') {+ Write-Output $state+ Show-Forwarder+ throw "the $service service is not running"+ }+}++function Show-Forwarder {+ Write-Output "--- $service ---"+ & sc.exe queryex $service 2>&1 | Write-Output+ & sc.exe qc $service 2>&1 | Write-Output+ & $beacon endpoint sentinel forwarder status --system 2>&1 | Write-Output+ Get-ChildItem (Join-Path $forwarderDir 'logs') -Filter 'vector-*.log' -ErrorAction SilentlyContinue |+ ForEach-Object { Write-Output "--- $($_.Name) (tail) ---"; Get-Content -LiteralPath $_.FullName -Tail 30 | Write-Output }+ $global:LASTEXITCODE = 0+}++# Only SYSTEM and Administrators may be granted anything on the credential and its directory.+function Assert-Private {+ param([string]$Path)+ $allowed = @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators')+ $acl = Get-Acl -LiteralPath $Path+ foreach ($rule in $acl.Access) {+ if ($rule.AccessControlType -eq 'Allow' -and $allowed -notcontains $rule.IdentityReference.Value) {+ throw "$Path grants $($rule.FileSystemRights) to $($rule.IdentityReference.Value)"+ }+ }+ Write-Output "ok: only SYSTEM and Administrators can open $Path"+}++switch ($Phase) {+ 'setup' {+ New-Item -ItemType Directory -Force -Path $work | Out-Null+ if (-not $MockExe -or -not (Test-Path -LiteralPath $MockExe)) { throw "-MockExe must name the built sentinel-mock.exe" }++ # A certificate credential, the one the docs lead with, exported the way OpenSSL 3 reads it.+ $cert = New-SelfSignedCertificate -Subject 'CN=beacon-sentinel-smoke' -CertStoreLocation Cert:\LocalMachine\My `+ -KeyAlgorithm RSA -KeyLength 2048 -KeyExportPolicy Exportable -NotAfter (Get-Date).AddDays(2)+ $secure = ConvertTo-SecureString $pfxPassword -AsPlainText -Force+ Export-PfxCertificate -Cert $cert -FilePath $pfx -Password $secure -CryptoAlgorithmOption AES256_SHA256 | Out-Null+ $cert.Thumbprint | Set-Content -LiteralPath (Join-Path $work 'cert-thumbprint')++ # The mock outlives this step: it keeps answering through the upgrade and the log access+ # switches, until the cleanup phase stops it.+ $mock = Start-Process -FilePath $MockExe -PassThru -WindowStyle Hidden `+ -RedirectStandardOutput (Join-Path $work 'mock.out') -RedirectStandardError (Join-Path $work 'mock.err') `+ -ArgumentList @('--ca-out', $caFile, '--rows-out', $rowsFile, '--url-out', $urlFile,+ '--tenant', $tenant, '--client-id', $client, '--dcr', $dcr,+ # A role assignment that has not propagated yet: the forwarder must retry, not drop.+ '--ingest-statuses', '403,403')+ $mock.Id | Set-Content -LiteralPath (Join-Path $work 'mock.pid')+ $deadline = (Get-Date).AddSeconds(30)+ while (-not (Test-Path -LiteralPath $urlFile)) {+ if ((Get-Date) -gt $deadline) { Get-Content (Join-Path $work 'mock.err') -ErrorAction SilentlyContinue; throw "the mock never started" }+ Start-Sleep -Milliseconds 200+ }+ $url = (Get-Content -LiteralPath $urlFile -Raw).Trim()+ # Vector's token client trusts only the Windows store, as SYSTEM.+ & certutil.exe -addstore -f Root $caFile | Out-Null+ if ($LASTEXITCODE -ne 0) { throw "certutil -addstore Root failed" }+ Write-Output "mock at $url"++ $env:AZURE_CLIENT_CERTIFICATE_PASSWORD = $pfxPassword+ Invoke-Beacon @('endpoint', 'sentinel', 'forwarder', 'install', '--system',+ '--endpoint', $url, '--authority-host', $url, '--dcr-immutable-id', $dcr,+ '--tenant-id', $tenant, '--client-id', $client, '--client-certificate', $pfx) | Write-Output+ Remove-Item Env:\AZURE_CLIENT_CERTIFICATE_PASSWORD+ Assert-Running++ $environment = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\$service").Environment+ if ($environment -notcontains "AZURE_AUTHORITY_HOST=$url") { throw "the service environment is '$environment'" }++ # The deployment's copy of the certificate can go; the forwarder keeps its own.+ Remove-Item -LiteralPath $pfx+ foreach ($path in @($forwarderDir, (Join-Path $forwarderDir 'secrets.json'), (Join-Path $forwarderDir 'client.pfx'))) {+ Assert-Private $path+ }+ $settings = Get-Content -LiteralPath (Join-Path $forwarderDir 'forwarder.json') -Raw+ if ($settings -match [regex]::Escape($pfxPassword)) { throw "forwarder.json holds the certificate password" }++ Invoke-Beacon @('endpoint', 'sentinel', 'validate', '--system') | Out-Null+ Wait-Validation -Count 1+ $status = Invoke-Beacon @('endpoint', 'status', '--system', '--json') | ConvertFrom-Json+ if (-not $status.sentinel_forwarder.service.running) { throw "endpoint status does not report the forwarder running" }+ Write-Output "ok: the forwarder authenticated with a certificate, retried 403s, and delivered"+ }+ 'after-upgrade' {+ # The old package's uninstall removed the service so vector.exe could be replaced; the new+ # package's install put it back from the state it kept.+ Assert-Running+ Invoke-Beacon @('endpoint', 'sentinel', 'validate', '--system') | Out-Null+ Wait-Validation -Count 2+ Write-Output "ok: the forwarder came back after the upgrade and kept delivering"+ }+ 'verify' {+ Assert-Running+ Invoke-Beacon @('endpoint', 'sentinel', 'validate', '--system') | Out-Null+ Wait-Validation -Count 3+ $deadline = (Get-Date).AddSeconds(120)+ while ($true) {+ $logIds = Get-LogIds+ $rowIds = Get-RowIds+ $missing = @($logIds | Where-Object { -not $rowIds.ContainsKey($_) })+ if ($missing.Count -eq 0) { break }+ if ((Get-Date) -gt $deadline) {+ Show-Forwarder+ throw "$($missing.Count) of $($logIds.Count) runtime log events never reached the mock, first: $($missing[0])"+ }+ Start-Sleep -Seconds 3+ }+ $twice = @($rowIds.Keys | Where-Object { $rowIds[$_] -gt 1 })+ if ($twice.Count -gt 0) { throw "$($twice.Count) events reached the mock more than once, first: $($twice[0])" }+ Write-Output "ok: all $($logIds.Count) runtime log events reached the mock exactly once, across an upgrade and two log access switches"+ }+ 'after-uninstall' {+ $query = (& sc.exe query $service 2>&1 | Out-String)+ $global:LASTEXITCODE = 0+ if ($query -notmatch '1060') { Write-Output $query; throw "the $service service still exists after uninstall" }+ if (-not (Test-Path -LiteralPath (Join-Path $forwarderDir 'forwarder.json'))) {+ throw "a non-purge uninstall removed the forwarder's settings"+ }+ Write-Output "ok: uninstall removed the forwarder service and kept its settings for a reinstall"+ }+ 'cleanup' {+ $ErrorActionPreference = 'Continue'+ $pidFile = Join-Path $work 'mock.pid'+ if (Test-Path -LiteralPath $pidFile) {+ Stop-Process -Id ([int](Get-Content -LiteralPath $pidFile)) -Force -ErrorAction SilentlyContinue+ }+ if (Test-Path -LiteralPath $caFile) {+ $ca = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($caFile)+ Get-ChildItem Cert:\LocalMachine\Root | Where-Object Thumbprint -eq $ca.Thumbprint | Remove-Item+ }+ $thumbFile = Join-Path $work 'cert-thumbprint'+ if (Test-Path -LiteralPath $thumbFile) {+ $thumb = (Get-Content -LiteralPath $thumbFile).Trim()+ Get-ChildItem Cert:\LocalMachine\My | Where-Object Thumbprint -eq $thumb | Remove-Item+ }+ $global:LASTEXITCODE = 0+ }+}diff --git a/packaging/windows/test-endpoint-scripts.ps1 b/packaging/windows/test-endpoint-scripts.ps1index 1230a092..7c017fe7 100644--- a/packaging/windows/test-endpoint-scripts.ps1+++ b/packaging/windows/test-endpoint-scripts.ps1@@ -20,7 +20,7 @@ function Fail {$script:failures++}-$scripts = @('install-endpoint.ps1', 'uninstall-endpoint.ps1', 'package-common.ps1', 'build-msi.ps1', 'fetch-vector.ps1', 'smoke-restricted-log.ps1')+$scripts = @('install-endpoint.ps1', 'uninstall-endpoint.ps1', 'package-common.ps1', 'build-msi.ps1', 'fetch-vector.ps1', 'smoke-restricted-log.ps1', 'smoke-sentinel-forwarder.ps1')foreach ($name in $scripts) {$path = Join-Path $scriptDir $nameif (-not (Test-Path -LiteralPath $path)) {diff --git a/packaging/windows/uninstall-endpoint.ps1 b/packaging/windows/uninstall-endpoint.ps1index 614643ea..46299c5d 100644--- a/packaging/windows/uninstall-endpoint.ps1+++ b/packaging/windows/uninstall-endpoint.ps1@@ -32,34 +32,41 @@ $uninstallTimeoutSeconds = 180# defer the replacement to a reboot or keep running the old collector. The registration goes too, so# a removal leaves no service pointing at a deleted binary; an upgrade's install action registers it# again.-function Stop-BeaconCollectorService {- param([string]$InstallRoot)+function Stop-BeaconService {+ param([string]$Name, [string]$Executable)# Best effort throughout: sc.exe reports a service that is already gone on stderr, which the# script's 'Stop' preference would otherwise turn into a failed uninstall.$ErrorActionPreference = 'Continue'- $name = 'BeaconCollector'- $service = Get-Service -Name $name -ErrorAction SilentlyContinue+ $service = Get-Service -Name $Name -ErrorAction SilentlyContinueif ($null -eq $service) { return }if ($service.Status -ne 'Stopped') {- Write-BeaconPackageLog "stopping the $name service directly"- & sc.exe stop $name 2>&1 | ForEach-Object { Write-BeaconPackageLog " $_" }+ Write-BeaconPackageLog "stopping the $Name service directly"+ & sc.exe stop $Name 2>&1 | ForEach-Object { Write-BeaconPackageLog " $_" }try {$service.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(30))} catch {- Write-BeaconPackageLog "the $name service did not stop within 30s"+ Write-BeaconPackageLog "the $Name service did not stop within 30s"}}- $collector = Join-Path $InstallRoot 'bin\beacon-otelcol.exe'- Get-Process -Name 'beacon-otelcol' -ErrorAction SilentlyContinue |- Where-Object { $_.Path -eq $collector } |+ $processName = [System.IO.Path]::GetFileNameWithoutExtension($Executable)+ Get-Process -Name $processName -ErrorAction SilentlyContinue |+ Where-Object { $_.Path -eq $Executable } |ForEach-Object {- Write-BeaconPackageLog "terminating collector process $($_.Id)"+ Write-BeaconPackageLog "terminating $processName process $($_.Id)"Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue}- & sc.exe delete $name 2>&1 | ForEach-Object { Write-BeaconPackageLog " $_" }+ & sc.exe delete $Name 2>&1 | ForEach-Object { Write-BeaconPackageLog " $_" }$global:LASTEXITCODE = 0}+# The services that hold a file the package is about to remove or replace: the collector, and the+# Sentinel forwarder's Vector when one is set up.+function Stop-BeaconServices {+ param([string]$InstallRoot)+ Stop-BeaconService -Name 'BeaconCollector' -Executable (Join-Path $InstallRoot 'bin\beacon-otelcol.exe')+ Stop-BeaconService -Name 'BeaconSentinelForwarder' -Executable (Join-Path $InstallRoot 'bin\vector.exe')+}+function Get-EnvOrDefault {param([string]$Name, [string]$Default)$value = [Environment]::GetEnvironmentVariable($Name)@@ -150,7 +157,7 @@ $code = Invoke-BeaconBounded -Beacon $beaconBin -Arguments $uninstallArgs -Timeoif ($code -eq $script:BeaconTimeoutExitCode) {# Stopped, not waited on. A removal that hangs is worse for the person running it than one that# finishes with the collector forced down, and the package log records what happened.- Stop-BeaconCollectorService -InstallRoot $installRoot+ Stop-BeaconServices -InstallRoot $installRoot} elseif ($code -ne 0) {# Reported, not thrown. The service and its registration are what matter here, and `endpoint# uninstall` is idempotent -- so a non-zero exit is worth surfacing but not worth wedging an MSI