diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40ee259..0aa2e46 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,13 +40,13 @@ jobs: restore-keys: nuget-${{ runner.os }}- - name: Test with coverage - run: dotnet test -c Release --collect:"XPlat Code Coverage" --results-directory ./coverage + run: dotnet test -c Release --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings --results-directory ./coverage - - name: Enforce coverage threshold (line >= 0.60) + - name: Enforce coverage threshold (line >= 0.80) run: | COUNT=$(find ./coverage -name 'coverage.cobertura.xml' | wc -l) test "$COUNT" -eq 1 || { echo "expected exactly 1 coverage report (single test project), found $COUNT"; exit 1; } FILE=$(find ./coverage -name 'coverage.cobertura.xml') RATE=$(grep -o 'line-rate="[0-9.]*"' "$FILE" | head -1 | grep -o '[0-9.]*') - echo "line coverage: $RATE (threshold 0.60)" - awk -v r="$RATE" 'BEGIN { exit (r >= 0.60 ? 0 : 1) }' + echo "line coverage: $RATE (threshold 0.80)" + awk -v r="$RATE" 'BEGIN { exit (r >= 0.80 ? 0 : 1) }' diff --git a/README-SCAFFOLD.md b/README-SCAFFOLD.md index 19e6580..82e6f9b 100644 --- a/README-SCAFFOLD.md +++ b/README-SCAFFOLD.md @@ -27,9 +27,9 @@ dotnet build dotnet test ``` -Coverage (target: ≥60% line coverage on src/, governance hardest): +Coverage (CI gate: ≥80% line coverage on src/, scoped by tests/coverlet.runsettings — same command as CI): ``` -dotnet test --collect:"XPlat Code Coverage" +dotnet test --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings # summary: the generated coverage.cobertura.xml under tests/Covenant.Tests/TestResults// grep -o 'line-rate="[0-9.]*"' tests/Covenant.Tests/TestResults/*/coverage.cobertura.xml | head -1 ``` @@ -215,8 +215,11 @@ from openai import OpenAI client = OpenAI(base_url="http://localhost:5100/v1", api_key="demo-key") client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "hi"}]) ``` -First slice speaks plain-text chat (buffered + SSE). Multimodal content and tool calls are not yet -part of the wire surface. +Wire surface: plain-text chat (buffered + SSE) on both dialects; `max_tokens` is forwarded to the +model. Anything governance cannot inspect — image/file content parts, tool definitions, tool calls +and results — is **refused with HTTP 400** (`unsupported` / `invalid_request_error`) and audited, +never silently stripped: an image could carry PHI the classifier never saw. Tool-call governance +is a future ADR. ## 6. Next - Run the **NativeAOT spike** from ADR-0001 (`PublishAot=true` in `Covenant.Host.csproj`) and record the diff --git a/docs/diagrams/covenant-architecture.drawio b/docs/diagrams/covenant-architecture.drawio index d59d0b2..679a66f 100644 --- a/docs/diagrams/covenant-architecture.drawio +++ b/docs/diagrams/covenant-architecture.drawio @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/diagrams/covenant-architecture.svg b/docs/diagrams/covenant-architecture.svg index 0d866e7..916c391 100644 --- a/docs/diagrams/covenant-architecture.svg +++ b/docs/diagrams/covenant-architecture.svg @@ -1,4 +1,4 @@ - + Covenant — in-perimeter AI inference governance & FinOps control plane @@ -27,8 +27,8 @@ Audit stage — outermost; records allow, deny, and error alike metadata + SHA-256 prompt fingerprint — never content -Auth -virtual API keys +Auth + shape +keys · text only Classify PII / PHI @@ -52,7 +52,7 @@ team, workflow Denied — fail-closed -401 · 403 · 429 · 502 +400 · 401 · 403 · 429 · 502 no provider call, still audited Response + usage diff --git a/docs/diagrams/covenant-overview.drawio b/docs/diagrams/covenant-overview.drawio index 36baed1..1023b22 100644 --- a/docs/diagrams/covenant-overview.drawio +++ b/docs/diagrams/covenant-overview.drawio @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/diagrams/covenant-overview.svg b/docs/diagrams/covenant-overview.svg index ec74ad6..7290c8d 100644 --- a/docs/diagrams/covenant-overview.svg +++ b/docs/diagrams/covenant-overview.svg @@ -1,4 +1,4 @@ - + Covenant at a glance @@ -11,7 +11,7 @@ SDKs, Open WebUI, agents Covenant — one governed pipeline -auth → classify → policy → cache → rate limit +auth → shape → classify → policy → cache → rate limit → budget / kill switch → provider → attribute cost fail-closed: no match, no call diff --git a/docs/diagrams/gen_diagram.py b/docs/diagrams/gen_diagram.py index 15eac17..8ebd3e2 100644 --- a/docs/diagrams/gen_diagram.py +++ b/docs/diagrams/gen_diagram.py @@ -25,7 +25,7 @@ ("ingress", "caller", 310, 180, 150, 200, ["Ingress", "/v1/chat/completions", "/v1/messages", "/v1/models", "", "→ one canonical request"], {}), ("audit", "evidence", 490, 160, 470, 250, ["Audit stage — outermost; records allow, deny, and error alike", "metadata + SHA-256 prompt fingerprint — never content"], {"container": True}), - ("s_auth", "govern", 510, 210, 100, 55, ["Auth", "virtual API keys"], {}), + ("s_auth", "govern", 510, 210, 100, 55, ["Auth + shape", "keys · text only"], {}), ("s_classify", "govern", 620, 210, 100, 55, ["Classify", "PII / PHI"], {}), ("s_policy", "govern", 730, 210, 100, 55, ["Policy", "route, complexity"], {}), ("s_cache", "govern", 840, 210, 100, 55, ["Cache", "team-scoped TTL"], {}), @@ -34,7 +34,7 @@ ("s_provider", "provider", 620, 320, 100, 55, ["Provider call", "adapter:model"], {}), ("s_attr", "evidence", 510, 320, 100, 55, ["Attribute cost", "team, workflow"], {}), - ("denied", "denied", 490, 440, 210, 70, ["Denied — fail-closed", "401 · 403 · 429 · 502", "no provider call, still audited"], {}), + ("denied", "denied", 490, 440, 210, 70, ["Denied — fail-closed", "400 · 401 · 403 · 429 · 502", "no provider call, still audited"], {}), ("response", "caller", 730, 440, 230, 70, ["Response + usage", "OpenAI or Anthropic wire", "buffered or SSE stream"], {}), ("log", "evidence", 310, 560, 200, 80, ["Hash-chained audit log", "append-only · SHA-256 links", "tampered chain refuses boot"], {}), @@ -160,7 +160,7 @@ def svg(embed_xml): N_HL = [ ("perimeter", "none", 250, 50, 700, 420, ["Customer perimeter — nothing leaves except allow-listed model egress"], {"container": True, "dashed": True}), ("clients", "caller", 30, 230, 180, 90, ["Any AI client", "OpenAI or Anthropic wire", "SDKs, Open WebUI, agents"], {}), - ("covenant", "govern", 290, 120, 360, 150, ["Covenant — one governed pipeline", "auth → classify → policy → cache → rate limit", "→ budget / kill switch → provider → attribute cost", "", "fail-closed: no match, no call"], {}), + ("covenant", "govern", 290, 120, 360, 150, ["Covenant — one governed pipeline", "auth → shape → classify → policy → cache → rate limit", "→ budget / kill switch → provider → attribute cost", "", "fail-closed: no match, no call"], {}), ("evidence", "evidence", 290, 320, 360, 110, ["Tamper-evident evidence", "hash-chained audit log + anchored head", "spend ledger · evidence export · dashboard"], {}), ("local", "provider", 700, 320, 210, 90, ["In-perimeter model", "Ollama / vLLM", "PII / PHI never leave"], {}), ("external", "provider", 1000, 130, 200, 110, ["Allow-listed providers", "OpenAI · Anthropic", "egress only to these"], {}), diff --git a/src/CLAUDE.md b/src/CLAUDE.md index 62f4de0..3dac44c 100644 --- a/src/CLAUDE.md +++ b/src/CLAUDE.md @@ -13,7 +13,7 @@ Governance and Adapters never depend on each other; they meet only through Core' ## The three patterns that define this codebase 1. **Canonical schema at the center.** Everything normalizes to one internal model. Provider-specific shapes exist *only* inside adapters. If a provider concept leaks past an adapter, that's a bug. 2. **Adapter contract.** Each provider implements one interface: canonical→request, response→canonical, SSE stream normalization, error mapping, token/usage accounting. Adding a provider is one adapter and nothing else. Start set: OpenAI, Anthropic, one self-hosted OpenAI-compatible (vLLM) target. -3. **Pipeline = ordered middleware.** `auth → classify → policy → cache-lookup → route → budget/rate → provider-call → post-process → attribute → audit`. Governance features are *stages*, not special cases. +3. **Pipeline = ordered middleware.** `auth → shape → classify → policy → cache-lookup → route → budget/rate → provider-call → post-process → attribute → audit`. Governance features are *stages*, not special cases. ## Ordering rules (non-obvious — do not reorder) - **Cache before route** — a hit skips the model call entirely. diff --git a/src/Covenant.Adapters/ProviderLayer.cs b/src/Covenant.Adapters/ProviderLayer.cs index 1bb2de8..607cf5c 100644 --- a/src/Covenant.Adapters/ProviderLayer.cs +++ b/src/Covenant.Adapters/ProviderLayer.cs @@ -35,7 +35,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance } var messages = ctx.Request.Messages.Select(ToMeai).ToList(); - var options = new MEAI.ChatOptions { ModelId = route.ModelId }; + var options = new MEAI.ChatOptions { ModelId = route.ModelId, MaxOutputTokens = ctx.Request.MaxOutputTokens }; // ADR-0002: streaming is an emission mode, not a different pipeline. The stream is consumed // HERE so attribution, budget, and audit run on the normal unwind with real usage. diff --git a/src/Covenant.Core/CanonicalModel.cs b/src/Covenant.Core/CanonicalModel.cs index daf5a96..1eab6ca 100644 --- a/src/Covenant.Core/CanonicalModel.cs +++ b/src/Covenant.Core/CanonicalModel.cs @@ -26,7 +26,9 @@ public sealed record InferenceRequest( string? RequestedModel, AttributionTags Attribution, bool Stream = false, - string? Credential = null); + string? Credential = null, + int? MaxOutputTokens = null, + string? UnsupportedFeature = null); // set by ingress when the wire carried something governance cannot see (images, tools) → denied in-pipeline, audited /// Who the pipeline decided the caller is: self-declared until the auth stage overwrites it /// on a valid key. Everything downstream reads THIS, never the raw request headers. diff --git a/src/Covenant.Core/InferenceContext.cs b/src/Covenant.Core/InferenceContext.cs index cdf8ea2..58f8fef 100644 --- a/src/Covenant.Core/InferenceContext.cs +++ b/src/Covenant.Core/InferenceContext.cs @@ -2,7 +2,7 @@ namespace Covenant.Core; /// Why a request was refused. Callers see different HTTP statuses (401 vs 403 vs 502); /// the audit trail records all of them as denials. -public enum DenialKind { None, Governance, UpstreamFailure, Unauthenticated, RateLimited } +public enum DenialKind { None, Governance, UpstreamFailure, Unauthenticated, RateLimited, Unsupported } /// Mutable pipeline state; exactly one terminal outcome: Response (served) or DenialReason /// (refused). Default Classification is the most restrictive — fail-closed until classify runs. diff --git a/src/Covenant.Governance/Cache.cs b/src/Covenant.Governance/Cache.cs index 19b9649..316fae0 100644 --- a/src/Covenant.Governance/Cache.cs +++ b/src/Covenant.Governance/Cache.cs @@ -62,7 +62,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance return; } - var key = Key(ctx.Identity.Tags.Team, route.ModelId, ctx.Request.Messages); + var key = Key(ctx.Identity.Tags.Team, route.ModelId, ctx.Request.Messages, ctx.Request.MaxOutputTokens); if (cache.TryGet(key, out var hit)) { ctx.ServedFromCache = true; @@ -78,9 +78,10 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance cache.Store(key, fresh, TimeSpan.FromSeconds(config.TtlSeconds), config.MaxEntries); } - private static string Key(string team, string modelId, IReadOnlyList messages) + private static string Key(string team, string modelId, IReadOnlyList messages, int? maxOutputTokens) { - var sb = new StringBuilder(team).Append('\u001f').Append(modelId); + // max_tokens is part of the contract: a 400-token cached answer must not serve a max_tokens=5 ask. + var sb = new StringBuilder(team).Append('\u001f').Append(modelId).Append('\u001f').Append(maxOutputTokens?.ToString() ?? ""); foreach (var m in messages) sb.Append('\u001f').Append(m.Role).Append(':').Append(m.Content); return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString()))); } diff --git a/src/Covenant.Governance/EvidenceText.cs b/src/Covenant.Governance/EvidenceText.cs new file mode 100644 index 0000000..c75fb56 --- /dev/null +++ b/src/Covenant.Governance/EvidenceText.cs @@ -0,0 +1,15 @@ +namespace Covenant.Governance; + +/// Denial reasons are evidence (append-only, forever). Client-supplied identifiers may appear +/// in them only bounded: short, printable, and truncated with a marker — never an unbounded payload. +public static class Evidence +{ + public const int MaxIdentifierChars = 64; + + public static string Bounded(string? value) + { + if (string.IsNullOrEmpty(value)) return ""; + var clean = new string(value.Where(c => !char.IsControl(c)).ToArray()); + return clean.Length <= MaxIdentifierChars ? clean : clean[..MaxIdentifierChars] + "…(truncated)"; + } +} diff --git a/src/Covenant.Governance/Policy.cs b/src/Covenant.Governance/Policy.cs index 1fdf2bb..59adc69 100644 --- a/src/Covenant.Governance/Policy.cs +++ b/src/Covenant.Governance/Policy.cs @@ -38,7 +38,7 @@ public PolicyOutcome Evaluate(InferenceContext ctx) var match = routes.FirstOrDefault(r => string.Equals(r.ModelId, requested, StringComparison.OrdinalIgnoreCase)); return match is not null ? PolicyOutcome.Allow(match) - : PolicyOutcome.Deny($"model '{requested}' not permitted for classification '{ctx.Classification}'"); + : PolicyOutcome.Deny($"model '{Evidence.Bounded(requested)}' not permitted for classification '{ctx.Classification}'"); } if (routes.Count == 1) diff --git a/src/Covenant.Governance/Shape.cs b/src/Covenant.Governance/Shape.cs new file mode 100644 index 0000000..77d7301 --- /dev/null +++ b/src/Covenant.Governance/Shape.cs @@ -0,0 +1,25 @@ +using Covenant.Core; + +namespace Covenant.Governance; + +/// Shape stage (right after auth, so the audit entry names the resolved caller): a request whose +/// wire carried content governance cannot inspect — image/file blocks, tool definitions, tool results — +/// is denied fail-closed rather than silently stripped. Silently dropping an image would let unclassified +/// data reach a provider; silently dropping tools would lie to the client. Both are recorded as evidence. +public sealed class ShapeStage : IPipelineStage +{ + public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, CancellationToken ct) + { + if (ctx.Request.UnsupportedFeature is { } feature) + { + ctx.Deny($"unsupported request shape: {feature}", DenialKind.Unsupported); + return; + } + if (ctx.Request.MaxOutputTokens is < 1) + { + ctx.Deny("max_tokens must be a positive integer", DenialKind.Unsupported); + return; + } + await next(ctx, ct); + } +} diff --git a/src/Covenant.Host/AdminUi.cs b/src/Covenant.Host/AdminUi.cs index 2b6563a..889e08d 100644 --- a/src/Covenant.Host/AdminUi.cs +++ b/src/Covenant.Host/AdminUi.cs @@ -312,6 +312,7 @@ function clsPill(c) { function explain(reason) { const r = (reason || '').toLowerCase(); if (r.includes('no adapter registered')) return 'Policy routed this to the in-perimeter model, but none is configured — so it was refused rather than sent to a public provider. That is fail-closed working. To serve this class of data, configure Local:Endpoint.'; + if (r.includes('unsupported request shape') || r.includes('max_tokens must be')) return 'The request carried something governance cannot inspect (an image, a file, tool definitions or calls) or an invalid cap. It was refused (HTTP 400) rather than sent with the ungovernable part silently stripped.'; if (r.includes('kill switch')) return 'An operator engaged the kill switch; all inference stops until it is disengaged (Overview tab).'; if (r.includes('global budget')) return 'The appliance-wide spend cap is exhausted. Raise Budget:GlobalCapUsd, or archive & reset in Settings.'; if (r.includes('budget exhausted for team')) return 'This team hit its spend cap. Raise its cap, or archive & reset in Settings.'; diff --git a/src/Covenant.Host/AnthropicContracts.cs b/src/Covenant.Host/AnthropicContracts.cs index b40a44d..8a97429 100644 --- a/src/Covenant.Host/AnthropicContracts.cs +++ b/src/Covenant.Host/AnthropicContracts.cs @@ -11,7 +11,9 @@ namespace Covenant.Host; public sealed class AnthropicMessagesRequest { [JsonPropertyName("model")] public string? Model { get; set; } - [JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; } // accepted; not yet forwarded + [JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; } + /// Everything else (tools, tool_choice, …) — inspected by AnthropicWire.Unsupported. + [JsonExtensionData] public Dictionary? Extra { get; set; } [JsonPropertyName("stream")] public bool? Stream { get; set; } [JsonPropertyName("system")] public JsonElement? System { get; set; } [JsonPropertyName("messages")] public List Messages { get; set; } = []; @@ -65,16 +67,45 @@ public sealed class AnthropicErrorBody /// 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. + /// Why this request cannot be governed (image/document/tool blocks, tool definitions), or null. + private static readonly string[] UnsupportedTopLevel = ["tools", "tool_choice", "mcp_servers", "thinking", "container"]; + + public static string? Unsupported(AnthropicMessagesRequest r) + { + if (r.Extra is { } extra) + foreach (var key in UnsupportedTopLevel) + if (extra.TryGetValue(key, out var v) && WireLabels.Present(v)) + return $"'{key}' (not yet governed)"; + if (r.Messages is null) return "'messages' is null"; + if (r.Messages.Any(m => m is null)) return "a message is null"; + foreach (var block in r.Messages.Select(m => m.Content).Append(r.System ?? default)) + { + switch (block.ValueKind) + { + case JsonValueKind.String or JsonValueKind.Null or JsonValueKind.Undefined: + break; + case JsonValueKind.Array: + foreach (var b in block.EnumerateArray()) + { + if (WireLabels.PartType(b) is var type && type != "text") + return $"content block '{WireLabels.Safe(type)}' (only text can be classified)"; + if (!WireLabels.HasStringText(b)) + return "content block 'text' without a string text field"; + } + break; + default: + return "content is neither a string nor an array of blocks"; + } + } + return null; + } + + /// Normalizes string-or-block-array content to plain text (Unsupported already refused non-text blocks). 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() ?? "")), + JsonValueKind.Array => string.Concat(content.EnumerateArray() + .Where(b => WireLabels.PartType(b) == "text").Select(WireLabels.TextOf)), _ => "", }; @@ -83,8 +114,8 @@ 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( + foreach (var m in request.Messages ?? []) + if (m is not null) messages.Add(new ChatMessage( string.Equals(m.Role, "assistant", StringComparison.OrdinalIgnoreCase) ? ChatRole.Assistant : ChatRole.User, ExtractText(m.Content))); return messages; @@ -109,6 +140,7 @@ public static List ToCanonical(AnthropicMessagesRequest request) DenialKind.Unauthenticated => ("authentication_error", StatusCodes.Status401Unauthorized), DenialKind.RateLimited => ("rate_limit_error", StatusCodes.Status429TooManyRequests), DenialKind.UpstreamFailure => ("api_error", StatusCodes.Status502BadGateway), + DenialKind.Unsupported => ("invalid_request_error", StatusCodes.Status400BadRequest), _ => ("permission_error", StatusCodes.Status403Forbidden), }; diff --git a/src/Covenant.Host/OpenAiContracts.cs b/src/Covenant.Host/OpenAiContracts.cs index 1cc245a..f27ba26 100644 --- a/src/Covenant.Host/OpenAiContracts.cs +++ b/src/Covenant.Host/OpenAiContracts.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using System.Text.Json.Serialization; namespace Covenant.Host; @@ -9,12 +10,108 @@ public sealed class OpenAiChatRequest [JsonPropertyName("model")] public string? Model { get; set; } [JsonPropertyName("messages")] public List Messages { get; set; } = []; [JsonPropertyName("stream")] public bool? Stream { get; set; } + [JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; } + [JsonPropertyName("max_completion_tokens")] public int? MaxCompletionTokens { get; set; } + /// Everything else the client sent. Inspected by OpenAiWire.Unsupported so that features + /// governance cannot see (tools, functions) are refused, never silently dropped. + [JsonExtensionData] public Dictionary? Extra { get; set; } } public sealed class OpenAiMessage { [JsonPropertyName("role")] public string Role { get; set; } = "user"; - [JsonPropertyName("content")] public string Content { get; set; } = ""; + /// String in the classic protocol; an array of content parts (text/image_url/…) in the + /// multimodal one. Bound raw so ingress can refuse anything but text — see OpenAiWire. + [JsonPropertyName("content")] public JsonElement? Content { get; set; } + [JsonPropertyName("tool_calls"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public JsonElement? ToolCalls { get; set; } +} + +/// Pure OpenAI-wire ↔ canonical helpers — unit-tested without a server. +public static class OpenAiWire +{ + private static readonly string[] UnsupportedTopLevel = + ["tools", "tool_choice", "functions", "function_call", "modalities", "audio", "web_search_options", "prediction"]; + + /// Why this request cannot be governed, or null if it is plain text chat. Total (never throws + /// on odd JSON) and never echoes client bytes: the denial reason ends up in the audit chain, so only + /// allow-listed labels from WireLabels appear in it. + public static string? Unsupported(OpenAiChatRequest r) + { + if (r.Extra is { } extra) + foreach (var key in UnsupportedTopLevel) + if (extra.TryGetValue(key, out var v) && WireLabels.Present(v)) + return $"'{key}' (not yet governed)"; + if (r.Extra is { } e2 && e2.TryGetValue("n", out var n) && n.ValueKind == JsonValueKind.Number && n.TryGetDouble(out var nn) && nn > 1) + return "'n' > 1 (one governed choice per request)"; + if (r.Messages is null) return "'messages' is null"; + foreach (var m in r.Messages) + { + if (m is null) return "a message is null"; + if (m.ToolCalls is { } tc && WireLabels.Present(tc)) + return "'tool_calls' (not yet governed)"; + if (string.Equals(m.Role, "tool", StringComparison.OrdinalIgnoreCase)) + return "role 'tool' (not yet governed)"; + switch (m.Content) + { + case null or { ValueKind: JsonValueKind.String or JsonValueKind.Null }: + break; + case { ValueKind: JsonValueKind.Array } parts: + foreach (var p in parts.EnumerateArray()) + { + if (WireLabels.PartType(p) is var type && type != "text") + return $"content part '{WireLabels.Safe(type)}' (only text can be classified)"; + if (!WireLabels.HasStringText(p)) + return "content part 'text' without a string text field"; + } + break; + default: + return "content is neither a string nor an array of parts"; + } + } + return null; + } + + /// Text of a message: a string, or the concatenation of text parts (Unsupported already + /// guaranteed there are no other kinds). Total: non-string 'text' fields contribute nothing. + public static string Text(OpenAiMessage m) => m.Content switch + { + { ValueKind: JsonValueKind.String } s => s.GetString() ?? "", + { ValueKind: JsonValueKind.Array } parts => string.Concat(parts.EnumerateArray().Select(WireLabels.TextOf)), + _ => "", + }; + + /// Response content is always a string on this wire. + public static JsonElement TextElement(string s) => JsonSerializer.SerializeToElement(s, CovenantJsonContext.Default.String); +} + +/// Never let client bytes into a denial reason (it is evidence): labels are allow-listed. +public static class WireLabels +{ + private static readonly HashSet Known = new(StringComparer.Ordinal) + { + "image_url", "input_audio", "file", "refusal", "image", "document", "tool_use", "tool_result", + "thinking", "redacted_thinking", "server_tool_use", "web_search_tool_result", + }; + + public static string Safe(string? type) => type is not null && Known.Contains(type) ? type : "unknown"; + + /// The part/block 'type' as a string, or null when absent or not a string. + public static string? PartType(JsonElement p) + => p.ValueKind == JsonValueKind.Object && p.TryGetProperty("type", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null; + + public static bool HasStringText(JsonElement p) + => p.ValueKind == JsonValueKind.Object && p.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String; + + public static string TextOf(JsonElement p) + => p.ValueKind == JsonValueKind.Object && p.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? "" : ""; + + /// A value counts as present unless null/undefined or an empty array (clients send tools: []). + public static bool Present(JsonElement v) => v.ValueKind switch + { + JsonValueKind.Null or JsonValueKind.Undefined => false, + JsonValueKind.Array => v.GetArrayLength() > 0, + _ => true, + }; } public sealed class OpenAiChatResponse @@ -104,6 +201,7 @@ public sealed class ResetResponse [JsonPropertyName("archived_to")] public string? ArchivedTo { get; set; } } +[JsonSerializable(typeof(string))] [JsonSerializable(typeof(OpenAiChatRequest))] [JsonSerializable(typeof(OpenAiChatResponse))] [JsonSerializable(typeof(OpenAiChatChunk))] diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index b5c6c08..cadb6b6 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -250,6 +250,7 @@ void FailIfConfigErrors() new AuditStage(auditSink, promptPreviewChars: // outermost: audits allow, deny, and error alike promptPreviewChars), new AuthStage(new AuthConfig { AllowAnonymous = allowAnonymous, Keys = apiKeys }), // auth first + new ShapeStage(), // refuse shapes governance can't see (images, tools) — audited new ClassifyStage(new RegexDataClassifier()), // classify new PolicyStage(new PolicyEngine(policy, new RoutingOptions { @@ -297,7 +298,8 @@ void FailIfConfigErrors() 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); + Stream: body.Stream == true, Credential: credential, + MaxOutputTokens: body.MaxTokens, UnsupportedFeature: AnthropicWire.Unsupported(body)); var ctx = new InferenceContext(request); var msgId = $"msg_{Guid.NewGuid():n}"; @@ -395,11 +397,13 @@ async ValueTask WriteEventAsync(string evt, string json, CancellationToken token var request = new InferenceRequest( Principal: principal, - Messages: body.Messages.Select(m => new ChatMessage(ParseRole(m.Role), m.Content)).ToList(), + Messages: (body.Messages ?? []).Where(m => m is not null).Select(m => new ChatMessage(ParseRole(m.Role), OpenAiWire.Text(m))).ToList(), RequestedModel: body.Model, Attribution: tags, Stream: body.Stream == true, - Credential: credential); + Credential: credential, + MaxOutputTokens: body.MaxCompletionTokens ?? body.MaxTokens, + UnsupportedFeature: OpenAiWire.Unsupported(body)); var ctx = new InferenceContext(request); @@ -478,7 +482,7 @@ async ValueTask WriteChunkAsync(OpenAiChatChunk chunk, CancellationToken token) var dto = new OpenAiChatResponse { Model = r.ServedByModel, - Choices = [new OpenAiChoice { Index = 0, Message = new OpenAiMessage { Role = "assistant", Content = r.Message.Content } }], + Choices = [new OpenAiChoice { Index = 0, Message = new OpenAiMessage { Role = "assistant", Content = OpenAiWire.TextElement(r.Message.Content) } }], Usage = new OpenAiUsage { PromptTokens = r.Usage.InputTokens, @@ -497,6 +501,7 @@ static IResult DenialResult(InferenceContext ctx) DenialKind.Unauthenticated => ("unauthenticated", StatusCodes.Status401Unauthorized), DenialKind.UpstreamFailure => ("upstream_error", StatusCodes.Status502BadGateway), DenialKind.RateLimited => ("rate_limited", StatusCodes.Status429TooManyRequests), + DenialKind.Unsupported => ("unsupported", StatusCodes.Status400BadRequest), _ => ("denied", StatusCodes.Status403Forbidden), }; return Results.Json( @@ -643,7 +648,7 @@ StatusReport BuildStatus() app.Run(); -static ChatRole ParseRole(string role) => role.ToLowerInvariant() switch +static ChatRole ParseRole(string? role) => (role ?? "user").ToLowerInvariant() switch { "system" => ChatRole.System, "assistant" => ChatRole.Assistant, diff --git a/tests/Covenant.Tests/AnthropicWireTests.cs b/tests/Covenant.Tests/AnthropicWireTests.cs index f350066..44a436a 100644 --- a/tests/Covenant.Tests/AnthropicWireTests.cs +++ b/tests/Covenant.Tests/AnthropicWireTests.cs @@ -46,7 +46,8 @@ public void Block_array_content_concatenates_text_blocks_and_ignores_the_rest() var canonical = AnthropicWire.ToCanonical(request); - Assert.Equal("part one, part two", canonical[0].Content); // image block dropped, text kept + // Defence in depth only: ingress refuses non-text blocks (AnthropicWire.Unsupported) before this runs. + Assert.Equal("part one, part two", canonical[0].Content); } [Fact] @@ -96,6 +97,7 @@ public void Response_builder_produces_the_messages_api_shape() [InlineData(DenialKind.RateLimited, "rate_limit_error", 429)] [InlineData(DenialKind.UpstreamFailure, "api_error", 502)] [InlineData(DenialKind.Governance, "permission_error", 403)] + [InlineData(DenialKind.Unsupported, "invalid_request_error", 400)] public void Denial_kinds_map_to_anthropics_error_taxonomy(DenialKind kind, string errorType, int status) { var (type, code) = AnthropicWire.MapDenial(kind); diff --git a/tests/Covenant.Tests/CacheTests.cs b/tests/Covenant.Tests/CacheTests.cs index 18b0c4a..05a72b2 100644 --- a/tests/Covenant.Tests/CacheTests.cs +++ b/tests/Covenant.Tests/CacheTests.cs @@ -71,9 +71,22 @@ private static (InferencePipeline Pipeline, CountingChatClient Client, NullSink return (pipeline, client, sink); } - private static InferenceContext Ctx(string content, string team = "platform") => + private static InferenceContext Ctx(string content, string team = "platform", int? maxTokens = null) => new(new InferenceRequest("tester", [new ChatMessage(ChatRole.User, content)], null, - new AttributionTags(team, "w", "u"))); + new AttributionTags(team, "w", "u"), MaxOutputTokens: maxTokens)); + + [Fact] + public async Task Different_max_tokens_is_a_different_contract_so_no_cache_hit() + { + var (pipeline, client, _) = Build(new ResponseCache(), ttlSeconds: 60); + + await pipeline.ExecuteAsync(Ctx("classify this", maxTokens: 400), default); + var capped = Ctx("classify this", maxTokens: 5); + await pipeline.ExecuteAsync(capped, default); + + Assert.Equal(2, client.Calls); // a 400-token answer never serves a 5-token ask + Assert.False(capped.ServedFromCache); + } [Fact] public async Task Identical_request_hits_cache_costs_zero_and_never_reaches_the_provider_again() diff --git a/tests/Covenant.Tests/RoutingTests.cs b/tests/Covenant.Tests/RoutingTests.cs index 54254cf..95377b2 100644 --- a/tests/Covenant.Tests/RoutingTests.cs +++ b/tests/Covenant.Tests/RoutingTests.cs @@ -59,4 +59,17 @@ public void Explicitly_requested_model_bypasses_complexity_routing_but_not_polic var denied = Engine().Evaluate(Ctx("hi", requestedModel: "claude-3-opus")); Assert.Equal(PolicyEffect.Deny, denied.Effect); // …but only within the permitted set } + + [Fact] + public void Denial_reason_bounds_the_client_supplied_model_id() + { + // The reason is evidence: an unbounded model string must not land in the audit chain verbatim. + var huge = new string('x', 5000) + "\u0007"; + var outcome = Engine().Evaluate(Ctx("hi", requestedModel: huge)); + + Assert.Equal(PolicyEffect.Deny, outcome.Effect); + Assert.True(outcome.Reason.Length < 200); + Assert.Contains("truncated", outcome.Reason); + Assert.DoesNotContain("\u0007", outcome.Reason, StringComparison.Ordinal); // ordinal: ICU treats control chars as ignorable, so culture IndexOf "finds" them anywhere + } } diff --git a/tests/Covenant.Tests/WireShapeTests.cs b/tests/Covenant.Tests/WireShapeTests.cs new file mode 100644 index 0000000..2531f42 --- /dev/null +++ b/tests/Covenant.Tests/WireShapeTests.cs @@ -0,0 +1,293 @@ +using System.Net; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.Json; +using Covenant.Adapters; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// Wire-surface robustness: content governance cannot classify (images, files) and features it +/// cannot govern (tools) are REFUSED, never silently stripped — and the refusal is audited. max_tokens +/// is forwarded to the provider rather than accepted-and-dropped. +public class WireShapeTests +{ + private static JsonElement J(string raw) => JsonDocument.Parse(raw).RootElement.Clone(); + + // ---------- pure mapping ---------- + + [Fact] + public void OpenAi_plain_text_and_text_parts_are_supported() + { + var r = new OpenAiChatRequest { Messages = [ + new OpenAiMessage { Role = "user", Content = J("\"hi\"") }, + new OpenAiMessage { Role = "user", Content = J("""[{"type":"text","text":"a"},{"type":"text","text":"b"}]""") }] }; + + Assert.Null(OpenAiWire.Unsupported(r)); + Assert.Equal("ab", OpenAiWire.Text(r.Messages[1])); + } + + [Theory] + [InlineData("""{"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:x"}}]}]}""", "image_url")] + [InlineData("""{"messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"f"}}]}""", "tools")] + [InlineData("""{"messages":[{"role":"user","content":"hi"}],"functions":[{"name":"f"}]}""", "functions")] + [InlineData("""{"messages":[{"role":"assistant","content":null,"tool_calls":[{"id":"c"}]}]}""", "tool_calls")] + [InlineData("""{"messages":[{"role":"tool","content":"result"}]}""", "role 'tool'")] + public void OpenAi_ungovernable_shapes_are_named(string json, string expected) + { + var r = JsonSerializer.Deserialize(json, CovenantJsonContext.Default.OpenAiChatRequest)!; + Assert.Contains(expected, OpenAiWire.Unsupported(r)); + } + + [Theory] + [InlineData("""{"messages":[{"role":"user","content":"hi"}],"tools":null}""")] + [InlineData("""{"messages":[{"role":"user","content":"hi"}],"tools":[]}""")] // clients send tools: [] when tool use is off + [InlineData("""{"messages":[{"role":"user","content":"hi"}],"n":1,"temperature":0.2,"stream_options":{"include_usage":true}}""")] + public void OpenAi_absent_or_harmless_extras_are_not_refused(string json) + { + var r = JsonSerializer.Deserialize(json, CovenantJsonContext.Default.OpenAiChatRequest)!; + Assert.Null(OpenAiWire.Unsupported(r)); + } + + [Theory] + [InlineData("""{"messages":[{"role":"user","content":[{"type":1}]}]}""")] // type not a string + [InlineData("""{"messages":[{"role":"user","content":[{"type":"text","text":5}]}]}""")] // text not a string + [InlineData("""{"messages":[{"role":"user","content":{"weird":true}}]}""")] // content an object + [InlineData("""{"messages":[{"role":"user","content":[7,"x",null]}]}""")] // parts not objects + [InlineData("""{"messages":null}""")] + [InlineData("""{"messages":[null]}""")] + [InlineData("""{"messages":[{"role":null,"content":"hi"}],"n":2.0}""")] // null role, non-integer n>1 + public void OpenAi_malformed_content_is_refused_never_thrown(string json) + { + var r = JsonSerializer.Deserialize(json, CovenantJsonContext.Default.OpenAiChatRequest)!; + var reason = OpenAiWire.Unsupported(r); // must not throw (a throw = un-audited 500) + if (r.Messages is [{ } first]) _ = OpenAiWire.Text(first); + Assert.NotNull(reason); + } + + [Fact] + public void Denial_reasons_never_echo_client_bytes() + { + // The reason lands in the append-only audit chain: only allow-listed labels may appear in it. + const string secret = "ZZZ-secret-phi-ZZZ"; + var o = JsonSerializer.Deserialize($$"""{"messages":[{"role":"user","content":[{"type":"{{secret}}"}]}]}""", CovenantJsonContext.Default.OpenAiChatRequest)!; + var a = JsonSerializer.Deserialize($$"""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":"{{secret}}"}]}]}""", CovenantJsonContext.Default.AnthropicMessagesRequest)!; + + Assert.DoesNotContain(secret, OpenAiWire.Unsupported(o)); + Assert.DoesNotContain(secret, AnthropicWire.Unsupported(a)); + Assert.Contains("unknown", OpenAiWire.Unsupported(o)); + Assert.Contains("image_url", OpenAiWire.Unsupported(JsonSerializer.Deserialize( + """{"messages":[{"role":"user","content":[{"type":"image_url"}]}]}""", CovenantJsonContext.Default.OpenAiChatRequest)!)); + } + + [Theory] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":"hi"}],"tools":[]}""")] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}],"metadata":{"user_id":"u"}}""")] + public void Anthropic_absent_or_harmless_extras_are_not_refused(string json) + { + var r = JsonSerializer.Deserialize(json, CovenantJsonContext.Default.AnthropicMessagesRequest)!; + Assert.Null(AnthropicWire.Unsupported(r)); + } + + [Theory] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":2}]}]}""")] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":{"x":1}}]}""")] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":"text","text":[1]}]}]}""")] + [InlineData("""{"max_tokens":5,"messages":null}""")] + [InlineData("""{"max_tokens":5,"messages":[null]}""")] + public void Anthropic_malformed_content_is_refused_never_thrown(string json) + { + var r = JsonSerializer.Deserialize(json, CovenantJsonContext.Default.AnthropicMessagesRequest)!; + var reason = AnthropicWire.Unsupported(r); + _ = AnthropicWire.ToCanonical(r); + Assert.NotNull(reason); + } + + [Theory] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":"image","source":{}}]}]}""", "image")] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":"document","source":{}}]}]}""", "document")] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"x"}]}]}""", "tool_result")] + [InlineData("""{"max_tokens":5,"messages":[{"role":"user","content":"hi"}],"tools":[{"name":"f"}]}""", "tools")] + [InlineData("""{"max_tokens":5,"system":[{"type":"image","source":{}}],"messages":[{"role":"user","content":"hi"}]}""", "image")] + public void Anthropic_ungovernable_shapes_are_named(string json, string expected) + { + var r = JsonSerializer.Deserialize(json, CovenantJsonContext.Default.AnthropicMessagesRequest)!; + Assert.Contains(expected, AnthropicWire.Unsupported(r)); + } + + [Fact] + public void Anthropic_text_blocks_are_supported() + { + var r = JsonSerializer.Deserialize("""{"max_tokens":5,"system":"s","messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}]}""", + CovenantJsonContext.Default.AnthropicMessagesRequest)!; + Assert.Null(AnthropicWire.Unsupported(r)); + } + + // ---------- stage guarantees ---------- + + private static InferenceContext Ctx(string? unsupported = null, int? maxTokens = null) => + new(new InferenceRequest("t", [new ChatMessage(ChatRole.User, "hi")], null, new AttributionTags("a", "b", "c"), + MaxOutputTokens: maxTokens, UnsupportedFeature: unsupported)); + + [Fact] + public async Task Shape_stage_denies_unsupported_as_400_kind_and_never_continues() + { + bool reached = false; + var ctx = Ctx(unsupported: "content part 'image_url'"); + + await new ShapeStage().InvokeAsync(ctx, (_, _) => { reached = true; return Task.CompletedTask; }, default); + + Assert.True(ctx.IsDenied); + Assert.Equal(DenialKind.Unsupported, ctx.DenialKind); + Assert.Contains("image_url", ctx.DenialReason); + Assert.False(reached); // fail-closed: nothing downstream ran + } + + [Fact] + public async Task Shape_stage_rejects_non_positive_max_tokens_and_passes_clean_requests() + { + var bad = Ctx(maxTokens: 0); + await new ShapeStage().InvokeAsync(bad, (_, _) => Task.CompletedTask, default); + Assert.Equal(DenialKind.Unsupported, bad.DenialKind); + + bool reached = false; + await new ShapeStage().InvokeAsync(Ctx(maxTokens: 64), (_, _) => { reached = true; return Task.CompletedTask; }, default); + Assert.True(reached); + } + + private sealed class CapturingClient : MEAI.IChatClient + { + public MEAI.ChatOptions? Seen; + public Task GetResponseAsync(IEnumerable m, MEAI.ChatOptions? o = null, CancellationToken ct = default) + { Seen = o; return Task.FromResult(new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, "ok")) { Usage = new MEAI.UsageDetails { InputTokenCount = 1, OutputTokenCount = 1 } }); } + public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable m, MEAI.ChatOptions? o = null, [EnumeratorCancellation] CancellationToken ct = default) + { Seen = o; await Task.Yield(); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "ok"); } + public object? GetService(Type t, object? k = null) => null; + public void Dispose() { } + } + + [Fact] + public async Task Provider_stage_forwards_max_tokens_to_the_model_call() + { + var client = new CapturingClient(); + var stage = new ProviderCallStage(new ChatClientRegistry(new Dictionary { ["openai:m"] = client })); + var ctx = Ctx(maxTokens: 77); + ctx.Policy = PolicyOutcome.Allow(new RouteTarget("openai", "m")); + + await stage.InvokeAsync(ctx, (_, _) => Task.CompletedTask, default); + + Assert.Equal(77, client.Seen?.MaxOutputTokens); + } + + // ---------- through the Host: both dialects return 400 in their own error shape, and the refusal is audited ---------- + + public sealed class Ingress : IClassFixture>, IDisposable + { + private readonly string _auditPath = Path.Combine(Path.GetTempPath(), $"covenant-shape-{Guid.NewGuid():n}.log"); + private readonly WebApplicationFactory _factory; + private readonly HttpClient _client; + + public Ingress(WebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(b => + { + b.UseEnvironment("Production"); + b.UseSetting("OpenAI:ApiKey", "test-key"); + b.UseSetting("OpenAI:Endpoint", "http://127.0.0.1:9"); + b.UseSetting("Admin:Token", "test-admin"); + b.UseSetting("Budget:GlobalCapUsd", "100"); + b.UseSetting("Auth:Keys:0:Key", "k"); + b.UseSetting("Auth:Keys:0:Principal", "shape-tester"); + b.UseSetting("Auth:Keys:0:Team", "t"); + b.UseSetting("Audit:Path", _auditPath); + }); + _client = _factory.CreateClient(); + _client.DefaultRequestHeaders.Add("x-api-key", "k"); + _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "k"); + } + + public void Dispose() { _factory.Dispose(); if (File.Exists(_auditPath)) File.Delete(_auditPath); } + + private static StringContent Body(string json) => new(json, Encoding.UTF8, "application/json"); + + /// The audit sink drains off the hot path — poll for the entry instead of sleeping. + private async Task WaitForAuditAsync(string marker) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (DateTime.UtcNow < deadline) + { + if (File.Exists(_auditPath) && await File.ReadAllTextAsync(_auditPath) is var s && s.Contains(marker)) return s; + await Task.Delay(25); + } + throw new TimeoutException($"audit entry '{marker}' not written within 5s"); + } + + [Fact] + public async Task OpenAi_image_content_is_400_unsupported_and_audited() + { + var resp = await _client.PostAsync("/v1/chat/completions", + Body("""{"messages":[{"role":"user","content":[{"type":"text","text":"what is this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]}""")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode); + Assert.Contains("\"error\":\"unsupported\"", json); + Assert.Contains("image_url", json); + + var log = await WaitForAuditAsync("unsupported request shape"); + Assert.Contains("shape-tester", log); // the resolved caller, not "anonymous" + Assert.DoesNotContain("AAAA", log); // the image bytes never reach evidence + } + + [Fact] + public async Task Client_supplied_type_label_never_reaches_response_or_evidence() + { + const string secret = "QQQ-not-for-evidence-QQQ"; + var resp = await _client.PostAsync("/v1/chat/completions", + Body($$"""{"messages":[{"role":"user","content":[{"type":"{{secret}}","data":"x"}]}]}""")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode); + Assert.DoesNotContain(secret, json); + var log = await WaitForAuditAsync("unsupported request shape"); + Assert.DoesNotContain(secret, log); + } + + [Fact] + public async Task OpenAi_tools_are_400_unsupported() + { + var resp = await _client.PostAsync("/v1/chat/completions", + Body("""{"messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"get_weather"}}]}""")); + + Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode); + Assert.Contains("tools", await resp.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Anthropic_image_block_is_400_invalid_request_error() + { + var resp = await _client.PostAsync("/v1/messages", + Body("""{"model":"gpt-4o-mini","max_tokens":10,"messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AAAA"}}]}]}""")); + var json = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode); + Assert.Contains("invalid_request_error", json); + Assert.Contains("image", json); + } + + [Fact] + public async Task Streamed_unsupported_request_is_plain_json_400_not_sse() + { + var resp = await _client.PostAsync("/v1/chat/completions", + Body("""{"stream":true,"messages":[{"role":"user","content":"hi"}],"tool_choice":"auto","tools":[{"type":"function","function":{"name":"f"}}]}""")); + + Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode); + Assert.NotEqual("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + } + } +}