From d3a3b3a4b5197a87c75cef5ae1635e070d5aec75 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 22:09:11 -0400 Subject: [PATCH 1/8] =?UTF-8?q?feat:=20chain-head=20anchoring=20per=20ADR-?= =?UTF-8?q?0007=20=E2=80=94=20end-truncation=20becomes=20detectable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every Nth entry's head hash is appended to a separate anchor file (Audit:AnchorPath on an independent storage domain, Audit:AnchorEvery cadence; both-or-neither, validated fail-closed). Verification requires the log to contain every anchored count with exactly the anchored hash: truncation past an anchor and coherent whole-log rewrites both fail. Rotation archives log and anchors together. ADR-0007 also records the Postgres verdict: the file stays the evidence of record; DB triggers are HA or runtime-editable config, never bundled. Tests prove the gap closure explicitly: the same truncated log passes plain verification and fails anchored verification. --- README-SCAFFOLD.md | 7 ++ ...R-0007-audit-store-chain-head-anchoring.md | 48 ++++++++ src/Covenant.Host/Evidence.cs | 76 ++++++++---- src/Covenant.Host/EvidenceGraph.cs | 4 +- src/Covenant.Host/FileAuditSink.cs | 30 +++-- src/Covenant.Host/Program.cs | 20 +++- tests/Covenant.Tests/AnchorTests.cs | 112 ++++++++++++++++++ 7 files changed, 259 insertions(+), 38 deletions(-) create mode 100644 docs/adr/ADR-0007-audit-store-chain-head-anchoring.md create mode 100644 tests/Covenant.Tests/AnchorTests.cs diff --git a/README-SCAFFOLD.md b/README-SCAFFOLD.md index 1e7180f..5178ee4 100644 --- a/README-SCAFFOLD.md +++ b/README-SCAFFOLD.md @@ -76,6 +76,13 @@ Reset between demo runs: **Settings → Archive log & reset counters** in the da `curl -X POST localhost:5100/admin/reset -H 'X-Covenant-Admin-Token: dev-admin-token'`). The audit log is archived with a timestamp, never deleted; budgets reopen. +Chain-head anchoring (ADR-0007 — makes end-truncation of the audit log detectable; point the anchor +file at an INDEPENDENT storage domain, that placement is the security): +``` +dotnet user-secrets set "Audit:AnchorPath" "/Volumes/other-disk/covenant.anchors" --project src/Covenant.Host +dotnet user-secrets set "Audit:AnchorEvery" "100" --project src/Covenant.Host +``` + Rate limits (opt-in; refusals are HTTP 429 and audited; 0 = unlimited): ``` dotnet user-secrets set "RateLimit:PerTeamPerMinute" "30" --project src/Covenant.Host diff --git a/docs/adr/ADR-0007-audit-store-chain-head-anchoring.md b/docs/adr/ADR-0007-audit-store-chain-head-anchoring.md new file mode 100644 index 0000000..f2adfb9 --- /dev/null +++ b/docs/adr/ADR-0007-audit-store-chain-head-anchoring.md @@ -0,0 +1,48 @@ +# ADR-0007 — Audit store: chain-head anchoring; the file stays the evidence of record + +**Status:** Accepted (2026-07-20) +**Date:** 2026-07-20 + +## Context +The hash-chained audit file detects edits, deletions, reordering, and forged hashes — but truncation +from the END is undetectable from the file alone (documented in `AuditChain.cs` since the chain +landed): an attacker who removes the last N lines leaves a perfectly valid shorter chain. Separately, +the Postgres question has recurred: should evidence move to a database? + +## Decision +1. **The append-only hash-chained file remains the evidence of record.** No database replaces it: a + relational store adds mutability surface (a DBA's DELETE is the same attack as `truncate`) without + adding integrity. Queryability is already served by the evidence export and the evidence graph + (ADR-0006), both derived and rebuildable. +2. **Chain-head anchoring closes the truncation gap.** Every N entries (`Audit:AnchorEvery`), the sink + appends `{entryCount}\t{headHash}\t{timestamp}` to a separate anchor file (`Audit:AnchorPath`). + Verification then requires the log to contain at least every anchored count with exactly the + anchored hash at that position — a log truncated past any anchor fails verification. The anchor + file's whole value is *placement*: the operator points it at storage with a different failure and + attacker domain (another volume, a WORM share, object storage with object-lock). Exposure is + bounded to the entries since the last anchor (the cadence is the knob). +3. **Both settings are required together** (one without the other → refuse to start); unset means + anchoring off — the first-slice posture, with the gap still documented. +4. **Rotation archives log and anchor file together**; a fresh chain starts fresh anchors. +5. **Postgres trigger, recorded for the future:** multi-instance HA (shared serving state) or + runtime-editable policy (a config store) — and then customer-operated, never bundled. Ledger + replay cost at boot is the trigger for snapshotting, not for a database. + +## Consequences +- (+) End-truncation becomes detectable wherever an operator can mount one independent path — no new + infrastructure, no new dependency, ~40 bytes per anchor. +- (+) The threat model is explicit: an attacker must now compromise two storage domains coherently. +- (−) Entries newer than the last anchor remain truncatable — bounded, configurable, stated. +- (−) An attacker who can write BOTH files can still rewrite history; anchoring raises the bar, only + external notarization (e.g. publishing anchor hashes to a customer's existing WORM/ledger service) + removes it. Deliberately out of scope until a customer mandate names the target system. + +## Alternatives considered +- **Move evidence to Postgres/SQL.** Rejected for evidence (mutability without integrity gain); + triggers for a store recorded above. +- **Hash-chain the anchor file too.** Rejected: circular — anchors are trusted because of *where* + they live, not how they're formatted; chaining them adds format complexity, not security. +- **Anchor every entry.** Rejected: doubles hot-path writes for negligible exposure reduction vs + N=100; cadence is configurable for those who disagree. +- **External notarization now.** Deferred: needs a named customer target (their TSA, ledger DB, or + object-lock bucket); the anchor-file seam is exactly where it will plug in. diff --git a/src/Covenant.Host/Evidence.cs b/src/Covenant.Host/Evidence.cs index 06577a9..e24b49d 100644 --- a/src/Covenant.Host/Evidence.cs +++ b/src/Covenant.Host/Evidence.cs @@ -16,37 +16,67 @@ public sealed record ChainVerification(bool Valid, int EntryCount, int? FirstInv public static class AuditChainVerifier { public static (ChainVerification Verification, IReadOnlyList Entries) VerifyAndRead(string path) + => VerifyAndRead(path, anchorPath: null); + + /// With an anchor path (ADR-0007), the log must contain every anchored count with exactly + /// the anchored head hash at that position — end-truncation past any anchor fails verification. + public static (ChainVerification Verification, IReadOnlyList Entries) VerifyAndRead(string path, string? anchorPath) { var entries = new List(); - if (!File.Exists(path)) - return (ChainVerification.Ok(0), entries); - - var previous = AuditChain.GenesisHash; - int lineNo = 0; + var hashes = new List(); - foreach (var line in File.ReadLines(path)) + if (File.Exists(path)) { - if (string.IsNullOrWhiteSpace(line)) continue; - lineNo++; + var previous = AuditChain.GenesisHash; + int lineNo = 0; + + foreach (var line in File.ReadLines(path)) + { + if (string.IsNullOrWhiteSpace(line)) continue; + lineNo++; - var parts = line.Split(AuditChain.Separator, 3); - if (parts.Length != 3) - return (ChainVerification.Broken(entries.Count, lineNo, "malformed line"), entries); + var parts = line.Split(AuditChain.Separator, 3); + if (parts.Length != 3) + return (ChainVerification.Broken(entries.Count, lineNo, "malformed line"), entries); - var (prevHash, entryHash, content) = (parts[0], parts[1], parts[2]); + var (prevHash, entryHash, content) = (parts[0], parts[1], parts[2]); - if (!string.Equals(prevHash, previous, StringComparison.Ordinal)) - return (ChainVerification.Broken(entries.Count, lineNo, "chain link mismatch (removed, reordered, or restarted)"), entries); + if (!string.Equals(prevHash, previous, StringComparison.Ordinal)) + return (ChainVerification.Broken(entries.Count, lineNo, "chain link mismatch (removed, reordered, or restarted)"), entries); - if (!string.Equals(entryHash, AuditChain.Hash(previous, content), StringComparison.Ordinal)) - return (ChainVerification.Broken(entries.Count, lineNo, "content hash mismatch (entry altered)"), entries); + if (!string.Equals(entryHash, AuditChain.Hash(previous, content), StringComparison.Ordinal)) + return (ChainVerification.Broken(entries.Count, lineNo, "content hash mismatch (entry altered)"), entries); - var entry = JsonSerializer.Deserialize(content, AuditJsonContext.Default.AuditEntry); - if (entry is null) - return (ChainVerification.Broken(entries.Count, lineNo, "entry is not valid JSON"), entries); + var entry = JsonSerializer.Deserialize(content, AuditJsonContext.Default.AuditEntry); + if (entry is null) + return (ChainVerification.Broken(entries.Count, lineNo, "entry is not valid JSON"), entries); - entries.Add(entry); - previous = entryHash; + entries.Add(entry); + hashes.Add(entryHash); + previous = entryHash; + } + } + + if (anchorPath is not null && File.Exists(anchorPath)) + { + int anchorNo = 0; + foreach (var line in File.ReadLines(anchorPath)) + { + if (string.IsNullOrWhiteSpace(line)) continue; + anchorNo++; + + var parts = line.Split(AuditChain.Separator, 3); + if (parts.Length != 3 || !long.TryParse(parts[0], out var anchoredCount) || anchoredCount < 1) + return (ChainVerification.Broken(entries.Count, anchorNo, $"malformed anchor #{anchorNo}"), entries); + + if (anchoredCount > entries.Count) + return (ChainVerification.Broken(entries.Count, anchorNo, + $"log truncated: anchor #{anchorNo} attests {anchoredCount} entries, log has {entries.Count}"), entries); + + if (!string.Equals(hashes[(int)anchoredCount - 1], parts[1], StringComparison.Ordinal)) + return (ChainVerification.Broken(entries.Count, anchorNo, + $"anchor #{anchorNo} hash mismatch at entry {anchoredCount} (history rewritten)"), entries); + } } return (ChainVerification.Ok(entries.Count), entries); @@ -86,9 +116,9 @@ public static void Rebuild(IReadOnlyList entries, Covenant.Governanc public static class EvidenceExport { - public static EvidenceReport Build(string auditLogPath, TimeProvider clock) + public static EvidenceReport Build(string auditLogPath, TimeProvider clock, string? anchorPath = null) { - var (verification, entries) = AuditChainVerifier.VerifyAndRead(auditLogPath); + var (verification, entries) = AuditChainVerifier.VerifyAndRead(auditLogPath, anchorPath); var costByTeam = new Dictionary(StringComparer.OrdinalIgnoreCase); var byClassification = new Dictionary(); diff --git a/src/Covenant.Host/EvidenceGraph.cs b/src/Covenant.Host/EvidenceGraph.cs index b951855..6609465 100644 --- a/src/Covenant.Host/EvidenceGraph.cs +++ b/src/Covenant.Host/EvidenceGraph.cs @@ -6,7 +6,7 @@ namespace Covenant.Host; /// ADR-0006: optional projection of the audit log into in-perimeter Neo4j; never load-bearing — the chained log stays the evidence of record, the graph is rebuildable derived data. /// Idempotent (MERGE on stable keys), so restarts/replays are safe; if Neo4j is down, governance is unaffected and the projector catches up. -public sealed class EvidenceGraphProjector(string auditPath, string uri, string user, string password) +public sealed class EvidenceGraphProjector(string auditPath, string uri, string user, string password, string? anchorPath = null) : BackgroundService { private const string UpsertCypher = @@ -42,7 +42,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) try { // Only verified prefix is projected — nothing past a chain break enters the graph. - var (_, entries) = AuditChainVerifier.VerifyAndRead(auditPath); + var (_, entries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); if (entries.Count > _projected) { var batch = ToParameters(entries.Skip(_projected).ToList()); diff --git a/src/Covenant.Host/FileAuditSink.cs b/src/Covenant.Host/FileAuditSink.cs index 90d8f54..5a8d474 100644 --- a/src/Covenant.Host/FileAuditSink.cs +++ b/src/Covenant.Host/FileAuditSink.cs @@ -7,8 +7,9 @@ namespace Covenant.Host; /// Off-hot-path audit sink: hash-chains entries to an append-only file (tamper-evident). -/// First slice; WORM store is the audit-store ADR (deploy/CLAUDE.md). -public sealed class FileAuditSink(string path) : IAuditSink, IHostedService +/// With anchoring configured (ADR-0007), every Nth entry's head hash is appended to a separate anchor +/// file — its value is placement on an independent storage/attacker domain. +public sealed class FileAuditSink(string path, string? anchorPath = null, int anchorEvery = 0) : IAuditSink, IHostedService { private readonly Channel _channel = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); @@ -16,6 +17,7 @@ public sealed class FileAuditSink(string path) : IAuditSink, IHostedService private readonly SemaphoreSlim _fileLock = new(1, 1); private Task? _drain; private string _previousHash = AuditChain.GenesisHash; + private long _count; public ValueTask EnqueueAsync(AuditEntry entry, CancellationToken cancellationToken = default) => _channel.Writer.WriteAsync(entry, cancellationToken); @@ -25,9 +27,13 @@ public Task StartAsync(CancellationToken cancellationToken) // Resume the chain across restarts: a fresh genesis mid-file would (correctly) fail verification. if (File.Exists(path)) { - var last = File.ReadLines(path).LastOrDefault(l => !string.IsNullOrWhiteSpace(l)); - var parts = last?.Split(AuditChain.Separator, 3); - if (parts is { Length: 3 }) _previousHash = parts[1]; + foreach (var line in File.ReadLines(path)) + { + if (string.IsNullOrWhiteSpace(line)) continue; + _count++; + var parts = line.Split(AuditChain.Separator, 3); + if (parts.Length == 3) _previousHash = parts[1]; + } } _drain = Task.Run(DrainAsync, cancellationToken); @@ -52,6 +58,11 @@ private async Task DrainAsync() await File.AppendAllTextAsync(path, $"{_previousHash}{AuditChain.Separator}{entryHash}{AuditChain.Separator}{content}{Environment.NewLine}"); _previousHash = entryHash; + _count++; + + if (anchorEvery > 0 && anchorPath is not null && _count % anchorEvery == 0) + await File.AppendAllTextAsync(anchorPath, + $"{_count}{AuditChain.Separator}{entryHash}{AuditChain.Separator}{DateTimeOffset.UtcNow:o}{Environment.NewLine}"); } finally { @@ -60,17 +71,20 @@ await File.AppendAllTextAsync(path, } } - /// Archives the current log (rename, never delete — evidence retires, it doesn't die) and - /// restarts the chain at genesis. Returns the archive path, or null if nothing to archive. + /// Archives log AND anchor file together (rename, never delete); fresh chain, fresh anchors. public async Task RotateAsync() { await _fileLock.WaitAsync(); try { if (!File.Exists(path)) return null; - var archive = $"{path}.{DateTime.UtcNow:yyyyMMdd-HHmmss}.archived"; + var stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); + var archive = $"{path}.{stamp}.archived"; File.Move(path, archive); + if (anchorPath is not null && File.Exists(anchorPath)) + File.Move(anchorPath, $"{anchorPath}.{stamp}.archived"); _previousHash = AuditChain.GenesisHash; + _count = 0; return archive; } finally diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index 5df426d..e418f9e 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -191,13 +191,22 @@ void FailIfConfigErrors() // Second gate: every later section (pricing, routing, cache, rate limits, preview) has parsed by now. FailIfConfigErrors(); -var auditSink = new FileAuditSink(auditPath); +// Chain-head anchoring (ADR-0007): both settings together or neither; the anchor path should live +// on an independent storage domain — that placement is the entire security value. +string? anchorPath = builder.Configuration["Audit:AnchorPath"]; +int anchorEvery = OptionalNonNegativeInt("Audit:AnchorEvery", 0); +if (string.IsNullOrWhiteSpace(anchorPath)) anchorPath = null; +if ((anchorPath is null) != (anchorEvery == 0)) + configErrors.Add("Audit:AnchorPath / Audit:AnchorEvery — set both to enable anchoring, or neither"); +FailIfConfigErrors(); + +var auditSink = new FileAuditSink(auditPath, anchorPath, anchorEvery); var killSwitch = new KillSwitch(); var spendLedger = new InMemorySpendLedger(); // Budgets survive restarts: replay the audit log (event store) into the ledger (projection). // A tampered chain at boot is fail-closed — never serve on top of corrupted evidence. -var (chainAtBoot, priorEntries) = AuditChainVerifier.VerifyAndRead(auditPath); +var (chainAtBoot, priorEntries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); if (!chainAtBoot.Valid) { Console.Error.WriteLine( @@ -238,7 +247,8 @@ void FailIfConfigErrors() auditPath, neo4jUri, builder.Configuration["Neo4j:User"] ?? "neo4j", - builder.Configuration["Neo4j:Password"] ?? "")); + builder.Configuration["Neo4j:Password"] ?? "", + anchorPath)); } var app = builder.Build(); @@ -426,7 +436,7 @@ IResult Unauthorized() => Results.Json( { if (!Authorized(http)) return Unauthorized(); - var report = EvidenceExport.Build(auditPath, TimeProvider.System); + var report = EvidenceExport.Build(auditPath, TimeProvider.System, anchorPath); return Results.Json(report, CovenantJsonContext.Default.EvidenceReport); }); @@ -436,7 +446,7 @@ IResult Unauthorized() => Results.Json( StatusReport BuildStatus() { - var (verification, entries) = AuditChainVerifier.VerifyAndRead(auditPath); + var (verification, entries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); var teamSpend = spendLedger.SnapshotByTeam(); var teams = new List(); diff --git a/tests/Covenant.Tests/AnchorTests.cs b/tests/Covenant.Tests/AnchorTests.cs new file mode 100644 index 0000000..9f12841 --- /dev/null +++ b/tests/Covenant.Tests/AnchorTests.cs @@ -0,0 +1,112 @@ +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// ADR-0007 guarantees: end-truncation past an anchor is detected (the gap the plain chain cannot see), anchor tampering is detected, rotation archives both files, and no anchors = unchanged behavior. +public sealed class AnchorTests : IDisposable +{ + private readonly string _log = Path.Combine(Path.GetTempPath(), $"covenant-anchor-test-{Guid.NewGuid():n}.log"); + private readonly string _anchors; + + public AnchorTests() => _anchors = _log + ".anchors"; + + public void Dispose() + { + foreach (var f in new[] { _log, _anchors }) + if (File.Exists(f)) File.Delete(f); + foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(_log) + "*.archived")) + File.Delete(f); + foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(_anchors) + "*.archived")) + File.Delete(f); + } + + private static AuditEntry Entry(string id) => + new(id, DateTimeOffset.UtcNow, "tester", new AttributionTags("platform", "w", "u"), + DataClassification.Internal, PolicyEffect.Allow, "allowed", "gpt-4o-mini", new Usage(10, 5, 0.001m)); + + private async Task Write(int count, int anchorEvery) + { + var sink = new FileAuditSink(_log, _anchors, anchorEvery); + await sink.StartAsync(default); + for (int i = 0; i < count; i++) await sink.EnqueueAsync(Entry($"e{i}")); + await sink.StopAsync(default); + return sink; + } + + [Fact] + public async Task End_truncation_is_invisible_to_the_plain_chain_but_caught_by_anchors() + { + await Write(4, anchorEvery: 2); // anchors at entries 2 and 4 + + var lines = await File.ReadAllLinesAsync(_log); + await File.WriteAllLinesAsync(_log, lines.Take(3)); // silently drop the last entry + + var (plain, _) = AuditChainVerifier.VerifyAndRead(_log); + Assert.True(plain.Valid); // the documented blind spot… + + var (anchored, _) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + Assert.False(anchored.Valid); // …closed by ADR-0007 + Assert.Contains("truncated", anchored.Failure); + } + + [Fact] + public async Task Rewritten_history_with_forged_log_hashes_is_caught_by_the_anchor_hash() + { + await Write(2, anchorEvery: 1); + + // Rewrite the whole log coherently (valid chain, different content) — only the anchor knows. + File.Delete(_log); + var sink = new FileAuditSink(_log); // no anchors: writes a fresh valid chain + await sink.StartAsync(default); + await sink.EnqueueAsync(Entry("forged-1")); + await sink.EnqueueAsync(Entry("forged-2")); + await sink.StopAsync(default); + + var (verification, _) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + + Assert.False(verification.Valid); + Assert.Contains("hash mismatch", verification.Failure); + } + + [Fact] + public async Task Rotation_archives_log_and_anchor_file_together() + { + var sink = await Write(2, anchorEvery: 1); + + var archived = await sink.RotateAsync(); + + Assert.NotNull(archived); + Assert.False(File.Exists(_log)); + Assert.False(File.Exists(_anchors)); // anchors retire with their chain + Assert.True(File.Exists(archived)); + } + + [Fact] + public async Task Anchor_cadence_only_anchors_every_nth_entry() + { + await Write(5, anchorEvery: 2); + + var anchors = (await File.ReadAllLinesAsync(_anchors)).Where(l => !string.IsNullOrWhiteSpace(l)).ToList(); + + Assert.Equal(2, anchors.Count); // at entries 2 and 4; entry 5 unanchored + Assert.StartsWith("2\t", anchors[0]); + Assert.StartsWith("4\t", anchors[1]); + } + + [Fact] + public async Task Without_anchors_configured_verification_behaves_as_before() + { + var sink = new FileAuditSink(_log); + await sink.StartAsync(default); + await sink.EnqueueAsync(Entry("a")); + await sink.StopAsync(default); + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, anchorPath: null); + + Assert.True(verification.Valid); + Assert.Single(entries); + Assert.False(File.Exists(_anchors)); + } +} From 9a6adc31cd2ad354333353e1eb67f0b55ed63f02 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 22:15:13 -0400 Subject: [PATCH 2/8] fix: verifier findings on anchoring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - anchor failure now returns ZERO trusted entries (a coherent forgery has no trustworthy prefix); the graph projector gates on verification validity instead of discarding it — forged history can no longer be projected or aggregated - audit log write failure halts the appliance (FailFast) — serving without evidence is the thing this product exists to prevent; anchor write failure warns loudly and widens exposure by one cadence only, never killing the primary drain - rotation archives stale anchors even when the log is missing - anchor monotonicity enforced (tamper tell on the anchor file itself) - tests: restart continuity, anchors-without-log, malformed anchors, anchor-archive-not-deleted --- src/Covenant.Host/AuditChain.cs | 2 +- src/Covenant.Host/Evidence.cs | 18 ++++++++---- src/Covenant.Host/EvidenceGraph.cs | 8 ++++-- src/Covenant.Host/FileAuditSink.cs | 38 ++++++++++++++++++++----- src/Covenant.Host/Program.cs | 3 +- tests/Covenant.Tests/AnchorTests.cs | 43 +++++++++++++++++++++++++++++ 6 files changed, 96 insertions(+), 16 deletions(-) diff --git a/src/Covenant.Host/AuditChain.cs b/src/Covenant.Host/AuditChain.cs index 7ad3b3b..9ecc53c 100644 --- a/src/Covenant.Host/AuditChain.cs +++ b/src/Covenant.Host/AuditChain.cs @@ -4,7 +4,7 @@ namespace Covenant.Host; /// Hash-chain primitives shared by writer and verifier: line = {previousHash}\t{entryHash}\t{contentJson}, entryHash = SHA256(previousHash + contentJson); altering, removing, or reordering any past line breaks every hash after it. -/// Known limit (deliberate, first slice): truncation from the END is NOT detectable from the file alone — needs external chain-head anchoring (WORM / notarization), the audit-store ADR. +/// Truncation from the END is not detectable from the file alone — closed by opt-in chain-head anchoring (ADR-0007, Audit:AnchorPath). public static class AuditChain { public const char Separator = '\t'; diff --git a/src/Covenant.Host/Evidence.cs b/src/Covenant.Host/Evidence.cs index e24b49d..6efb991 100644 --- a/src/Covenant.Host/Evidence.cs +++ b/src/Covenant.Host/Evidence.cs @@ -59,7 +59,10 @@ public static (ChainVerification Verification, IReadOnlyList Entries if (anchorPath is not null && File.Exists(anchorPath)) { + // Anchor failure ⇒ the log itself may be a coherent forgery, so NO prefix is trustworthy: + // fail closed with an EMPTY entry list (unlike chain-walk breaks, whose prefix is hash-verified). int anchorNo = 0; + long lastCount = 0; foreach (var line in File.ReadLines(anchorPath)) { if (string.IsNullOrWhiteSpace(line)) continue; @@ -67,15 +70,20 @@ public static (ChainVerification Verification, IReadOnlyList Entries var parts = line.Split(AuditChain.Separator, 3); if (parts.Length != 3 || !long.TryParse(parts[0], out var anchoredCount) || anchoredCount < 1) - return (ChainVerification.Broken(entries.Count, anchorNo, $"malformed anchor #{anchorNo}"), entries); + return (ChainVerification.Broken(0, anchorNo, $"malformed anchor at anchor-file line {anchorNo}"), []); + + if (anchoredCount <= lastCount) + return (ChainVerification.Broken(0, anchorNo, + $"anchor sequence not increasing at anchor-file line {anchorNo} (anchor file tampered)"), []); + lastCount = anchoredCount; if (anchoredCount > entries.Count) - return (ChainVerification.Broken(entries.Count, anchorNo, - $"log truncated: anchor #{anchorNo} attests {anchoredCount} entries, log has {entries.Count}"), entries); + return (ChainVerification.Broken(0, anchorNo, + $"log truncated: anchor at anchor-file line {anchorNo} attests {anchoredCount} entries, log has {entries.Count}"), []); if (!string.Equals(hashes[(int)anchoredCount - 1], parts[1], StringComparison.Ordinal)) - return (ChainVerification.Broken(entries.Count, anchorNo, - $"anchor #{anchorNo} hash mismatch at entry {anchoredCount} (history rewritten)"), entries); + return (ChainVerification.Broken(0, anchorNo, + $"anchor hash mismatch at entry {anchoredCount} (anchor-file line {anchorNo}: history rewritten)"), []); } } diff --git a/src/Covenant.Host/EvidenceGraph.cs b/src/Covenant.Host/EvidenceGraph.cs index 6609465..f726438 100644 --- a/src/Covenant.Host/EvidenceGraph.cs +++ b/src/Covenant.Host/EvidenceGraph.cs @@ -42,8 +42,12 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) try { // Only verified prefix is projected — nothing past a chain break enters the graph. - var (_, entries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); - if (entries.Count > _projected) + var (verification, entries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); + if (!verification.Valid) + { + // Fail closed: nothing unverified enters the graph; retry next cycle. + } + else if (entries.Count > _projected) { var batch = ToParameters(entries.Skip(_projected).ToList()); await using var session = driver.AsyncSession(); diff --git a/src/Covenant.Host/FileAuditSink.cs b/src/Covenant.Host/FileAuditSink.cs index 5a8d474..840e697 100644 --- a/src/Covenant.Host/FileAuditSink.cs +++ b/src/Covenant.Host/FileAuditSink.cs @@ -55,14 +55,33 @@ private async Task DrainAsync() { var content = JsonSerializer.Serialize(entry, AuditJsonContext.Default.AuditEntry); var entryHash = AuditChain.Hash(_previousHash, content); - await File.AppendAllTextAsync(path, - $"{_previousHash}{AuditChain.Separator}{entryHash}{AuditChain.Separator}{content}{Environment.NewLine}"); + try + { + await File.AppendAllTextAsync(path, + $"{_previousHash}{AuditChain.Separator}{entryHash}{AuditChain.Separator}{content}{Environment.NewLine}"); + } + catch (Exception ex) + { + // Fail-closed: an appliance that cannot write evidence must not keep serving. + Environment.FailFast($"covenant: audit log write failed ({ex.Message}) — halting rather than serving unaudited."); + } _previousHash = entryHash; _count++; if (anchorEvery > 0 && anchorPath is not null && _count % anchorEvery == 0) - await File.AppendAllTextAsync(anchorPath, - $"{_count}{AuditChain.Separator}{entryHash}{AuditChain.Separator}{DateTimeOffset.UtcNow:o}{Environment.NewLine}"); + { + try + { + await File.AppendAllTextAsync(anchorPath, + $"{_count}{AuditChain.Separator}{entryHash}{AuditChain.Separator}{DateTimeOffset.UtcNow:o}{Environment.NewLine}"); + } + catch (Exception ex) + { + // A missed anchor only widens exposure by one cadence (verification stays sound); + // surface loudly, never let the anchor volume kill the primary drain. + Console.Error.WriteLine($"covenant: WARNING — anchor write to '{anchorPath}' failed ({ex.Message}); exposure widened by one cadence."); + } + } } finally { @@ -77,10 +96,15 @@ await File.AppendAllTextAsync(anchorPath, await _fileLock.WaitAsync(); try { - if (!File.Exists(path)) return null; var stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); - var archive = $"{path}.{stamp}.archived"; - File.Move(path, archive); + string? archive = null; + if (File.Exists(path)) + { + archive = $"{path}.{stamp}.archived"; + File.Move(path, archive); + } + // Archive anchors even when the log is absent (out-of-band deletion): otherwise stale + // anchors would fail verification forever with no sanctioned recovery path. if (anchorPath is not null && File.Exists(anchorPath)) File.Move(anchorPath, $"{anchorPath}.{stamp}.archived"); _previousHash = AuditChain.GenesisHash; diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index e418f9e..a69d1ed 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -188,7 +188,8 @@ void FailIfConfigErrors() var rateCounterTeams = new RateCounter(); int promptPreviewChars = OptionalNonNegativeInt("Audit:PromptPreviewChars", 0); -// Second gate: every later section (pricing, routing, cache, rate limits, preview) has parsed by now. +// Second gate: pricing, routing, cache, rate limits, and preview have parsed by now (anchoring +// parses just below and has its own gate before sink construction). FailIfConfigErrors(); // Chain-head anchoring (ADR-0007): both settings together or neither; the anchor path should live diff --git a/tests/Covenant.Tests/AnchorTests.cs b/tests/Covenant.Tests/AnchorTests.cs index 9f12841..79ce3ad 100644 --- a/tests/Covenant.Tests/AnchorTests.cs +++ b/tests/Covenant.Tests/AnchorTests.cs @@ -81,6 +81,49 @@ public async Task Rotation_archives_log_and_anchor_file_together() Assert.False(File.Exists(_log)); Assert.False(File.Exists(_anchors)); // anchors retire with their chain Assert.True(File.Exists(archived)); + Assert.NotEmpty(Directory.GetFiles(Path.GetTempPath(), // archived, not deleted — + Path.GetFileName(_anchors) + ".*.archived")); // evidence retires, it doesn't die + } + + [Fact] + public async Task Anchoring_continues_correctly_across_restarts() + { + await Write(3, anchorEvery: 2); // anchor at 2 + await Write(1, anchorEvery: 2); // new sink instance = restart; entry 4 → anchor at 4 + + var anchors = (await File.ReadAllLinesAsync(_anchors)).Where(l => !string.IsNullOrWhiteSpace(l)).ToList(); + Assert.Equal(2, anchors.Count); + Assert.StartsWith("4\t", anchors[1]); // count resumed, not restarted + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + Assert.True(verification.Valid); + Assert.Equal(4, entries.Count); + } + + [Fact] + public async Task Anchors_without_a_log_fail_verification_with_no_trusted_entries() + { + await Write(2, anchorEvery: 1); + File.Delete(_log); // the strongest attack: fresh start + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + + Assert.False(verification.Valid); + Assert.Contains("truncated", verification.Failure); + Assert.Empty(entries); // nothing is trusted + } + + [Fact] + public async Task Malformed_anchor_file_fails_closed() + { + await Write(2, anchorEvery: 1); + await File.AppendAllTextAsync(_anchors, "not-a-number\tdeadbeef\tgarbage\n"); + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + + Assert.False(verification.Valid); + Assert.Contains("malformed anchor", verification.Failure); + Assert.Empty(entries); } [Fact] From 6fc8255375e239c63a2783e1d1cf492ae825d7c0 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 22:19:56 -0400 Subject: [PATCH 3/8] fix: anchors are checked even when the chain walk breaks; monotonicity + empty-return tests A forged prefix ending in a deliberate break can no longer dodge anchor comparison: anchors within the verified prefix are always evaluated, and any contradiction returns zero trusted entries. Doc comments updated; tests pin monotonicity, the empty-return contract on hash mismatch, and the walk-break-dodge attack. --- src/Covenant.Host/Evidence.cs | 36 ++++++++++++++++++--------- src/Covenant.Host/Program.cs | 3 ++- tests/Covenant.Tests/AnchorTests.cs | 38 ++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/Covenant.Host/Evidence.cs b/src/Covenant.Host/Evidence.cs index 6efb991..eda0d43 100644 --- a/src/Covenant.Host/Evidence.cs +++ b/src/Covenant.Host/Evidence.cs @@ -12,18 +12,22 @@ public sealed record ChainVerification(bool Valid, int EntryCount, int? FirstInv } /// Re-walks the log recomputing every hash (format in AuditChain): detects edits, forged hashes, -/// removed/reordered lines, mid-file restarts. Entries return only up to the first invalid line. +/// removed/reordered lines, mid-file restarts; anchored verification adds truncation and whole-log +/// rewrites. Walk break → hash-verified prefix returned; anchor contradiction → empty (nothing trusted). public static class AuditChainVerifier { public static (ChainVerification Verification, IReadOnlyList Entries) VerifyAndRead(string path) => VerifyAndRead(path, anchorPath: null); /// With an anchor path (ADR-0007), the log must contain every anchored count with exactly - /// the anchored head hash at that position — end-truncation past any anchor fails verification. + /// the anchored head hash at that position — end-truncation past any anchor fails verification. + /// On a chain-walk break the hash-verified prefix is returned (after anchors within the prefix are + /// checked); on any anchor contradiction NOTHING is trusted — entries come back empty. public static (ChainVerification Verification, IReadOnlyList Entries) VerifyAndRead(string path, string? anchorPath) { var entries = new List(); var hashes = new List(); + ChainVerification walk = ChainVerification.Ok(0); if (File.Exists(path)) { @@ -37,30 +41,32 @@ public static (ChainVerification Verification, IReadOnlyList Entries var parts = line.Split(AuditChain.Separator, 3); if (parts.Length != 3) - return (ChainVerification.Broken(entries.Count, lineNo, "malformed line"), entries); + { walk = ChainVerification.Broken(entries.Count, lineNo, "malformed line"); break; } var (prevHash, entryHash, content) = (parts[0], parts[1], parts[2]); if (!string.Equals(prevHash, previous, StringComparison.Ordinal)) - return (ChainVerification.Broken(entries.Count, lineNo, "chain link mismatch (removed, reordered, or restarted)"), entries); + { walk = ChainVerification.Broken(entries.Count, lineNo, "chain link mismatch (removed, reordered, or restarted)"); break; } if (!string.Equals(entryHash, AuditChain.Hash(previous, content), StringComparison.Ordinal)) - return (ChainVerification.Broken(entries.Count, lineNo, "content hash mismatch (entry altered)"), entries); + { walk = ChainVerification.Broken(entries.Count, lineNo, "content hash mismatch (entry altered)"); break; } var entry = JsonSerializer.Deserialize(content, AuditJsonContext.Default.AuditEntry); if (entry is null) - return (ChainVerification.Broken(entries.Count, lineNo, "entry is not valid JSON"), entries); + { walk = ChainVerification.Broken(entries.Count, lineNo, "entry is not valid JSON"); break; } entries.Add(entry); hashes.Add(entryHash); previous = entryHash; } + + if (walk.Valid) walk = ChainVerification.Ok(entries.Count); } + // Anchors are checked even when the walk broke: a forged prefix ending in a deliberate break + // must not dodge anchor comparison. Any anchor contradiction ⇒ no prefix is trustworthy. if (anchorPath is not null && File.Exists(anchorPath)) { - // Anchor failure ⇒ the log itself may be a coherent forgery, so NO prefix is trustworthy: - // fail closed with an EMPTY entry list (unlike chain-walk breaks, whose prefix is hash-verified). int anchorNo = 0; long lastCount = 0; foreach (var line in File.ReadLines(anchorPath)) @@ -77,9 +83,15 @@ public static (ChainVerification Verification, IReadOnlyList Entries $"anchor sequence not increasing at anchor-file line {anchorNo} (anchor file tampered)"), []); lastCount = anchoredCount; - if (anchoredCount > entries.Count) - return (ChainVerification.Broken(0, anchorNo, - $"log truncated: anchor at anchor-file line {anchorNo} attests {anchoredCount} entries, log has {entries.Count}"), []); + if (anchoredCount > hashes.Count) + { + // Beyond the verified prefix: with a valid walk this is truncation; with a broken + // walk it is unevaluable (the walk break already fails verification) — skip. + if (walk.Valid) + return (ChainVerification.Broken(0, anchorNo, + $"log truncated: anchor at anchor-file line {anchorNo} attests {anchoredCount} entries, log has {hashes.Count}"), []); + continue; + } if (!string.Equals(hashes[(int)anchoredCount - 1], parts[1], StringComparison.Ordinal)) return (ChainVerification.Broken(0, anchorNo, @@ -87,7 +99,7 @@ public static (ChainVerification Verification, IReadOnlyList Entries } } - return (ChainVerification.Ok(entries.Count), entries); + return (walk, entries); } } diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index a69d1ed..44951c0 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -71,7 +71,8 @@ int OptionalNonNegativeInt(string key, int fallback) if (apiKeys.Count == 0 && !allowAnonymous) configErrors.Add("Auth — no API keys configured and Auth:AllowAnonymous is not 'true' (fail-closed: unauthenticated serving must be an explicit choice)"); -// Fail-closed refusal, printed as a diagnostic (never a crash). Called twice: before provider-client +// Fail-closed refusal, printed as a diagnostic (never a crash). Called after each config region — +// the first gate sits before provider-client // construction (which would throw on a missing key) and again after ALL config sections have parsed. void FailIfConfigErrors() { diff --git a/tests/Covenant.Tests/AnchorTests.cs b/tests/Covenant.Tests/AnchorTests.cs index 79ce3ad..eea1312 100644 --- a/tests/Covenant.Tests/AnchorTests.cs +++ b/tests/Covenant.Tests/AnchorTests.cs @@ -64,10 +64,46 @@ public async Task Rewritten_history_with_forged_log_hashes_is_caught_by_the_anch await sink.EnqueueAsync(Entry("forged-2")); await sink.StopAsync(default); - var (verification, _) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); Assert.False(verification.Valid); Assert.Contains("hash mismatch", verification.Failure); + Assert.Empty(entries); // a coherent forgery has no trusted prefix + } + + [Fact] + public async Task Non_increasing_anchor_sequence_fails_closed() + { + await Write(2, anchorEvery: 1); + var lines = await File.ReadAllLinesAsync(_anchors); + await File.AppendAllTextAsync(_anchors, lines[0] + Environment.NewLine); // replayed anchor + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + + Assert.False(verification.Valid); + Assert.Contains("not increasing", verification.Failure); + Assert.Empty(entries); + } + + [Fact] + public async Task Forged_prefix_ending_in_a_deliberate_break_cannot_dodge_anchor_comparison() + { + await Write(2, anchorEvery: 1); + + // Rewrite the log as a coherent forgery, then append one garbage line so the walk breaks + // before reaching the end — pre-fix, anchors were skipped and the forged prefix trusted. + File.Delete(_log); + var sink = new FileAuditSink(_log); + await sink.StartAsync(default); + await sink.EnqueueAsync(Entry("forged-1")); + await sink.EnqueueAsync(Entry("forged-2")); + await sink.StopAsync(default); + await File.AppendAllTextAsync(_log, "garbage line" + Environment.NewLine); + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + + Assert.False(verification.Valid); + Assert.Empty(entries); // anchors contradict the forged prefix } [Fact] From 51a4df85c02ef10213a21e5500135c9623ec75b9 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 22:50:56 -0400 Subject: [PATCH 4/8] feat: Anthropic provider + /v1/messages ingress (ADR-0001 start set) Official Anthropic SDK over IChatClient, opt-in via Anthropic:ApiKey; the configured model joins the permitted set mid-list (explicit request only, never default escalation). The /v1/messages dialect works with or without the provider: x-api-key auth, string-or-block content normalization, Anthropic error taxonomy on every denial path, Messages SSE event protocol with lazy header commit. One pipeline, two dialects, cross-protocol routing (Anthropic wire in, any permitted adapter out). Tests +10: wire mapping (content forms, system, roles, response shape, error taxonomy table) and integration (401/403/502 shapes, PII fail- closed, streamed pre-flight denial stays JSON, cross-protocol route). --- README-SCAFFOLD.md | 10 ++ docs/PROVENANCE.md | 1 + src/Covenant.Host/AnthropicContracts.cs | 140 ++++++++++++++++ src/Covenant.Host/Covenant.Host.csproj | 2 + src/Covenant.Host/Program.cs | 111 ++++++++++++- tests/Covenant.Tests/AnthropicIngressTests.cs | 113 +++++++++++++ tests/Covenant.Tests/AnthropicWireTests.cs | 153 ++++++++++++++++++ 7 files changed, 527 insertions(+), 3 deletions(-) create mode 100644 src/Covenant.Host/AnthropicContracts.cs create mode 100644 tests/Covenant.Tests/AnthropicIngressTests.cs create mode 100644 tests/Covenant.Tests/AnthropicWireTests.cs diff --git a/README-SCAFFOLD.md b/README-SCAFFOLD.md index 5178ee4..19e6580 100644 --- a/README-SCAFFOLD.md +++ b/README-SCAFFOLD.md @@ -68,6 +68,16 @@ dotnet user-secrets set "Local:Endpoint" "http://localhost:11434/v1" --project s dotnet user-secrets set "Local:ModelId" "llama3.1:8b" --project src/Covenant.Host ``` +Optional Anthropic provider + dialect: `/v1/messages` (Anthropic wire, `x-api-key` auth, Messages SSE +protocol) works regardless — same pipeline, same governance, Anthropic's error taxonomy. To also +ROUTE to Claude models: +``` +dotnet user-secrets set "Anthropic:ApiKey" "" --project src/Covenant.Host +dotnet user-secrets set "Anthropic:ModelId" "claude-haiku-4-5" --project src/Covenant.Host +``` +Configured, the model joins the Public/Internal permitted set (mid-list: reachable by explicit +request, never the default escalation). Anthropic clients then work unchanged against Covenant. + Pricing: defaults are real per-1M rates (gpt-4o-mini $0.15/$0.60, gpt-4o $2.50/$10.00) converted internally to per-1K. Override per model when providers change prices: `dotnet user-secrets set "Pricing:gpt-4o-mini:InPer1M" "0.15" ...` (+ `OutPer1M`). diff --git a/docs/PROVENANCE.md b/docs/PROVENANCE.md index fdefc62..f30c22e 100644 --- a/docs/PROVENANCE.md +++ b/docs/PROVENANCE.md @@ -21,5 +21,6 @@ No third-party source code has been copied into this repository. Everything belo - Test-only: `xunit` 2.9.3 (Apache-2.0), `xunit.runner.visualstudio` 3.1.5 (Apache-2.0), `Microsoft.NET.Test.Sdk` 18.7.0 (MIT). Never shipped in the appliance. - `OpenTelemetry.Extensions.Hosting` / `OpenTelemetry.Exporter.OpenTelemetryProtocol` 1.17.0 — Apache-2.0. Host-only, activated only when `Otel:Endpoint` is configured (ADR-0003). Core instruments via BCL `ActivitySource` and takes no OTel dependency. - `Neo4j.Driver` 6.2.1 — Apache-2.0, official Bolt driver. Host-only, activated only when `Neo4j:Uri` is configured (ADR-0006 evidence graph projection). +- `Anthropic` 12.8.0 — MIT, official Anthropic SDK (IChatClient integration). Host-only, activated only when `Anthropic:ApiKey` is configured (ADR-0001 provider start set). _Update this file in the same change as any code that introduces a new influence or dependency._ diff --git a/src/Covenant.Host/AnthropicContracts.cs b/src/Covenant.Host/AnthropicContracts.cs new file mode 100644 index 0000000..33ba2df --- /dev/null +++ b/src/Covenant.Host/AnthropicContracts.cs @@ -0,0 +1,140 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Covenant.Core; + +namespace Covenant.Host; + +// Anthropic Messages API wire shapes (/v1/messages) — the second ingress dialect (ADR-0001 start set). +// Content fields are string-or-block-array in the protocol, so they bind as JsonElement and normalize +// through AnthropicWire. First slice speaks text blocks; tool_use/multimodal are not yet parsed. + +public sealed class AnthropicMessagesRequest +{ + [JsonPropertyName("model")] public string? Model { get; set; } + [JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; } // accepted; not yet forwarded + [JsonPropertyName("stream")] public bool? Stream { get; set; } + [JsonPropertyName("system")] public JsonElement? System { get; set; } + [JsonPropertyName("messages")] public List Messages { get; set; } = []; +} + +public sealed class AnthropicWireMessage +{ + [JsonPropertyName("role")] public string Role { get; set; } = "user"; + [JsonPropertyName("content")] public JsonElement Content { get; set; } +} + +public sealed class AnthropicTextBlock +{ + [JsonPropertyName("type")] public string Type { get; set; } = "text"; + [JsonPropertyName("text")] public string Text { get; set; } = ""; +} + +public sealed class AnthropicUsage +{ + [JsonPropertyName("input_tokens")] public long InputTokens { get; set; } + [JsonPropertyName("output_tokens")] public long OutputTokens { get; set; } +} + +public sealed class AnthropicMessageResponse +{ + [JsonPropertyName("id")] public string Id { get; set; } = ""; + [JsonPropertyName("type")] public string Type { get; set; } = "message"; + [JsonPropertyName("role")] public string Role { get; set; } = "assistant"; + [JsonPropertyName("model")] public string Model { get; set; } = ""; + [JsonPropertyName("content")] public List Content { get; set; } = []; + [JsonPropertyName("stop_reason")] public string? StopReason { get; set; } + [JsonPropertyName("stop_sequence")] public string? StopSequence { get; set; } + [JsonPropertyName("usage")] public AnthropicUsage Usage { get; set; } = new(); +} + +public sealed class AnthropicErrorResponse +{ + [JsonPropertyName("type")] public string Type { get; set; } = "error"; + [JsonPropertyName("error")] public AnthropicErrorBody Error { get; set; } = new(); +} + +public sealed class AnthropicErrorBody +{ + [JsonPropertyName("type")] public string Type { get; set; } = "invalid_request_error"; + [JsonPropertyName("message")] public string Message { get; set; } = ""; +} + +[JsonSerializable(typeof(AnthropicMessagesRequest))] +[JsonSerializable(typeof(AnthropicMessageResponse))] +[JsonSerializable(typeof(AnthropicErrorResponse))] +public partial class CovenantJsonContext; + +/// Pure Anthropic-wire ↔ canonical mapping — unit-tested without a server. +public static class AnthropicWire +{ + /// Normalizes string-or-block-array content to plain text; non-text blocks are ignored. + public static string ExtractText(JsonElement content) => content.ValueKind switch + { + JsonValueKind.String => content.GetString() ?? "", + JsonValueKind.Array => string.Concat( + content.EnumerateArray() + .Where(b => b.ValueKind == JsonValueKind.Object + && b.TryGetProperty("type", out var t) && t.GetString() == "text" + && b.TryGetProperty("text", out _)) + .Select(b => b.GetProperty("text").GetString() ?? "")), + _ => "", + }; + + public static List ToCanonical(AnthropicMessagesRequest request) + { + var messages = new List(); + if (request.System is { } sys && ExtractText(sys) is { Length: > 0 } sysText) + messages.Add(new ChatMessage(ChatRole.System, sysText)); + foreach (var m in request.Messages) + messages.Add(new ChatMessage( + string.Equals(m.Role, "assistant", StringComparison.OrdinalIgnoreCase) ? ChatRole.Assistant : ChatRole.User, + ExtractText(m.Content))); + return messages; + } + + public static AnthropicMessageResponse BuildResponse(string id, InferenceResponse response) => new() + { + Id = id, + Model = response.ServedByModel, + Content = [new AnthropicTextBlock { Text = response.Message.Content }], + StopReason = "end_turn", + Usage = new AnthropicUsage + { + InputTokens = response.Usage.InputTokens, + OutputTokens = response.Usage.OutputTokens, + }, + }; + + /// Denial kinds → Anthropic error taxonomy + HTTP status (matches the API's own table). + public static (string ErrorType, int Status) MapDenial(DenialKind kind) => kind switch + { + DenialKind.Unauthenticated => ("authentication_error", StatusCodes.Status401Unauthorized), + DenialKind.RateLimited => ("rate_limit_error", StatusCodes.Status429TooManyRequests), + DenialKind.UpstreamFailure => ("api_error", StatusCodes.Status502BadGateway), + _ => ("permission_error", StatusCodes.Status403Forbidden), + }; + + // Messages-API SSE event payloads, hand-built (source-gen contexts don't cover partial stream frames). + // JsonEncodedText escapes interpolated values, so model ids and delta text can't break the JSON. + // These are pure so the wire format is unit-tested by parsing, not proven only in a live stream. + private static string J(string s) => System.Text.Json.JsonEncodedText.Encode(s).ToString(); + + public static string MessageStartEvent(string id, string model) => + $"{{\"type\":\"message_start\",\"message\":{{\"id\":\"{J(id)}\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"{J(model)}\",\"content\":[],\"stop_reason\":null,\"usage\":{{\"input_tokens\":0,\"output_tokens\":0}}}}}}"; + + public const string ContentBlockStartEvent = + "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}"; + + public static string ContentBlockDeltaEvent(string text) => + $"{{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{{\"type\":\"text_delta\",\"text\":\"{J(text)}\"}}}}"; + + public const string ContentBlockStopEvent = "{\"type\":\"content_block_stop\",\"index\":0}"; + + public static string MessageDeltaEvent(long outputTokens) => + $"{{\"type\":\"message_delta\",\"delta\":{{\"stop_reason\":\"end_turn\",\"stop_sequence\":null}},\"usage\":{{\"output_tokens\":{outputTokens}}}}}"; + + public const string MessageStopEvent = "{\"type\":\"message_stop\"}"; + + public static string ErrorEvent(string errorType, string message) => + $"{{\"type\":\"error\",\"error\":{{\"type\":\"{J(errorType)}\",\"message\":\"{J(message)}\"}}}}"; +} diff --git a/src/Covenant.Host/Covenant.Host.csproj b/src/Covenant.Host/Covenant.Host.csproj index ca27d00..201ad85 100644 --- a/src/Covenant.Host/Covenant.Host.csproj +++ b/src/Covenant.Host/Covenant.Host.csproj @@ -27,6 +27,8 @@ + + diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index 44951c0..ef47e9d 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -1,5 +1,7 @@ using System.ClientModel; using System.Globalization; +using System.Text.Json; +using Anthropic; using System.Security.Cryptography; using System.Text; using Covenant.Adapters; @@ -136,16 +138,33 @@ void FailIfConfigErrors() .AsIChatClient(); } +// Optional Anthropic provider (ADR-0001 start set) — official SDK over IChatClient, opt-in via key. +string anthropicModelId = builder.Configuration["Anthropic:ModelId"] ?? "claude-haiku-4-5"; +bool anthropicEnabled = false; +if (builder.Configuration["Anthropic:ApiKey"] is { Length: > 0 } anthropicKey) +{ + anthropicEnabled = true; + var anthropicClient = builder.Configuration["Anthropic:Endpoint"] is { Length: > 0 } anthropicEndpoint + ? new AnthropicClient { ApiKey = anthropicKey, BaseUrl = anthropicEndpoint } + : new AnthropicClient { ApiKey = anthropicKey }; + clients[$"anthropic:{anthropicModelId}"] = anthropicClient.AsIChatClient(anthropicModelId); +} + var registry = new ChatClientRegistry(clients); // --- Policy (first slice): PII/PHI have no public route, so they fail closed until "local" is wired. --- +// Ordered cheapest → strongest: the policy engine complexity-routes within this set. Anthropic (when +// configured) sits mid-list: reachable by explicit model request, never the default escalation. +List generalRoutes = [new("openai", publicModelId)]; +if (anthropicEnabled) generalRoutes.Add(new("anthropic", anthropicModelId)); +generalRoutes.Add(new("openai", strongModelId)); + var policy = new PolicyConfig { AllowedRoutes = new Dictionary> { - // Ordered cheapest → strongest: the policy engine complexity-routes within this set. - [DataClassification.Public] = [new("openai", publicModelId), new("openai", strongModelId)], - [DataClassification.Internal] = [new("openai", publicModelId), new("openai", strongModelId)], + [DataClassification.Public] = generalRoutes, + [DataClassification.Internal] = generalRoutes, [DataClassification.Pii] = [new("local", localModelId)], [DataClassification.Phi] = [new("local", localModelId)], } @@ -159,6 +178,7 @@ void FailIfConfigErrors() [strongModelId] = (0.0025m, 0.01m), // gpt-4o: $2.50 / $10.00 per 1M [localModelId] = (0m, 0m), // in-perimeter compute: no per-token provider cost }; +if (anthropicEnabled) priceMap[anthropicModelId] = (0.001m, 0.005m); // claude-haiku-4-5: $1 / $5 per 1M foreach (var child in builder.Configuration.GetSection("Pricing").GetChildren()) { if (decimal.TryParse(child["InPer1M"], NumberStyles.Number, CultureInfo.InvariantCulture, out var inPer1M) @@ -257,6 +277,81 @@ void FailIfConfigErrors() // Model discovery for OpenAI-compatible clients (Open WebUI, SDKs). Same auth semantics as chat: // a valid API key, or anonymous only if explicitly allowed. Only policy-permitted models are listed. +// Anthropic-dialect ingress (/v1/messages): same pipeline, same governance — only the wire differs. +// Anthropic clients authenticate with x-api-key (Bearer also accepted); errors use Anthropic's +// taxonomy; streaming speaks the Messages SSE event protocol with lazy header commit (pre-flight +// denials stay plain JSON). +app.MapPost("/v1/messages", async (AnthropicMessagesRequest body, InferencePipeline pipe, HttpContext http, CancellationToken ct) => +{ + string? credential = http.Request.Headers["x-api-key"].FirstOrDefault(); + if (string.IsNullOrEmpty(credential) + && http.Request.Headers.Authorization.FirstOrDefault() is { } authHeader + && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + credential = authHeader["Bearer ".Length..].Trim(); + + var principal = http.Request.Headers["X-Covenant-Principal"].FirstOrDefault() ?? "anonymous"; + var tags = new AttributionTags( + Team: http.Request.Headers["X-Covenant-Team"].FirstOrDefault() ?? "unknown", + Workflow: http.Request.Headers["X-Covenant-Workflow"].FirstOrDefault() ?? "unknown", + UseCase: http.Request.Headers["X-Covenant-UseCase"].FirstOrDefault() ?? "unknown"); + + var request = new InferenceRequest(principal, AnthropicWire.ToCanonical(body), body.Model, tags, + Stream: body.Stream == true, Credential: credential); + var ctx = new InferenceContext(request); + var msgId = $"msg_{Guid.NewGuid():n}"; + + if (request.Stream) + { + var resp = http.Response; + bool sseStarted = false; + + async ValueTask WriteEventAsync(string evt, string json, CancellationToken token) + { + await resp.WriteAsync($"event: {evt}\ndata: {json}\n\n", token); + await resp.Body.FlushAsync(token); + } + + ctx.DeltaSink = async (delta, token) => + { + if (!sseStarted) + { + sseStarted = true; + resp.StatusCode = StatusCodes.Status200OK; + resp.ContentType = "text/event-stream"; + resp.Headers.CacheControl = "no-cache"; + await WriteEventAsync("message_start", AnthropicWire.MessageStartEvent(msgId, ctx.Policy?.Route?.ModelId ?? ""), token); + await WriteEventAsync("content_block_start", AnthropicWire.ContentBlockStartEvent, token); + } + await WriteEventAsync("content_block_delta", AnthropicWire.ContentBlockDeltaEvent(delta.Content), token); + }; + + await pipe.ExecuteAsync(ctx, ct); + + if (!sseStarted) + return AnthropicDenial(ctx); // denied before the first byte — plain JSON error + + if (ctx.IsDenied) + { + var (streamErrType, _) = AnthropicWire.MapDenial(ctx.DenialKind); + await WriteEventAsync("error", AnthropicWire.ErrorEvent(streamErrType, ctx.DenialReason ?? "stream failed"), ct); + } + else if (ctx.Response is { } fin) + { + await WriteEventAsync("content_block_stop", AnthropicWire.ContentBlockStopEvent, ct); + await WriteEventAsync("message_delta", AnthropicWire.MessageDeltaEvent(fin.Usage.OutputTokens), ct); + await WriteEventAsync("message_stop", AnthropicWire.MessageStopEvent, ct); + } + return Results.Empty; + } + + await pipe.ExecuteAsync(ctx, ct); + + if (ctx.IsDenied || ctx.Response is null) + return AnthropicDenial(ctx); + + return Results.Json(AnthropicWire.BuildResponse(msgId, ctx.Response), CovenantJsonContext.Default.AnthropicMessageResponse); +}); + app.MapGet("/v1/models", (HttpContext http) => { string? cred = null; @@ -408,6 +503,16 @@ static IResult DenialResult(InferenceContext ctx) CovenantJsonContext.Default.ErrorResponse, statusCode: status); } +// Anthropic-dialect denial: same DenialKind semantics, Anthropic's error taxonomy and statuses. +static IResult AnthropicDenial(InferenceContext ctx) +{ + var (errType, status) = AnthropicWire.MapDenial(ctx.DenialKind); + return Results.Json(new AnthropicErrorResponse + { + Error = new AnthropicErrorBody { Type = errType, Message = ctx.DenialReason ?? "no response" } + }, CovenantJsonContext.Default.AnthropicErrorResponse, statusCode: status); +} + bool Authorized(HttpContext http) { var provided = http.Request.Headers["X-Covenant-Admin-Token"].FirstOrDefault() ?? string.Empty; diff --git a/tests/Covenant.Tests/AnthropicIngressTests.cs b/tests/Covenant.Tests/AnthropicIngressTests.cs new file mode 100644 index 0000000..dd60dc1 --- /dev/null +++ b/tests/Covenant.Tests/AnthropicIngressTests.cs @@ -0,0 +1,113 @@ +using System.Net; +using System.Text; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Xunit; + +namespace Covenant.Tests; + +/// The Anthropic dialect through the real Host: x-api-key auth, Anthropic error taxonomy on every denial path, and the cross-protocol case — Anthropic wire in, OpenAI-adapter route out. +public sealed class AnthropicIngressTests : IClassFixture>, IDisposable +{ + private readonly string _auditPath = Path.Combine(Path.GetTempPath(), $"covenant-anthropic-test-{Guid.NewGuid():n}.log"); + private readonly WebApplicationFactory _factory; + private readonly HttpClient _client; + + public AnthropicIngressTests(WebApplicationFactory factory) + { + // Anthropic:ApiKey deliberately NOT configured — the provider stays unwired, the DIALECT works. + _factory = factory.WithWebHostBuilder(b => + { + b.UseEnvironment("Production"); + b.UseSetting("OpenAI:ApiKey", "test-key"); + b.UseSetting("OpenAI:Endpoint", "http://127.0.0.1:9"); // unroutable → instant governed 502 + b.UseSetting("Admin:Token", "test-admin"); + b.UseSetting("Budget:GlobalCapUsd", "100"); + b.UseSetting("Auth:Keys:0:Key", "test-api-key"); + b.UseSetting("Auth:Keys:0:Principal", "itest"); + b.UseSetting("Auth:Keys:0:Team", "itest-team"); + b.UseSetting("Audit:Path", _auditPath); + }); + _client = _factory.CreateClient(); + _client.DefaultRequestHeaders.Add("x-api-key", "test-api-key"); // Anthropic-style auth header + } + + public void Dispose() + { + _factory.Dispose(); + if (File.Exists(_auditPath)) File.Delete(_auditPath); + } + + private static StringContent Messages(string content, string? model = null, bool stream = false) => + new($"{{\"model\":{(model is null ? "null" : $"\"{model}\"")},\"max_tokens\":100,\"stream\":{(stream ? "true" : "false")},\"messages\":[{{\"role\":\"user\",\"content\":\"{content}\"}}]}}", + Encoding.UTF8, "application/json"); + + [Fact] + public async Task Missing_key_is_401_in_anthropic_error_shape() + { + using var bare = _factory.CreateClient(); // no x-api-key + var resp = await bare.PostAsync("/v1/messages", Messages("hi")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.Unauthorized, resp.StatusCode); + Assert.Contains("authentication_error", json); + Assert.Contains("\"type\":\"error\"", json); + } + + [Fact] + public async Task Unpermitted_claude_model_is_403_permission_error() + { + // Anthropic provider unconfigured → claude models are not in the permitted set: fail-closed. + var resp = await _client.PostAsync("/v1/messages", Messages("hi", model: "claude-haiku-4-5")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + Assert.Contains("permission_error", json); + Assert.Contains("not permitted", json); + } + + [Fact] + public async Task Cross_protocol_anthropic_wire_reaches_the_openai_route_and_maps_upstream_failure() + { + // The point of one canonical model: Anthropic dialect in, OpenAI-adapter route out. + var resp = await _client.PostAsync("/v1/messages", Messages("hi", model: "gpt-4o-mini")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode); // unroutable upstream, governed + Assert.Contains("api_error", json); + } + + [Fact] + public async Task Pii_over_the_anthropic_dialect_fails_closed_with_permission_error() + { + var resp = await _client.PostAsync("/v1/messages", Messages("my SSN is 123-45-6789")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + Assert.Contains("permission_error", json); + } + + [Fact] + public async Task Streamed_preflight_denial_is_plain_json_not_sse() + { + var resp = await _client.PostAsync("/v1/messages", Messages("my SSN is 123-45-6789", stream: true)); + + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + Assert.NotEqual("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + Assert.Contains("permission_error", await resp.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Bearer_auth_is_accepted_as_a_fallback_on_the_anthropic_dialect() + { + using var bearer = _factory.CreateClient(); + bearer.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "test-api-key"); // no x-api-key + + var resp = await bearer.PostAsync("/v1/messages", Messages("hi", model: "gpt-4o-mini")); + + // Authenticated (not 401): reaches the unroutable provider → governed 502, not authentication_error. + Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode); + Assert.Contains("api_error", await resp.Content.ReadAsStringAsync()); + } +} diff --git a/tests/Covenant.Tests/AnthropicWireTests.cs b/tests/Covenant.Tests/AnthropicWireTests.cs new file mode 100644 index 0000000..f350066 --- /dev/null +++ b/tests/Covenant.Tests/AnthropicWireTests.cs @@ -0,0 +1,153 @@ +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// Anthropic wire ↔ canonical mapping: string and block-array content normalize identically, system prepends, non-text blocks are ignored, denial kinds map to Anthropic's error taxonomy. +public class AnthropicWireTests +{ + private static JsonElement Json(string raw) => JsonDocument.Parse(raw).RootElement.Clone(); + + [Fact] + public void String_content_maps_to_a_user_message() + { + var request = new AnthropicMessagesRequest + { + Messages = [new AnthropicWireMessage { Role = "user", Content = Json("\"hello claude\"") }], + }; + + var canonical = AnthropicWire.ToCanonical(request); + + Assert.Single(canonical); + Assert.Equal(ChatRole.User, canonical[0].Role); + Assert.Equal("hello claude", canonical[0].Content); + } + + [Fact] + public void Block_array_content_concatenates_text_blocks_and_ignores_the_rest() + { + var request = new AnthropicMessagesRequest + { + Messages = + [ + new AnthropicWireMessage + { + Role = "user", + Content = Json(""" + [{"type":"text","text":"part one, "}, + {"type":"image","source":{"type":"base64","data":"zzz"}}, + {"type":"text","text":"part two"}] + """), + }, + ], + }; + + var canonical = AnthropicWire.ToCanonical(request); + + Assert.Equal("part one, part two", canonical[0].Content); // image block dropped, text kept + } + + [Fact] + public void System_prompt_prepends_as_a_system_message_and_roles_map() + { + var request = new AnthropicMessagesRequest + { + System = Json("\"you are terse\""), + Messages = + [ + new AnthropicWireMessage { Role = "user", Content = Json("\"hi\"") }, + new AnthropicWireMessage { Role = "assistant", Content = Json("\"hello\"") }, + ], + }; + + var canonical = AnthropicWire.ToCanonical(request); + + Assert.Equal(3, canonical.Count); + Assert.Equal(ChatRole.System, canonical[0].Role); + Assert.Equal("you are terse", canonical[0].Content); + Assert.Equal(ChatRole.User, canonical[1].Role); + Assert.Equal(ChatRole.Assistant, canonical[2].Role); + } + + [Fact] + public void Response_builder_produces_the_messages_api_shape() + { + var response = new InferenceResponse( + new ChatMessage(ChatRole.Assistant, "governed answer"), + new Usage(120, 45, 0.0007m), + "claude-haiku-4-5"); + + var wire = AnthropicWire.BuildResponse("msg_abc", response); + + Assert.Equal("msg_abc", wire.Id); + Assert.Equal("message", wire.Type); + Assert.Equal("assistant", wire.Role); + Assert.Equal("claude-haiku-4-5", wire.Model); + Assert.Equal("governed answer", Assert.Single(wire.Content).Text); + Assert.Equal("end_turn", wire.StopReason); + Assert.Equal(120, wire.Usage.InputTokens); + Assert.Equal(45, wire.Usage.OutputTokens); + } + + [Theory] + [InlineData(DenialKind.Unauthenticated, "authentication_error", 401)] + [InlineData(DenialKind.RateLimited, "rate_limit_error", 429)] + [InlineData(DenialKind.UpstreamFailure, "api_error", 502)] + [InlineData(DenialKind.Governance, "permission_error", 403)] + public void Denial_kinds_map_to_anthropics_error_taxonomy(DenialKind kind, string errorType, int status) + { + var (type, code) = AnthropicWire.MapDenial(kind); + + Assert.Equal(errorType, type); + Assert.Equal(status, code); + } + + // The SSE event payloads are hand-built strings — parse each to prove it is well-formed JSON with + // the right shape, and that interpolated values (which could contain quotes) are escaped. + private static JsonElement Parse(string s) => JsonDocument.Parse(s).RootElement.Clone(); + + [Fact] + public void Message_start_event_is_well_formed_and_escapes_its_values() + { + var e = Parse(AnthropicWire.MessageStartEvent("msg_1", "weird\"model")); + + Assert.Equal("message_start", e.GetProperty("type").GetString()); + Assert.Equal("msg_1", e.GetProperty("message").GetProperty("id").GetString()); + Assert.Equal("weird\"model", e.GetProperty("message").GetProperty("model").GetString()); // survived escaping + Assert.Equal("assistant", e.GetProperty("message").GetProperty("role").GetString()); + } + + [Fact] + public void Content_block_delta_escapes_quotes_and_newlines_in_text() + { + var e = Parse(AnthropicWire.ContentBlockDeltaEvent("he said \"hi\"\nbye")); + + Assert.Equal("content_block_delta", e.GetProperty("type").GetString()); + Assert.Equal("he said \"hi\"\nbye", e.GetProperty("delta").GetProperty("text").GetString()); + } + + [Fact] + public void All_static_and_computed_events_parse_as_json() + { + foreach (var payload in new[] + { + AnthropicWire.ContentBlockStartEvent, + AnthropicWire.ContentBlockStopEvent, + AnthropicWire.MessageStopEvent, + AnthropicWire.MessageDeltaEvent(42), + AnthropicWire.ErrorEvent("rate_limit_error", "slow down \"friend\""), + }) + { + var e = Parse(payload); + Assert.True(e.TryGetProperty("type", out _)); // every event carries a type + } + + var delta = Parse(AnthropicWire.MessageDeltaEvent(42)); + Assert.Equal(42, delta.GetProperty("usage").GetProperty("output_tokens").GetInt32()); + var err = Parse(AnthropicWire.ErrorEvent("rate_limit_error", "slow down \"friend\"")); + Assert.Equal("rate_limit_error", err.GetProperty("error").GetProperty("type").GetString()); + Assert.Equal("slow down \"friend\"", err.GetProperty("error").GetProperty("message").GetString()); + } +} From 2f80aaf89e21f30c7a02ea7d70d2302fd465e5c4 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 23:18:54 -0400 Subject: [PATCH 5/8] fix: consolidate JsonSerializable attributes onto one CovenantJsonContext partial CI CS8785: splitting [JsonSerializable] across two partial declarations of the same JsonSerializerContext collided the source generator's hint names (CovenantJsonContext.Boolean.g.cs), which made the generator bail and left both CovenantJsonContext and AuditJsonContext without their generated members (CS0534). All registrations now live on the single attributed declaration in OpenAiContracts.cs. --- src/Covenant.Host/AnthropicContracts.cs | 6 ++---- src/Covenant.Host/OpenAiContracts.cs | 5 +++++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Covenant.Host/AnthropicContracts.cs b/src/Covenant.Host/AnthropicContracts.cs index 33ba2df..b40a44d 100644 --- a/src/Covenant.Host/AnthropicContracts.cs +++ b/src/Covenant.Host/AnthropicContracts.cs @@ -59,10 +59,8 @@ public sealed class AnthropicErrorBody [JsonPropertyName("message")] public string Message { get; set; } = ""; } -[JsonSerializable(typeof(AnthropicMessagesRequest))] -[JsonSerializable(typeof(AnthropicMessageResponse))] -[JsonSerializable(typeof(AnthropicErrorResponse))] -public partial class CovenantJsonContext; +// The [JsonSerializable] registrations for these types live on the single CovenantJsonContext +// declaration in OpenAiContracts.cs — one attributed partial only (source-generator requirement). /// Pure Anthropic-wire ↔ canonical mapping — unit-tested without a server. public static class AnthropicWire diff --git a/src/Covenant.Host/OpenAiContracts.cs b/src/Covenant.Host/OpenAiContracts.cs index d18b734..1cc245a 100644 --- a/src/Covenant.Host/OpenAiContracts.cs +++ b/src/Covenant.Host/OpenAiContracts.cs @@ -114,4 +114,9 @@ public sealed class ResetResponse [JsonSerializable(typeof(ResetResponse))] [JsonSerializable(typeof(EvidenceReport))] [JsonSerializable(typeof(StatusReport))] +// Anthropic dialect (types defined in AnthropicContracts.cs) — every [JsonSerializable] must live on +// ONE partial declaration of the context; splitting them collides the source generator's hint names. +[JsonSerializable(typeof(AnthropicMessagesRequest))] +[JsonSerializable(typeof(AnthropicMessageResponse))] +[JsonSerializable(typeof(AnthropicErrorResponse))] public partial class CovenantJsonContext : JsonSerializerContext; From 156b5865b833990b2e89b16aed07532303e5e605 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 23:24:51 -0400 Subject: [PATCH 6/8] =?UTF-8?q?fix:=20idempotent=20audit-sink=20shutdown?= =?UTF-8?q?=20(TryComplete)=20=E2=80=94=20no=20ChannelClosedException=20on?= =?UTF-8?q?=20double=20StopAsync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WebApplicationFactory disposal can invoke StopAsync more than once; Channel.Writer.Complete() throws on an already-completed channel, which surfaced as flaky teardown failures in the integration tests. TryComplete is idempotent. --- src/Covenant.Host/FileAuditSink.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Covenant.Host/FileAuditSink.cs b/src/Covenant.Host/FileAuditSink.cs index 840e697..63aa355 100644 --- a/src/Covenant.Host/FileAuditSink.cs +++ b/src/Covenant.Host/FileAuditSink.cs @@ -42,7 +42,9 @@ public Task StartAsync(CancellationToken cancellationToken) public async Task StopAsync(CancellationToken cancellationToken) { - _channel.Writer.Complete(); + // TryComplete, not Complete: StopAsync can run more than once across host disposal + // (Complete throws ChannelClosedException on an already-completed channel). Idempotent. + _channel.Writer.TryComplete(); if (_drain is not null) await _drain; } From 9f7e82c0bf57f05fa88728a05774d4586ad02371 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 23:33:52 -0400 Subject: [PATCH 7/8] test: injectable provider registry + served-path integration tests Registry resolves from DI (ConfigureTestServices override wins); the pipeline becomes a lazily-resolved singleton. Unlocks success paths an unroutable provider never reaches. +5 tests through the real Host with a stub provider: OpenAI buffered + SSE serving, Anthropic buffered + SSE serving (cross-protocol), served request in evidence with attributed spend. Raises coverage over response building, SSE emission, attribution. --- src/Covenant.Host/Program.cs | 13 +- tests/Covenant.Tests/ServedPathTests.cs | 190 ++++++++++++++++++++++++ 2 files changed, 197 insertions(+), 6 deletions(-) create mode 100644 tests/Covenant.Tests/ServedPathTests.cs diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index ef47e9d..b5c6c08 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -241,8 +241,11 @@ void FailIfConfigErrors() LedgerReplay.Rebuild(priorEntries, spendLedger); var budget = new BudgetConfig { GlobalCapUsd = globalCapUsd, TeamCapsUsd = teamCapsUsd }; -// --- Pipeline assembly. Outermost first; audit wraps everything; order per src/CLAUDE.md. --- -var pipeline = new InferencePipeline( +// --- Pipeline assembly. The provider registry is resolved from DI so tests can substitute a stub +// provider (a later registration wins); everything else is captured here. Outermost first; +// audit wraps everything; order per src/CLAUDE.md. --- +builder.Services.AddSingleton(registry); +builder.Services.AddSingleton(sp => new InferencePipeline( [ new AuditStage(auditSink, promptPreviewChars: // outermost: audits allow, deny, and error alike promptPreviewChars), @@ -255,11 +258,9 @@ void FailIfConfigErrors() new CacheStage(responseCache, cacheConfig), // cache before budget/provider: a hit skips the model call new RateLimitStage(rateCounterGlobal, rateCounterTeams, rateConfig), // rate half of budget/rate; cache hits bypass (free) new BudgetStage(killSwitch, spendLedger, budget),// kill switch + caps, before anything costs money - new ProviderCallStage(registry), // route + provider call + new ProviderCallStage(sp.GetRequiredService()), // route + provider call new AttributionStage(prices), // attribute cost -]); - -builder.Services.AddSingleton(pipeline); +])); builder.Services.AddHostedService(_ => auditSink); // drains the audit channel in the background // ADR-0006: evidence graph — optional, in-perimeter, never load-bearing. No Neo4j:Uri → not registered. diff --git a/tests/Covenant.Tests/ServedPathTests.cs b/tests/Covenant.Tests/ServedPathTests.cs new file mode 100644 index 0000000..41336ca --- /dev/null +++ b/tests/Covenant.Tests/ServedPathTests.cs @@ -0,0 +1,190 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Covenant.Adapters; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// The success paths through the real Host with an in-memory stub provider (registry swapped +/// via DI): served buffered + streamed responses in BOTH the OpenAI and Anthropic dialects, model +/// discovery content, and a served request landing in evidence with attributed cost. These exercise +/// response building, SSE emission, and attribution — the paths an unroutable provider never reaches. +public sealed class ServedPathTests : IClassFixture +{ + public sealed class StubFactory : WebApplicationFactory + { + public readonly string AuditPath = Path.Combine(Path.GetTempPath(), $"covenant-served-{Guid.NewGuid():n}.log"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + builder.UseSetting("OpenAI:ApiKey", "unused-stubbed"); + builder.UseSetting("Admin:Token", "test-admin"); + builder.UseSetting("Budget:GlobalCapUsd", "100"); + builder.UseSetting("Auth:Keys:0:Key", "k"); + builder.UseSetting("Auth:Keys:0:Principal", "p"); + builder.UseSetting("Auth:Keys:0:Team", "t"); + builder.UseSetting("Audit:Path", AuditPath); + + // Replace the provider registry with in-memory stubs for the policy's OpenAI routes. + // ConfigureTestServices runs AFTER the app's registrations, so this override wins; the + // pipeline factory resolves it when first used. + builder.ConfigureTestServices(services => + { + var stub = new StubChatClient("served governed reply"); + services.AddSingleton(new ChatClientRegistry( + new Dictionary + { + ["openai:gpt-4o-mini"] = stub, + ["openai:gpt-4o"] = stub, + })); + }); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(AuditPath) + "*")) + File.Delete(f); + } + } + + private sealed class StubChatClient(string reply) : MEAI.IChatClient + { + public Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken ct = default) + => Task.FromResult(new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, reply)) + { Usage = new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 4 } }); + + public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default) + { + await Task.Yield(); + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[..6]); + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[6..]); + yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 4 })] }; + } + + public object? GetService(Type t, object? key = null) => null; + public void Dispose() { } + } + + private readonly StubFactory _factory; + private readonly HttpClient _client; + + public ServedPathTests(StubFactory factory) + { + _factory = factory; + _client = factory.CreateClient(); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "k"); + } + + private static StringContent OpenAi(string content, bool stream = false) => + new($"{{\"stream\":{(stream ? "true" : "false")},\"messages\":[{{\"role\":\"user\",\"content\":\"{content}\"}}]}}", + Encoding.UTF8, "application/json"); + + private static StringContent Anthropic(string content, bool stream = false) => + new($"{{\"model\":\"gpt-4o-mini\",\"max_tokens\":50,\"stream\":{(stream ? "true" : "false")},\"messages\":[{{\"role\":\"user\",\"content\":\"{content}\"}}]}}", + Encoding.UTF8, "application/json"); + + [Fact] + public async Task OpenAi_buffered_request_is_served_with_usage() + { + var resp = await _client.PostAsync("/v1/chat/completions", OpenAi("a normal internal question")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + var root = doc.RootElement; + Assert.Equal("gpt-4o-mini", root.GetProperty("model").GetString()); // routed to cheapest + Assert.Equal("served governed reply", + root.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString()); + Assert.Equal(11, root.GetProperty("usage").GetProperty("total_tokens").GetInt32()); + } + + [Fact] + public async Task OpenAi_streamed_request_emits_chunks_then_done() + { + var resp = await _client.PostAsync("/v1/chat/completions", OpenAi("stream it", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + + var body = await resp.Content.ReadAsStringAsync(); + var text = new StringBuilder(); + bool sawDone = false; + foreach (var line in body.Split('\n')) + { + if (!line.StartsWith("data: ")) continue; + var payload = line["data: ".Length..].Trim(); + if (payload == "[DONE]") { sawDone = true; continue; } + using var chunk = JsonDocument.Parse(payload); + var delta = chunk.RootElement.GetProperty("choices")[0].GetProperty("delta"); + if (delta.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.String) + text.Append(c.GetString()); + } + Assert.True(sawDone); + Assert.Equal("served governed reply", text.ToString()); + } + + [Fact] + public async Task Anthropic_buffered_request_is_served_with_messages_shape() + { + using var aclient = _factory.CreateClient(); + aclient.DefaultRequestHeaders.Add("x-api-key", "k"); + + var resp = await aclient.PostAsync("/v1/messages", Anthropic("hello")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + var root = doc.RootElement; + Assert.Equal("message", root.GetProperty("type").GetString()); + Assert.Equal("served governed reply", root.GetProperty("content")[0].GetProperty("text").GetString()); + Assert.Equal("end_turn", root.GetProperty("stop_reason").GetString()); + Assert.Equal(7, root.GetProperty("usage").GetProperty("input_tokens").GetInt32()); + } + + [Fact] + public async Task Anthropic_streamed_request_emits_the_messages_event_sequence() + { + using var aclient = _factory.CreateClient(); + aclient.DefaultRequestHeaders.Add("x-api-key", "k"); + + var resp = await aclient.PostAsync("/v1/messages", Anthropic("stream it", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + + var body = await resp.Content.ReadAsStringAsync(); + var events = new List(); + var text = new StringBuilder(); + foreach (var line in body.Split('\n')) + { + if (!line.StartsWith("data: ")) continue; + using var ev = JsonDocument.Parse(line["data: ".Length..].Trim()); + var type = ev.RootElement.GetProperty("type").GetString()!; + events.Add(type); + if (type == "content_block_delta") + text.Append(ev.RootElement.GetProperty("delta").GetProperty("text").GetString()); + } + Assert.Equal("message_start", events[0]); + Assert.Equal("message_stop", events[^1]); + Assert.Equal("served governed reply", text.ToString()); + } + + [Fact] + public async Task Served_request_lands_in_evidence_with_attributed_cost() + { + await _client.PostAsync("/v1/chat/completions", OpenAi("bill me")); + + var req = new HttpRequestMessage(HttpMethod.Get, "/admin/status"); + req.Headers.Add("X-Covenant-Admin-Token", "test-admin"); + var status = await _client.SendAsync(req); + using var doc = JsonDocument.Parse(await status.Content.ReadAsStringAsync()); + + var finops = doc.RootElement.GetProperty("finops"); + Assert.True(finops.GetProperty("allowed").GetInt32() >= 1); + Assert.True(doc.RootElement.GetProperty("budget").GetProperty("global_spend_usd").GetDecimal() > 0m); + } +} From c4578ab32aa51837918f6cfa6891de4cd3510b82 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Thu, 3 Sep 2026 23:37:15 -0400 Subject: [PATCH 8/8] test: add coverlet.runsettings to this branch (scopes coverage to governance logic) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runsettings landed on main via the CI PR; this branch predated it, so local coverage runs errored on the missing file. Identical content — dedupes on merge. --- tests/coverlet.runsettings | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/coverlet.runsettings diff --git a/tests/coverlet.runsettings b/tests/coverlet.runsettings new file mode 100644 index 0000000..b581f35 --- /dev/null +++ b/tests/coverlet.runsettings @@ -0,0 +1,17 @@ + + + + + + + + cobertura + **/AdminUi.cs,**/OpenAiContracts.cs + Obsolete,GeneratedCode,CompilerGenerated,ExcludeFromCodeCoverage + + + + +