Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README-SCAFFOLD.md
Original file line number Diff line number Diff line change
Expand Up @@ -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" "<key>" --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`).
Expand All @@ -76,6 +86,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
Expand Down
1 change: 1 addition & 0 deletions docs/PROVENANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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._
48 changes: 48 additions & 0 deletions docs/adr/ADR-0007-audit-store-chain-head-anchoring.md
Original file line number Diff line number Diff line change
@@ -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.
138 changes: 138 additions & 0 deletions src/Covenant.Host/AnthropicContracts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
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<AnthropicWireMessage> 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<AnthropicTextBlock> 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; } = "";
}

// The [JsonSerializable] registrations for these types live on the single CovenantJsonContext
// declaration in OpenAiContracts.cs — one attributed partial only (source-generator requirement).

/// <summary>Pure Anthropic-wire ↔ canonical mapping — unit-tested without a server.</summary>
public static class AnthropicWire
{
/// <summary>Normalizes string-or-block-array content to plain text; non-text blocks are ignored.</summary>
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<ChatMessage> ToCanonical(AnthropicMessagesRequest request)
{
var messages = new List<ChatMessage>();
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,
},
};

/// <summary>Denial kinds → Anthropic error taxonomy + HTTP status (matches the API's own table).</summary>
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)}\"}}}}";
}
2 changes: 1 addition & 1 deletion src/Covenant.Host/AuditChain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace Covenant.Host;

/// <summary>Hash-chain primitives shared by writer and verifier: line = <c>{previousHash}\t{entryHash}\t{contentJson}</c>, <c>entryHash = SHA256(previousHash + contentJson)</c>; 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.</summary>
/// Truncation from the END is not detectable from the file alone — closed by opt-in chain-head anchoring (ADR-0007, Audit:AnchorPath).</summary>
public static class AuditChain
{
public const char Separator = '\t';
Expand Down
2 changes: 2 additions & 0 deletions src/Covenant.Host/Covenant.Host.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.17.0" />
<!-- ADR-0006: evidence graph projector, active only when Neo4j:Uri is configured. -->
<PackageReference Include="Neo4j.Driver" Version="6.2.1" />
<!-- ADR-0001 start set: Anthropic provider via the official SDK's IChatClient (opt-in via Anthropic:ApiKey). -->
<PackageReference Include="Anthropic" Version="12.8.0" />
</ItemGroup>

</Project>
Loading
Loading