From 7e3a6c6926964f69b348a3515ddcc3dd1eb761b5 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 09:49:25 +1100 Subject: [PATCH] feat(sources): add allow-listed journald and Kubernetes container log sources with DaemonSet (#92) --- Bower.sln | 29 ++ deploy/kubernetes/daemonset.yaml | 111 +++++ docs/deployment/journald-source.md | 36 ++ docs/deployment/kubernetes-source.md | 34 ++ docs/security/threat-model.md | 16 + src/Bower.Source.Journald/AGENTS.md | 16 + .../Bower.Source.Journald.csproj | 13 + src/Bower.Source.Journald/IJournalReader.cs | 22 + src/Bower.Source.Journald/JournaldSource.cs | 195 +++++++++ .../JournaldSourceOptions.cs | 78 ++++ .../LibSystemdJournalReader.cs | 224 ++++++++++ src/Bower.Source.Journald/packages.lock.json | 22 + src/Bower.Source.Kubernetes/AGENTS.md | 19 + .../Bower.Source.Kubernetes.csproj | 11 + src/Bower.Source.Kubernetes/CriLogParser.cs | 85 ++++ .../KubernetesLogSource.cs | 405 ++++++++++++++++++ .../KubernetesLogSourceOptions.cs | 145 +++++++ .../KubernetesPodCatalog.cs | 187 ++++++++ .../packages.lock.json | 48 +++ tests/Bower.UnitTests/Bower.UnitTests.csproj | 2 + .../JournaldAndKubernetesSourceTests.cs | 356 +++++++++++++++ tests/Bower.UnitTests/packages.lock.json | 16 + website/sidebars.ts | 10 + 23 files changed, 2080 insertions(+) create mode 100644 deploy/kubernetes/daemonset.yaml create mode 100644 docs/deployment/journald-source.md create mode 100644 docs/deployment/kubernetes-source.md create mode 100644 src/Bower.Source.Journald/AGENTS.md create mode 100644 src/Bower.Source.Journald/Bower.Source.Journald.csproj create mode 100644 src/Bower.Source.Journald/IJournalReader.cs create mode 100644 src/Bower.Source.Journald/JournaldSource.cs create mode 100644 src/Bower.Source.Journald/JournaldSourceOptions.cs create mode 100644 src/Bower.Source.Journald/LibSystemdJournalReader.cs create mode 100644 src/Bower.Source.Journald/packages.lock.json create mode 100644 src/Bower.Source.Kubernetes/AGENTS.md create mode 100644 src/Bower.Source.Kubernetes/Bower.Source.Kubernetes.csproj create mode 100644 src/Bower.Source.Kubernetes/CriLogParser.cs create mode 100644 src/Bower.Source.Kubernetes/KubernetesLogSource.cs create mode 100644 src/Bower.Source.Kubernetes/KubernetesLogSourceOptions.cs create mode 100644 src/Bower.Source.Kubernetes/KubernetesPodCatalog.cs create mode 100644 src/Bower.Source.Kubernetes/packages.lock.json create mode 100644 tests/Bower.UnitTests/JournaldAndKubernetesSourceTests.cs diff --git a/Bower.sln b/Bower.sln index 264d2789..9d07a6c9 100644 --- a/Bower.sln +++ b/Bower.sln @@ -101,6 +101,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.DevSinks", "tools\Bow EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.AppHost.Tests", "tests\Bower.AppHost.Tests\Bower.AppHost.Tests.csproj", "{827CAE03-02C1-4625-AB39-B32FAF688A1D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.Source.Journald", "src\Bower.Source.Journald\Bower.Source.Journald.csproj", "{D784F971-24BA-435F-831E-4442A33FBC02}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.Source.Kubernetes", "src\Bower.Source.Kubernetes\Bower.Source.Kubernetes.csproj", "{DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -663,6 +667,30 @@ Global {827CAE03-02C1-4625-AB39-B32FAF688A1D}.Release|x64.Build.0 = Release|Any CPU {827CAE03-02C1-4625-AB39-B32FAF688A1D}.Release|x86.ActiveCfg = Release|Any CPU {827CAE03-02C1-4625-AB39-B32FAF688A1D}.Release|x86.Build.0 = Release|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Debug|x64.ActiveCfg = Debug|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Debug|x64.Build.0 = Debug|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Debug|x86.ActiveCfg = Debug|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Debug|x86.Build.0 = Debug|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Release|Any CPU.Build.0 = Release|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Release|x64.ActiveCfg = Release|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Release|x64.Build.0 = Release|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Release|x86.ActiveCfg = Release|Any CPU + {D784F971-24BA-435F-831E-4442A33FBC02}.Release|x86.Build.0 = Release|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Debug|x64.ActiveCfg = Debug|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Debug|x64.Build.0 = Debug|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Debug|x86.ActiveCfg = Debug|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Debug|x86.Build.0 = Debug|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|Any CPU.Build.0 = Release|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x64.ActiveCfg = Release|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x64.Build.0 = Release|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x86.ActiveCfg = Release|Any CPU + {DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -700,5 +728,6 @@ Global {29ABB074-0C7B-4729-B57D-8856A47AA932} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {BBF9180B-5DEE-43BB-8D0B-B11F7D368A2E} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {827CAE03-02C1-4625-AB39-B32FAF688A1D} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {D784F971-24BA-435F-831E-4442A33FBC02} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/deploy/kubernetes/daemonset.yaml b/deploy/kubernetes/daemonset.yaml new file mode 100644 index 00000000..2f3f7fc1 --- /dev/null +++ b/deploy/kubernetes/daemonset.yaml @@ -0,0 +1,111 @@ +# Hardened read-only DaemonSet for allow-listed Kubernetes container security telemetry (#92). +# RBAC is strictly namespaced (Role, never ClusterRole) and limited to get/list pods in +# explicitly approved namespaces. Replace 'app-production' with each approved namespace. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: bower-node-reader + namespace: bower-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: bower-pod-metadata-reader + namespace: app-production +rules: + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: bower-pod-metadata-reader + namespace: app-production +subjects: + - kind: ServiceAccount + name: bower-node-reader + namespace: bower-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: bower-pod-metadata-reader +--- +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: bower-node-collector + namespace: bower-system + labels: + app.kubernetes.io/name: bower-node-collector +spec: + selector: + matchLabels: + app.kubernetes.io/name: bower-node-collector + template: + metadata: + labels: + app.kubernetes.io/name: bower-node-collector + spec: + serviceAccountName: bower-node-reader + automountServiceAccountToken: true + securityContext: + runAsNonRoot: true + runAsUser: 1654 + runAsGroup: 1654 + fsGroup: 1654 + seccompProfile: + type: RuntimeDefault + containers: + - name: collector + image: ghcr.io/replace-me/bower:1.0.1 + imagePullPolicy: IfNotPresent + env: + - name: BOWER_KUBERNETES_NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName + - name: BOWER_KUBERNETES_NAMESPACES + value: app-production + - name: BOWER_KUBERNETES_LABEL_SELECTORS + value: bower.io/collect=true + - name: BOWER_KUBERNETES_ALLOWED_LABELS + value: app.kubernetes.io/name,app.kubernetes.io/component + - name: BOWER_QUEUE_PATH + value: /var/lib/bower/queue.db + - name: BOWER_POLICY_DIRECTORY + value: /app/policies/default + volumeMounts: + - name: varlogpods + mountPath: /var/log/pods + readOnly: true + - name: state + mountPath: /var/lib/bower + - name: temporary + mountPath: /tmp + resources: + requests: + cpu: 50m + memory: 128Mi + ephemeral-storage: 64Mi + limits: + cpu: 500m + memory: 256Mi + ephemeral-storage: 256Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + volumes: + - name: varlogpods + hostPath: + path: /var/log/pods + type: Directory + - name: state + hostPath: + path: /var/lib/bower + type: DirectoryOrCreate + - name: temporary + emptyDir: + sizeLimit: 64Mi diff --git a/docs/deployment/journald-source.md b/docs/deployment/journald-source.md new file mode 100644 index 00000000..21e2bc80 --- /dev/null +++ b/docs/deployment/journald-source.md @@ -0,0 +1,36 @@ +# systemd journald source + +`Bower.Source.Journald` reads security-relevant entries directly from the host's +systemd journal (`libsystemd.so.0`) using explicit unit and `SYSLOG_IDENTIFIER` +allow-lists and durable SQLite cursors. + +## Selection and default deny + +- Configuration (`JournaldSourceOptions`) **requires** at least one explicit systemd + unit (`Units`, e.g. `sshd.service`) or `SYSLOG_IDENTIFIER` (`Identifiers`, e.g. `sshd`). +- Wildcards (`*`, `?`) and collect-all subscriptions are rejected at validation time. +- Even when `LibSystemdJournalReader` pushes `_SYSTEMD_UNIT=` / `SYSLOG_IDENTIFIER=` + disjunctions into `libsystemd`, `JournaldSource` enforces the same allow-list in + managed code before serialising any entry. +- Reading an entry never means delivering it: every record still flows through a signed + pack parser (such as `packs/linux-journald-ssh`), the Privacy & Secret Protection + Engine, and default-deny telemetry policies. + +## Durability and backpressure + +- Cursors are stored in `ISourceCursorStore` under `journald:`. +- A cursor advances **only after** the downstream processor acknowledges durable enqueue + or a definitive drop (unselected unit, malformed or oversized entry). +- If the collector crashes or downstream signals backpressure, polling stops before + advancing past the unacknowledged entry so restart resumes with zero loss; deterministic + event IDs derived from `__CURSOR` deduplicate retries. +- Per-record size is capped at 32 KiB and batch sizes are capped at 500 entries. + +## Linux prerequisites + +- Requires Linux with `libsystemd.so.0` and read access to the system journal (typically + membership in the `systemd-journal` group for the `bower` service account — no root + privileges required). +- Keep the `IJournalReader` seam when writing tests on macOS or Windows so unit tests + exercise cursor recovery, allow-list enforcement, malformed inputs and backpressure + without a live systemd daemon. diff --git a/docs/deployment/kubernetes-source.md b/docs/deployment/kubernetes-source.md new file mode 100644 index 00000000..e3c849d3 --- /dev/null +++ b/docs/deployment/kubernetes-source.md @@ -0,0 +1,34 @@ +# Kubernetes container log source + +`Bower.Source.Kubernetes` collects allow-listed security telemetry from container logs +under `/var/log/pods` on Linux nodes with minimal pod metadata enrichment. + +## Selection and least privilege + +- **No cluster-wide default collection:** `KubernetesLogSourceOptions` requires explicit + allow-listed `Namespaces` (DNS-1123 names, max 32) and explicit `LabelSelectors` + (`key=value`, max 16). +- **No pod annotation auto-discovery:** pods cannot opt themselves into collection via + annotations. Only operator-approved namespaces and label selectors are queried. +- **Namespaced RBAC only:** grant the DaemonSet `ServiceAccount` a namespaced `Role` + (`get`, `list` on `pods`) strictly in each approved namespace — see + [`deploy/kubernetes/daemonset.yaml`](../../deploy/kubernetes/daemonset.yaml). Never + use a `ClusterRole` or secret/exec permissions. +- **Minimal metadata:** attaches `k8s.namespace`, `k8s.pod`, `k8s.container`, + `k8s.stream`, and only pod label keys explicitly named in `AllowedMetadataLabels`. All + labels pass through Bower's Privacy & Secret Protection Engine before persistence. + +## CRI parsing, rotation and checkpoints + +- Reuses `Bower.Source.File.FileTailReader` for symlink-safe, bounded file reads with + rename and copytruncate rotation detection. +- Parses standard CRI container log lines (` `), + joining partial (`P`) fragments up to `MaxPartialBytes` (default 64 KiB) until the final + (`F`) line arrives. Malformed and oversized lines are counted and skipped safely. +- Only validated Bower `SecurityEventEnvelope` JSON records are forwarded; unrecognised + unstructured stdout noise is dropped at the source. +- Checkpoints (`FileTailCursor`) are persisted in `ISourceCursorStore` under + `k8s://` strictly **after** caller acknowledgement, + surviving restarts and log rotation without loss or duplicates. Deterministic `EventId` + values derived from `(podUid, container, fileFingerprint, startOffset)` deduplicate + replays. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 3b90b197..fb9fc892 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -147,6 +147,22 @@ evidence. (including not-selected, rejected, invalid and oversized records); event ids from channel, computer, record id and creation time deduplicate re-reads. Counters and failure codes only. See [Windows Event Log source](../deployment/windows-event-log-source.md). +- systemd journald source (`Bower.Source.Journald`, new trust boundary: host journal + read via `libsystemd.so.0`): requires explicit unit or `SYSLOG_IDENTIFIER` + allow-lists (wildcards and collect-all forms are rejected at load and enforced in + managed code). Records are bounded to 32 KiB, mapped through signed pack parsers, + redacted before persistence, and cursors advance in `ISourceCursorStore` only after + durable acknowledgement. The service account needs only read membership in + `systemd-journal`, never root. See [journald source](../deployment/journald-source.md). +- Kubernetes container log source (`Bower.Source.Kubernetes`, new trust boundary: + namespaced Kubernetes API pod metadata lookup and read-only `/var/log/pods` mount): + enforces explicit namespace and label-selector allow-lists with no cluster-wide + default and no pod annotation auto-discovery. RBAC is limited to namespaced `Role` + `get`/`list` on `pods` in approved namespaces; ServiceAccount tokens are read only + from files and never logged. File reads reuse `Bower.Source.File`'s symlink-safe, + bounded tailer; CRI partial joins are capped; only allow-listed metadata labels are + attached (and pass through the privacy engine); non-envelope stdout noise is dropped. + See [Kubernetes source](../deployment/kubernetes-source.md). - Event injection: the collector requires a shared bearer token (`BOWER_INGEST_TOKEN`, compared in constant time) whenever it listens beyond loopback and refuses to start without one. Kubernetes manifests add a diff --git a/src/Bower.Source.Journald/AGENTS.md b/src/Bower.Source.Journald/AGENTS.md new file mode 100644 index 00000000..6da07e98 --- /dev/null +++ b/src/Bower.Source.Journald/AGENTS.md @@ -0,0 +1,16 @@ +# Bower.Source.Journald instructions + +Bounded, allow-listed systemd journald source. + +- Default deny: configuration must name at least one explicit systemd unit or + `SYSLOG_IDENTIFIER`. Wildcards and collect-all subscriptions are refused. +- Enforce unit and identifier allow-lists in managed code even when the underlying + reader applies native filters. +- Never log raw `MESSAGE` text or raw journal entries. Diagnostics report counters + and safe metadata codes only. +- Persist the journald cursor in `ISourceCursorStore` strictly **after** the caller + acknowledges durable enqueue or definitive drop. Never advance past an + unacknowledged record. +- Bound per-record bytes (at most 32 KiB) and batch counts; honour cancellation. +- Keep `LibSystemdJournalReader` behind `IJournalReader` so cursor, filtering, + malformed-input and backpressure logic remain platform-neutral and testable. diff --git a/src/Bower.Source.Journald/Bower.Source.Journald.csproj b/src/Bower.Source.Journald/Bower.Source.Journald.csproj new file mode 100644 index 00000000..fcd51f9d --- /dev/null +++ b/src/Bower.Source.Journald/Bower.Source.Journald.csproj @@ -0,0 +1,13 @@ + + + + true + + + + + + + + + diff --git a/src/Bower.Source.Journald/IJournalReader.cs b/src/Bower.Source.Journald/IJournalReader.cs new file mode 100644 index 00000000..234b039b --- /dev/null +++ b/src/Bower.Source.Journald/IJournalReader.cs @@ -0,0 +1,22 @@ +namespace Bower.Source.Journald; + +/// One raw allow-listed systemd journal entry. +public sealed record JournaldEntry( + string Cursor, + long RealtimeMicroseconds, + string? Unit, + string? SyslogIdentifier, + string Message, + string? Priority = null, + string? Hostname = null); + +/// +/// Platform seam for reading systemd journald entries sequentially after an opaque cursor. +/// +public interface IJournalReader : IDisposable +{ + ValueTask> ReadBatchAsync( + string? afterCursor, + int maxRecords, + CancellationToken cancellationToken = default); +} diff --git a/src/Bower.Source.Journald/JournaldSource.cs b/src/Bower.Source.Journald/JournaldSource.cs new file mode 100644 index 00000000..f9d198c3 --- /dev/null +++ b/src/Bower.Source.Journald/JournaldSource.cs @@ -0,0 +1,195 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; + +namespace Bower.Source.Journald; + +/// One bounded journald record ready for signed pack parsing. +public sealed record JournaldRecord( + string SubscriptionName, + string Cursor, + string RecordJson); + +/// Outcome counters of one bounded poll cycle. Metadata only. +public sealed record JournaldPollResult( + int Read, + int Delivered, + int FilteredOut, + int RejectedInvalid, + int RejectedOversized, + string? CommittedCursor, + bool StoppedOnBackpressure); + +/// +/// Allow-listed, cursor-durable systemd journald source. Produces bounded JSON records +/// compatible with packs/linux-journald-ssh and commits the cursor strictly after +/// caller acknowledgment (at-least-once semantics). +/// +public sealed class JournaldSource +{ + private readonly JournaldSourceOptions options; + private readonly IJournalReader reader; + private readonly ISourceCursorStore cursorStore; + private readonly TimeProvider clock; + private readonly HashSet allowedUnits; + private readonly HashSet allowedIdentifiers; + private readonly string cursorKey; + + public JournaldSource( + JournaldSourceOptions options, + IJournalReader reader, + ISourceCursorStore cursorStore, + TimeProvider? clock = null) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(cursorStore); + options.Validate(); + + this.options = options; + this.reader = reader; + this.cursorStore = cursorStore; + this.clock = clock ?? TimeProvider.System; + allowedUnits = new HashSet(options.Units, StringComparer.Ordinal); + allowedIdentifiers = new HashSet(options.Identifiers, StringComparer.Ordinal); + cursorKey = $"journald:{options.SubscriptionName}"; + } + + public string CursorKey => cursorKey; + + /// + /// Reads at most entries after the stored + /// cursor, filters strictly by allow-list, invokes , and commits + /// the cursor only for acknowledged or definitively dropped entries. + /// + public async Task PollOnceAsync( + Func> onRecord, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(onRecord); + cancellationToken.ThrowIfCancellationRequested(); + + SourceCursorSnapshot? snapshot = await cursorStore.ReadAsync(cursorKey, cancellationToken); + string? currentCursor = snapshot?.Value; + long expectedVersion = snapshot?.Version ?? 0; + + IReadOnlyList batch = await reader.ReadBatchAsync( + currentCursor, + options.MaxBatchSize, + cancellationToken); + + int delivered = 0; + int filteredOut = 0; + int rejectedInvalid = 0; + int rejectedOversized = 0; + string? lastCommitCursor = null; + bool backpressure = false; + + foreach (JournaldEntry entry in batch) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (string.IsNullOrWhiteSpace(entry.Cursor) || entry.Cursor.Length > 512) + { + rejectedInvalid++; + continue; + } + + if (!IsAllowed(entry)) + { + filteredOut++; + lastCommitCursor = entry.Cursor; + continue; + } + + if (entry.RealtimeMicroseconds <= 0 || entry.Message is null) + { + rejectedInvalid++; + lastCommitCursor = entry.Cursor; + continue; + } + + string recordJson = SerializeJournalJson(entry); + if (Encoding.UTF8.GetByteCount(recordJson) > options.MaxRecordBytes) + { + rejectedOversized++; + lastCommitCursor = entry.Cursor; + continue; + } + + bool acknowledged = await onRecord( + new JournaldRecord(options.SubscriptionName, entry.Cursor, recordJson), + cancellationToken); + if (!acknowledged) + { + backpressure = true; + break; + } + + delivered++; + lastCommitCursor = entry.Cursor; + } + + if (lastCommitCursor is not null) + { + await cursorStore.TryAdvanceAsync( + cursorKey, + expectedVersion, + lastCommitCursor, + clock.GetUtcNow(), + cancellationToken); + } + + return new JournaldPollResult( + batch.Count, + delivered, + filteredOut, + rejectedInvalid, + rejectedOversized, + lastCommitCursor, + backpressure); + } + + internal bool IsAllowed(JournaldEntry entry) + { + bool unitMatch = !string.IsNullOrWhiteSpace(entry.Unit) && allowedUnits.Contains(entry.Unit); + bool identifierMatch = !string.IsNullOrWhiteSpace(entry.SyslogIdentifier) && allowedIdentifiers.Contains(entry.SyslogIdentifier); + return unitMatch || identifierMatch; + } + + internal static string SerializeJournalJson(JournaldEntry entry) + { + using MemoryStream buffer = new(); + using (Utf8JsonWriter writer = new(buffer)) + { + writer.WriteStartObject(); + writer.WriteString("__CURSOR", entry.Cursor); + writer.WriteString("__REALTIME_TIMESTAMP", entry.RealtimeMicroseconds.ToString(CultureInfo.InvariantCulture)); + if (!string.IsNullOrWhiteSpace(entry.Unit)) + { + writer.WriteString("_SYSTEMD_UNIT", entry.Unit); + } + + if (!string.IsNullOrWhiteSpace(entry.SyslogIdentifier)) + { + writer.WriteString("SYSLOG_IDENTIFIER", entry.SyslogIdentifier); + } + + writer.WriteString("MESSAGE", entry.Message); + if (!string.IsNullOrWhiteSpace(entry.Priority)) + { + writer.WriteString("PRIORITY", entry.Priority); + } + + if (!string.IsNullOrWhiteSpace(entry.Hostname)) + { + writer.WriteString("_HOSTNAME", entry.Hostname); + } + + writer.WriteEndObject(); + } + + return Encoding.UTF8.GetString(buffer.ToArray()); + } +} diff --git a/src/Bower.Source.Journald/JournaldSourceOptions.cs b/src/Bower.Source.Journald/JournaldSourceOptions.cs new file mode 100644 index 00000000..0dbab4c8 --- /dev/null +++ b/src/Bower.Source.Journald/JournaldSourceOptions.cs @@ -0,0 +1,78 @@ +namespace Bower.Source.Journald; + +public sealed record JournaldSourceOptions +{ + public const int DefaultMaxRecordBytes = 32 * 1024; + public const int MaxAllowedRecordBytes = 32 * 1024; + public const int DefaultMaxBatchSize = 128; + public const int MaxAllowedBatchSize = 500; + public const int MaxAllowListEntries = 64; + + public required string SubscriptionName { get; init; } + + /// Explicit systemd unit names (for example ssh.service, sshd.service). + public IReadOnlyList Units { get; init; } = []; + + /// Explicit SYSLOG_IDENTIFIER values (for example sshd, sudo). + public IReadOnlyList Identifiers { get; init; } = []; + + public int MaxRecordBytes { get; init; } = DefaultMaxRecordBytes; + + public int MaxBatchSize { get; init; } = DefaultMaxBatchSize; + + public void Validate() + { + if (!IsSafeName(SubscriptionName, maxLength: 64)) + { + throw new ArgumentException("SubscriptionName must be 1..64 ASCII letters, digits, '.', '_', or '-'.", nameof(SubscriptionName)); + } + + if (Units.Count == 0 && Identifiers.Count == 0) + { + throw new ArgumentException("Journald source requires at least one explicit unit or SYSLOG_IDENTIFIER allow-list entry."); + } + + if (Units.Count + Identifiers.Count > MaxAllowListEntries) + { + throw new ArgumentOutOfRangeException(nameof(Units), $"Total allow-list entries cannot exceed {MaxAllowListEntries}."); + } + + foreach (string unit in Units) + { + if (!IsSafeUnitOrIdentifier(unit)) + { + throw new ArgumentException($"Invalid journald unit allow-list entry '{unit}'. Wildcards and control characters are refused."); + } + } + + foreach (string identifier in Identifiers) + { + if (!IsSafeUnitOrIdentifier(identifier)) + { + throw new ArgumentException($"Invalid journald identifier allow-list entry '{identifier}'. Wildcards and control characters are refused."); + } + } + + if (MaxRecordBytes is < 512 or > MaxAllowedRecordBytes) + { + throw new ArgumentOutOfRangeException(nameof(MaxRecordBytes), $"MaxRecordBytes must be between 512 and {MaxAllowedRecordBytes}."); + } + + if (MaxBatchSize is < 1 or > MaxAllowedBatchSize) + { + throw new ArgumentOutOfRangeException(nameof(MaxBatchSize), $"MaxBatchSize must be between 1 and {MaxAllowedBatchSize}."); + } + } + + internal static bool IsSafeName(string? value, int maxLength) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= maxLength + && value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '.' or '_' or '-'); + + internal static bool IsSafeUnitOrIdentifier(string? value) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= 128 + && !value.Contains('*') + && !value.Contains('?') + && value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '.' or '_' or '-' or '@' or ':'); +} diff --git a/src/Bower.Source.Journald/LibSystemdJournalReader.cs b/src/Bower.Source.Journald/LibSystemdJournalReader.cs new file mode 100644 index 00000000..a70647ed --- /dev/null +++ b/src/Bower.Source.Journald/LibSystemdJournalReader.cs @@ -0,0 +1,224 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace Bower.Source.Journald; + +/// +/// Linux libsystemd.so.0 journal reader using Native AOT-compatible . +/// Applies unit and SYSLOG_IDENTIFIER matches at the journal API boundary before reading messages. +/// +public sealed partial class LibSystemdJournalReader : IJournalReader +{ + private const string LibSystemd = "libsystemd.so.0"; + private const int SdJournalLocalOnly = 1 << 0; + private const int SdJournalSystem = 1 << 2; + + private readonly JournaldSourceOptions options; + private IntPtr journal; + private bool disposed; + + public LibSystemdJournalReader(JournaldSourceOptions options) + { + ArgumentNullException.ThrowIfNull(options); + options.Validate(); + if (!OperatingSystem.IsLinux()) + { + throw new PlatformNotSupportedException("LibSystemdJournalReader requires Linux with libsystemd.so.0."); + } + + this.options = options; + int rc = SdJournalOpen(out journal, SdJournalLocalOnly | SdJournalSystem); + if (rc < 0 || journal == IntPtr.Zero) + { + throw new InvalidOperationException($"sd_journal_open failed with errno {-rc}."); + } + + try + { + ApplyMatches(); + } + catch + { + SdJournalClose(journal); + journal = IntPtr.Zero; + throw; + } + } + + public ValueTask> ReadBatchAsync( + string? afterCursor, + int maxRecords, + CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + + if (!string.IsNullOrWhiteSpace(afterCursor)) + { + byte[] cursorUtf8 = Encoding.UTF8.GetBytes(afterCursor + '\0'); + int seekRc = SdJournalSeekCursor(journal, cursorUtf8); + if (seekRc < 0) + { + throw new InvalidOperationException($"sd_journal_seek_cursor failed with errno {-seekRc}."); + } + + // Advance onto the cursor entry so the loop's next() moves past it. + _ = SdJournalNext(journal); + } + + List entries = new(Math.Min(maxRecords, 64)); + while (entries.Count < maxRecords) + { + cancellationToken.ThrowIfCancellationRequested(); + int step = SdJournalNext(journal); + if (step < 0) + { + throw new InvalidOperationException($"sd_journal_next failed with errno {-step}."); + } + + if (step == 0) + { + break; + } + + string? cursor = ReadCursor(); + if (string.IsNullOrWhiteSpace(cursor)) + { + continue; + } + + int timeRc = SdJournalGetRealtimeUsec(journal, out ulong usec); + long realtime = timeRc >= 0 ? unchecked((long)usec) : 0; + + string? unit = ReadField("_SYSTEMD_UNIT"); + string? identifier = ReadField("SYSLOG_IDENTIFIER"); + string message = ReadField("MESSAGE") ?? string.Empty; + string? priority = ReadField("PRIORITY"); + string? hostname = ReadField("_HOSTNAME"); + + entries.Add(new JournaldEntry(cursor, realtime, unit, identifier, message, priority, hostname)); + } + + return ValueTask.FromResult>(entries); + } + + public void Dispose() + { + if (disposed) + { + return; + } + + disposed = true; + if (journal != IntPtr.Zero) + { + SdJournalClose(journal); + journal = IntPtr.Zero; + } + } + + private void ApplyMatches() + { + bool first = true; + foreach (string unit in options.Units) + { + if (!first) + { + CheckRc(SdJournalAddDisjunction(journal), "sd_journal_add_disjunction"); + } + + AddMatch($"_SYSTEMD_UNIT={unit}"); + first = false; + } + + foreach (string identifier in options.Identifiers) + { + if (!first) + { + CheckRc(SdJournalAddDisjunction(journal), "sd_journal_add_disjunction"); + } + + AddMatch($"SYSLOG_IDENTIFIER={identifier}"); + first = false; + } + } + + private void AddMatch(string expression) + { + byte[] bytes = Encoding.UTF8.GetBytes(expression); + CheckRc(SdJournalAddMatch(journal, bytes, (nuint)bytes.Length), "sd_journal_add_match"); + } + + private unsafe string? ReadField(string fieldName) + { + byte[] nameBytes = Encoding.UTF8.GetBytes(fieldName + '\0'); + int rc = SdJournalGetData(journal, nameBytes, out IntPtr dataPtr, out nuint length); + if (rc < 0 || dataPtr == IntPtr.Zero || length == 0) + { + return null; + } + + int capped = (int)Math.Min(length, (nuint)(options.MaxRecordBytes + fieldName.Length + 2)); + ReadOnlySpan span = new((void*)dataPtr, capped); + int eq = span.IndexOf((byte)'='); + if (eq < 0 || eq + 1 > span.Length) + { + return null; + } + + return Encoding.UTF8.GetString(span[(eq + 1)..]); + } + + private unsafe string? ReadCursor() + { + int rc = SdJournalGetCursor(journal, out IntPtr cursorPtr); + if (rc < 0 || cursorPtr == IntPtr.Zero) + { + return null; + } + + try + { + return Marshal.PtrToStringUTF8(cursorPtr); + } + finally + { + NativeMemory.Free((void*)cursorPtr); + } + } + + private static void CheckRc(int rc, string function) + { + if (rc < 0) + { + throw new InvalidOperationException($"{function} failed with errno {-rc}."); + } + } + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_open")] + private static partial int SdJournalOpen(out IntPtr ret, int flags); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_close")] + private static partial void SdJournalClose(IntPtr j); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_add_match")] + private static partial int SdJournalAddMatch(IntPtr j, ReadOnlySpan data, nuint size); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_add_disjunction")] + private static partial int SdJournalAddDisjunction(IntPtr j); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_seek_cursor")] + private static partial int SdJournalSeekCursor(IntPtr j, ReadOnlySpan cursor); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_next")] + private static partial int SdJournalNext(IntPtr j); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_get_data")] + private static partial int SdJournalGetData(IntPtr j, ReadOnlySpan field, out IntPtr data, out nuint length); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_get_cursor")] + private static partial int SdJournalGetCursor(IntPtr j, out IntPtr cursor); + + [LibraryImport(LibSystemd, EntryPoint = "sd_journal_get_realtime_usec")] + private static partial int SdJournalGetRealtimeUsec(IntPtr j, out ulong usec); +} diff --git a/src/Bower.Source.Journald/packages.lock.json b/src/Bower.Source.Journald/packages.lock.json new file mode 100644 index 00000000..668a49ec --- /dev/null +++ b/src/Bower.Source.Journald/packages.lock.json @@ -0,0 +1,22 @@ +{ + "version": 2, + "dependencies": { + "net11.0": { + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "gK2aq4XvChj5kvozpPHrkfKkr7zc5Z4xoTrJb4GPZzDEPMlCk0TX632bwY3LsWcX2UVcVRQBBGzsBGC2lq6YhA==" + }, + "bower.abstractions": { + "type": "Project", + "dependencies": { + "Bower.Contracts": "[1.0.0, )" + } + }, + "bower.contracts": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/src/Bower.Source.Kubernetes/AGENTS.md b/src/Bower.Source.Kubernetes/AGENTS.md new file mode 100644 index 00000000..292ebf7b --- /dev/null +++ b/src/Bower.Source.Kubernetes/AGENTS.md @@ -0,0 +1,19 @@ +# Bower.Source.Kubernetes instructions + +Bounded, allow-listed Kubernetes container log source (`/var/log/pods` + namespaced pod metadata). + +- Default deny: configuration must specify explicit allow-listed `Namespaces` and + `LabelSelectors`. No cluster-wide default collection and no pod annotation + auto-discovery. +- Kubernetes RBAC is strictly namespaced `get`/`list` on `pods` in allow-listed + namespaces only — never `ClusterRole` or secret/exec access. +- Reuse `Bower.Source.File.FileTailReader` for symlink-safe, rotation-aware, + bounded file tailing and durable `FileTailCursor` persistence. +- Persist checkpoints strictly after caller acknowledgement (at-least-once). +- Parse CRI log lines (` `), bounding partial + joins and rejecting malformed/oversized lines safely. +- Forward only validated Bower envelopes; unrecognised unstructured stdout lines + are dropped here (Bower is not a generic log shipper). +- Attach minimal pod metadata (`k8s.namespace`, `k8s.pod`, `k8s.container`) and + only explicitly allow-listed pod labels; all labels pass through the privacy engine. +- Never log raw log lines, ServiceAccount tokens, or raw API responses. diff --git a/src/Bower.Source.Kubernetes/Bower.Source.Kubernetes.csproj b/src/Bower.Source.Kubernetes/Bower.Source.Kubernetes.csproj new file mode 100644 index 00000000..771667ff --- /dev/null +++ b/src/Bower.Source.Kubernetes/Bower.Source.Kubernetes.csproj @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/Bower.Source.Kubernetes/CriLogParser.cs b/src/Bower.Source.Kubernetes/CriLogParser.cs new file mode 100644 index 00000000..b243e07f --- /dev/null +++ b/src/Bower.Source.Kubernetes/CriLogParser.cs @@ -0,0 +1,85 @@ +using System.Globalization; + +namespace Bower.Source.Kubernetes; + +/// One parsed CRI container log line: <timestamp> <stdout|stderr> <P|F> <message>. +public sealed record CriLogLine( + DateTimeOffset Timestamp, + string Stream, + bool IsPartial, + string Message); + +public static class CriLogParser +{ + public static bool TryParse(string line, out CriLogLine? parsed) + { + parsed = null; + if (string.IsNullOrEmpty(line)) + { + return false; + } + + int sp1 = line.IndexOf(' '); + if (sp1 <= 0) + { + return false; + } + + int sp2 = line.IndexOf(' ', sp1 + 1); + if (sp2 <= sp1 + 1) + { + return false; + } + + int sp3 = line.IndexOf(' ', sp2 + 1); + if (sp3 <= sp2 + 1) + { + return false; + } + + ReadOnlySpan timeSpan = line.AsSpan(0, sp1); + ReadOnlySpan streamSpan = line.AsSpan(sp1 + 1, sp2 - sp1 - 1); + ReadOnlySpan tagSpan = line.AsSpan(sp2 + 1, sp3 - sp2 - 1); + + if (!DateTimeOffset.TryParse( + timeSpan, + CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, + out DateTimeOffset timestamp)) + { + return false; + } + + string stream; + if (streamSpan.Equals("stdout", StringComparison.Ordinal)) + { + stream = "stdout"; + } + else if (streamSpan.Equals("stderr", StringComparison.Ordinal)) + { + stream = "stderr"; + } + else + { + return false; + } + + bool isPartial; + if (tagSpan.Equals("P", StringComparison.Ordinal)) + { + isPartial = true; + } + else if (tagSpan.Equals("F", StringComparison.Ordinal)) + { + isPartial = false; + } + else + { + return false; + } + + string message = line[(sp3 + 1)..]; + parsed = new CriLogLine(timestamp.ToUniversalTime(), stream, isPartial, message); + return true; + } +} diff --git a/src/Bower.Source.Kubernetes/KubernetesLogSource.cs b/src/Bower.Source.Kubernetes/KubernetesLogSource.cs new file mode 100644 index 00000000..1aebb8da --- /dev/null +++ b/src/Bower.Source.Kubernetes/KubernetesLogSource.cs @@ -0,0 +1,405 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Contracts; +using Bower.Source.File; + +namespace Bower.Source.Kubernetes; + +public sealed record KubernetesPollResult( + int PodsScanned, + int FilesTailed, + int LinesRead, + int EventsDelivered, + int DroppedNonSecurity, + int MalformedLines, + int OversizedLines, + bool StoppedOnBackpressure); + +/// +/// Allow-listed Kubernetes container log source. Resolves pods strictly within allow-listed +/// namespaces and label selectors, tails /var/log/pods via +/// (rotation-aware, symlink-safe, bounded), parses CRI partial/final lines, attaches minimal +/// pod metadata plus allow-listed labels, and advances durable checkpoints only after +/// caller acknowledgement. +/// +public sealed class KubernetesLogSource +{ + private readonly KubernetesLogSourceOptions options; + private readonly IKubernetesPodCatalog catalog; + private readonly ISourceCursorStore cursorStore; + private readonly TimeProvider clock; + private readonly HashSet allowedNamespaces; + private readonly HashSet allowedMetadataLabels; + private readonly FileTailReaderOptions tailOptions; + private readonly Dictionary partials = new(StringComparer.Ordinal); + + public KubernetesLogSource( + KubernetesLogSourceOptions options, + IKubernetesPodCatalog catalog, + ISourceCursorStore cursorStore, + TimeProvider? clock = null) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(catalog); + ArgumentNullException.ThrowIfNull(cursorStore); + options.Validate(); + + this.options = options; + this.catalog = catalog; + this.cursorStore = cursorStore; + this.clock = clock ?? TimeProvider.System; + allowedNamespaces = new HashSet(options.Namespaces, StringComparer.Ordinal); + allowedMetadataLabels = new HashSet(options.AllowedMetadataLabels, StringComparer.Ordinal); + tailOptions = new FileTailReaderOptions + { + MaxLineBytes = options.MaxLineBytes, + MaxLinesPerBatch = options.MaxBatchLines, + MaxBytesPerBatch = options.MaxLineBytes * Math.Min(options.MaxBatchLines, 64), + StartAtEnd = options.StartAtEnd, + UseFileIds = false + }; + } + + public async Task PollOnceAsync( + Func> onEvent, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(onEvent); + cancellationToken.ThrowIfCancellationRequested(); + + List pods = await DiscoverAllowedPodsAsync(cancellationToken); + + int filesTailed = 0; + int linesRead = 0; + int eventsDelivered = 0; + int droppedNonSecurity = 0; + int malformedLines = 0; + int oversizedLines = 0; + bool backpressure = false; + + foreach (KubernetesPodInfo pod in pods) + { + cancellationToken.ThrowIfCancellationRequested(); + if (backpressure) + { + break; + } + + foreach (string container in pod.Containers) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!KubernetesLogSourceOptions.IsSafePathSegment(container)) + { + continue; + } + + string? logPath = ResolveCurrentContainerLogPath(pod, container); + if (logPath is null) + { + continue; + } + + filesTailed++; + string cursorKey = $"k8s:{pod.Namespace}/{pod.Uid}/{container}"; + SourceCursorSnapshot? snapshot = await cursorStore.ReadAsync(cursorKey, cancellationToken); + FileTailCursor? existingCursor = FileTailCursor.Deserialize(snapshot?.Value); + long expectedVersion = snapshot?.Version ?? 0; + + string rotatedPath = $"{logPath}.1"; + FileTailBatch batch = FileTailReader.Read( + logPath, + System.IO.File.Exists(rotatedPath) ? rotatedPath : null, + existingCursor, + tailOptions, + cancellationToken); + linesRead += batch.Lines.Count; + + FileTailCursor? committedCursor = null; + bool stoppedHere = false; + + foreach (FileTailLine line in batch.Lines) + { + cancellationToken.ThrowIfCancellationRequested(); + if (line.Oversized) + { + oversizedLines++; + partials.Remove(cursorKey); + continue; + } + + string lineText = Encoding.UTF8.GetString(line.Bytes); + if (!CriLogParser.TryParse(lineText, out CriLogLine? cri) || cri is null) + { + malformedLines++; + partials.Remove(cursorKey); + continue; + } + + string? assembledMessage; + if (cri.IsPartial) + { + if (!TryAppendPartial(cursorKey, cri.Message)) + { + oversizedLines++; + partials.Remove(cursorKey); + } + + continue; + } + + if (partials.Remove(cursorKey, out PartialBuffer? partial)) + { + if (partial.Length + Encoding.UTF8.GetByteCount(cri.Message) > options.MaxPartialBytes) + { + oversizedLines++; + continue; + } + + partial.Builder.Append(cri.Message); + assembledMessage = partial.Builder.ToString(); + } + else + { + assembledMessage = cri.Message; + } + + SecurityEventEnvelope? envelope = TryParseSecurityEnvelope( + assembledMessage, + pod, + container, + cri.Stream, + batch.Cursor.Fingerprint, + line.StartOffset); + if (envelope is null) + { + droppedNonSecurity++; + continue; + } + + bool accepted = await onEvent(envelope, cancellationToken); + if (!accepted) + { + committedCursor = batch.RewindTo(line); + backpressure = true; + stoppedHere = true; + break; + } + + eventsDelivered++; + } + + FileTailCursor targetCursor = stoppedHere ? committedCursor! : batch.Cursor; + string serialized = targetCursor.Serialize(); + if (!string.Equals(serialized, snapshot?.Value, StringComparison.Ordinal)) + { + await cursorStore.TryAdvanceAsync( + cursorKey, + expectedVersion, + serialized, + clock.GetUtcNow(), + cancellationToken); + } + + if (backpressure) + { + break; + } + } + } + + return new KubernetesPollResult( + pods.Count, + filesTailed, + linesRead, + eventsDelivered, + droppedNonSecurity, + malformedLines, + oversizedLines, + backpressure); + } + + private async Task> DiscoverAllowedPodsAsync(CancellationToken cancellationToken) + { + Dictionary byUid = new(StringComparer.Ordinal); + foreach (string ns in options.Namespaces) + { + foreach (LabelSelectorEntry selector in options.LabelSelectors) + { + cancellationToken.ThrowIfCancellationRequested(); + IReadOnlyList listed = await catalog.ListPodsAsync(ns, selector, cancellationToken); + foreach (KubernetesPodInfo pod in listed) + { + // Enforce allow-lists fail-closed even if the catalog returns unselected pods. + if (!IsPodAllowed(pod)) + { + continue; + } + + byUid.TryAdd(pod.Uid, pod); + if (byUid.Count >= options.MaxPods) + { + return [.. byUid.Values.OrderBy(p => p.Uid, StringComparer.Ordinal)]; + } + } + } + } + + return [.. byUid.Values.OrderBy(p => p.Uid, StringComparer.Ordinal)]; + } + + internal bool IsPodAllowed(KubernetesPodInfo pod) + { + if (!allowedNamespaces.Contains(pod.Namespace)) + { + return false; + } + + if (!KubernetesLogSourceOptions.IsSafePathSegment(pod.Namespace) + || !KubernetesLogSourceOptions.IsSafePathSegment(pod.Name) + || !KubernetesLogSourceOptions.IsSafePathSegment(pod.Uid)) + { + return false; + } + + foreach (LabelSelectorEntry selector in options.LabelSelectors) + { + if (pod.Labels.TryGetValue(selector.Key, out string? actual) + && string.Equals(actual, selector.Value, StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + + internal string? ResolveCurrentContainerLogPath(KubernetesPodInfo pod, string container) + { + string podDirName = $"{pod.Namespace}_{pod.Name}_{pod.Uid}"; + string containerDir = Path.Combine(options.PodLogRoot, podDirName, container); + if (!Directory.Exists(containerDir)) + { + return null; + } + + // Standard kubelet container log files are numeric restart indices: 0.log, 1.log, ... + int bestRestart = -1; + string? bestPath = null; + foreach (string file in Directory.EnumerateFiles(containerDir, "*.log")) + { + string name = Path.GetFileNameWithoutExtension(file); + if (int.TryParse(name, out int restartIndex) && restartIndex > bestRestart) + { + bestRestart = restartIndex; + bestPath = file; + } + } + + return bestPath; + } + + private bool TryAppendPartial(string cursorKey, string fragment) + { + int fragmentBytes = Encoding.UTF8.GetByteCount(fragment); + if (!partials.TryGetValue(cursorKey, out PartialBuffer? buffer)) + { + if (fragmentBytes > options.MaxPartialBytes) + { + return false; + } + + buffer = new PartialBuffer(); + partials[cursorKey] = buffer; + } + + if (buffer.Length + fragmentBytes > options.MaxPartialBytes) + { + return false; + } + + buffer.Builder.Append(fragment); + buffer.Length += fragmentBytes; + return true; + } + + private SecurityEventEnvelope? TryParseSecurityEnvelope( + string message, + KubernetesPodInfo pod, + string container, + string stream, + string fileFingerprint, + long startOffset) + { + string trimmed = message.Trim(); + if (!trimmed.StartsWith('{') || !trimmed.EndsWith('}')) + { + return null; + } + + SecurityEventEnvelope? parsed; + try + { + parsed = JsonSerializer.Deserialize(trimmed, BowerJson.Envelope); + } + catch (JsonException) + { + return null; + } + + if (parsed is null + || string.IsNullOrWhiteSpace(parsed.EventCategory) + || string.IsNullOrWhiteSpace(parsed.EventType) + || string.IsNullOrWhiteSpace(parsed.EventAction) + || parsed.Application is null + || string.IsNullOrWhiteSpace(parsed.Application.Name)) + { + return null; + } + + Dictionary labels = parsed.Labels is { Count: > 0 } existing + ? new Dictionary(existing, StringComparer.Ordinal) + : new Dictionary(StringComparer.Ordinal); + labels["k8s.namespace"] = pod.Namespace; + labels["k8s.pod"] = pod.Name; + labels["k8s.container"] = container; + labels["k8s.stream"] = stream; + + foreach (string key in allowedMetadataLabels) + { + if (pod.Labels.TryGetValue(key, out string? value) && !string.IsNullOrWhiteSpace(value)) + { + labels[$"k8s.label.{key}"] = value; + } + } + + string deterministicId = string.IsNullOrWhiteSpace(parsed.EventId) + ? BuildDeterministicEventId(pod.Uid, container, fileFingerprint, startOffset) + : parsed.EventId; + + return parsed with + { + EventId = deterministicId, + EventOriginalId = parsed.EventOriginalId ?? deterministicId, + Labels = labels + }; + } + + internal static string BuildDeterministicEventId( + string podUid, + string container, + string fileFingerprint, + long startOffset) + { + string material = $"k8s\u001f{podUid}\u001f{container}\u001f{fileFingerprint}\u001f{startOffset}"; + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(material)); + return $"k8s-{Convert.ToHexStringLower(hash)[..32]}"; + } + + private sealed class PartialBuffer + { + public StringBuilder Builder { get; } = new(); + public int Length { get; set; } + } +} diff --git a/src/Bower.Source.Kubernetes/KubernetesLogSourceOptions.cs b/src/Bower.Source.Kubernetes/KubernetesLogSourceOptions.cs new file mode 100644 index 00000000..765fecbe --- /dev/null +++ b/src/Bower.Source.Kubernetes/KubernetesLogSourceOptions.cs @@ -0,0 +1,145 @@ +using Bower.Pipeline; + +namespace Bower.Source.Kubernetes; + +/// Exact key=value pod label selector. +public sealed record LabelSelectorEntry(string Key, string Value); + +public sealed record KubernetesLogSourceOptions +{ + public const int DefaultMaxLineBytes = 64 * 1024; + public const int MaxAllowedLineBytes = 64 * 1024; + public const int DefaultMaxPartialBytes = 64 * 1024; + public const int DefaultMaxBatchLines = 256; + public const int MaxAllowedBatchLines = 500; + public const int DefaultMaxPods = 200; + public const int MaxAllowedPods = 500; + + public string PodLogRoot { get; init; } = "/var/log/pods"; + + /// Explicit allow-listed Kubernetes namespaces. No wildcards or cluster-wide collection. + public IReadOnlyList Namespaces { get; init; } = []; + + /// Explicit label selectors (key=value). Pods must match at least one selector. + public IReadOnlyList LabelSelectors { get; init; } = []; + + /// Explicit allow-list of pod label keys to attach to emitted events (redacted like any field). + public IReadOnlyList AllowedMetadataLabels { get; init; } = []; + + public int MaxLineBytes { get; init; } = DefaultMaxLineBytes; + + public int MaxPartialBytes { get; init; } = DefaultMaxPartialBytes; + + public int MaxBatchLines { get; init; } = DefaultMaxBatchLines; + + public int MaxPods { get; init; } = DefaultMaxPods; + + /// When a container log file is first seen, start at its end unless false. + public bool StartAtEnd { get; init; } = true; + + /// Optional bounded multi-line continuation rule for joined CRI messages. + public CustomLogMultilineRule? Multiline { get; init; } + + public void Validate() + { + if (string.IsNullOrWhiteSpace(PodLogRoot) || !Path.IsPathRooted(PodLogRoot)) + { + throw new ArgumentException("PodLogRoot must be a rooted directory path.", nameof(PodLogRoot)); + } + + if (Namespaces.Count is 0 or > 32) + { + throw new ArgumentException("Kubernetes log source requires 1..32 explicitly allow-listed namespaces.", nameof(Namespaces)); + } + + foreach (string ns in Namespaces) + { + if (!IsValidDnsLabel(ns)) + { + throw new ArgumentException($"Invalid Kubernetes namespace '{ns}'. Wildcards and uppercase letters are refused."); + } + } + + if (LabelSelectors.Count is 0 or > 16) + { + throw new ArgumentException("Kubernetes log source requires 1..16 explicit label selectors.", nameof(LabelSelectors)); + } + + foreach (LabelSelectorEntry selector in LabelSelectors) + { + if (!IsValidLabelKey(selector.Key) || !IsValidLabelValue(selector.Value)) + { + throw new ArgumentException($"Invalid Kubernetes label selector '{selector.Key}={selector.Value}'."); + } + } + + if (AllowedMetadataLabels.Count > 16) + { + throw new ArgumentOutOfRangeException(nameof(AllowedMetadataLabels), "AllowedMetadataLabels cannot exceed 16 keys."); + } + + foreach (string key in AllowedMetadataLabels) + { + if (!IsValidLabelKey(key)) + { + throw new ArgumentException($"Invalid allowed metadata label key '{key}'."); + } + } + + if (MaxLineBytes is < 512 or > MaxAllowedLineBytes) + { + throw new ArgumentOutOfRangeException(nameof(MaxLineBytes), $"MaxLineBytes must be between 512 and {MaxAllowedLineBytes}."); + } + + if (MaxPartialBytes is < 512 or > MaxAllowedLineBytes) + { + throw new ArgumentOutOfRangeException(nameof(MaxPartialBytes), $"MaxPartialBytes must be between 512 and {MaxAllowedLineBytes}."); + } + + if (MaxBatchLines is < 1 or > MaxAllowedBatchLines) + { + throw new ArgumentOutOfRangeException(nameof(MaxBatchLines), $"MaxBatchLines must be between 1 and {MaxAllowedBatchLines}."); + } + + if (MaxPods is < 1 or > MaxAllowedPods) + { + throw new ArgumentOutOfRangeException(nameof(MaxPods), $"MaxPods must be between 1 and {MaxAllowedPods}."); + } + + if (Multiline is not null) + { + List issues = []; + CustomLogMultilineRule.Validate(Multiline, issues); + if (issues.Count > 0) + { + throw new ArgumentException(string.Join(" ", issues), nameof(Multiline)); + } + } + } + + internal static bool IsValidDnsLabel(string? value) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= 63 + && char.IsAsciiLetterLower(value[0]) || (value is { Length: > 0 and <= 63 } && char.IsAsciiDigit(value[0])) + && value is { Length: > 0 and <= 63 } + && (char.IsAsciiLetterLower(value[^1]) || char.IsAsciiDigit(value[^1])) + && value.All(ch => char.IsAsciiLetterLower(ch) || char.IsAsciiDigit(ch) || ch == '-'); + + internal static bool IsValidLabelKey(string? value) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= 128 + && value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '.' or '_' or '-' or '/'); + + internal static bool IsValidLabelValue(string? value) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= 63 + && value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '.' or '_' or '-'); + + internal static bool IsSafePathSegment(string? value) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= 128 + && !value.Contains('/') + && !value.Contains('\\') + && !value.Contains("..", StringComparison.Ordinal) + && value.All(ch => char.IsAsciiLetterOrDigit(ch) || ch is '.' or '_' or '-'); +} diff --git a/src/Bower.Source.Kubernetes/KubernetesPodCatalog.cs b/src/Bower.Source.Kubernetes/KubernetesPodCatalog.cs new file mode 100644 index 00000000..c306d5c4 --- /dev/null +++ b/src/Bower.Source.Kubernetes/KubernetesPodCatalog.cs @@ -0,0 +1,187 @@ +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Bower.Source.Kubernetes; + +public sealed record KubernetesPodInfo( + string Namespace, + string Name, + string Uid, + IReadOnlyList Containers, + IReadOnlyDictionary Labels); + +/// +/// Platform seam for listing allow-listed pods on the current node. +/// +public interface IKubernetesPodCatalog +{ + Task> ListPodsAsync( + string namespaceName, + LabelSelectorEntry selector, + CancellationToken cancellationToken = default); +} + +/// +/// Minimal Kubernetes API client using only namespaced get/list pods RBAC. +/// Reads its bearer token strictly from a file (never env vars) and caps response bytes. +/// +public sealed class KubernetesApiPodCatalog : IKubernetesPodCatalog +{ + public const int MaxResponseBytes = 4 * 1024 * 1024; + + private readonly HttpClient httpClient; + private readonly Uri apiServerBaseUri; + private readonly string? tokenFilePath; + private readonly string? nodeName; + + public KubernetesApiPodCatalog( + HttpClient httpClient, + Uri apiServerBaseUri, + string? tokenFilePath = null, + string? nodeName = null) + { + ArgumentNullException.ThrowIfNull(httpClient); + ArgumentNullException.ThrowIfNull(apiServerBaseUri); + this.httpClient = httpClient; + this.apiServerBaseUri = apiServerBaseUri; + this.tokenFilePath = tokenFilePath; + this.nodeName = nodeName; + } + + public async Task> ListPodsAsync( + string namespaceName, + LabelSelectorEntry selector, + CancellationToken cancellationToken = default) + { + if (!KubernetesLogSourceOptions.IsValidDnsLabel(namespaceName)) + { + throw new ArgumentException("Invalid namespace.", nameof(namespaceName)); + } + + string query = $"?labelSelector={Uri.EscapeDataString($"{selector.Key}={selector.Value}")}"; + if (!string.IsNullOrWhiteSpace(nodeName)) + { + query += $"&fieldSelector={Uri.EscapeDataString($"spec.nodeName={nodeName}")}"; + } + + Uri requestUri = new(apiServerBaseUri, $"/api/v1/namespaces/{Uri.EscapeDataString(namespaceName)}/pods{query}"); + using HttpRequestMessage request = new(HttpMethod.Get, requestUri); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (!string.IsNullOrWhiteSpace(tokenFilePath) && System.IO.File.Exists(tokenFilePath)) + { + string token = (await System.IO.File.ReadAllTextAsync(tokenFilePath, cancellationToken)).Trim(); + if (!string.IsNullOrEmpty(token)) + { + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + } + + using HttpResponseMessage response = await httpClient.SendAsync( + request, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken); + response.EnsureSuccessStatusCode(); + + await using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using MemoryStream bounded = new(); + byte[] buffer = new byte[16 * 1024]; + int total = 0; + while (true) + { + int read = await stream.ReadAsync(buffer, cancellationToken); + if (read == 0) + { + break; + } + + total += read; + if (total > MaxResponseBytes) + { + throw new InvalidDataException("Kubernetes pod list response exceeded 4 MiB safety cap."); + } + + bounded.Write(buffer, 0, read); + } + + bounded.Position = 0; + K8sPodList? list = await JsonSerializer.DeserializeAsync( + bounded, + KubernetesJsonContext.Default.K8sPodList, + cancellationToken); + if (list?.Items is null) + { + return []; + } + + List result = new(list.Items.Count); + foreach (K8sPodItem item in list.Items) + { + string? ns = item.Metadata?.Namespace; + string? name = item.Metadata?.Name; + string? uid = item.Metadata?.Uid; + if (string.IsNullOrWhiteSpace(ns) || string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(uid)) + { + continue; + } + + string[] containers = item.Spec?.Containers? + .Select(c => c.Name) + .Where(c => !string.IsNullOrWhiteSpace(c)) + .Cast() + .Distinct(StringComparer.Ordinal) + .ToArray() ?? []; + IReadOnlyDictionary labels = item.Metadata?.Labels is { Count: > 0 } map + ? map + : new Dictionary(StringComparer.Ordinal); + result.Add(new KubernetesPodInfo(ns, name, uid, containers, labels)); + } + + return result; + } +} + +internal sealed class K8sPodList +{ + [JsonPropertyName("items")] + public List? Items { get; set; } +} + +internal sealed class K8sPodItem +{ + [JsonPropertyName("metadata")] + public K8sPodMetadata? Metadata { get; set; } + + [JsonPropertyName("spec")] + public K8sPodSpec? Spec { get; set; } +} + +internal sealed class K8sPodMetadata +{ + [JsonPropertyName("namespace")] + public string? Namespace { get; set; } + + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("uid")] + public string? Uid { get; set; } + + [JsonPropertyName("labels")] + public Dictionary? Labels { get; set; } +} + +internal sealed class K8sPodSpec +{ + [JsonPropertyName("containers")] + public List? Containers { get; set; } +} + +internal sealed class K8sContainer +{ + [JsonPropertyName("name")] + public string? Name { get; set; } +} + +[JsonSerializable(typeof(K8sPodList))] +internal sealed partial class KubernetesJsonContext : JsonSerializerContext; diff --git a/src/Bower.Source.Kubernetes/packages.lock.json b/src/Bower.Source.Kubernetes/packages.lock.json new file mode 100644 index 00000000..d4ab6a5f --- /dev/null +++ b/src/Bower.Source.Kubernetes/packages.lock.json @@ -0,0 +1,48 @@ +{ + "version": 2, + "dependencies": { + "net11.0": { + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "gK2aq4XvChj5kvozpPHrkfKkr7zc5Z4xoTrJb4GPZzDEPMlCk0TX632bwY3LsWcX2UVcVRQBBGzsBGC2lq6YhA==" + }, + "bower.abstractions": { + "type": "Project", + "dependencies": { + "Bower.Contracts": "[1.0.0, )" + } + }, + "bower.contracts": { + "type": "Project" + }, + "bower.pipeline": { + "type": "Project", + "dependencies": { + "Bower.Redaction": "[1.0.0, )", + "YamlDotNet": "[18.1.0, )" + } + }, + "bower.redaction": { + "type": "Project", + "dependencies": { + "Bower.Abstractions": "[1.0.0, )", + "YamlDotNet": "[18.1.0, )" + } + }, + "bower.source.file": { + "type": "Project", + "dependencies": { + "Bower.Abstractions": "[1.0.0, )" + } + }, + "YamlDotNet": { + "type": "CentralTransitive", + "requested": "[18.1.0, )", + "resolved": "18.1.0", + "contentHash": "5K+9KFg2TdTl7VXv88Qzi/0lqK6JFoNP3lRuImPYGRV7K/QYklDyTrj4+A+KAki1JsQi6qKY+hDyY7d6WRqjrw==" + } + } + } +} \ No newline at end of file diff --git a/tests/Bower.UnitTests/Bower.UnitTests.csproj b/tests/Bower.UnitTests/Bower.UnitTests.csproj index 9263a684..60dae8c3 100644 --- a/tests/Bower.UnitTests/Bower.UnitTests.csproj +++ b/tests/Bower.UnitTests/Bower.UnitTests.csproj @@ -173,5 +173,7 @@ + + diff --git a/tests/Bower.UnitTests/JournaldAndKubernetesSourceTests.cs b/tests/Bower.UnitTests/JournaldAndKubernetesSourceTests.cs new file mode 100644 index 00000000..dbd22f78 --- /dev/null +++ b/tests/Bower.UnitTests/JournaldAndKubernetesSourceTests.cs @@ -0,0 +1,356 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Contracts; +using Bower.Integrity; +using Bower.Packs; +using Bower.Persistence; +using Bower.PolicyEngine; +using Bower.Redaction.Privacy; +using Bower.Source.Journald; +using Bower.Source.Kubernetes; + +namespace Bower.UnitTests; + +public sealed class JournaldAndKubernetesSourceTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 22, 0, 0, 0, TimeSpan.Zero); + + [Fact] + public void JournaldOptions_DefaultDenyAndRejectWildcards() + { + Assert.Throws(() => new JournaldSourceOptions + { + SubscriptionName = "ssh" + }.Validate()); + + Assert.Throws(() => new JournaldSourceOptions + { + SubscriptionName = "ssh", + Units = ["ssh*.service"] + }.Validate()); + + Assert.Throws(() => new JournaldSourceOptions + { + SubscriptionName = "ssh", + Identifiers = ["*"] + }.Validate()); + } + + [Fact] + public async Task JournaldSource_EnforcesAllowList_ResumesDurableCursor_AndParsesWithSignedSshPack() + { + CancellationToken ct = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory temp = new(); + EfSourceCursorStore store = new(Path.Combine(temp.Path, "cursors.db")); + await store.InitializeAsync(ct); + + long usec = Now.ToUnixTimeMilliseconds() * 1000L; + JournaldEntry[] stream = + [ + new("c-1", usec, "cron.service", "CRON", "ignored cron noise"), + new("c-2", usec + 1000, "sshd.service", "sshd", "Failed password for invalid user alice from 192.0.2.44 port 51234 ssh2"), + new("c-3", usec + 2000, "sshd.service", "sshd", new string('x', 40_000)), // oversized + new("c-4", usec + 3000, "sshd.service", "sshd", "Failed publickey for bob from 192.0.2.45 port 51235 ssh2") + ]; + + FakeJournalReader reader = new(stream); + JournaldSourceOptions options = new() + { + SubscriptionName = "ssh-auth", + Units = ["sshd.service"], + MaxBatchSize = 10 + }; + JournaldSource source = new(options, reader, store); + + // Simulate backpressure/crash on c-4: accept c-2, reject c-4 so cursor must stop at c-3 (before c-4). + List received = []; + JournaldPollResult first = await source.PollOnceAsync((record, _) => + { + if (record.Cursor == "c-4") + { + return Task.FromResult(false); + } + + received.Add(record); + return Task.FromResult(true); + }, ct); + + Assert.Equal(4, first.Read); + Assert.Equal(1, first.Delivered); + Assert.Equal(1, first.FilteredOut); + Assert.Equal(1, first.RejectedOversized); + Assert.True(first.StoppedOnBackpressure); + Assert.Equal("c-3", first.CommittedCursor); + Assert.Single(received); + Assert.Equal("c-2", received[0].Cursor); + + // Parse c-2 through signed packs/linux-journald-ssh -> privacy -> policy! + LoadedPack sshPack = BuildPack("linux-journald-ssh"); + SecurityEventEnvelope? parsed = PackRuntime.Parse(sshPack.Parsers[0], received[0].RecordJson, Now); + Assert.NotNull(parsed); + Assert.Equal("authentication_failure", parsed.EventType); + Assert.Equal("alice", parsed.Actor!.Username); + Assert.Equal("192.0.2.44", parsed.Source!.IpAddress); + + // Simulate restart with a fresh JournaldSource reading the same durable SQLite store. + JournaldSource restarted = new(options, reader, store); + JournaldPollResult second = await restarted.PollOnceAsync((record, _) => + { + received.Add(record); + return Task.FromResult(true); + }, ct); + + Assert.Equal(1, second.Read); + Assert.Equal(1, second.Delivered); + Assert.False(second.StoppedOnBackpressure); + Assert.Equal("c-4", second.CommittedCursor); + Assert.Equal(2, received.Count); + Assert.Equal("c-4", received[1].Cursor); + + // Third poll has nothing left -> zero duplicates. + JournaldPollResult third = await restarted.PollOnceAsync((_, _) => Task.FromResult(true), ct); + Assert.Equal(0, third.Read); + Assert.Equal(0, third.Delivered); + } + + [Fact] + public void KubernetesOptions_RefuseClusterWideOrWildcardNamespaces() + { + Assert.Throws(() => new KubernetesLogSourceOptions + { + PodLogRoot = "/var/log/pods", + Namespaces = [], + LabelSelectors = [new("bower.io/collect", "true")] + }.Validate()); + + Assert.Throws(() => new KubernetesLogSourceOptions + { + PodLogRoot = "/var/log/pods", + Namespaces = ["*"], + LabelSelectors = [new("bower.io/collect", "true")] + }.Validate()); + + Assert.Throws(() => new KubernetesLogSourceOptions + { + PodLogRoot = "/var/log/pods", + Namespaces = ["payments"], + LabelSelectors = [] + }.Validate()); + } + + [Fact] + public async Task KubernetesSource_EnforcesAllowLists_JoinsCriPartials_SurvivesRotationAndRestart() + { + CancellationToken ct = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory temp = new(); + EfSourceCursorStore store = new(Path.Combine(temp.Path, "cursors.db")); + await store.InitializeAsync(ct); + + string podLogRoot = Path.Combine(temp.Path, "pods"); + KubernetesPodInfo allowedPod = new( + "payments", + "checkout-api-0", + "uid-allowed-1", + ["app"], + new Dictionary + { + ["bower.io/collect"] = "true", + ["app.kubernetes.io/name"] = "checkout-api", + ["secret-label"] = "must-not-attach" + }); + KubernetesPodInfo forbiddenNsPod = new( + "kube-system", + "coredns-0", + "uid-forbidden-ns", + ["coredns"], + new Dictionary { ["bower.io/collect"] = "true" }); + KubernetesPodInfo forbiddenLabelPod = new( + "payments", + "debug-pod-0", + "uid-forbidden-label", + ["debug"], + new Dictionary { ["app"] = "debug" }); + + string allowedDir = Path.Combine(podLogRoot, "payments_checkout-api-0_uid-allowed-1", "app"); + string forbiddenDir = Path.Combine(podLogRoot, "kube-system_coredns-0_uid-forbidden-ns", "coredns"); + Directory.CreateDirectory(allowedDir); + Directory.CreateDirectory(forbiddenDir); + + string env1 = BuildEnvelopeJson("evt-k8s-1", "alice@example.com"); + string env2 = BuildEnvelopeJson("evt-k8s-2", "bob@example.com"); + string env1PartA = env1[..45]; + string env1PartB = env1[45..]; + + string allowedLog = Path.Combine(allowedDir, "0.log"); + await File.WriteAllTextAsync( + allowedLog, + $"2026-11-22T00:00:01.000000000Z stdout F plain stdout debug noise\n" + + $"not-a-cri-line\n" + + $"2026-11-22T00:00:02.000000000Z stdout P {env1PartA}\n" + + $"2026-11-22T00:00:02.000000001Z stdout F {env1PartB}\n", + ct); + await File.WriteAllTextAsync( + Path.Combine(forbiddenDir, "0.log"), + $"2026-11-22T00:00:01.000000000Z stdout F {BuildEnvelopeJson("evt-forbidden", "eve@example.com")}\n", + ct); + + FakePodCatalog catalog = new([allowedPod, forbiddenNsPod, forbiddenLabelPod]); + KubernetesLogSourceOptions options = new() + { + PodLogRoot = podLogRoot, + Namespaces = ["payments"], + LabelSelectors = [new("bower.io/collect", "true")], + AllowedMetadataLabels = ["app.kubernetes.io/name"], + StartAtEnd = false + }; + + KubernetesLogSource source = new(options, catalog, store); + List delivered = []; + KubernetesPollResult first = await source.PollOnceAsync((env, _) => + { + delivered.Add(env); + return Task.FromResult(true); + }, ct); + + Assert.Equal(1, first.PodsScanned); + Assert.Equal(1, first.FilesTailed); + Assert.Equal(1, first.EventsDelivered); + Assert.Equal(1, first.DroppedNonSecurity); + Assert.Equal(1, first.MalformedLines); + Assert.Single(delivered); + Assert.Equal("evt-k8s-1", delivered[0].EventId); + Assert.Equal("payments", delivered[0].Labels!["k8s.namespace"]); + Assert.Equal("checkout-api-0", delivered[0].Labels!["k8s.pod"]); + Assert.Equal("app", delivered[0].Labels!["k8s.container"]); + Assert.Equal("checkout-api", delivered[0].Labels!["k8s.label.app.kubernetes.io/name"]); + Assert.False(delivered[0].Labels!.ContainsKey("k8s.label.secret-label")); + + // Rotate log file (rename 0.log -> 0.log.1, write new 0.log) and restart source from SQLite cursor. + string rotatedLog = Path.Combine(allowedDir, "0.log.1"); + File.Move(allowedLog, rotatedLog); + await File.WriteAllTextAsync( + allowedLog, + $"2026-11-22T00:01:00.000000000Z stderr F {env2}\n", + ct); + + KubernetesLogSource restarted = new(options, catalog, store); + // Poll enough times for rename grace polls (5) + transition to read the new file. + for (int i = 0; i < 10 && delivered.Count < 2; i++) + { + await restarted.PollOnceAsync((env, _) => + { + delivered.Add(env); + return Task.FromResult(true); + }, ct); + } + + Assert.Equal(2, delivered.Count); + Assert.Equal("evt-k8s-2", delivered[1].EventId); + Assert.Equal("stderr", delivered[1].Labels!["k8s.stream"]); + } + + [Fact] + public async Task KubernetesApiPodCatalog_UsesNamespacedEndpointAndBearerTokenFile() + { + CancellationToken ct = TestContext.Current.CancellationToken; + using TemporaryDirectory temp = new(); + string tokenFile = Path.Combine(temp.Path, "token"); + await File.WriteAllTextAsync(tokenFile, "k8s-sa-token-xyz\n", ct); + + Uri? capturedUri = null; + string? capturedAuth = null; + using HttpClient client = new(new StubHttpHandler(req => + { + capturedUri = req.RequestUri; + capturedAuth = req.Headers.Authorization?.ToString(); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent( + """{"items":[{"metadata":{"namespace":"payments","name":"api-1","uid":"u-1","labels":{"bower.io/collect":"true"}},"spec":{"containers":[{"name":"app"}]}}]}""", + Encoding.UTF8, + "application/json") + }; + })); + + KubernetesApiPodCatalog catalog = new(client, new Uri("https://kubernetes.default.svc"), tokenFile, "node-a"); + IReadOnlyList pods = await catalog.ListPodsAsync("payments", new("bower.io/collect", "true"), ct); + + Assert.Single(pods); + Assert.Equal("api-1", pods[0].Name); + Assert.Equal("Bearer k8s-sa-token-xyz", capturedAuth); + Assert.Contains("/api/v1/namespaces/payments/pods", capturedUri!.AbsolutePath, StringComparison.Ordinal); + Assert.Contains("labelSelector=bower.io%2Fcollect%3Dtrue", capturedUri.Query, StringComparison.Ordinal); + Assert.Contains("fieldSelector=spec.nodeName%3Dnode-a", capturedUri.Query, StringComparison.Ordinal); + } + + private static string BuildEnvelopeJson(string eventId, string username) => + JsonSerializer.Serialize(new SecurityEventEnvelope + { + SchemaVersion = SecurityEventEnvelope.CurrentSchemaVersion, + EventId = eventId, + TimeGenerated = Now, + EventCategory = SecurityEventCategories.Authentication, + EventType = SecurityEventTypes.AuthenticationFailure, + EventAction = "authentication.attempt", + EventResult = EventResult.Failure, + EventOutcomeReason = "InvalidCredentials", + Application = new ApplicationContext { Name = "checkout-api", Environment = "production" }, + Actor = new ActorContext { Username = username }, + Source = new SourceContext { IpAddress = "192.0.2.90" }, + Request = new RequestContext { CorrelationId = $"corr-{eventId}" } + }, BowerJson.Envelope); + + private static LoadedPack BuildPack(string packId) + { + using TemporaryDirectory output = new(); + (string privatePem, string publicPem, _) = DetachedSigner.GenerateKeyPair(); + string archive = PackArchive.Build(Path.Combine(AppContext.BaseDirectory, "packs", packId), privatePem, output.Path); + return PackArchive.Load(archive, [publicPem]); + } + + private sealed class FakeJournalReader(IReadOnlyList entries) : IJournalReader + { + public ValueTask> ReadBatchAsync( + string? afterCursor, + int maxRecords, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + int start = 0; + if (!string.IsNullOrWhiteSpace(afterCursor)) + { + for (int i = 0; i < entries.Count; i++) + { + if (string.Equals(entries[i].Cursor, afterCursor, StringComparison.Ordinal)) + { + start = i + 1; + break; + } + } + } + + return ValueTask.FromResult>(entries.Skip(start).Take(maxRecords).ToArray()); + } + + public void Dispose() + { + } + } + + private sealed class FakePodCatalog(IReadOnlyList pods) : IKubernetesPodCatalog + { + public Task> ListPodsAsync( + string namespaceName, + LabelSelectorEntry selector, + CancellationToken cancellationToken = default) => + Task.FromResult(pods); + } + + private sealed class StubHttpHandler(Func responder) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(responder(request)); + } +} diff --git a/tests/Bower.UnitTests/packages.lock.json b/tests/Bower.UnitTests/packages.lock.json index 60c63e4b..dd4af024 100644 --- a/tests/Bower.UnitTests/packages.lock.json +++ b/tests/Bower.UnitTests/packages.lock.json @@ -997,6 +997,22 @@ "Bower.Contracts": "[1.0.0, )" } }, + "bower.source.journald": { + "type": "Project", + "dependencies": { + "Bower.Abstractions": "[1.0.0, )", + "Bower.Contracts": "[1.0.0, )" + } + }, + "bower.source.kubernetes": { + "type": "Project", + "dependencies": { + "Bower.Abstractions": "[1.0.0, )", + "Bower.Contracts": "[1.0.0, )", + "Bower.Pipeline": "[1.0.0, )", + "Bower.Source.File": "[1.0.0, )" + } + }, "bower.source.sqlserver": { "type": "Project", "dependencies": { diff --git a/website/sidebars.ts b/website/sidebars.ts index ceb207da..8b5881c9 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -198,6 +198,16 @@ const sidebars: SidebarsConfig = { "id": "deployment/file-tail-source", "label": "Local files" }, + { + "type": "doc", + "id": "deployment/journald-source", + "label": "systemd journald" + }, + { + "type": "doc", + "id": "deployment/kubernetes-source", + "label": "Kubernetes container logs" + }, { "type": "doc", "id": "deployment/ama-companion",