diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..8de2b673 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,22 @@ +## Summary + + + +## Verification + +- [ ] `dotnet build --configuration Release` +- [ ] `dotnet test --configuration Release` +- [ ] `dotnet format --verify-no-changes` +- [ ] UI checks (`cd ui/Bower.Management.Web && npm run lint && npm test && npm run build`) if UI changed +- [ ] Docs checks (`python3 -I tools/docs/generate_cli_reference.py --check`, `python3 -I tools/docs/generate_config_and_api_reference.py --check`, `python3 -I tools/docs/generate_glossary.py --check`, `python3 -m unittest tools/docs/tests/test_build_tools.py`) + +## Documentation & security checklist + +- [ ] **Docs updated?** (CLI, API, configuration, schema, or console changes include matching docs updates, or a `documentation` waiver is explained below) +- [ ] Australian English spelling used in user-facing text and docs +- [ ] Only synthetic data and example domains (`example.gov.au`, `example.com`, `192.0.2.x`) appear in examples and tests +- [ ] Security and compatibility impact explained below + +## Security and compatibility impact + + diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 944c32ad..f2812011 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -13,6 +13,10 @@ on: - 'deploy/kubernetes/deployment.yaml' - 'ui/Bower.Management.Web/src/components/glossary.json' - 'src/Bower.Cli/Commands/CliHelp.cs' + - 'src/Bower.Collector/CollectorSettings.cs' + - 'src/Bower.Collector/CollectorApplication.cs' + - 'src/Bower.Management.Api/*.cs' + - 'schemas/**' - '.github/workflows/docs.yml' push: branches: [main] @@ -27,6 +31,10 @@ on: - 'deploy/kubernetes/deployment.yaml' - 'ui/Bower.Management.Web/src/components/glossary.json' - 'src/Bower.Cli/Commands/CliHelp.cs' + - 'src/Bower.Collector/CollectorSettings.cs' + - 'src/Bower.Collector/CollectorApplication.cs' + - 'src/Bower.Management.Api/*.cs' + - 'schemas/**' - '.github/workflows/docs.yml' workflow_dispatch: @@ -60,6 +68,7 @@ jobs: run: | .venv-docs/bin/python tools/docs/generate_glossary.py --check .venv-docs/bin/python tools/docs/generate_cli_reference.py --check + .venv-docs/bin/python tools/docs/generate_config_and_api_reference.py --check .venv-docs/bin/python -m unittest discover -s tools/docs/tests -p 'test_*.py' - name: Build the site working-directory: website diff --git a/docs/deployment/syslog-vendors.md b/docs/deployment/syslog-vendors.md new file mode 100644 index 00000000..f2242aad --- /dev/null +++ b/docs/deployment/syslog-vendors.md @@ -0,0 +1,151 @@ +# Syslog vendor configuration guides + +These guides configure common Linux daemons and network security appliances to forward +security events to Bower's [syslog source](syslog-source.md) over **RFC 5424 TLS** +(`TCP/6514`). All hostnames and addresses below are synthetic (`192.0.2.x`, +`bower-collector.example.gov.au`). + +Never send raw unrestricted debug traffic to Bower: configure each appliance to forward +only security-relevant facilities (authentication, firewall denies, threat, and +configuration changes) and pair every listener with a signed Bower pack parser. + +## 1. Linux rsyslog (RFC 5424 over TLS) + +Install `rsyslog-gnutls` (or `rsyslog-openssl`), place the collector's CA bundle at +`/etc/ssl/certs/bower-ca.pem`, and create `/etc/rsyslog.d/60-bower-security.conf`: + +```text +global( + DefaultNetstreamDriver="gtls" + DefaultNetstreamDriverCAFile="/etc/ssl/certs/bower-ca.pem" +) + +# Forward only authentication and security facilities with a bounded disk-assisted queue. +auth,authpriv.* action( + type="omfwd" + target="bower-collector.example.gov.au" + port="6514" + protocol="tcp" + template="RSYSLOG_SyslogProtocol23Format" + StreamDriver="gtls" + StreamDriverMode="1" + StreamDriverAuthMode="x509/name" + StreamDriverPermittedPeers="bower-collector.example.gov.au" + queue.type="LinkedList" + queue.filename="bower_fwd" + queue.maxDiskSpace="256m" + queue.saveOnShutdown="on" + action.resumeRetryCount="-1" +) +``` + +Validate with `rsyslogd -N1` and restart `rsyslog`. + +## 2. Linux syslog-ng (RFC 5424 over TLS) + +Add `/etc/syslog-ng/conf.d/60-bower.conf`: + +```text +filter f_bower_security { + facility(auth, authpriv) or program("sshd") or program("sudo"); +}; + +destination d_bower_tls { + syslog( + "bower-collector.example.gov.au" + port(6514) + transport("tls") + tls( + ca-dir("/etc/syslog-ng/ca.d") + peer-verify(required-trusted) + ) + disk-buffer( + mem-buf-size(10485760) + disk-buf-size(268435456) + reliable(yes) + ) + ); +}; + +log { + source(s_src); + filter(f_bower_security); + destination(d_bower_tls); +}; +``` + +Validate with `syslog-ng --syntax-only` and reload `syslog-ng`. + +## 3. Palo Alto Networks PAN-OS + +1. **Import the collector CA certificate:** *Device → Certificate Management → Certificates + → Import* (`bower-ca.pem`). Create a *Certificate Profile* referencing it. +2. **Create a Syslog Server Profile:** *Device → Server Profiles → Syslog → Add*: + - Name: `Bower-Syslog-TLS` + - Syslog Server: `bower-collector.example.gov.au` + - Transport: **SSL** (TLS), Port: `6514` + - Format: **IETF** (RFC 5424), Facility: `LOG_USER` +3. **Create a Log Forwarding Profile:** *Objects → Log Forwarding → Add* and forward only + **Threat**, **Authentication**, **System**, and **Config** logs (plus security-relevant + **Traffic** denies) to `Bower-Syslog-TLS`. +4. Commit the configuration and verify receipt on the collector with `bower top`. + +## 4. Fortinet FortiGate (FortiOS) + +Configure RFC 5424 over TLS on the FortiGate CLI (replace `Bower_CA` with the imported CA +certificate name): + +```text +config log syslogd setting + set status enable + set server "bower-collector.example.gov.au" + set mode reliable + set port 6514 + set format rfc5424 + set enc-algorithm high + set ssl-min-proto-version TLSv1-2 + set certificate "Bower_CA" +end + +config log syslogd filter + set severity warning + set forward-traffic disable + set local-traffic enable + set anomaly enable + set voip disable +end +``` + +## 5. Cisco IOS-XE / ASA + +### Cisco IOS-XE (TCP / TLS via PKI trustpoint) + +```text +logging trap informational +logging facility local6 +logging source-interface Loopback0 +logging host 192.0.2.10 transport tcp port 6514 +logging origin-id hostname +service timestamps log datetime msec localtime show-timezone year +``` + +For TLS transport on IOS-XE releases supporting RFC 5425, attach a configured PKI +trustpoint (`transport tls`) or terminate TLS via a local rsyslog forwarder on the +management jump host. + +### Cisco ASA + +```text +logging enable +logging timestamp +logging trap notifications +logging facility 22 +logging host management 192.0.2.10 6/6514 secure +``` + +## Verify with Bower + +1. Confirm the listener is healthy in `/v1/status` (`syslog` block). +2. Watch post-redaction intake live with `bower tap --source syslog` or inspect counts with + `bower top`. +3. Verify zero unapproved event types leak past default-deny policies. diff --git a/docs/operations/alert-runbooks.md b/docs/operations/alert-runbooks.md new file mode 100644 index 00000000..8e571944 --- /dev/null +++ b/docs/operations/alert-runbooks.md @@ -0,0 +1,132 @@ +# Console alert runbooks + +Every condition surfaced on the console **Alerts** page (`/alerts`) and in collector +operational logs has a plain-language explanation, verification steps, and a recovery path +below. All examples use synthetic hosts (`collector-01.example.gov.au`). + +## Fleet and collector alerts + +### Collector offline (`offline`) + +- **What it means:** The collector has stopped sending heartbeats to the management API. +- **How to check:** Run `systemctl status bower` (Linux) or `Get-Service BowerCollector` + (Windows) on the host, and run `bower doctor` to test outbound HTTPS connectivity to the + management endpoint. +- **How to fix:** Start the service, verify proxy/firewall rules allow outbound port 443 to + the management API, and check disk space on `/var/lib/bower`. +- **Safe to mute?** Only during planned host maintenance (set an expiry matching the + maintenance window). + +### Collector history changed (`history-changed`) + +- **What it means:** The collector's queue ledger hash chain reported tampering, truncation, + or an unexpected reset. +- **How to check:** Inspect `/v1/status` (`ledger` and `recovery` blocks) and run + `bower queue verify --queue /var/lib/bower/queue.db`. +- **How to fix:** Treat as a security incident until explained. Preserve a backup copy of + the queue database (`bower queue backup`) before re-initialising. +- **Safe to mute?** No — investigate immediately. + +### Collector not sending (`not-sending`) + +- **What it means:** Events are queued locally, but no batch has been acknowledged by the + destination recently. +- **How to check:** Run `bower doctor` against the DCE/DCR endpoint and inspect `/v1/status` + (`deliveryActivity.lastFailureCode`). +- **How to fix:** Verify managed identity / workload identity RBAC (`Monitoring Metrics + Publisher` on the DCR), check network egress and TLS trust, and verify the DCR stream name + matches `Custom-BowerSecurity`. + +### Collector stale (`stale`) + +- **What it means:** The collector's last heartbeat is older than the staleness threshold, + though not yet marked fully offline. +- **How to check:** Check host CPU/disk load and outbound management proxy latency. +- **How to fix:** Resolve host congestion or proxy timeouts; check `management-heartbeat` + status in `/v1/status`. + +### Queue full or storage pressure (`queue-full`, EventId `1500` / `1501`) + +- **What it means:** The queue database or its underlying volume (or AMA spool / archive + volume) has crossed the warning or critical free-space watermark. +- **How to check:** Check `df -h /var/lib/bower` (Linux) or volume free space on Windows, + and inspect `/v1/status` (`storage` and `volumes`). +- **How to fix:** Restore destination delivery so the backlog drains, expand the volume, or + increase `BOWER_QUEUE_MAX_BYTES` only when volume headroom allows. See + [storage pressure](../production-readiness/03-storage-pressure.md). + +### Delivery trouble (`send-trouble`, EventId `1008`) + +- **What it means:** Repeated transient or permanent HTTP errors occurred when delivering to + Azure Logs Ingestion, S3, or an HTTP sink. +- **How to check:** Inspect `deliveryActivity.lastFailureCode` and collector logs for the + metadata-only failure code (`azure-http-403`, `azure-http-429`, `azure-http-400-isolated`). +- **How to fix:** Fix DCR permissions for `403`, allow adaptive backoff to absorb `429`, or + inspect dead-letter counts for `400`. + +### Events set aside in dead-letter queue (`set-aside`) + +- **What it means:** One or more events could not be delivered after retries or failed a + permanent validation check and were moved to the dead-letter queue. +- **How to check:** Run `bower queue dead-letter --queue /var/lib/bower/queue.db` (metadata + only — never raw payloads). +- **How to fix:** Fix the underlying schema or destination issue, then replay with + `bower queue replay`. + +### Delivery backlog (`backlog`) + +- **What it means:** Queued events waiting for delivery exceed the expected steady-state + backlog. +- **How to check:** Compare `/v1/status` queued depth against `delivery.concurrency`. +- **How to fix:** Verify destination reachability and check for throttling (`429`). + +### Quiet source (`quiet-source`) + +- **What it means:** An application or WEC subscription listed in `BOWER_SOURCE_EXPECTATIONS` + has emitted no accepted events within its expected silence window. +- **How to check:** Verify the upstream producer or WEC forwarder is running (`bower doctor + --wec-channel ForwardedEvents` on Windows) and confirm events are not being quarantined by + a policy change (`bower top`). +- **How to fix:** Restart the upstream forwarder or fix producer credentials/TLS. + +### Policy or privacy profile not applied (`policy-not-applied`, `privacy-not-applied`, EventId `1702`) + +- **What it means:** The collector's active policy hash or privacy profile hash does not match + the approved desired hash, or a hot reload failed validation (`EventId 1702`). +- **How to check:** Inspect `/v1/status` (`reload.errorType` and active hashes) and run + `bower validate` on the policy directory. +- **How to fix:** Correct the invalid YAML/signature, verify trusted signing keys, and + trigger a reload (`POST /v1/reload` or `SIGHUP`). + +### Pending approval (`pending`) or suspended collector (`suspended`) + +- **What it means:** A newly enrolled collector is waiting for an Approver decision, or an + Approver has suspended the collector. +- **How to check:** Open **Approvals** (`/approvals`) or **Fleet** (`/collectors`). +- **How to fix:** Have a second person with `Bower.Approver` review and approve or + re-activate the collector. + +### Background job failed (`job-failed`, EventId `1600`) + +- **What it means:** A scheduled maintenance or health job (such as retention, heartbeat, or + alert notifications) threw an error. +- **How to check:** Open **Jobs** (`/jobs`) or inspect collector EventId `1600` metadata. +- **How to fix:** Resolve the failing dependency (disk permissions, management connectivity, + or webhook/SMTP endpoint). + +### Redaction failure (`EventId 1302`) and configuration error (`EventId 2101`) + +- **What it means:** `1302` indicates the Privacy & Secret Protection Engine rejected or + quarantined an event before persistence (fail-closed). `2101` indicates invalid startup or + source configuration. +- **How to check:** Run `bower privacy test` on synthetic fixtures or `bower doctor` to + validate local files. +- **How to fix:** Fix the invalid privacy rule or source configuration and reload. + +### Sentinel proof missing or expired (`sentinel-proof`) + +- **What it means:** No recent destination-verified evidence bundle confirms rows landed in + `BowerSecurity_CL` in Microsoft Sentinel. +- **How to check:** Run `bower evidence run` with read access to the Log Analytics workspace. +- **How to fix:** Verify end-to-end delivery and upload the signed evidence bundle in the + console. Remember that simulated evidence never counts as production proof. diff --git a/docs/reference/api.md b/docs/reference/api.md new file mode 100644 index 00000000..24f5cb84 --- /dev/null +++ b/docs/reference/api.md @@ -0,0 +1,99 @@ +# Collector and Management HTTP API reference + + + +This page is generated directly from the route registrations in +`src/Bower.Collector/CollectorApplication.cs` and `src/Bower.Management.Api/*.cs`. +All endpoints return metadata or post-redaction views only; management storage never holds raw event payloads. + +## Collector HTTP endpoints + +| Method | Path | Access | +|---|---|---| +| `GET` | `/health` | Host policy | +| `GET` | `/health/live` | Host policy | +| `GET` | `/v1/status` | Host policy | +| `POST` | `/v1/events` | Host policy | +| `POST` | `/v1/reload` | Ingest bearer token | + +## Management API endpoints + +Authenticated via Microsoft Entra ID (`Bower.Viewer`, `Bower.Operator`, `Bower.Approver`, `Bower.Collector`) or enrolled collector key assertions. + +| Method | Path | Access | +|---|---|---| +| `GET` | `/api/access/me` | Role: `View` | +| `GET` | `/api/alerts/catalogue` | Role: `View` | +| `GET` | `/api/alerts/channels` | Role: `View` | +| `POST` | `/api/alerts/mute` | Host policy | +| `GET` | `/api/alerts/mutes` | Role: `View` | +| `POST` | `/api/alerts/mutes/{id}/unmute` | Host policy | +| `GET` | `/api/approvals` | Role: `View` | +| `POST` | `/api/approvals/{collectorId}/approve` | Role: `Approve` | +| `POST` | `/api/approvals/{collectorId}/reject` | Role: `Approve` | +| `GET` | `/api/audit` | Role: `View` | +| `GET` | `/api/collector-credentials` | Role: `View` | +| `GET` | `/api/collectors` | Host policy | +| `POST` | `/api/collectors/enrol` | Host policy | +| `POST` | `/api/collectors/register` | Host policy | +| `POST` | `/api/collectors/{collectorId}/desired-policy` | Host policy | +| `POST` | `/api/collectors/{collectorId}/reinstate` | Role: `Administer` | +| `POST` | `/api/collectors/{collectorId}/revoke` | Role: `Administer` | +| `POST` | `/api/collectors/{collectorId}/suspend` | Role: `Administer` | +| `GET` | `/api/collectors/{id}` | Role: `View` | +| `GET` | `/api/collectors/{id}/commands` | Role: `View` | +| `POST` | `/api/collectors/{id}/commands` | Role: `Operate` | +| `POST` | `/api/collectors/{id}/credentials/rotate` | Host policy | +| `POST` | `/api/collectors/{id}/credentials/{credentialId}/revoke` | Host policy | +| `POST` | `/api/collectors/{id}/heartbeat` | Host policy | +| `POST` | `/api/collectors/{id}/privacy-profile` | Role: `Administer` | +| `POST` | `/api/collectors/{id}/privacy-profile/clear` | Role: `Administer` | +| `GET` | `/api/collectors/{id}/privacy-profile/deployment` | Host policy | +| `POST` | `/api/custom-logs/generate` | Role: `Operate` | +| `POST` | `/api/custom-logs/preview` | Host policy | +| `GET` | `/api/enrolment-tokens` | Role: `View` | +| `POST` | `/api/enrolment-tokens` | Host policy | +| `POST` | `/api/enrolment-tokens/{id}/revoke` | Host policy | +| `GET` | `/api/fleet` | Role: `View` | +| `POST` | `/api/fleet/offline-import` | Host policy | +| `GET` | `/api/fleet/{id}` | Role: `View` | +| `GET` | `/api/home` | Role: `View` | +| `GET` | `/api/jobs` | Role: `View` | +| `POST` | `/api/jobs/{id}/trigger` | Role: `Administer` | +| `GET` | `/api/overview` | Role: `View` | +| `GET` | `/api/packs` | Host policy | +| `GET` | `/api/packs/install-requests` | Role: `View` | +| `POST` | `/api/packs/install-requests` | Role: `Operate` | +| `POST` | `/api/packs/install-requests/{id}/approve` | Role: `Approve` | +| `POST` | `/api/packs/install-requests/{id}/reject` | Role: `Approve` | +| `POST` | `/api/pipelines/collectors/{id}/tap` | Host policy | +| `GET` | `/api/pipelines/live` | Role: `View` | +| `GET` | `/api/pipelines/templates` | Role: `View` | +| `POST` | `/api/pipelines/validate` | Role: `Operate` | +| `POST` | `/api/policies/form` | Host policy | +| `GET` | `/api/policies/templates` | Role: `View` | +| `GET` | `/api/privacy-profiles` | Role: `View` | +| `POST` | `/api/privacy-profiles` | Host policy | +| `GET` | `/api/privacy-profiles/assignments` | Role: `View` | +| `POST` | `/api/privacy-profiles/form` | Host policy | +| `POST` | `/api/privacy-profiles/preview` | Role: `Operate` | +| `POST` | `/api/privacy-profiles/validate` | Role: `Operate` | +| `GET` | `/api/privacy-profiles/versions/{id}` | Role: `View` | +| `POST` | `/api/privacy-profiles/versions/{id}/approve` | Role: `Approve` | +| `POST` | `/api/privacy-profiles/versions/{id}/reject` | Role: `Approve` | +| `GET` | `/api/setup` | Role: `View` | +| `POST` | `/api/setup/canary` | Host policy | +| `GET` | `/api/setup/canary/runs/{id}/bundle` | Role: `View` | +| `GET` | `/api/setup/dcr-template` | Role: `View` | +| `POST` | `/api/setup/destination` | Host policy | +| `POST` | `/api/setup/destination/check` | Role: `Administer` | +| `POST` | `/api/setup/probe-profile` | Host policy | +| `POST` | `/api/sources/plan` | Role: `Operate` | +| `GET` | `/api/sources/requests` | Role: `View` | +| `POST` | `/api/sources/requests` | Role: `Operate` | +| `GET` | `/api/sources/requests/{id}` | Role: `View` | +| `POST` | `/api/sources/requests/{id}/approve` | Role: `Approve` | +| `POST` | `/api/sources/requests/{id}/reject` | Role: `Approve` | +| `GET` | `/api/sources/requests/{id}/signed` | Host policy | +| `GET` | `/api/sources/types` | Role: `View` | +| `GET` | `/health` | Anonymous | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md new file mode 100644 index 00000000..250c2373 --- /dev/null +++ b/docs/reference/configuration.md @@ -0,0 +1,273 @@ +# Configuration and schema reference + + + +This page is generated directly from `schemas/` and `src/Bower.Collector/CollectorSettings.cs`. +CI runs `generate_config_and_api_reference.py --check` so the reference cannot drift from the code. + +## Collector environment variables + +Recognised collector settings (`82` variables in `CollectorSettings.cs`): + +| Environment variable | +|---| +| `BOWER_ALLOW_UNAUTHENTICATED_INGEST` | +| `BOWER_AMA_SPOOL_PATH` | +| `BOWER_AMA_SYSLOG_BUSY_WAIT_SECONDS` | +| `BOWER_AMA_SYSLOG_FACILITY` | +| `BOWER_AMA_SYSLOG_MAX_BYTES` | +| `BOWER_AMA_SYSLOG_SOCKET` | +| `BOWER_ARCHIVE_PATH` | +| `BOWER_AZURE_CLIENT_ID` | +| `BOWER_AZURE_CREDENTIAL` | +| `BOWER_COLLECTOR_ID` | +| `BOWER_DCE_ENDPOINT` | +| `BOWER_DCR_ID` | +| `BOWER_DEAD_LETTER_RETENTION_DAYS` | +| `BOWER_DELIVERY_LEASE_SECONDS` | +| `BOWER_DELIVERY_TIMEOUT_SECONDS` | +| `BOWER_ENVIRONMENT` | +| `BOWER_FILE_CONFIG` | +| `BOWER_HEALTH_RECORD_INTERVAL_SECONDS` | +| `BOWER_INGEST_RATE_PER_SECOND` | +| `BOWER_INGEST_TOKEN` | +| `BOWER_INGEST_TOKENS_FILE` | +| `BOWER_INGEST_TOKEN_FILE` | +| `BOWER_LISTEN_URL` | +| `BOWER_MANAGED_PRIVACY_ALLOW_DEFAULT` | +| `BOWER_MANAGED_PRIVACY_DIRECTORY` | +| `BOWER_MANAGED_PRIVACY_TRUSTED_KEYS` | +| `BOWER_MANAGEMENT_AUTH` | +| `BOWER_MANAGEMENT_CA_BUNDLE` | +| `BOWER_MANAGEMENT_COMMAND_TRUSTED_KEYS` | +| `BOWER_MANAGEMENT_ENDPOINT` | +| `BOWER_MANAGEMENT_ENROLMENT_TOKEN_FILE` | +| `BOWER_MANAGEMENT_ENROLMENT_TOKEN_REMOVE_AFTER_USE` | +| `BOWER_MANAGEMENT_PROXY` | +| `BOWER_MANAGEMENT_PROXY_PASSWORD_FILE` | +| `BOWER_MANAGEMENT_PROXY_USERNAME` | +| `BOWER_MANAGEMENT_SCOPE` | +| `BOWER_MANAGEMENT_VIA_RELAY` | +| `BOWER_MAX_DELIVERY_ATTEMPTS` | +| `BOWER_ORIGIN_PRODUCERS` | +| `BOWER_OUTPUT` | +| `BOWER_PACKS` | +| `BOWER_PACK_TRUSTED_KEYS` | +| `BOWER_POLICY_DIRECTORY` | +| `BOWER_POLICY_WATCH` | +| `BOWER_POLICY_WATCH_DEBOUNCE_MS` | +| `BOWER_PRIVACY_HMAC_KEY_FILE` | +| `BOWER_PRIVACY_HMAC_KEY_ID` | +| `BOWER_PRIVACY_PROFILE` | +| `BOWER_PRIVACY_PROFILE_SOURCE` | +| `BOWER_PRODUCER_SCOPES_FILE` | +| `BOWER_PRODUCER_SCOPES_JSON` | +| `BOWER_QUEUE_MAX_BYTES` | +| `BOWER_QUEUE_PATH` | +| `BOWER_QUEUE_PRESSURE_RETENTION_MINUTES` | +| `BOWER_QUEUE_RETENTION_HOURS` | +| `BOWER_RELAY_CA_BUNDLE` | +| `BOWER_RELAY_CERTIFICATE_FILE` | +| `BOWER_RELAY_CLIENT_CERTIFICATE_FILE` | +| `BOWER_RELAY_CLIENT_KEY_FILE` | +| `BOWER_RELAY_DOWNSTREAMS_FILE` | +| `BOWER_RELAY_KEY_FILE` | +| `BOWER_RELAY_LISTEN_URL` | +| `BOWER_RELAY_MANAGEMENT_TUNNEL` | +| `BOWER_RELAY_URL` | +| `BOWER_S3_BUCKET` | +| `BOWER_S3_REGION` | +| `BOWER_SINGLE_TRUST_DOMAIN` | +| `BOWER_SOURCE_EXPECTATIONS` | +| `BOWER_STORAGE_CRITICAL_FREE_BYTES` | +| `BOWER_STORAGE_CRITICAL_FREE_PERCENT` | +| `BOWER_STORAGE_WARNING_FREE_BYTES` | +| `BOWER_STORAGE_WARNING_FREE_PERCENT` | +| `BOWER_STREAM_NAME` | +| `BOWER_SYSLOG_CONFIG` | +| `BOWER_TAP_ENABLED` | +| `BOWER_TAP_MAX_DURATION_SECONDS` | +| `BOWER_TAP_MAX_EVENTS` | +| `BOWER_TAP_MAX_EVENTS_PER_SECOND` | +| `BOWER_TAP_MAX_EVENT_BYTES` | +| `BOWER_TAP_MAX_SESSIONS` | +| `BOWER_TAP_PRODUCERS` | +| `BOWER_WINDOWS_EVENTLOG_CONFIG` | + +## Versioned JSON schemas + +| Schema file | Title | Top-level properties | +|---|---|---| +| `schemas/configuration/collector-configuration.schema.json` | Bower Collector Configuration | 10 | +| `schemas/configuration/source-expectations.schema.json` | Bower Source Expectations | 3 | +| `schemas/configuration/windows-event-log-source.schema.json` | Bower Windows Event Log Source | 3 | +| `schemas/custom-log-parser-config.schema.json` | Bower custom log parser configuration | 8 | +| `schemas/envelope/security-event.schema.json` | Bower Security Event Envelope | 21 | +| `schemas/packs/pack-sample.schema.json` | Bower Pack Sample Line | 10 | +| `schemas/policy/telemetry-policy.schema.json` | Bower Telemetry Policy | 8 | +| `schemas/privacy-profile.schema.json` | Bower Privacy Profile | 12 | +| `schemas/producer-scopes.schema.json` | Bower producer identity scopes | 0 | +| `schemas/tap/tap-frame.schema.json` | Bower Tap Frame | 15 | + +### `schemas/configuration/collector-configuration.schema.json` + +Required fields: `apiVersion`, `kind`, `collector`, `storage`, `policies`, `outputs`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `apiVersion` | `object` | Yes | | +| `kind` | `object` | Yes | | +| `collector` | `object` | Yes | | +| `storage` | `object` | Yes | | +| `policies` | `object` | Yes | | +| `sources` | `array` | No | | +| `outputs` | `array` | Yes | | +| `routing` | `array` | No | | +| `health` | `object` | No | | +| `logging` | `object` | No | | + +### `schemas/configuration/source-expectations.schema.json` + +Applications that must keep sending accepted security events (BOWER_SOURCE_EXPECTATIONS), with the longest acceptable silence for each. + +Required fields: `apiVersion`, `kind`, `sources`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `apiVersion` | `object` | Yes | | +| `kind` | `object` | Yes | | +| `sources` | `array` | Yes | | + +### `schemas/configuration/windows-event-log-source.schema.json` + +Channel subscriptions with explicit event ID allow-lists, each mapped by one signed pack parser (BOWER_WINDOWS_EVENTLOG_CONFIG, C# collector on Windows only). The collector generates the Windows query; there is no free-text query or collect-all form. + +Required fields: `apiVersion`, `kind`, `subscriptions`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `apiVersion` | `object` | Yes | | +| `kind` | `object` | Yes | | +| `subscriptions` | `array` | Yes | | + +### `schemas/custom-log-parser-config.schema.json` + +Required fields: `version`, `format`, `fields`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `version` | `object` | Yes | | +| `format` | `object` | Yes | | +| `fields` | `array` | Yes | | +| `delimiter` | `string \| null` | No | | +| `keyValueSeparator` | `string \| null` | No | | +| `pattern` | `string \| null` | No | | +| `multiline` | `object \| null` | No | Optional bounded multi-line merge rule applied before parsing and redaction. | +| `runtime` | `object \| null` | No | Explicit signed semantic mapping; absent means preview-only. | + +### `schemas/envelope/security-event.schema.json` + +Required fields: `schemaVersion`, `eventId`, `timeGenerated`, `eventCategory`, `eventType`, `eventAction`, `eventResult`, `application`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `schemaVersion` | `object` | Yes | | +| `eventId` | `string` | Yes | | +| `eventOriginalId` | `string \| null` | No | | +| `timeGenerated` | `string` | Yes | | +| `timeObserved` | `string \| null` | No | | +| `eventCategory` | `object` | Yes | | +| `eventType` | `string` | Yes | | +| `eventAction` | `string` | Yes | | +| `eventResult` | `object` | Yes | | +| `eventSeverity` | `object` | No | | +| `eventOutcomeReason` | `string \| null` | No | | +| `application` | `object` | Yes | | +| `actor` | `object` | No | | +| `target` | `object` | No | | +| `source` | `object` | No | | +| `request` | `object \| null` | No | | +| `change` | `object \| null` | No | | +| `security` | `object \| null` | No | | +| `collector` | `object \| null` | No | | +| `labels` | `object \| null` | No | | +| `attributes` | `object \| null` | No | | + +### `schemas/packs/pack-sample.schema.json` + +One line of a pack samples/*.jsonl file, version 2. Version 2 adds expectFields and parser names; every version 1 line (event or raw samples with decision, mustNotContain and expectedDetections) is a valid version 2 line. Editor support only: PackTester is authoritative and also rejects unknown or duplicated members, duplicate expectFields paths and expectations that name a pre-redaction value. + +| Property | Type | Required | Description | +|---|---|---|---| +| `name` | `string` | No | Shown in test output and reports. Defaults to sample-N. | +| `expect` | `object` | No | Expected decision. accept also passes for redact-and-accept; redact-and-accept requires redaction. | +| `event` | `object` | No | A semantic security event envelope. {{now}} is replaced with the current UTC time. | +| `raw` | `object` | No | A raw record for a pack parser (parse, transform, map, redact, select). {{now}} is replaced with the current UTC time, which is also the transform evaluation time. | +| `rawLines` | `array` | No | Physical text lines merged through the parser's multiline rule before parsing, transform, redaction and selection. {{now}} is replaced with the current UTC time. | +| `expectEvents` | `integer` | No | Exact number of merged events expected from rawLines. Defaults to 1 when rawLines is used. | +| `parser` | `object` | No | Parser for a raw sample: zero-based index in manifest (ordinal path) order, or a parser name (file name without extension, or its pack path). | +| `mustNotContain` | `array` | No | Strings that must not appear anywhere in the redacted event. | +| `expectedDetections` | `array` | No | Exact set of local detection rule ids expected on the redacted event. | +| `expectFields` | `object` | No | Post-redaction field assertions: path to "present", "absent" (missing or null) or an exact string, finite number or boolean. A string that equals a pre-redaction value missing from the redacted event, or contains a mustNotContain entry, fails without being printed. | + +### `schemas/policy/telemetry-policy.schema.json` + +Required fields: `apiVersion`, `kind`, `metadata`, `match`, `requirements`, `decision`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `apiVersion` | `object` | Yes | | +| `kind` | `object` | Yes | | +| `metadata` | `object` | Yes | | +| `match` | `object` | Yes | | +| `requirements` | `object` | Yes | | +| `decision` | `object` | Yes | | +| `routing` | `object` | No | | +| `suppression` | `object` | No | Admit at most allowPerWindow accepted events per key in each epoch-aligned window; count the rest and report them in one telemetry_aggregation_summary event per window. With decision action aggregate, allowPerWindow is 0 or omitted and every matching event is only counted. Not allowed with neverSample, non-accepting actions or the summary event type. A policy set that suppresses or aggregates must also accept telemetry_aggregation_summary. | + +### `schemas/privacy-profile.schema.json` + +Privacy profile for the Privacy & Secret Protection Engine (kind: PrivacyProfile). Editor support only: the loader is authoritative and also rejects unknown keys, invalid custom detector patterns and failing custom detector tests. + +Required fields: `apiVersion`, `kind`, `metadata`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `apiVersion` | `object` | Yes | | +| `kind` | `object` | Yes | | +| `metadata` | `object` | Yes | | +| `defaultAction` | `object` | No | | +| `detectors` | `object` | No | Built-in detector action overrides. Custom detectors set their action in customDetectors. | +| `disabled` | `array` | No | Built-in or custom detector ids to switch off. | +| `enableOptIn` | `array` | No | Opt-in built-in detectors to switch on (custom detectors are always on unless disabled). | +| `fields` | `array` | No | | +| `maximumFieldLength` | `integer` | No | | +| `emitMetadata` | `boolean` | No | | +| `customDetectors` | `array` | No | | +| `secretFieldNames` | `array` | No | Extra field names removed like built-in field-name secrets. Compared after normalisation (letters and digits only, lower-cased), so sessionKey also covers session_key and SESSION-KEY. | + +### `schemas/producer-scopes.schema.json` + +### `schemas/tap/tap-frame.schema.json` + +The data of one 'frame' server-sent event from GET /v1/tap (bower tap). Post-redaction only: 'event' is the exact redacted queued payload of an accepted event; every other outcome is metadata only and carries 'eventOmitted'. + +Required fields: `schemaVersion`, `sequence`, `observedAt`, `stage`, `action`, `queued`, `duplicate`, `suppressed`, `eventType`, `application`, `environment`, `policyId`, `reasons`. + +| Property | Type | Required | Description | +|---|---|---|---| +| `schemaVersion` | `object` | Yes | | +| `sequence` | `integer` | Yes | | +| `observedAt` | `string` | Yes | | +| `stage` | `object` | Yes | | +| `action` | `object` | Yes | | +| `queued` | `boolean` | Yes | | +| `duplicate` | `boolean` | Yes | | +| `suppressed` | `boolean` | Yes | | +| `eventType` | `string \| null` | Yes | | +| `application` | `string \| null` | Yes | | +| `environment` | `string \| null` | Yes | | +| `policyId` | `string \| null` | Yes | | +| `reasons` | `array` | Yes | | +| `event` | `object` | No | | +| `eventOmitted` | `object` | No | | diff --git a/tools/docs/generate_config_and_api_reference.py b/tools/docs/generate_config_and_api_reference.py new file mode 100644 index 00000000..cae6347b --- /dev/null +++ b/tools/docs/generate_config_and_api_reference.py @@ -0,0 +1,192 @@ +"""Generate docs/reference/configuration.md and docs/reference/api.md from repo sources. + +Reads JSON schemas under schemas/, collector environment variables in +src/Bower.Collector/CollectorSettings.cs, and HTTP routes in +src/Bower.Collector/CollectorApplication.cs and src/Bower.Management.Api/*.cs. +Standard library only. + + python3 -I tools/docs/generate_config_and_api_reference.py # write + python3 -I tools/docs/generate_config_and_api_reference.py --check # fail if stale +""" +import argparse +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SCHEMAS_DIR = ROOT / "schemas" +COLLECTOR_SETTINGS = ROOT / "src/Bower.Collector/CollectorSettings.cs" +COLLECTOR_APP = ROOT / "src/Bower.Collector/CollectorApplication.cs" +MANAGEMENT_DIR = ROOT / "src/Bower.Management.Api" +CONFIG_TARGET = ROOT / "docs/reference/configuration.md" +API_TARGET = ROOT / "docs/reference/api.md" + +ENV_PATTERN = re.compile(r"\b(BOWER_[A-Z0-9_]+)\b") +ROUTE_PATTERN = re.compile( + r'\b(app|api|relay|group)\.Map(Get|Post|Put|Delete|Patch)\(\s*"([^"]+)"', + re.S, +) + + +def _clean(text: str) -> str: + return re.sub(r"\s+", " ", text or "").strip().replace("|", "\\|") + + +def render_configuration() -> str: + schema_files = sorted(SCHEMAS_DIR.rglob("*.json")) + schema_rows: list[str] = [] + schema_sections: list[str] = [] + + for path in schema_files: + rel = path.relative_to(ROOT).as_posix() + data = json.loads(path.read_text(encoding="utf-8")) + title = _clean(data.get("title") or path.stem) + desc = _clean(data.get("description") or "") + required = data.get("required") or [] + props = data.get("properties") or {} + schema_rows.append(f"| `{rel}` | {title} | {len(props)} |") + + schema_sections.append(f"### `{rel}`") + schema_sections.append("") + if desc: + schema_sections.append(desc) + schema_sections.append("") + if required: + req_list = ", ".join(f"`{r}`" for r in required) + schema_sections.append(f"Required fields: {req_list}.") + schema_sections.append("") + if props: + schema_sections.append("| Property | Type | Required | Description |") + schema_sections.append("|---|---|---|---|") + for prop_name, prop_def in props.items(): + if not isinstance(prop_def, dict): + continue + ptype = prop_def.get("type", "object") + if isinstance(ptype, list): + ptype = " \\| ".join(str(t) for t in ptype) + is_req = "Yes" if prop_name in required else "No" + pdesc = _clean(prop_def.get("description") or "") + schema_sections.append(f"| `{prop_name}` | `{ptype}` | {is_req} | {pdesc} |") + schema_sections.append("") + + settings_text = COLLECTOR_SETTINGS.read_text(encoding="utf-8") + env_vars = sorted( + {m.group(1) for m in ENV_PATTERN.finditer(settings_text) if not m.group(1).endswith("_")} + ) + + lines = [ + "# Configuration and schema reference", + "", + "", + "", + "This page is generated directly from `schemas/` and `src/Bower.Collector/CollectorSettings.cs`.", + "CI runs `generate_config_and_api_reference.py --check` so the reference cannot drift from the code.", + "", + "## Collector environment variables", + "", + f"Recognised collector settings (`{len(env_vars)}` variables in `CollectorSettings.cs`):", + "", + "| Environment variable |", + "|---|", + *(f"| `{var}` |" for var in env_vars), + "", + "## Versioned JSON schemas", + "", + "| Schema file | Title | Top-level properties |", + "|---|---|---|", + *schema_rows, + "", + *schema_sections, + ] + return "\n".join(lines).rstrip() + "\n" + + +def _extract_routes(file_path: Path, default_prefix: str) -> list[tuple[str, str, str]]: + text = file_path.read_text(encoding="utf-8") + routes: list[tuple[str, str, str]] = [] + for match in ROUTE_PATTERN.finditer(text): + receiver = match.group(1) + method = match.group(2).upper() + raw_path = match.group(3) + if receiver == "api" and not raw_path.startswith("/api"): + full_path = f"{default_prefix}{raw_path}" + else: + full_path = raw_path + # Look ahead briefly for RequireAuthorization("Role") + tail = text[match.end():match.end() + 900] + auth_match = re.search(r'RequireAuthorization\("([^"]+)"\)', tail) + allow_anon = "AllowAnonymous()" in tail[:300] + if allow_anon: + access = "Anonymous" + elif auth_match: + access = f"Role: `{auth_match.group(1)}`" + elif "IngestAuthenticationFilter" in tail[:500]: + access = "Ingest bearer token" + else: + access = "Host policy" + routes.append((method, full_path, access)) + return routes + + +def render_api() -> str: + collector_routes = sorted(set(_extract_routes(COLLECTOR_APP, ""))) + management_routes_set: set[tuple[str, str, str]] = set() + for cs_file in sorted(MANAGEMENT_DIR.glob("*.cs")): + for route in _extract_routes(cs_file, "/api"): + management_routes_set.add(route) + management_routes = sorted(management_routes_set, key=lambda r: (r[1], r[0])) + + lines = [ + "# Collector and Management HTTP API reference", + "", + "", + "", + "This page is generated directly from the route registrations in", + "`src/Bower.Collector/CollectorApplication.cs` and `src/Bower.Management.Api/*.cs`.", + "All endpoints return metadata or post-redaction views only; management storage never holds raw event payloads.", + "", + "## Collector HTTP endpoints", + "", + "| Method | Path | Access |", + "|---|---|---|", + *(f"| `{m}` | `{p}` | {a} |" for m, p, a in collector_routes), + "", + "## Management API endpoints", + "", + "Authenticated via Microsoft Entra ID (`Bower.Viewer`, `Bower.Operator`, `Bower.Approver`, `Bower.Collector`) or enrolled collector key assertions.", + "", + "| Method | Path | Access |", + "|---|---|---|", + *(f"| `{m}` | `{p}` | {a} |" for m, p, a in management_routes), + "", + ] + return "\n".join(lines) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + + outputs = [ + (CONFIG_TARGET, render_configuration()), + (API_TARGET, render_api()), + ] + if args.check: + stale = [ + target.relative_to(ROOT).as_posix() + for target, expected in outputs + if not target.exists() or target.read_text(encoding="utf-8") != expected + ] + if stale: + raise SystemExit( + f"Generated reference is stale ({', '.join(stale)}). " + "Run python3 -I tools/docs/generate_config_and_api_reference.py and commit the result." + ) + else: + for target, content in outputs: + target.write_text(content, encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tools/docs/tests/test_build_tools.py b/tools/docs/tests/test_build_tools.py index f382d04d..1d7d6443 100644 --- a/tools/docs/tests/test_build_tools.py +++ b/tools/docs/tests/test_build_tools.py @@ -125,5 +125,18 @@ def legacy_open(file, mode="r", buffering=-1, encoding=None, errors=None, with self.assertRaisesRegex(SystemExit, "Glossary is stale"): runpy.run_path(str(script), run_name="__main__") + +class ConfigAndApiReferenceTests(unittest.TestCase): + def test_generated_configuration_and_api_references_are_up_to_date(self): + mod = load("generate_config_and_api_reference") + config_md = mod.render_configuration() + api_md = mod.render_api() + self.assertIn("BOWER_QUEUE_PATH", config_md) + self.assertIn("schemas/policy/", config_md) + self.assertIn("/v1/events", api_md) + self.assertIn("/api/collectors", api_md) + self.assertEqual(mod.CONFIG_TARGET.read_text(encoding="utf-8"), config_md) + self.assertEqual(mod.API_TARGET.read_text(encoding="utf-8"), api_md) + if __name__ == "__main__": unittest.main() diff --git a/website/sidebars.ts b/website/sidebars.ts index 8b5881c9..c5ac0c95 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -183,6 +183,11 @@ const sidebars: SidebarsConfig = { "id": "deployment/syslog-source", "label": "Syslog source" }, + { + "type": "doc", + "id": "deployment/syslog-vendors", + "label": "Syslog vendor guides" + }, { "type": "doc", "id": "deployment/windows-event-log-source", @@ -349,6 +354,11 @@ const sidebars: SidebarsConfig = { "type": "doc", "id": "operations/index" }, + { + "type": "doc", + "id": "operations/alert-runbooks", + "label": "Alert runbooks" + }, { "type": "doc", "id": "operations/tap-and-top", @@ -488,6 +498,16 @@ const sidebars: SidebarsConfig = { "id": "reference/cli", "label": "bower CLI" }, + { + "type": "doc", + "id": "reference/configuration", + "label": "Configuration and schemas" + }, + { + "type": "doc", + "id": "reference/api", + "label": "HTTP API reference" + }, { "type": "doc", "id": "reference/sentinel-table",