diff --git a/README.md b/README.md index f78fe59..c261188 100644 --- a/README.md +++ b/README.md @@ -1,55 +1,37 @@ # Covenant -An in-perimeter **AI inference governance and FinOps control plane** for organizations that must show who used which model, with what data, where it ran and what it cost. Every LLM request passes through one governed pipeline: identified, classified, policy-routed, budget-checked, cost-attributed and audited — including the requests that get refused. +An in-perimeter **AI inference governance and FinOps control plane** for organizations that must show who used which model, with what data, where it ran and what it cost. Every LLM request passes through one governed pipeline: identified, classified, policy-routed, budget-checked, cost-attributed and audited; including the requests that get refused. -Research artifact: can inference governance be an architecturally separable control layer — enforceably, evidentially, and at acceptable cost? +Research artifact: can inference governance be an architecturally separable control layer; enforceably, evidentially, and at acceptable cost? **Start here:** [User guide](docs/user-guide.md) · [7-minute demo](docs/demo-7-minute.md) · [Console usage guide](docs/console-quickstart.md) · [Tavily setup](docs/web-search.md) -## Deployment and trust boundaries - -```mermaid -flowchart LR - subgraph Org["Customer perimeter"] - direction LR - Apps["Calling applications
(app key → team)"] --> C["Covenant appliance
canonical proxy + policy middleware"] - Console["Admin console
(admin token)"] --> C - C --> Ollama["Local models
(Ollama, in perimeter)"] - C -.-> Audit[("Hash-chained audit
+ budget ledger")] - Vault["Server-side secrets
(env / vault)"] -.-> C - end - C == "approved egress allow-list only" ==> Providers["Approved model providers
(Anthropic, OpenAI)"] - C == "Public only, opt-in" ==> Search["Tavily web search"] - Browser["Direct SaaS use in a browser"] -. "outside Covenant's scope" .-> Providers -``` - -Credentials stay on the server; the console never holds an application key or a provider key. Egress is limited to the -startup allow-list. Traffic that does not pass through Covenant (for example a browser talking to a SaaS chatbot) is not -governed by it; that needs network or endpoint controls. - -## Request journey - -```mermaid -flowchart LR - A["Identify caller
application → team"] --> B["Classify
workload baseline,
detection may raise"] - B --> P["Policy
one match → approved
primary + fallback"] - P --> R["Sanitize
only for an opted-in
structured-record route"] - R --> K["Exact cache"] --> G["Rate · pause · budget
reserve before spend"] - G --> W["Web search
(Public, opt-in)"] --> M["Model call
Local or External"] - M --> F["Finalize cost"] --> E[("Audit record
every request, refused too")] - P -. "no match / not eligible" .-> X["Refuse (fail-closed)"] -.-> E -``` - -The patterns are a canonical proxy with policy middleware, approved model routing with bounded fallback, -retrieval-augmented answers from one governed web search, an exact-match cache, and per-request attribution and -tamper-evident audit. Covenant does **not** rewrite prompts, does not judge answer quality, and has no learned quality -router. The optional length-based strategy is a deterministic size threshold (characters / 4), not a quality signal. -Sanitization (ADR-0016) applies only to a bounded structured record on a dedicated route. It is not anonymisation. +## System overview + +Applications send AI requests through Covenant. It checks the caller, data, policy and budget before selecting an approved model. Local processing stays inside the organization. Cloud inference and web search cross the boundary only when permitted. Every outcome has an audit record and cost attribution. + +![Covenant system overview](docs/diagrams/covenant-overview.svg) + +[Edit the overview in Draw.io](docs/diagrams/covenant-overview.drawio) + +## Request flow + +The numbered flow shows the checks in execution order. A matching cache entry avoids a model call. A refusal stops further work, but earlier calls can still have a cost. The final record identifies the application, team, route, outcome and charges. + +![Covenant request processing flow](docs/diagrams/covenant-architecture.svg) + +[Edit the detailed diagram in Draw.io](docs/diagrams/covenant-architecture.drawio) + +**Architecture patterns:** canonical proxy, policy middleware, provider adapters, exact-match cache, governed retrieval and tamper-evident audit. Routing follows configured rules. Covenant does not evaluate answer quality or automatically rewrite prompts. + +**Scope:** traffic must pass through Covenant to be governed. Direct chatbot access needs network or endpoint controls. Sensitive-data inspection is heuristic, not comprehensive DLP. The optional sanitized route accepts a narrow structured schema; it does not anonymize arbitrary prose or PHI. + +Both diagrams use editable Draw.io shapes and connectors. The matching SVG images are generated from [the diagram source](docs/diagrams/gen_diagram.py). ## Working principles -1. **Fail-closed.** No policy match → deny. Unclassified defaults to the most restrictive class. Misconfiguration → the appliance refuses to start. Raw PII/PHI never reaches a public provider. The one opt-in exception (ADR-0016) sends only a Covenant-built, sanitized payload of a bounded structured record for a dedicated PII workload; PHI and free text never qualify. -2. **Governance is the pipeline, not a bolt-on.** Every capability — classification, policy, budgets, attribution, audit — is an ordered stage in one middleware chain. Nothing bypasses it. +1. **Fail-closed.** No policy match → deny. Unclassified defaults to the most restrictive class. Misconfiguration → the appliance refuses to start. Detected raw PII/PHI is excluded from public provider routes. The one opt-in exception (ADR-0016) sends only a Covenant-built, sanitized payload of a bounded structured record for a dedicated PII workload; PHI and free text never qualify. +2. **Governance is the pipeline, not a bolt-on.** Every capability; classification, policy, budgets, attribution, audit; is an ordered stage in one middleware chain. Nothing bypasses it. 3. **Everything is evidence.** Each request, allowed or denied, appends exactly one hash-chained audit entry. Altering any past entry breaks every hash after it. 4. **The perimeter is sacred.** Deployed inside the customer boundary; egress only to approved model endpoints and explicitly enabled Public web search (ADR-0015); no phone-home. diff --git a/docs/adr/ADR-0019-workload-sensitive-data-action.md b/docs/adr/ADR-0019-workload-sensitive-data-action.md new file mode 100644 index 0000000..b48b6c9 --- /dev/null +++ b/docs/adr/ADR-0019-workload-sensitive-data-action.md @@ -0,0 +1,104 @@ +# ADR-0019 — Per-workload action on detected sensitive data: route or reject + +**Status:** Accepted +**Date:** 2026-11-02 +**Relates to:** ADR-0012 (trusted baseline; detection may only escalate), ADR-0013 (PII/PHI never external; no match ⇒ +refuse), ADR-0016 (sanitized structured-record exception), ADR-0018 (local inspection; incomplete ⇒ refuse). + +## Context +Detection escalates a request's classification (ADR-0012): final = max(workload baseline, detected). The escalated +request is then routed by whatever policy covers PII/PHI. In the demo seed that is `sensitive` (PII & PHI → local +model), a policy with no profile scope. So a request sent under the **Public** workload that contains an SSN is +served by the local model. + +That is safe: nothing leaves the perimeter. The evidence also records it: the audit record and the console show the +escalated classification and the detector signal. But the request still succeeds on a destination the caller did not +declare for: they said "this is public content", the content contradicts that, and the gateway serves it elsewhere +instead of refusing. Two things follow: + +- a workload cannot say "never accept sensitive data" — the most it gets is an after-the-fact evidence entry; +- the demo cannot show the difference between "an Internal workload that is approved to process sensitive data + locally" and "a Public workload that must never receive it". Both end up on the same local model. + +A UI-side fix (pinning a model, special-casing an example name) would not change what the gateway does for a raw API +caller, so it would be theatre. The decision has to be server-side, per workload, versioned and audited. + +## Decision +1. **A workload profile states what happens when detection finds PII or PHI.** New field + `WorkloadProfileConfig.SensitiveDataAction`, wire name `sensitive_data_action`: + - `route` (default): today's behaviour. The classification is escalated and the policy for PII/PHI decides. + ADR-0013 still applies, so that policy can only use local targets — except the ADR-0016 sanitized policy. + - `reject`: when detection raises the classification to PII or PHI, the request is **refused at the classify + stage**, before policy, sanitization, cache, rate limit, budget, web search and provider. Nothing is sent + anywhere and nothing is reserved. + + The name is `route`, not `route_local`: the profile does not choose the destination; the versioned policy does, + and the existing invariants keep PII/PHI local. + +2. **Default `route`; existing configurations are unchanged.** A version without the field reads as `route`. No + stored version is rewritten. The dedicated sanitized-record workload (baseline PII, ADR-0016) keeps working. + +3. **Validation.** `reject` is valid only on a Public- or Internal-baseline profile (code + `sensitive_action_requires_non_sensitive_baseline`). On a PII/PHI baseline every request is sensitive by + declaration, so rejecting "detected" sensitive data would reject everything. An undefined value is `invalid_enum`. + +4. **One rule, three callers.** `SensitiveDataRules.Rejects(cfg, profileId, finalClassification)` decides; + `SensitiveDataRules.Explain(...)` builds the reason and `SensitiveDataRules.Suggestions(...)` the suggested + workloads. The rule is called by: + - the classify stage (runtime); + - `POST /admin/policies/simulate` (the preview shows the same refusal and reason); + - `PolicyEngineV2.Evaluate` (defence in depth). This also means the impact preview and route summaries show + "refused" for PII/PHI under a `reject` workload. + + Incomplete inspection (ADR-0018) is still checked first and still refuses with `inspection_incomplete`. + +5. **Evidence and feedback.** The refusal is a governance denial at stage `classify` with reason code + `sensitive_data_rejected`. The audit record keeps: + - the escalated classification (PII/PHI); + - the detector signal label (never the matched value); + - the application, team and workload. + + The reason names the workload and the detected kind. When the same application is granted another workload under + which the engine would route that classification (action `route`, an eligible route), the reason also suggests it + by id. The simulate response returns the same suggestion as `suggested_profiles`. The suggestion is computed by + the policy engine, never hard-coded. + +6. **Demo seed.** `public-demo` is seeded with `reject`; `internal-default` keeps `route`. Seeds only create a first + version; an existing runtime is not changed (see Migration). + +## Migration (existing saved configurations) +Nothing changes until an operator saves a new version. To get the new demo behaviour on a runtime created before +this ADR, set `sensitive_data_action` to `reject` on the Public workload. This creates version N+1, audited as +`config.activated`. Either: + +- **Console:** Policies → Workloads → *Public demo* → Edit → "When sensitive data is detected" → **Reject the + request** → Save. +- **API:** + 1. `GET /admin/config`; note `etag` (`"vN"`). + 2. In `config.profiles`, on the entry with `"id": "public-demo"`, add `"sensitive_data_action": "reject"`. + 3. `POST /admin/config/validate` with `{"base_version": N, "config": …}`. Expect `valid: true`. The impact lists + PII and PHI under `public-demo` changing to `refused: …`. + 4. `PUT /admin/config` with `If-Match: "vN"` and `{"config": …, "change_summary": "public-demo rejects detected + sensitive data (ADR-0019)"}`. + +Rollback is the normal configuration rollback to vN. + +## Consequences +- A Public workload can now say "never accept sensitive data". The caller gets an explicit refusal with the reason + and a suggested workload, instead of a local answer to a request it declared public. +- The console offers the Internal-local / Public-rejected example pair only to an application whose workloads show both + halves, so applications without that set-up are not shown sensitive-data examples. +- The audit still shows what was detected, so Usage still counts "sensitive detected". +- One more profile field in the configuration contract, the UI DTO and the workload editor. +- Detection quality limits still apply (ADR-0018): `reject` acts on what the local inspector detects. It does not + guarantee that a Public request is free of sensitive data. + +## Alternatives considered +- **Policy-level flag** ("this PII policy refuses for Public"). Rejected: the policy is chosen by the escalated + classification, so it no longer knows which workload the caller declared, unless every sensitive policy is + profile-scoped. It is also the wrong owner: the declaration belongs to the workload. +- **Always reject sensitive data under Public.** Rejected: a breaking change for existing deployments, and some + operators want "serve locally" as the safe default. +- **UI pin / example special-casing.** Rejected: it does not govern raw API callers. +- **`route_local` as a second action.** Rejected: the profile would then pick a destination, bypassing the + versioned policy that owns routing. diff --git a/docs/demo-7-minute.md b/docs/demo-7-minute.md index 6692bf8..63e2fe3 100644 --- a/docs/demo-7-minute.md +++ b/docs/demo-7-minute.md @@ -44,10 +44,11 @@ pricing. ## 3. Sensitive record: denied, then an explicit sanitized route (≈2.5 min) -1. **Local, then denied:** example **Sensitive data detected: served locally** (same prompt, policy chooses → local), then - **Sensitive data: explicit external attempt is blocked**. The synthetic SSN `000-12-3456` raises the request - to PII, and the pinned external model is refused at Policy. The red **Sensitive · PII (detected …)** chip shows it; - nothing is sent. +1. **Local, then denied:** choose **Demo application**, then **Internal workload: sensitive data served locally**. + Use example selects Internal. Run it, switch to Public, and run the identical prompt. The synthetic SSN raises + classification to PII; the Public workload rejects it at Classify, before cache, search or any model call. + The paired **Public workload: the same sensitive data is rejected** example is recommended too. + Configure the Public workload to **Reject the request** on detection before the session. 2. **Explicit policy:** Policies → Routes → the `support-records` route. Show the **Sanitized external route** section: - only the dedicated PII workload uses it; - only the listed identifier fields and tasks are accepted; diff --git a/docs/demo-quickstart.md b/docs/demo-quickstart.md index 265d27c..3a48893 100644 --- a/docs/demo-quickstart.md +++ b/docs/demo-quickstart.md @@ -8,7 +8,7 @@ From **Overview**, click **Open Playground**. Choose **Send a request as → Exa 1. **Research assistant → Public research: local model + governed web search.** Show local inference, Tavily sources and the separate search charge. 2. **Engineering assistant → Compare local coding with ** (for example Claude Opus 5.5; the title comes from the approved route). Before Run, the steps say: local first, then an explicit comparison. Run locally, then press **Compare with Claude Opus 5.5**. It is a separate paid request using the same original prompt and caller; which answer is better is your judgement. -3. **Communications assistant → More examples → Sensitive data detected: served locally**, then **Sensitive data: explicit external attempt is blocked**. Same synthetic prompt: with policy choosing it is *Served locally · sensitive data detected*; with the example's explicit external pin it is *Blocked · sensitive data cannot go external* (a governance block, not a provider outage). Switching workload resets the example's pin to “Let policy choose”. +3. **Demo application → Internal workload: sensitive data served locally.** Use example selects **Internal**. Run and show the local answer. Switch only the workload to **Public** and run the same prompt: the gateway rejects it before cache, search or model calls. The paired Public rejection example is also in the recommended list. This requires the Public workload's **When sensitive data is detected** setting to be **Reject the request**. 4. **Support assistant → Sensitive record: sanitized external call (opt-in).** Use example, review the placeholder-only payload, tick the confirmation and Run. Only the supported structured record qualifies; arbitrary prose and PHI do not. 5. **Engineering assistant → More examples → Repeat a request: exact cache hit.** Run twice within five minutes. The second is audited but makes no provider call. 6. Open **Usage** to show who pays; **Requests** (25 per page, Previous/Next) → **View** explains an individual decision; **Budgets** shows Global plus the additional application ceiling over the same charges. **Audit & evidence → Check audit integrity** checks record consistency, not answer correctness. diff --git a/docs/diagrams/covenant-architecture.drawio b/docs/diagrams/covenant-architecture.drawio index 679a66f..6d9fbab 100644 --- a/docs/diagrams/covenant-architecture.drawio +++ b/docs/diagrams/covenant-architecture.drawio @@ -1 +1,2 @@ - \ No newline at end of file + + \ No newline at end of file diff --git a/docs/diagrams/covenant-architecture.png b/docs/diagrams/covenant-architecture.png new file mode 100644 index 0000000..e992113 Binary files /dev/null and b/docs/diagrams/covenant-architecture.png differ diff --git a/docs/diagrams/covenant-architecture.svg b/docs/diagrams/covenant-architecture.svg index 916c391..2178fa3 100644 --- a/docs/diagrams/covenant-architecture.svg +++ b/docs/diagrams/covenant-architecture.svg @@ -1,164 +1,4 @@ - - - -Covenant — in-perimeter AI inference governance & FinOps control plane -Every request passes the same ordered governance pipeline; the hash-chained audit log is the evidence of record, everything else is a derived view. - -Customer perimeter — no prompt, response, or metadata leaves; egress only to the allow-listed models - -Covenant appliance — single .NET process, NativeAOT target - -OpenAI-compatible clients -SDKs · Open WebUI · Bearer key - -Anthropic clients -x-api-key · Messages API - -Admins / auditors -admin token - -Ingress -/v1/chat/completions -/v1/messages -/v1/models - -→ one canonical request - -Audit stage — outermost; records allow, deny, and error alike -metadata + SHA-256 prompt fingerprint — never content - -Auth + shape -keys · text only - -Classify -PII / PHI - -Policy -route, complexity - -Cache -team-scoped TTL - -Rate limit -team + global - -Budget -caps, kill switch - -Provider call -adapter:model - -Attribute cost -team, workflow - -Denied — fail-closed -400 · 401 · 403 · 429 · 502 -no provider call, still audited - -Response + usage -OpenAI or Anthropic wire -buffered or SSE stream - -Hash-chained audit log -append-only · SHA-256 links -tampered chain refuses boot - -Chain-head anchors -Nth head hash → separate storage -end-truncation detectable (ADR-0007) - -Spend ledger -replayed from the log at boot -read by the Budget stage - -Local model -Ollama / vLLM -in-perimeter, PII/PHI - -OpenAI -openai adapter - -Anthropic -anthropic adapter -Egress allow-list only - -Admin dashboard -/admin/ui · FinOps savings -kill switch · live SSE · reset - -Evidence export -/admin/evidence -verifies chain + anchors - -Neo4j evidence graph -optional (ADR-0006) -verified prefix only - -OTel collector -optional (ADR-0003) -spans, never content - - - - - - - - - - - - - - - -miss - - - - - - - - - - - -any stage denies - - - - - - - - - -every request - - - - - -boot replay - - - - - - - - - - - -Callers / wire - -Governance stages - -Providers - -Evidence - -Denial (fail-closed) - \ No newline at end of file + + + +
How a request is governed
Read top to bottom. A refusal stops further work and still creates an audit record.
INPUT AND CONTROL
REQUEST PIPELINE
DESTINATIONS AND RESULTS
1
Identify the caller
Authenticate the application; bind its team.
Validate the request format.
2
Inspect the content
Combine the workload label with detection.
Incomplete inspection means refuse.
3
Apply the policy
Enforce sensitive-data handling and routes.
Sanitize only an approved structured record.
4
Check the exact cache
Reuse only an eligible, matching response.
A cache hit avoids a new model call.
5
Check limits and retrieve
Check rate, pause and budget reservation.
Optional Public web search is governed too.
6
Call an approved model
Use the selected local or external adapter.
Fallback stays within the approved routes.
7
Finalize and record
Settle usage and attribute cost to the team.
Record the outcome and return the response.
Application request
OpenAI / Anthropic compatible API
Application key identifies the caller
Sensitive data rules
Internal: approved local processing
Public demo: reject detected PII/PHI
Detection can raise the data label.
No match is not proof of safe data.
Configuration
Profiles, routes and model allow-list
Budgets and permission settings
Provider secrets stay on the server.
Refused or failed
Record the reason and any usage.
Do not continue to later stages.
Earlier tool or model calls may
already have incurred a charge.
Exact cache hit
Skip retrieval and model execution.
Still record and attribute the request.
Tavily web search
Public only, explicitly enabled
Sources and cost recorded separately
Approved models
Local: Ollama / Qwen
External: Anthropic / OpenAI
Audit and budget ledger
Hash-linked request evidence
Costs by application and team
DESIGN PATTERNS Canonical proxy • Policy middleware • Provider adapters • Exact cache • Governed retrieval • Audit trail
Sensitive-data inspection is bounded and heuristic. Sanitization supports a narrow schema, not arbitrary prose or PHI.
Text is not SVG - cannot display
\ No newline at end of file diff --git a/docs/diagrams/covenant-overview.drawio b/docs/diagrams/covenant-overview.drawio index 1023b22..ebd2ed9 100644 --- a/docs/diagrams/covenant-overview.drawio +++ b/docs/diagrams/covenant-overview.drawio @@ -1 +1,2 @@ - \ No newline at end of file + + \ No newline at end of file diff --git a/docs/diagrams/covenant-overview.png b/docs/diagrams/covenant-overview.png new file mode 100644 index 0000000..90bdef2 Binary files /dev/null and b/docs/diagrams/covenant-overview.png differ diff --git a/docs/diagrams/covenant-overview.svg b/docs/diagrams/covenant-overview.svg index 7290c8d..5adb507 100644 --- a/docs/diagrams/covenant-overview.svg +++ b/docs/diagrams/covenant-overview.svg @@ -1,61 +1,4 @@ - - - -Covenant at a glance - - -Customer perimeter — nothing leaves except allow-listed model egress - -Any AI client -OpenAI or Anthropic wire -SDKs, Open WebUI, agents - -Covenant — one governed pipeline -auth → shape → classify → policy → cache → rate limit -→ budget / kill switch → provider → attribute cost - -fail-closed: no match, no call - -Tamper-evident evidence -hash-chained audit log + anchored head -spend ledger · evidence export · dashboard - -In-perimeter model -Ollama / vLLM -PII / PHI never leave - -Allow-listed providers -OpenAI · Anthropic -egress only to these - -Admins / auditors -kill switch · evidence - - - -every request - - - -permitted routes - - - -sensitive data - - - -allow, deny, error alike - - - -Callers / wire - -Governance stages - -Providers - -Evidence - -Denial (fail-closed) - \ No newline at end of file + + + +
Covenant at a glance
One governed entry point between your applications and approved AI services.
YOUR ORGANIZATION
APPROVED EXTERNAL SERVICES
Applications
App identity
Owning team
Covenant
Inspect data and apply rules
Choose an approved route
Check spend and record proof
Local models
Ollama / Qwen
Cloud models
Anthropic / OpenAI
Only when policy permits
Admin console
Rules, routes and budgets
Evidence and costs
Every outcome, including refusals
Web search
Tavily, for approved Public work
Approved cloud route
Optional external search
All outcomes
LOCAL Data stays inside | EXTERNAL Data leaves only through an approved route | EVIDENCE Who, what, where and cost
Direct access to a chatbot bypasses Covenant. Use network and endpoint controls to require this path.
Text is not SVG - cannot display
\ No newline at end of file diff --git a/docs/diagrams/gen_diagram.py b/docs/diagrams/gen_diagram.py index 8ebd3e2..f0ad8c0 100644 --- a/docs/diagrams/gen_diagram.py +++ b/docs/diagrams/gen_diagram.py @@ -1,188 +1,110 @@ -"""Generates docs/diagrams/covenant-architecture.{drawio,svg} from one node/edge list. -The SVG embeds the draw.io XML (content attribute) so draw.io can reopen the SVG directly.""" -import html, sys, os - -# palette (matches README mermaid classDefs) -C = { - "caller": ("#e3f2fd", "#1565c0", "#0d47a1"), - "govern": ("#fff3e0", "#ef6c00", "#e65100"), - "provider": ("#e8f5e9", "#2e7d32", "#1b5e20"), - "evidence": ("#f3e5f5", "#6a1b9a", "#4a148c"), - "denied": ("#ffebee", "#c62828", "#b71c1c"), - "neutral": ("#f5f5f5", "#616161", "#212121"), - "none": ("none", "#616161", "#212121"), -} - -# id, kind, x, y, w, h, lines, opts -N_DETAIL = [ - ("perimeter", "none", 260, 60, 920, 830, ["Customer perimeter — no prompt, response, or metadata leaves; egress only to the allow-listed models"], {"container": True, "dashed": True}), - ("appliance", "none", 290, 120, 690, 560, ["Covenant appliance — single .NET process, NativeAOT target"], {"container": True}), - - ("c_openai", "caller", 30, 190, 190, 70, ["OpenAI-compatible clients", "SDKs · Open WebUI · Bearer key"], {}), - ("c_anthropic", "caller", 30, 290, 190, 70, ["Anthropic clients", "x-api-key · Messages API"], {}), - ("c_admin", "caller", 30, 720, 190, 70, ["Admins / auditors", "admin token"], {}), - - ("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 + 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"], {}), - ("s_rate", "govern", 840, 320, 100, 55, ["Rate limit", "team + global"], {}), - ("s_budget", "govern", 730, 320, 100, 55, ["Budget", "caps, kill switch"], {}), - ("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", "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"], {}), - ("anchors", "evidence", 530, 560, 220, 80, ["Chain-head anchors", "Nth head hash → separate storage", "end-truncation detectable (ADR-0007)"], {}), - ("ledger", "evidence", 770, 560, 190, 80, ["Spend ledger", "replayed from the log at boot", "read by the Budget stage"], {}), - - ("local", "provider", 1000, 380, 160, 70, ["Local model", "Ollama / vLLM", "in-perimeter, PII/PHI"], {}), - - ("p_openai", "provider", 1220, 180, 160, 60, ["OpenAI", "openai adapter"], {}), - ("p_anthropic", "provider", 1220, 270, 160, 60, ["Anthropic", "anthropic adapter"], {}), - ("egress", "none", 1200, 130, 200, 30, ["Egress allow-list only"], {"plain": True}), - - ("dash", "caller", 310, 730, 200, 80, ["Admin dashboard", "/admin/ui · FinOps savings", "kill switch · live SSE · reset"], {}), - ("export", "evidence", 540, 730, 200, 80, ["Evidence export", "/admin/evidence", "verifies chain + anchors"], {}), - ("neo4j", "evidence", 770, 730, 190, 80, ["Neo4j evidence graph", "optional (ADR-0006)", "verified prefix only"], {"dashed": True}), - ("otel", "neutral", 990, 730, 170, 80, ["OTel collector", "optional (ADR-0003)", "spans, never content"], {"dashed": True}), -] - -# source, target, label, dashed, svg points (explicit polyline for the SVG render) -E_DETAIL = [ - ("c_openai", "ingress", "", False, [(220, 225), (310, 225)]), - ("c_anthropic", "ingress", "", False, [(220, 325), (310, 325)]), - ("ingress", "s_auth", "", False, [(460, 237), (510, 237)]), - ("s_auth", "s_classify", "", False, [(610, 237), (620, 237)]), - ("s_classify", "s_policy", "", False, [(720, 237), (730, 237)]), - ("s_policy", "s_cache", "", False, [(830, 237), (840, 237)]), - ("s_cache", "s_rate", "miss", False, [(890, 265), (890, 320)]), - ("s_rate", "s_budget", "", False, [(840, 347), (830, 347)]), - ("s_budget", "s_provider", "", False, [(730, 347), (720, 347)]), - ("s_provider", "s_attr", "", False, [(620, 347), (610, 347)]), - ("s_attr", "response", "", False, [(560, 375), (560, 395), (845, 395), (845, 440)]), - ("audit", "denied", "any stage denies", False, [(595, 410), (595, 440)]), - ("s_provider", "local", "", False, [(670, 375), (670, 425), (1000, 425)]), - ("s_provider", "p_openai", "", False, [(985, 425), (985, 210), (1220, 210)]), - ("s_provider", "p_anthropic", "", False, [(985, 290), (1220, 290)]), - ("audit", "log", "every request", False, [(490, 395), (475, 395), (475, 545), (410, 545), (410, 560)]), - ("log", "anchors", "", False, [(510, 600), (530, 600)]), - ("log", "ledger", "boot replay", False, [(510, 625), (525, 625), (525, 655), (755, 655), (755, 625), (770, 625)]), - ("log", "export", "", False, [(400, 640), (400, 690), (640, 690), (640, 730)]), - ("log", "neo4j", "", True, [(420, 640), (420, 705), (865, 705), (865, 730)]), - ("audit", "otel", "", True, [(960, 390), (970, 390), (970, 720), (1075, 720), (1075, 730)]), - ("c_admin", "dash", "", False, [(220, 755), (310, 755)]), - ("c_admin", "export", "", False, [(220, 770), (270, 770), (270, 825), (640, 825), (640, 810)]), -] - -N, E, SIZE, TITLE = [], [], [None], [None] - -# ---------------- draw.io ---------------- -def drawio(): - cells = ['', ''] - for nid, kind, x, y, w, h, lines, o in N: - fill, stroke, font = C[kind] - label = "<b>" + html.escape(lines[0]) + "</b>" + ("<br>" + "<br>".join(html.escape(l) for l in lines[1:]) if len(lines) > 1 else "") - style = f"rounded=1;whiteSpace=wrap;html=1;fillColor={fill};strokeColor={stroke};fontColor={font};" - if o.get("container"): style += "verticalAlign=top;align=left;spacingLeft=8;spacingTop=2;container=1;" - if o.get("dashed"): style += "dashed=1;" - if o.get("plain"): style = "text;html=1;align=center;verticalAlign=middle;fontStyle=2;fontColor=#616161;" - if kind == "none" and not o.get("plain"): style += "strokeWidth=2;" - cells.append(f'') - for i, (s, t, label, dashed, _) in enumerate(E): - style = "edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;endFill=1;strokeColor=#455a64;" + ("dashed=1;" if dashed else "") - cells.append(f'') - return ('' - '' - f'' - '' + "".join(cells) + '') - -# ---------------- SVG ---------------- -def svg(embed_xml): - W, H = SIZE[0] - out = [f'', - '', - f'', - f'{html.escape(TITLE[0])}', - (SIZE[0][0] > 1300 and 'Every request passes the same ordered governance pipeline; the hash-chained audit log is the evidence of record, everything else is a derived view.' or '')] - for nid, kind, x, y, w, h, lines, o in N: - fill, stroke, font = C[kind] - dash = ' stroke-dasharray="6 4"' if o.get("dashed") else "" - if o.get("plain"): - out.append(f'{html.escape(lines[0])}') - continue - sw = 2 if kind == "none" else 1.2 - out.append(f'') - if o.get("container"): - out.append(f'{html.escape(lines[0])}') - for j, l in enumerate(lines[1:]): - out.append(f'{html.escape(l)}') - continue - n = len(lines); lh = 15 - y0 = y + h/2 - (n - 1) * lh / 2 + 4 - for i, l in enumerate(lines): - fw = ' font-weight="700"' if i == 0 else ' fill-opacity="0.85"' - out.append(f'{html.escape(l)}') - for s, t, label, dashed, pts in E: - d = " ".join(f"{px},{py}" for px, py in pts) - dash = ' stroke-dasharray="6 4"' if dashed else "" - out.append(f'') - # explicit arrowhead (renderer-independent): triangle along the final segment - (x1, y1), (x2, y2) = pts[-2], pts[-1] - dx, dy = x2 - x1, y2 - y1 - L = (dx*dx + dy*dy) ** 0.5 or 1 - ux, uy = dx / L, dy / L - bx, by = x2 - ux * 9, y2 - uy * 9 - out.append(f'') - if label: - segs = list(zip(pts, pts[1:])) - (ax, ay), (cx, cy) = max(segs, key=lambda p: abs(p[1][0]-p[0][0]) + abs(p[1][1]-p[0][1])) - mx, my = (ax + cx) / 2, (ay + cy) / 2 - w = len(label) * 6.2 + 8 - out.append(f'') - out.append(f'{html.escape(label)}') - # legend - lx, ly = 20, 100 - for i, (name, kind) in enumerate([("Callers / wire", "caller"), ("Governance stages", "govern"), ("Providers", "provider"), ("Evidence", "evidence"), ("Denial (fail-closed)", "denied")]): - fill, stroke, font = C[kind] - out.append(f'') - out.append(f'{name}') - out.append('') - return "\n".join(out) - -# ---------------- high-level overview (one glance) ---------------- -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 → 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"], {}), - ("admins", "caller", 30, 360, 180, 70, ["Admins / auditors", "kill switch · evidence"], {}), -] -E_HL = [ - ("clients", "covenant", "every request", False, [(210, 265), (250, 265), (250, 195), (290, 195)]), - ("covenant", "external", "permitted routes", False, [(650, 185), (1000, 185)]), - ("covenant", "local", "sensitive data", False, [(650, 245), (805, 245), (805, 320)]), - ("covenant", "evidence", "allow, deny, error alike", False, [(470, 270), (470, 320)]), - ("admins", "evidence", "", False, [(210, 395), (290, 395)]), -] - -if __name__ == "__main__": - outdir = sys.argv[1] - os.makedirs(outdir, exist_ok=True) - for name, nodes, edges, size, title in [ - ("covenant-architecture", N_DETAIL, E_DETAIL, (1420, 910), "Covenant — in-perimeter AI inference governance & FinOps control plane"), - ("covenant-overview", N_HL, E_HL, (1240, 500), "Covenant at a glance"), - ]: - N[:] = nodes; E[:] = edges; SIZE[0] = size; TITLE[0] = title - xml = drawio() - open(os.path.join(outdir, f"{name}.drawio"), "w").write(xml) - open(os.path.join(outdir, f"{name}.svg"), "w").write(svg(xml)) - print("ok") +"""Original Covenant diagram artwork. Generates editable Draw.io XML and matching SVG. +Standard library only. Edit coordinates/content here, then run this script. +""" +from pathlib import Path +from xml.etree.ElementTree import Element, SubElement, tostring +from html import escape + +OUT=Path(__file__).parent +P={'blue':('#EFF6FF','#2563EB'),'teal':('#ECFDF5','#078568'),'purple':('#F5F3FF','#7653C7'),'amber':('#FFFBEB','#B77912'),'red':('#FFF1F2','#C0394D'),'slate':('#F1F5F9','#64748B')} +class Diagram: + def __init__(self,name,w,h,title,subtitle): + self.name,self.w,self.h=name,w,h + self.xml=Element('mxfile',host='app.diagrams.net',version='26.0.0') + dia=SubElement(self.xml,'diagram',id=name,name=title) + model=SubElement(dia,'mxGraphModel',dx=str(w),dy=str(h),grid='1',gridSize='10',page='1',pageScale='1',pageWidth=str(w),pageHeight=str(h),background='#FFFFFF') + self.root=SubElement(model,'root');SubElement(self.root,'mxCell',id='0');SubElement(self.root,'mxCell',id='1',parent='0');self.n=0 + self.svg=[f''] + self.text(40,32,w-80,42,title,30,'#14233B',True) + self.text(40,80,w-80,28,subtitle,17,'#54647B') + def cell(self,value,style,x,y,w,h): + self.n+=1;c=SubElement(self.root,'mxCell',id=str(self.n+1),value=value,style=style,vertex='1',parent='1');SubElement(c,'mxGeometry',x=str(x),y=str(y),width=str(w),height=str(h),attrib={'as':'geometry'});return str(self.n+1) + def text(self,x,y,w,h,s,size=16,color='#23354D',bold=False,center=False): + self.cell(s,f'text;html=0;whiteSpace=wrap;align={"center" if center else "left"};verticalAlign=middle;fontFamily=Arial;fontSize={size};fontColor={color};fontStyle={1 if bold else 0};spacing=0;',x,y,w,h) + self.svg.append(f'{escape(s)}') + def rect(self,x,y,w,h,fill,stroke,rounded=True,dash=False): + self.cell('',f'rounded={1 if rounded else 0};arcSize=10;fillColor={fill};strokeColor={stroke};strokeWidth=1.5;dashed={1 if dash else 0};',x,y,w,h) + self.svg.append(f'') + def card(self,x,y,w,h,title,lines=(),tone='blue',num=None): + fill,color=P[tone];self.rect(x,y,w,h,fill,color) + off=20 + if num: + self.rect(x+16,y+16,32,32,color,color);self.text(x+16,y+16,32,32,str(num),18,'#FFFFFF',True,True);off=60 + self.text(x+off,y+15,w-off-16,30,title,21,color,True) + for i,s in enumerate(lines):self.text(x+20,y+54+24*i,w-40,24,s,16) + def edge(self,points,label=None,lx=0,ly=0,lw=200,dash=False): + self.n+=1;c=SubElement(self.root,'mxCell',id=str(self.n+1),edge='1',parent='1',style=f'endArrow=block;endFill=1;rounded=0;strokeColor=#64748B;strokeWidth=2;dashed={1 if dash else 0};') + g=SubElement(c,'mxGeometry',relative='1',attrib={'as':'geometry'}) + SubElement(g,'mxPoint',x=str(points[0][0]),y=str(points[0][1]),attrib={'as':'sourcePoint'});SubElement(g,'mxPoint',x=str(points[-1][0]),y=str(points[-1][1]),attrib={'as':'targetPoint'}) + if len(points)>2: + a=SubElement(g,'Array',attrib={'as':'points'}) + for x,y in points[1:-1]:SubElement(a,'mxPoint',x=str(x),y=str(y)) + self.svg.append('') + if label:self.text(lx,ly,lw,24,label,14,'#54647B',False,True) + def save(self): + (OUT/(self.name+'.drawio')).write_bytes(tostring(self.xml,encoding='utf-8',xml_declaration=True)) + (OUT/(self.name+'.svg')).write_text('\n'.join(self.svg+[''])) + +# Overview: a small number of purposeful blocks, with a visible trust boundary. +d=Diagram('covenant-overview',1440,760,'Covenant at a glance','One governed entry point between your applications and approved AI services.') +d.rect(32,128,900,490,'#FBFCFE','#CCD6E3',dash=True);d.text(52,140,820,28,'YOUR ORGANIZATION',15,'#54647B',True) +d.rect(964,128,444,490,'#FCFAFF','#D9D0EE',dash=True);d.text(984,140,400,28,'APPROVED EXTERNAL SERVICES',15,'#7653C7',True) +d.card(64,236,220,126,'Applications',['App identity','Owning team'], 'blue') +d.card(340,224,290,150,'Covenant',['Inspect data and apply rules','Choose an approved route','Check spend and record proof'],'amber') +d.card(692,250,208,102,'Local models',['Ollama / Qwen'],'teal') +d.card(1000,236,372,126,'Cloud models',['Anthropic / OpenAI','Only when policy permits'],'purple') +d.card(64,468,220,102,'Admin console',['Rules, routes and budgets'],'blue') +d.card(340,468,290,102,'Evidence and costs',['Every outcome, including refusals'],'slate') +d.card(1000,468,372,102,'Web search',['Tavily, for approved Public work'],'purple') +d.edge([(284,299),(340,299)]) +d.edge([(630,299),(692,299)]) +d.edge([(610,224),(610,195),(1186,195),(1186,236)],'Approved cloud route',800,169,235) +d.edge([(630,344),(658,344),(658,408),(1186,408),(1186,468)],'Optional external search',810,380,235) +d.edge([(174,468),(174,415),(410,415),(410,374)],dash=True) +d.edge([(518,374),(518,468)],'All outcomes',530,414,130) +d.text(48,646,1344,28,'LOCAL Data stays inside | EXTERNAL Data leaves only through an approved route | EVIDENCE Who, what, where and cost',16,'#23354D',True) +d.text(48,694,1344,24,'Direct access to a chatbot bypasses Covenant. Use network and endpoint controls to require this path.',16,'#54647B') +d.save() + +# Detail: one downward spine, branches kept outside the reading path. +d=Diagram('covenant-architecture',1440,1240,'How a request is governed','Read top to bottom. A refusal stops further work and still creates an audit record.') +d.text(48,126,320,28,'INPUT AND CONTROL',15,'#54647B',True) +d.text(480,126,480,28,'REQUEST PIPELINE',15,'#54647B',True) +d.text(1060,126,330,28,'DESTINATIONS AND RESULTS',15,'#54647B',True) +steps=[('Identify the caller',['Authenticate the application; bind its team.','Validate the request format.'],'blue'),('Inspect the content',['Combine the workload label with detection.','Incomplete inspection means refuse.'],'amber'),('Apply the policy',['Enforce sensitive-data handling and routes.','Sanitize only an approved structured record.'],'amber'),('Check the exact cache',['Reuse only an eligible, matching response.','A cache hit avoids a new model call.'],'blue'),('Check limits and retrieve',['Check rate, pause and budget reservation.','Optional Public web search is governed too.'],'amber'),('Call an approved model',['Use the selected local or external adapter.','Fallback stays within the approved routes.'],'teal'),('Finalize and record',['Settle usage and attribute cost to the team.','Record the outcome and return the response.'],'slate')] +for i,(title,lines,tone) in enumerate(steps): + y=172+i*134;d.card(480,y,480,108,title,lines,tone,str(i+1)) + if i<6:d.edge([(720,y+108),(720,y+134)]) +d.card(48,172,340,108,'Application request',['OpenAI / Anthropic compatible API','Application key identifies the caller'],'blue') +d.edge([(388,226),(480,226)]) +d.card(48,332,340,156,'Sensitive data rules',['Internal: approved local processing','Public demo: reject detected PII/PHI','Detection can raise the data label.','No match is not proof of safe data.'],'red') +d.card(48,550,340,132,'Configuration',['Profiles, routes and model allow-list','Budgets and permission settings','Provider secrets stay on the server.'],'slate') +d.edge([(388,603),(426,603),(426,494),(480,494)],dash=True) +d.card(48,758,340,156,'Refused or failed',['Record the reason and any usage.','Do not continue to later stages.','Earlier tool or model calls may','already have incurred a charge.'],'red') +d.card(1060,574,332,108,'Exact cache hit',['Skip retrieval and model execution.','Still record and attribute the request.'],'blue') +d.edge([(960,628),(1060,628)]) +d.edge([(1392,628),(1420,628),(1420,1118),(1000,1118),(1000,1030),(960,1030)],dash=True) +d.card(1060,730,332,108,'Tavily web search',['Public only, explicitly enabled','Sources and cost recorded separately'],'purple') +d.edge([(960,762),(1010,762),(1010,784),(1060,784)]) +d.card(1060,870,332,108,'Approved models',['Local: Ollama / Qwen','External: Anthropic / OpenAI'],'teal') +d.edge([(960,896),(1010,896),(1010,924),(1060,924)]) +d.card(48,1010,340,108,'Audit and budget ledger',['Hash-linked request evidence','Costs by application and team'],'slate') +d.edge([(480,1030),(428,1030),(428,1064),(388,1064)]) +# Cache shortcut terminates at finalization, not an unimplemented provider stage. +d.text(48,1160,1344,28,'DESIGN PATTERNS Canonical proxy • Policy middleware • Provider adapters • Exact cache • Governed retrieval • Audit trail',16,'#23354D',True) +d.text(48,1200,1344,24,'Sensitive-data inspection is bounded and heuristic. Sanitization supports a narrow schema, not arbitrary prose or PHI.',16,'#54647B') +d.save() + +# Use Draw.io itself for final SVG exports, so wrapping matches the editable source. +# The built-in SVG is a portable preview when the desktop exporter is unavailable. +if __name__ == '__main__': + import os, shutil, subprocess + exporter=os.environ.get('DRAWIO') or shutil.which('drawio') + mac='/Applications/draw.io.app/Contents/MacOS/draw.io' + if not exporter and Path(mac).exists(): exporter=mac + if exporter: + for name in ('covenant-overview','covenant-architecture'): + for fmt in ('svg','png'): + subprocess.run([exporter,'--export','--format',fmt,'--theme','light','--size','page','--embed-diagram','--output',str(OUT/(name+'.'+fmt)),str(OUT/(name+'.drawio'))],check=True,timeout=90) + else: + print('Draw.io not installed: generated portable SVG previews. Export .drawio files with Draw.io before publishing.') diff --git a/docs/ui-api-contract.md b/docs/ui-api-contract.md index b5786dd..c335cb3 100644 --- a/docs/ui-api-contract.md +++ b/docs/ui-api-contract.md @@ -112,6 +112,7 @@ Properties are snake_case. Enum values are always written as: | `strategy` | RoutingStrategy | `"fixed"`, `"length-heuristic"` | | `period` | BudgetPeriod | `"none"`, `"daily"`, `"monthly"` | | `enforcement` | BudgetEnforcement | `"hard"`, `"warn-only"` | +| `sensitive_data_action` | SensitiveDataAction | `"route"` (default; absent ⇒ route), `"reject"` (ADR-0019) | | `kind` | ProviderKind | `"Ollama"`, `"OpenAiCompatible"`, `"OpenAi"`, `"Anthropic"` (C# names) | | `boundary` | Boundary | `"Local"`, `"Cloud"` (C# names) | | `classifications[]`, `baseline` | DataClassification | `"Public"`, `"Internal"`, `"Pii"`, `"Phi"` (C# names) | @@ -319,6 +320,11 @@ model-invoked tool. `/v1` is unchanged (always `web_search` off). "timeout_seconds":1–30 (default 10), "price_per_credit_usd":decimal|null, "price_basis"?:string ≤ 200, "price_effective_date"?:"yyyy-MM-dd" }`. The console must round-trip it on every save. - `profiles[].web_search_allowed`: bool, default false. Only a **Public**-baseline profile may carry it. +- `profiles[].sensitive_data_action` (ADR-0019): `"route"` (default) | `"reject"`. With `reject`, a request that detection + raises to PII/PHI is refused at the classify stage (reason code `sensitive_data_rejected`) — before policy, cache, + search and provider. Valid only on a Public/Internal baseline (`sensitive_action_requires_non_sensitive_baseline`). + The console must round-trip it on every save. `POST /admin/policies/simulate` then answers `decision: "refuse"`, + `refused_at_stage: "classify"` and `suggested_profiles` (granted workloads whose policy would route it). - Validation codes: `search_profile_not_public` (`profiles[i].web_search_allowed`), `invalid_setting` (`web_search.max_results|timeout_seconds|price_per_credit_usd|price_basis`); when enabled: `search_requires_hybrid`, `search_unpriced` (unknown price is not $0), `secret_unavailable` (`Tavily:ApiKey` not set), diff --git a/docs/user-guide.md b/docs/user-guide.md index 2948db8..edbf265 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -19,6 +19,12 @@ workload and one of the recommended examples, preview the route, and press Run. | Destination | **Local** (teal, inside the perimeter) or **External** (purple, an approved provider). Red means sensitive data was detected or blocked. Every tag also has text and an icon. | | Policy (route) | One match per workload + classification: an approved primary and optional fallback. No match means refused. | +## The sensitive-data comparison + +For **Demo application**, apply **Internal workload: sensitive data served locally** and run. Internal is selected automatically. Switch to Public and run the unchanged prompt: this workload rejects detected PII/PHI before cache, search or models. Both outcomes are audited. Public is still a data label, not a promise to use a cloud model. + +This behavior is a workload setting, not a special case for the example. Under **Policies → Workloads**, the Public workload must use **When sensitive data is detected → Reject the request**. Internal retains **Route by policy**. Existing saved setups keep their old behavior until this setting is saved; new demo seeds set it explicitly. + ## What detection can and cannot see Covenant inspects every message locally; no text leaves the perimeter for inspection (ADR-0018). It recognises: diff --git a/docs/verification/2026-11-02-public-rejection/README.md b/docs/verification/2026-11-02-public-rejection/README.md new file mode 100644 index 0000000..2adeadd --- /dev/null +++ b/docs/verification/2026-11-02-public-rejection/README.md @@ -0,0 +1,12 @@ +# Sensitive workload and diagram verification + +Verified on 2026-11-02. + +- Release suite: 1,274 passed, zero failed or skipped. +- Six live cases: hyphenated SSN, compact SSN and identifiable PHI, each accepted on the approved Internal local route and rejected on Public before any provider attempt. See live-results.json. +- Additional live checks: ordinary Public text reached Anthropic; sensitive Public content with required web search was rejected before search or inference. +- Final normal launcher: scripts/run-local-demo.sh on port 5210, existing saved state and audit history preserved. Public demo workload configured through the validated, audited configuration API to reject detected sensitive data (version 4). Internal routing unchanged. +- Actual browser: selected Demo application and the Internal sensitive example, filled and ran it successfully on Ollama. Switched the unchanged prompt to Public. The paired example label updated, and the next run returned HTTP 403 at classification, with evidence recorded and no provider call. Screenshot: public-rejected.png. +- Both architecture diagrams exported with Draw.io to SVG and PNG and visually inspected. Editable .drawio sources are included. + +Detection remains pattern-based and cannot guarantee detection of every possible sensitive input. Reject is an explicit workload setting, not an inherent meaning of the word Public. Existing profiles default to routing unless configured otherwise. diff --git a/docs/verification/2026-11-02-public-rejection/live-results.json b/docs/verification/2026-11-02-public-rejection/live-results.json new file mode 100644 index 0000000..38332c7 --- /dev/null +++ b/docs/verification/2026-11-02-public-rejection/live-results.json @@ -0,0 +1,107 @@ +[ + { + "name": "ssn", + "profile": "internal-default", + "ok": true, + "effect": "Allow", + "classification": "Pii", + "stage": null, + "reason": "allowed", + "attempts": [ + { + "AttemptId": "att_1", + "ConnectionId": "ollama", + "ModelId": "qwen2.5-coder:7b", + "Outcome": "served", + "ErrorClass": null, + "DurationMs": 1013.2126, + "CostUsd": 0.0, + "CostBasis": "zero_priced", + "ReservedUsd": 0.0, + "Overrun": false, + "EffectiveMaxOutputTokens": 128, + "Truncated": null + } + ] + }, + { + "name": "ssn", + "profile": "public-demo", + "ok": true, + "effect": "Deny", + "classification": "Pii", + "stage": "classify", + "reason": "sensitive data detected (PII: US SSN pattern): workload 'public-demo' rejects detected sensitive data \u2014 refused before routing, cache, web search or any model; nothing was sent. To process it on an approved route, choose workload 'internal-default'.", + "attempts": [] + }, + { + "name": "compact", + "profile": "internal-default", + "ok": true, + "effect": "Allow", + "classification": "Pii", + "stage": null, + "reason": "allowed", + "attempts": [ + { + "AttemptId": "att_1", + "ConnectionId": "ollama", + "ModelId": "qwen2.5-coder:7b", + "Outcome": "served", + "ErrorClass": null, + "DurationMs": 263.7005, + "CostUsd": 0.0, + "CostBasis": "zero_priced", + "ReservedUsd": 0.0, + "Overrun": false, + "EffectiveMaxOutputTokens": 128, + "Truncated": null + } + ] + }, + { + "name": "compact", + "profile": "public-demo", + "ok": true, + "effect": "Deny", + "classification": "Pii", + "stage": "classify", + "reason": "sensitive data detected (PII: possible identifier (standalone 9-digit number)): workload 'public-demo' rejects detected sensitive data \u2014 refused before routing, cache, web search or any model; nothing was sent. To process it on an approved route, choose workload 'internal-default'.", + "attempts": [] + }, + { + "name": "phi", + "profile": "internal-default", + "ok": true, + "effect": "Allow", + "classification": "Phi", + "stage": null, + "reason": "allowed", + "attempts": [ + { + "AttemptId": "att_1", + "ConnectionId": "ollama", + "ModelId": "qwen2.5-coder:7b", + "Outcome": "served", + "ErrorClass": null, + "DurationMs": 93.831, + "CostUsd": 0.0, + "CostBasis": "zero_priced", + "ReservedUsd": 0.0, + "Overrun": false, + "EffectiveMaxOutputTokens": 128, + "Truncated": null + } + ] + }, + { + "name": "phi", + "profile": "public-demo", + "ok": true, + "effect": "Deny", + "classification": "Phi", + "stage": "classify", + "reason": "sensitive data detected (PHI: health information about an identifiable person): workload 'public-demo' rejects detected sensitive data \u2014 refused before routing, cache, web search or any model; nothing was sent. To process it on an approved route, choose workload 'internal-default'.", + "attempts": [] + } +] \ No newline at end of file diff --git a/docs/verification/2026-11-02-public-rejection/public-rejected.png b/docs/verification/2026-11-02-public-rejection/public-rejected.png new file mode 100644 index 0000000..d23cd08 Binary files /dev/null and b/docs/verification/2026-11-02-public-rejection/public-rejected.png differ diff --git a/src/Covenant.Core/Configuration.cs b/src/Covenant.Core/Configuration.cs index 065168c..451a421 100644 --- a/src/Covenant.Core/Configuration.cs +++ b/src/Covenant.Core/Configuration.cs @@ -19,6 +19,11 @@ public enum BudgetPeriod { None, Daily, Monthly } public enum BudgetEnforcement { Hard, WarnOnly } +/// ADR-0019: what a workload does when detection raises a request to PII/PHI. (default, every +/// pre-0019 version): the escalated classification is routed by its policy (PII/PHI stay local, ADR-0013/0016). +/// : refused at the classify stage — nothing reaches policy, cache, search or any provider. +public enum SensitiveDataAction { Route, Reject } + public sealed record CovenantConfig { public required int Version { get; init; } @@ -134,6 +139,9 @@ public sealed record WorkloadProfileConfig /// May requests under this profile use governed web search (ADR-0015)? Default false. Only a Public-baseline /// profile may carry it (validation error otherwise). public bool WebSearchAllowed { get; init; } + /// ADR-0019: action when detection raises a request under this profile to PII/PHI. Default Route (unchanged + /// behaviour). Reject is valid only on a Public- or Internal-baseline profile. + public SensitiveDataAction SensitiveDataAction { get; init; } = SensitiveDataAction.Route; } public sealed record PolicyConfigV2 diff --git a/src/Covenant.Core/Execution.cs b/src/Covenant.Core/Execution.cs index 0ab545d..06fa248 100644 --- a/src/Covenant.Core/Execution.cs +++ b/src/Covenant.Core/Execution.cs @@ -65,6 +65,10 @@ public static class TraceReasons /// Classify stage: local sensitive-data inspection could not complete (ADR-0018) — refused, nothing sent. public const string InspectionIncomplete = "inspection_incomplete"; + /// Classify stage (ADR-0019): detection raised the request to PII/PHI and its workload rejects detected + /// sensitive data — refused before policy, cache, search and provider; nothing sent. + public const string SensitiveDataRejected = "sensitive_data_rejected"; + /// Default code of a denial when the denying stage did not name a finer one. public static string ForDenial(DenialKind kind) => kind switch { diff --git a/src/Covenant.Governance/Classification.cs b/src/Covenant.Governance/Classification.cs index 69266b0..70b1826 100644 --- a/src/Covenant.Governance/Classification.cs +++ b/src/Covenant.Governance/Classification.cs @@ -55,10 +55,63 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance } ctx.ClassificationSignal = result.Signal; ctx.ClassificationEvaluated = true; + // ADR-0019: a workload that rejects detected sensitive data stops here — before policy, sanitization, cache, rate + // limit, budget, web search and provider. The record keeps the escalated class and the signal label (never content). + if (ctx.Configuration is { } cfg && SensitiveDataRules.Rejects(cfg, ctx.ProfileId, ctx.Classification)) + { + var app = ctx.ApplicationId is { } aid ? cfg.FindApplication(aid) : null; + ctx.Deny(SensitiveDataRules.Explain(cfg, app, ctx.ProfileId!, ctx.Classification, result.Signal), + DenialKind.Governance, code: TraceReasons.SensitiveDataRejected); + return; + } await next(ctx, ct); } } +/// ADR-0019: the per-workload action on detected PII/PHI. One rule for the classify stage, the simulator and the +/// policy engine (defence in depth), so preview, impact and execution cannot diverge. +public static class SensitiveDataRules +{ + /// True when is PII/PHI and the workload rejects detected sensitive data. Only a + /// Public/Internal-baseline profile can reject (validation enforces it; re-checked here), so under such a profile a + /// PII/PHI classification can only come from detection. + public static bool Rejects(IRequestConfiguration cfg, string? profileId, DataClassification final) + => final >= DataClassification.Pii + && profileId is not null + && cfg.FindProfile(profileId) is { SensitiveDataAction: SensitiveDataAction.Reject } p + && p.Baseline < DataClassification.Pii; + + /// Granted workloads of under which the policy engine WOULD route + /// (action Route, an eligible target). Computed by the engine — never a hard-coded name. At most 3, config order. + public static IReadOnlyList Suggestions(IRequestConfiguration cfg, ApplicationConfig? app, string? currentProfile, DataClassification final) + { + var list = new List(); + if (app is null) return list; + foreach (var g in app.GrantedProfiles) + { + if (string.Equals(g, currentProfile, StringComparison.Ordinal) || list.Contains(g, StringComparer.Ordinal)) continue; + if (cfg.FindProfile(g) is not { SensitiveDataAction: SensitiveDataAction.Route } p || p.Baseline >= DataClassification.Pii) continue; + if (PolicyEngineV2.Evaluate(cfg, final, g, null, []).Effect != PolicyEffect.Allow) continue; + list.Add(g); + if (list.Count == 3) break; + } + return list; + } + + /// The bounded refusal reason (no content): what was detected, which workload rejected it, that nothing was + /// sent, and — when one exists — which granted workload would accept it. + public static string Explain(IRequestConfiguration cfg, ApplicationConfig? app, string profileId, DataClassification final, string? signal) + { + var what = final == DataClassification.Phi ? "PHI" : "PII"; + var reason = $"sensitive data detected ({what}{(signal is { Length: > 0 } s ? ": " + Evidence.Bounded(s) : "")}): " + + $"workload '{Evidence.Bounded(profileId)}' rejects detected sensitive data — refused before routing, cache, web search or any model; nothing was sent"; + var suggestions = Suggestions(cfg, app, profileId, final); + return suggestions.Count == 0 + ? reason + ". No other workload granted to this application accepts it." + : reason + $". To process it on an approved route, choose workload '{string.Join("' or '", suggestions)}'."; + } +} + /// ADR-0012: final = max(trusted baseline, detected); a no-match detector result (Internal with no /// signal) is "no escalation". Shared by the classify stage and the policy simulator. public static class ClassificationRules diff --git a/src/Covenant.Governance/ConfigValidation.cs b/src/Covenant.Governance/ConfigValidation.cs index 2f217c6..ea2f673 100644 --- a/src/Covenant.Governance/ConfigValidation.cs +++ b/src/Covenant.Governance/ConfigValidation.cs @@ -135,6 +135,7 @@ bool NonNullList(string path, IReadOnlyList? list) { if (pr.Id is null) Req($"profiles[{i}].id"); Defined($"profiles[{i}].baseline", pr.Baseline); + Defined($"profiles[{i}].sensitive_data_action", pr.SensitiveDataAction); if (pr.Name is null) Req($"profiles[{i}].name"); } @@ -416,6 +417,12 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro Warn("policies", "no_route_for_classification", $"no enabled policy covers {cls}: such requests are refused"); } + // ---- sensitive-data action (ADR-0019) ---- + foreach (var (pr, i) in c.Profiles.Select((pr, i) => (pr, i))) + if (pr.SensitiveDataAction == SensitiveDataAction.Reject && pr.Baseline >= DataClassification.Pii) + Err($"profiles[{i}].sensitive_data_action", "sensitive_action_requires_non_sensitive_baseline", + $"profile '{pr.Id}' has baseline {pr.Baseline}: every request under it is sensitive by declaration, so 'reject' is valid only on a Public or Internal workload"); + // ---- web search (ADR-0015) ---- foreach (var (pr, i) in c.Profiles.Select((pr, i) => (pr, i))) if (pr.WebSearchAllowed && pr.Baseline != DataClassification.Public) diff --git a/src/Covenant.Governance/PolicyV2.cs b/src/Covenant.Governance/PolicyV2.cs index 1a64aa0..0cb21b1 100644 --- a/src/Covenant.Governance/PolicyV2.cs +++ b/src/Covenant.Governance/PolicyV2.cs @@ -95,6 +95,11 @@ public static PolicyOutcome Evaluate( && cfg.Config.Policies.Any(p => p.Enabled && p.Redaction is not null && p.Profiles.Contains(profileId, StringComparer.Ordinal))) return PolicyOutcome.Deny($"workload profile '{Evidence.Bounded(profileId)}' is reserved for sanitized structured records and must have a PII baseline"); + // ADR-0019 (defence in depth; the classify stage refuses first): a workload that rejects detected sensitive data + // never has PII/PHI routed — also what impact previews and route summaries show for it. + if (SensitiveDataRules.Rejects(cfg, profileId, classification)) + return PolicyOutcome.Deny($"workload '{Evidence.Bounded(profileId!)}' rejects detected sensitive data ({classification}): refused, nothing is sent"); + var matches = Match(cfg.Config, classification, profileId); if (matches.Count == 0) return PolicyOutcome.Deny($"no permitted route for classification '{classification}'"); diff --git a/src/Covenant.Host/ConfigAdminApi.cs b/src/Covenant.Host/ConfigAdminApi.cs index afecdb1..7929b0a 100644 --- a/src/Covenant.Host/ConfigAdminApi.cs +++ b/src/Covenant.Host/ConfigAdminApi.cs @@ -270,6 +270,17 @@ public static SimulateResponse Simulate(IRequestConfiguration cfg, IDataClassifi return Refuse("sensitive-data inspection could not complete (input too large or too complex): the request would be refused; nothing would be sent", resolved.ProfileId, resolved.Baseline); var final = ClassificationRules.Combine(resolved.Baseline, detected); + // ADR-0019: the same rule and reason as the classify stage — refused before policy; no route is evaluated or shown. + if (SensitiveDataRules.Rejects(cfg, resolved.ProfileId, final)) + return new SimulateResponse + { + DryRun = true, ConfigVersion = cfg.Version, ApplicationId = app.Id, Profile = resolved.ProfileId, + Classification = final.ToString(), Baseline = resolved.Baseline.ToString(), DetectedSignal = detected.Signal, + Eligible = [], Decision = "refuse", Fallbacks = [], + Reason = SensitiveDataRules.Explain(cfg, app, resolved.ProfileId!, final, detected.Signal), + RefusedAtStage = "classify", + SuggestedProfiles = SensitiveDataRules.Suggestions(cfg, app, resolved.ProfileId, final).ToList(), + }; var outcome = PolicyEngineV2.Evaluate(cfg, final, resolved.ProfileId, body.Model, messages); var eligible = new List(); diff --git a/src/Covenant.Host/ConfigBootstrap.cs b/src/Covenant.Host/ConfigBootstrap.cs index f8dff23..096e5a1 100644 --- a/src/Covenant.Host/ConfigBootstrap.cs +++ b/src/Covenant.Host/ConfigBootstrap.cs @@ -293,7 +293,8 @@ internal static int OptionalNonNegativeInt(IConfiguration config, string key, in /// Isolated demonstration profiles (spec §3, Config:Seed). Restrictive defaults: Public → approved /// economical cloud model with an explicit local fallback (hybrid only); Internal, PII and PHI → the local -/// model, never a cloud fallback. Public is reachable only through the granted "public-demo" profile. +/// model, never a cloud fallback. Public is reachable only through the granted "public-demo" profile, which rejects +/// detected PII/PHI (ADR-0019); "internal-default" routes it to the local model. public static class DemoSeeds { public const string LocalOnly = "demo-local-only"; @@ -397,8 +398,11 @@ public static CovenantConfig Build(string seed, IConfiguration config, DateTimeO Applications = applications, Profiles = [ + // ADR-0019: the Public workload never accepts detected PII/PHI (explicit refusal, never a silent local reroute); + // the Internal workload is the one approved to process it on the local model. new() { Id = "public-demo", Name = "Public demo (synthetic public content)", Baseline = DataClassification.Public, - Description = "Deliberately public, synthetic content only." }, + Description = "Deliberately public, synthetic content only. Detected sensitive data is rejected.", + SensitiveDataAction = SensitiveDataAction.Reject }, new() { Id = "internal-default", Name = "Internal (default)", Baseline = DataClassification.Internal }, ], Policies = diff --git a/src/Covenant.Host/ConfigContracts.cs b/src/Covenant.Host/ConfigContracts.cs index 2e6450a..cf1867d 100644 --- a/src/Covenant.Host/ConfigContracts.cs +++ b/src/Covenant.Host/ConfigContracts.cs @@ -11,6 +11,7 @@ namespace Covenant.Host; // strategy RoutingStrategy "fixed" | "length-heuristic" (kebab-case) // period BudgetPeriod "none" | "daily" | "monthly" (kebab-case) // enforcement BudgetEnforcement "hard" | "warn-only" (kebab-case) +// sensitive_data_action SensitiveDataAction "route" | "reject" (kebab-case; absent ⇒ "route", ADR-0019) // kind ProviderKind "Ollama" | "OpenAiCompatible" | "OpenAi" | "Anthropic" (C# names) // boundary Boundary "Local" | "Cloud" (C# names) // classifications / baseline DataClassification "Public" | "Internal" | "Pii" | "Phi" (C# names) @@ -185,6 +186,10 @@ public sealed class SimulateResponse /// ADR-0016: present when the matched policy requires a sanitized structured payload — the payload that WOULD /// be sent (placeholders only) or the refusal. A preview is never authorization. public SimulatedRedaction? Redaction { get; init; } + /// ADR-0019: set when the request would be refused at the classify stage ("classify"); null otherwise. + public string? RefusedAtStage { get; init; } + /// ADR-0019: granted workloads under which the engine WOULD route this classification (empty when none). + public List? SuggestedProfiles { get; init; } } public sealed class SimulatedRedaction @@ -287,6 +292,7 @@ public KebabEnumConverter() : base(JsonNamingPolicy.KebabCaseLower, allowInteger typeof(KebabEnumConverter), typeof(KebabEnumConverter), typeof(KebabEnumConverter), + typeof(KebabEnumConverter), typeof(JsonStringEnumConverter), ])] [JsonSerializable(typeof(CovenantConfig))] diff --git a/src/Covenant.Ui/Components/ExamplePicker.razor b/src/Covenant.Ui/Components/ExamplePicker.razor index 55f3599..d7d7113 100644 --- a/src/Covenant.Ui/Components/ExamplePicker.razor +++ b/src/Covenant.Ui/Components/ExamplePicker.razor @@ -22,7 +22,7 @@ var pinned = !showMore && Selected is { } cur && groups.More.Contains(cur) ? cur : null;
- @foreach (var r in groups.Recommended) @@ -134,7 +134,7 @@ /// Only an example listed for the CURRENT application can be selected; a selection made under another /// application simply disappears (the list is per application). private ExampleResolution? Selected - => (_selected ?? Pg.Form.ExampleId) is { Length: > 0 } id ? Pg.Examples.FirstOrDefault(e => e.Example.Id == id) : null; + => ExampleSelection.Shown(_selected, Pg.Form.ExampleId) is { Length: > 0 } id ? Pg.Examples.FirstOrDefault(e => e.Example.Id == id) : null; private string? _forApp; @@ -163,7 +163,11 @@ if (string.Equals(_forApp, key, StringComparison.Ordinal)) return; bool first = _forApp is null; _forApp = key; - if (!first && _selected is { } id && !(Pg.Form.ExampleId == id)) { _selected = null; StateHasChanged(); } + // A twin relabel (Internal ⇄ Public sensitive pair) moves the selection WITH the form's example instead of + // dropping it to the placeholder while "Fill again" stays (pure rule: ExampleSelection.AfterSwitch). + if (first) return; + var next = ExampleSelection.AfterSwitch(_selected, Pg.Form.ExampleId); + if (!string.Equals(next, _selected, StringComparison.Ordinal)) { _selected = next; StateHasChanged(); } } private string EmptyText diff --git a/src/Covenant.Ui/Components/RequestComposer.razor b/src/Covenant.Ui/Components/RequestComposer.razor index c7523e8..6cc7d27 100644 --- a/src/Covenant.Ui/Components/RequestComposer.razor +++ b/src/Covenant.Ui/Components/RequestComposer.razor @@ -82,6 +82,7 @@
} + @* ADR-0019: the rejection sentence (and never the old "stricter (local) rule" copy) comes from WorkloadDestination.Note. *@ @if (dest.Note is { } dn) { @(dn + (dest.Href is null ? "" : " "))@if (dest.Href is { } nh) { @dest.HrefLabel } diff --git a/src/Covenant.Ui/Components/RoutePreviewPanel.razor b/src/Covenant.Ui/Components/RoutePreviewPanel.razor index c98c644..8747cdb 100644 --- a/src/Covenant.Ui/Components/RoutePreviewPanel.razor +++ b/src/Covenant.Ui/Components/RoutePreviewPanel.razor @@ -25,6 +25,21 @@ Configured for this workload (not a preview): @now.Target@(now.PolicyId is { } np ? " · policy " + np : "") } } + @if (scheme.State == "ready" && Pg.Preview?.Result is { RefusedAtStage: "classify", SuggestedProfiles.Count: > 0 } rej) + { + @* ADR-0019: the Host's own suggestion (granted workloads its policy engine WOULD route this classification under). + Switching keeps the prompt; nothing runs until Run. *@ +
+ @foreach (var pid in rej.SuggestedProfiles!) + { + var target = pid; + + } + This workload rejects detected sensitive data; the server suggests a workload approved for it. +
+ } @if (scheme.State == "ready" && Pg.Preview?.Result is { } r) {
@@ -70,6 +85,11 @@ private void OnChanged() => _ = InvokeAsync(StateHasChanged); + private async Task SwitchAndPreviewAsync(string profileId) + { + if (Pg.SelectProfile(profileId)) await Pg.PreviewRouteAsync(); + } + public void Dispose() { Pg.Changed -= OnChanged; diff --git a/src/Covenant.Ui/Logic/DemoExamples.cs b/src/Covenant.Ui/Logic/DemoExamples.cs index 6b246a5..f92f68f 100644 --- a/src/Covenant.Ui/Logic/DemoExamples.cs +++ b/src/Covenant.Ui/Logic/DemoExamples.cs @@ -17,8 +17,11 @@ public enum ExampleNeed InternalResearch, /// A Public profile with an eligible cloud target, used with an explicit cloud model pin and a synthetic SSN. SensitiveCloudPinRefusal, - /// A Public workload whose PII route is local: the same synthetic sensitive prompt, policy chooses (served locally). + /// An Internal workload approved for sensitive data (action route) whose PII route is local: the synthetic + /// sensitive prompt is served locally (ADR-0019). SensitiveLocal, + /// A Public workload that rejects detected sensitive data (ADR-0019): the SAME prompt is refused at the gateway. + SensitivePublicRejected, /// The exact cache enabled (TTL > 0) and a Public route. CacheRepeat, /// A hard budget applying to the application that cannot cover one more request. @@ -109,9 +112,10 @@ public static class DemoExamples "site:dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core .NET 10 support end date. " + "Answer in one sentence using only the retrieved sources and cite the page; if they do not state it, reply \"not stated in the sources\"."; - /// One synthetic sensitive prompt for BOTH sensitive examples (local by policy, blocked when pinned external). + /// One neutral synthetic sensitive prompt for the sensitive examples (Internal: served locally; Public: rejected; + /// explicit external pin: blocked). It claims no classification itself — the WORKLOAD declares it. public const string SensitivePrompt = - "Summarize this public support ticket in one sentence: \"Printer on floor 3 jammed again. Reporter SSN " + SyntheticSsn + " (synthetic test marker).\""; + "Summarize this note in one sentence: \"Customer asked to update their mailing address. SSN on file: " + SyntheticSsn + " (synthetic test marker).\""; public static readonly IReadOnlyList All = [ @@ -146,13 +150,21 @@ public static class DemoExamples ExampleNeed.InternalResearch, "For an internal ledger service, compare optimistic and pessimistic concurrency control: when to use each, and two failure modes of each. Keep it under 200 words.", WebSourcesMode.Off, "research", "internal-analysis", false, MaxTokens: 2048, Prefer: ["research"]), - new("sensitive-local", "Sensitive data detected: served locally", - "Detection raises a Public request containing a synthetic SSN to PII; with policy choosing, the PII route keeps it on a local model.", + new("sensitive-local", "Internal workload: sensitive data served locally", + "The Internal workload is approved for sensitive data: detection raises the request to PII and the PII route keeps it on a local model.", "Served locally · sensitive data detected. Nothing leaves the perimeter; the classification is never lowered.", - "The chips show Sensitive · PII (detected) and a Local destination. Compare with the next example: the SAME prompt with an explicit external pin is blocked.", + "The route shows Sensitive · PII (detected) and a Local destination. Then switch the workload to Public (the prompt stays): the gateway rejects the same request.", ExampleNeed.SensitiveLocal, SensitivePrompt, - WebSourcesMode.Off, "writing", "sensitive-local", false, Prefer: ["writing"]), + // Same workflow/use case as its Public pair: switching the workload keeps every attribution label true. + WebSourcesMode.Off, "demo", "sensitive-data", false, Prefer: ["internal"]), + new("sensitive-public-rejected", "Public workload: the same sensitive data is rejected", + "A Public workload declares public content. When detection finds PII or PHI, this workload rejects the request at the gateway — it is never silently rerouted.", + "Rejected at Classify · nothing sent. The reason names the detected data and the workload that would accept it.", + "The route shows Blocked — model not contacted, refused at Classify; no cache, web search or model call; no charge. Switch to the Internal workload to process it locally.", + ExampleNeed.SensitivePublicRejected, + SensitivePrompt, + WebSourcesMode.Off, "demo", "sensitive-data", false, Prefer: ["public"]), new("sensitive-refusal", "Sensitive data: explicit external attempt is blocked", "The same synthetic sensitive prompt, but the example explicitly pins an external model (shown before you apply it). Policy blocks it before any provider call.", "Blocked by policy · sensitive data cannot go external. Nothing is sent; no charge. This is a governance refusal, not a provider outage.", @@ -212,6 +224,11 @@ public static class DemoExamples /// Mirror of PolicyEngineV2.Match + Ineligibility (UI copy; the Host decides at run time). public static ResolvedRoute Route(CovenantConfigDto cfg, string classification, string? profileId) { + // ADR-0019 mirror: a Public/Internal workload that rejects detected sensitive data never has PII/PHI routed. + if (PolicyText.IsSensitive(classification) && profileId is not null + && cfg.Profiles.FirstOrDefault(p => string.Equals(p.Id, profileId, StringComparison.Ordinal)) is { } wp + && ProfileEditing.RejectsSensitive(wp) && !PolicyText.IsSensitive(wp.Baseline)) + return new(null, null, null, [], "workload " + profileId + " rejects detected sensitive data (refused at Classify; nothing is sent)"); var matching = cfg.Policies.Where(p => p.Enabled && p.Classifications.Contains(classification, StringComparer.OrdinalIgnoreCase) && (p.Profiles.Count == 0 || (profileId is not null && p.Profiles.Contains(profileId, StringComparer.Ordinal)))) @@ -292,8 +309,15 @@ public static bool IsRelevant(DemoExample ex, CovenantConfigDto cfg, Application ExampleNeed.InternalCoder => workloads.Any(w => Declares(w.Profile, Coding) && w.Route.Primary?.ModelId == CoderModel), ExampleNeed.InternalResearch => workloads.Any(w => Declares(w.Profile, Research) && w.Route.Primary?.ModelId == ResearchModel), ExampleNeed.InternalWriting => workloads.Any(w => Declares(w.Profile, Writing) && IsLocal(w.Route)), - ExampleNeed.SensitiveCloudPinRefusal => workloads.Any(w => w.Route.Eligible.Any(t => ComposerRules.BoundaryLabel(FindConnection(cfg, t.ConnectionId)?.Boundary) == "Cloud")), - ExampleNeed.SensitiveLocal => workloads.Any(w => IsLocal(Route(cfg, "Pii", w.Profile.Id))), + // A workload that REJECTS detected sensitive data refuses at Classify, before policy: the explicit-pin example + // (a POLICY refusal) does not describe it. + ExampleNeed.SensitiveCloudPinRefusal => workloads.Any(w => !ProfileEditing.RejectsSensitive(w.Profile) + && w.Route.Eligible.Any(t => ComposerRules.BoundaryLabel(FindConnection(cfg, t.ConnectionId)?.Boundary) == "Cloud")), + // ADR-0019 pair: offered only where the application shows BOTH halves (its Observe text promises the Public rejection), + // so an Internal-only application (e.g. engineering) is not given sensitive-data noise. + ExampleNeed.SensitiveLocal => HasRejectingPublic(cfg, app) + && workloads.Any(w => !ProfileEditing.RejectsSensitive(w.Profile) && IsLocal(Route(cfg, "Pii", w.Profile.Id))), + ExampleNeed.SensitivePublicRejected => workloads.Any(w => ProfileEditing.RejectsSensitive(w.Profile)), ExampleNeed.CacheRepeat => workloads.Any(w => w.Route.Primary is not null), ExampleNeed.BudgetRefusal => workloads.Any(w => w.Route.Primary is not null) && HasIsolatedBudget(cfg, app, budgets), ExampleNeed.PublicLocalResearch => workloads.Any(w => w.Profile.WebSearchAllowed && IsLocal(w.Route)), @@ -328,7 +352,7 @@ public static bool HasIsolatedBudget(CovenantConfigDto cfg, ApplicationSummaryDt private static string BaselineFor(DemoExample ex) => ex.Need switch { - ExampleNeed.InternalCoder or ExampleNeed.InternalResearch or ExampleNeed.InternalWriting => "Internal", + ExampleNeed.InternalCoder or ExampleNeed.InternalResearch or ExampleNeed.InternalWriting or ExampleNeed.SensitiveLocal => "Internal", ExampleNeed.SanitizedRecord => "Pii", _ => "Public", }; @@ -381,6 +405,8 @@ public static ExampleResolution Resolve(DemoExample ex, CovenantConfigDto? cfg, ? RouteText(Route(cfg, "Pii", best.Profile.Id)) + " — the explicit cloud pin is refused" : ex.Need == ExampleNeed.SensitiveLocal ? RouteText(Route(cfg, "Pii", best.Profile.Id)) + " (after detection raises it to PII)" + : ex.Need == ExampleNeed.SensitivePublicRejected + ? RouteText(Route(cfg, "Pii", best.Profile.Id)) : RouteText(best.Route); var (title, steps) = Describe(ex, cfg, best.Route); return new(ex, true, best.App.Id, best.Profile.Id, best.Pin.Length == 0 ? null : best.Pin, routeText, @@ -457,10 +483,13 @@ private static int Score(DemoExample ex, ApplicationSummaryDto app, WorkloadProf case ExampleNeed.InternalWriting: return Declares(profile, Writing) && IsLocal(route) ? "" : null; case ExampleNeed.SensitiveCloudPinRefusal: + if (ProfileEditing.RejectsSensitive(profile)) return null; var cloud = route.Eligible.FirstOrDefault(t => ComposerRules.BoundaryLabel(FindConnection(cfg, t.ConnectionId)?.Boundary) == "Cloud"); return cloud is null ? null : cloud.ConnectionId + "/" + cloud.ModelId; case ExampleNeed.SensitiveLocal: - return IsLocal(Route(cfg, "Pii", profile.Id)) ? "" : null; + return HasRejectingPublic(cfg, app) && !ProfileEditing.RejectsSensitive(profile) && IsLocal(Route(cfg, "Pii", profile.Id)) ? "" : null; + case ExampleNeed.SensitivePublicRejected: + return ProfileEditing.RejectsSensitive(profile) ? "" : null; case ExampleNeed.CacheRepeat: return route.Primary is not null && (cfg.Settings?.CacheTtlSeconds ?? 0) > 0 ? "" : null; case ExampleNeed.BudgetRefusal: @@ -476,6 +505,11 @@ private static int Score(DemoExample ex, ApplicationSummaryDto app, WorkloadProf return null; } + /// The application is granted a Public workload that rejects detected sensitive data (ADR-0019). + public static bool HasRejectingPublic(CovenantConfigDto cfg, ApplicationSummaryDto app) + => ComposerRules.GrantedProfiles(app).Any(g => cfg.Profiles.FirstOrDefault(p => p.Id == g) is { } p + && string.Equals(p.Baseline, "Public", StringComparison.Ordinal) && ProfileEditing.RejectsSensitive(p)); + private static bool PrimaryPriced(ResolvedRoute r) => r.Primary is { } p && r.PrimaryConnection?.Models.FirstOrDefault(m => m.ModelId == p.ModelId)?.Price is { } price && ((price.InputPer1M ?? 0m) > 0m || (price.OutputPer1M ?? 0m) > 0m); @@ -521,7 +555,10 @@ private static IEnumerable WhatIsMissing(DemoExample ex, Co yield return new("No Public profile has an eligible cloud target to pin. This example needs a Public cloud route (Hybrid mode).", "policies", "Policies"); break; case ExampleNeed.SensitiveLocal: - yield return new("No local route covers PII for this application's Public workloads. Add a PII route to a local model (Policies → Routes); without one, sensitive requests are refused.", "policies", "Policies"); + yield return new("This example needs both halves of the comparison: an Internal workload whose \"When sensitive data is detected\" is Route with a PII route to a local model, and a Public workload set to Reject — both granted to this application (Policies → Workloads, Routes).", "policies", "Policies"); + break; + case ExampleNeed.SensitivePublicRejected: + yield return new("No Public workload of this application rejects detected sensitive data. Set \"When sensitive data is detected\" to Reject on its Public workload (Policies → Workloads) — a new, audited configuration version.", "policies", "Policies"); break; case ExampleNeed.CacheRepeat: if ((cfg.Settings?.CacheTtlSeconds ?? 0) <= 0) @@ -597,6 +634,31 @@ public static bool ResetExamplePin(PlaygroundForm form) return true; } + /// After the operator switches the workload (PlaygroundState.SelectProfile). The prompt and every other field are + /// KEPT. An external pin the example set is reset (). The example label is kept only when + /// the form now holds EXACTLY what another ready example fills for the new workload (e.g. the Internal/Public sensitive + /// pair: same prompt, workflow and use case, no pin) — then it is relabelled to that example; otherwise it is cleared, so + /// no run is labelled with an example (or expected outcome) that no longer describes it. + public static void AfterWorkloadChange(PlaygroundForm form, IReadOnlyList? examples) + { + ResetExamplePin(form); + if (form.ExampleId is null || string.Equals(form.ExampleProfileId, form.ProfileId, StringComparison.Ordinal)) return; + var twin = examples?.FirstOrDefault(r => r.Ready && r.ModelPin is null + && string.Equals(r.ApplicationId, form.ApplicationId, StringComparison.Ordinal) + && string.Equals(r.ProfileId, form.ProfileId, StringComparison.Ordinal) + && string.Equals(r.Example.Prompt, form.Prompt, StringComparison.Ordinal) + && string.Equals(r.Example.Workflow, form.Workflow, StringComparison.Ordinal) + && string.Equals(r.Example.UseCase, form.UseCase, StringComparison.Ordinal)); + if (twin is not null) + { + form.ExampleId = twin.Example.Id; + form.ExampleApplicationId = form.ApplicationId; + form.ExampleProfileId = form.ProfileId; + if (StillMatches(twin.Example, form)) return; + } + form.ExampleId = null; + } + /// What "Use example" will change in the CURRENT form, shown before it is pressed. Empty = nothing visible changes /// besides the prompt. public static IReadOnlyList ChangesFor(ExampleResolution r, PlaygroundForm form) diff --git a/src/Covenant.Ui/Logic/ExampleRecommendations.cs b/src/Covenant.Ui/Logic/ExampleRecommendations.cs index e207d0d..0dab400 100644 --- a/src/Covenant.Ui/Logic/ExampleRecommendations.cs +++ b/src/Covenant.Ui/Logic/ExampleRecommendations.cs @@ -26,12 +26,20 @@ public static partial class ExampleRecommendations "budget-refusal", ]; + /// ADR-0019 demonstration pair: the same sensitive prompt served locally on an Internal workload and rejected on a + /// Public one. Recommended together — never one without the other — when the application's configuration shows BOTH (an + /// Internal workload approved for sensitive data and a Public workload that rejects it). + public static readonly IReadOnlyList SensitivePair = ["sensitive-local", "sensitive-public-rejected"]; + public static ExampleGroups Split(IReadOnlyList relevant) { - var recommended = relevant - .Where(r => Primary.Contains(r.Example.Id)) - .OrderBy(r => IndexOf(r.Example.Id)) - .Take(Max) + var pair = SensitivePair.Select(id => relevant.FirstOrDefault(r => r.Example.Id == id)).ToList(); + bool showPair = pair.All(r => r is not null); + var recommended = (showPair ? pair.Select(r => r!) : Enumerable.Empty()) + .Concat(relevant + .Where(r => Primary.Contains(r.Example.Id)) + .OrderBy(r => IndexOf(r.Example.Id)) + .Take(Max - (showPair ? SensitivePair.Count : 0))) .ToList(); if (recommended.Count == 0) recommended = relevant.Take(2).ToList(); // no task-specific fit: the first generic ones var more = relevant.Where(r => !recommended.Contains(r)).ToList(); @@ -45,6 +53,21 @@ private static int IndexOf(string id) } } +/// The example selector's value (pure; ExamplePicker). The operator's pick wins while it still describes the form; the +/// form's own example label (set by "Use example", or by a twin relabel after a workload switch — DemoExamples.AfterWorkloadChange) +/// is shown otherwise. The select, the "Fill again"/"Use example" button and the summary therefore always name the SAME example +/// (browser review: a relabelled twin showed the placeholder while its buttons stayed). +public static class ExampleSelection +{ + /// Value the selector shows (null = the placeholder). + public static string? Shown(string? picked, string? formExampleId) => picked ?? formExampleId; + + /// After an application or workload switch: a pick that no longer is the form's example follows the form's + /// (possibly relabelled) example, or clears when the form has none. + public static string? AfterSwitch(string? picked, string? formExampleId) + => picked is not null && !string.Equals(picked, formExampleId, StringComparison.Ordinal) ? formExampleId : picked; +} + /// Human labels for configured models — never an availability claim: the label comes from the APPLIED configuration /// (the model's display name when configured), else a readable form of the exact id. public static partial class ModelLabels diff --git a/src/Covenant.Ui/Logic/JourneyChips.cs b/src/Covenant.Ui/Logic/JourneyChips.cs index e008c35..1808046 100644 --- a/src/Covenant.Ui/Logic/JourneyChips.cs +++ b/src/Covenant.Ui/Logic/JourneyChips.cs @@ -44,6 +44,9 @@ public static IReadOnlyList For(AuditEntryView r, IReadOnlyListThe workload rejects requests that detection raises to PII/PHI (null / "route" = routed by policy). + public static bool RejectsSensitive(WorkloadProfileDto? p) => string.Equals(p?.SensitiveDataAction, ActionReject, StringComparison.Ordinal); + + /// Sets the action. "reject" only on a Public or Internal baseline (the Host validates too): on a PII/PHI + /// baseline every request is sensitive by declaration. + public static string? SetSensitiveAction(WorkloadProfileDto profile, string? action) + { + bool reject = string.Equals(action, ActionReject, StringComparison.Ordinal); + if (reject && PolicyText.IsSensitive(profile.Baseline)) + return "Only a Public or Internal workload can reject detected sensitive data — a PII/PHI workload is sensitive by declaration."; + profile.SensitiveDataAction = reject ? ActionReject : ActionRoute; + return null; + } + + /// One line for lists and the composer. + public static string SensitiveActionText(WorkloadProfileDto? p) => RejectsSensitive(p) + ? "rejects detected sensitive data" + : "detected sensitive data is routed by policy (local only)"; + + public const string SensitiveActionExplained = + "When local detection finds PII or PHI in a request under this workload: Route lets the PII/PHI policy decide (sensitive data never goes to an external model, except an opt-in sanitized record route). Reject refuses the request before routing, cache, web search or any model, and tells the caller which workload would accept it."; + public const string WebSearchExplained = "Web search sends a bounded query to Tavily for Public requests only, and only when web search is enabled in Settings. The search is charged to your budgets."; diff --git a/src/Covenant.Ui/Logic/RouteScheme.cs b/src/Covenant.Ui/Logic/RouteScheme.cs index 7a13422..d075dae 100644 --- a/src/Covenant.Ui/Logic/RouteScheme.cs +++ b/src/Covenant.Ui/Logic/RouteScheme.cs @@ -75,12 +75,19 @@ public static RouteSchemeView Expected(RoutePreview? preview, PlaygroundForm for if (activeVersion is { } v && r.ConfigVersion is { } pv && pv != v) return new("expected", "stale", "The configuration changed (v" + pv + " → v" + v + ") — preview again.", sender, CovenantPending, DestinationUnknown, searchBadge); + // ADR-0019: the workload rejects detected sensitive data — refused at Classify, before policy; nothing would run + // (no search either, so no search badge). + bool rejected = string.Equals(r.RefusedAtStage, "classify", StringComparison.Ordinal); var covenant = new SchemeBox("Covenant", ClassLine(r.Classification, r.Baseline, r.DetectedSignal, evaluated: r.Classification != "Not evaluated"), - Join(r.PolicyId is { } pid ? "policy " + pid : null, r.Redaction is { Outcome: "applied" } ? "builds a sanitized structured payload" : null), + rejected ? "rejected at Classify: this workload does not accept detected sensitive data" + : Join(r.PolicyId is { } pid ? "policy " + pid : null, r.Redaction is { Outcome: "applied" } ? "builds a sanitized structured payload" : null), r.DetectedSignal is not null ? "blocked" : "neutral", "policies"); SchemeBox destination; + if (rejected) + return new("expected", "ready", "Server dry run on configuration v" + (r.ConfigVersion?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "?") + " — runtime checks still apply.", + sender, covenant, new("Destination", "Rejected — nothing would be sent", r.Reason, "blocked", "cross"), []); if (!string.Equals(r.Decision, "route", StringComparison.Ordinal)) destination = new("Destination", "Blocked — would not be contacted", r.Reason, "blocked", "cross"); else if (r.Redaction is { Outcome: "refused" } red) @@ -162,7 +169,10 @@ public static RouteSchemeView Actual(RequestSnapshot snapshot, AuditEntryView? r destination = new("Destination", "Provider failed — no answer", Join(contacted, r.Reason), "blocked", "cross"); else destination = new("Destination", "Blocked — model not contacted", Join( - r.StoppedAtStage is { Length: > 0 } st ? "refused at " + TraceModel.Label(st) : null, + // ADR-0019: evaluated, sensitive, stopped at Classify = the workload rejected the detected sensitive data. + evaluated && r.StoppedAtStage == "classify" && PolicyText.IsSensitive(r.Classification) + ? "rejected at Classify: this workload does not accept detected sensitive data" + : r.StoppedAtStage is { Length: > 0 } st ? "refused at " + TraceModel.Label(st) : null, searches.Count > 0 ? "a web search was made before the refusal" : null), "blocked", "cross"); return new("actual", "ready", "From this run's audit record" + (r.ConfigVersion is { } v ? " (configuration v" + v + ")" : "") + ".", diff --git a/src/Covenant.Ui/Logic/TraceModel.cs b/src/Covenant.Ui/Logic/TraceModel.cs index 38baeb0..7c85221 100644 --- a/src/Covenant.Ui/Logic/TraceModel.cs +++ b/src/Covenant.Ui/Logic/TraceModel.cs @@ -100,6 +100,8 @@ public static class TraceModel ("cache", TraceStepState.Passed, "cache_miss") => "Miss", ("cache", TraceStepState.Skipped, "cache_disabled") => "Off", ("cache", TraceStepState.Skipped, "web_search_bypass") => "Bypassed", + ("classify", TraceStepState.Refused, "sensitive_data_rejected") => "Rejected", + ("classify", TraceStepState.Refused, "inspection_incomplete") => "Not inspected", ("search", TraceStepState.Skipped, "search_off") => "Off", ("search", TraceStepState.Skipped, "search_not_triggered") => "Not needed", ("attribution", TraceStepState.Skipped, _) => "No usage", @@ -110,6 +112,8 @@ public static class TraceModel /// A sentence for the popover when the step's state alone would mislead. public static string? OutcomeNote(TraceStepView s) => (s.Stage, s.State, s.ReasonCode) switch { + ("classify", TraceStepState.Refused, "sensitive_data_rejected") => "Sensitive data was detected and this workload rejects it (ADR-0019): refused before routing, cache, web search and any model. Nothing was sent.", + ("classify", TraceStepState.Refused, "inspection_incomplete") => "Inspection could not complete within its bounds: refused, classification not evaluated. Nothing was sent.", ("attribution", TraceStepState.Skipped, _) => "No provider answer to price. The request is still recorded with its application, team and workload; any reservation was released or settled by the budget stage.", ("cache", TraceStepState.Skipped, "cache_disabled") => "The exact cache is disabled (TTL 0): no lookup was made.", ("cache", TraceStepState.Passed, "cache_miss") => "Looked up; no identical recent request — continued to the provider.", diff --git a/src/Covenant.Ui/Logic/WorkloadDestination.cs b/src/Covenant.Ui/Logic/WorkloadDestination.cs index 0f00c00..b3b834c 100644 --- a/src/Covenant.Ui/Logic/WorkloadDestination.cs +++ b/src/Covenant.Ui/Logic/WorkloadDestination.cs @@ -21,6 +21,12 @@ public sealed record WorkloadDestinationView( public static class WorkloadDestination { + /// Route action (default): detection escalates and the PII/PHI policy (local) decides. + public const string StricterRuleNote = "If the prompt contains sensitive data, detection raises it and the stricter (local) rule applies."; + + /// Reject action (ADR-0019). + public const string RejectNote = "This workload rejects detected sensitive data (PII/PHI): such a request is refused at the gateway, never rerouted."; + public static WorkloadDestinationView For(CovenantConfigDto? cfg, WorkloadProfileDto? profile, string? requestedModel = null) { if (cfg is null) return Fail("Configuration not loaded yet.", null, null); @@ -35,12 +41,16 @@ public static WorkloadDestinationView For(CovenantConfigDto? cfg, WorkloadProfil var fallbacks = route.Eligible.Skip(1).Select(t => t.ConnectionId + "/" + t.ModelId).ToList(); string? note = null; bool isPublic = string.Equals(baseline, "Public", StringComparison.Ordinal); + // ADR-0019: a workload that rejects detected sensitive data never applies "the stricter (local) rule" — that copy would + // contradict the gateway's refusal, so it is replaced by the rejection sentence. + bool rejects = ProfileEditing.RejectsSensitive(profile); if (isPublic && boundary == "Local") note = PolicyRoutes.IsLocalOnly(cfg.Mode) ? "Public work runs locally: this configuration is Local-only. Cloud needs Hybrid mode and an approved cloud route." : "Public means cloud-eligible, not cloud: this workload's policy routes it to a local model."; - else if (isPublic && boundary == "Cloud") - note = "If the prompt contains sensitive data, detection raises it and the stricter (local) rule applies."; + else if (isPublic && boundary == "Cloud" && !rejects) + note = StricterRuleNote; + if (rejects) note = note is null ? RejectNote : note + " " + RejectNote; if (route.Policy is { } sp && PolicyText.IsSanitized(sp)) note = "Sanitized workload: only a covenant.record.v1 structured record leaves, as placeholders; prose and PHI are refused. Preview shows the exact payload."; // A pinned model is announced by the composer's own pin warning (with "Let policy choose"); not repeated here. diff --git a/src/Covenant.Ui/Models/ConfigContracts.cs b/src/Covenant.Ui/Models/ConfigContracts.cs index cdd24eb..ba3762e 100644 --- a/src/Covenant.Ui/Models/ConfigContracts.cs +++ b/src/Covenant.Ui/Models/ConfigContracts.cs @@ -127,6 +127,9 @@ public sealed class WorkloadProfileDto [JsonPropertyName("description")] public string? Description { get; set; } /// ADR-0015: this profile may use web search. Only a Public-baseline profile may carry it. [JsonPropertyName("web_search_allowed")] public bool WebSearchAllowed { get; set; } + /// ADR-0019: "route" | "reject" — what happens when detection raises a request under this workload to PII/PHI. + /// Null (older Host) = "route". Kept as received on save so the console never drops it. + [JsonPropertyName("sensitive_data_action")] public string? SensitiveDataAction { get; set; } } public sealed class PolicyDto @@ -450,6 +453,10 @@ public sealed class SimulateResponseDto [JsonPropertyName("explanation")] public string? Explanation { get; set; } /// ADR-0016: the sanitized payload that WOULD be sent, or why it is refused. Never authorization. [JsonPropertyName("redaction")] public SimulatedRedactionDto? Redaction { get; set; } + /// ADR-0019: "classify" when the workload rejects the detected sensitive data (refused before policy); else null. + [JsonPropertyName("refused_at_stage")] public string? RefusedAtStage { get; set; } + /// ADR-0019: granted workloads under which the Host's policy engine WOULD route this request's classification. + [JsonPropertyName("suggested_profiles")] public List? SuggestedProfiles { get; set; } } public sealed class SimulatedRedactionDto diff --git a/src/Covenant.Ui/Pages/Policies.razor b/src/Covenant.Ui/Pages/Policies.razor index ae4cbf2..b345e5b 100644 --- a/src/Covenant.Ui/Pages/Policies.razor +++ b/src/Covenant.Ui/Pages/Policies.razor @@ -171,7 +171,7 @@
  • @(wl.Name ?? wl.Id) - @wl.Id · baseline @PolicyText.ClassificationLabel(wl.Baseline)@(wl.WebSearchAllowed ? " · web search allowed" : "") · used by @(usage.GrantedTo.Count == 0 ? "no application" : string.Join(", ", usage.GrantedTo)) + @wl.Id · baseline @PolicyText.ClassificationLabel(wl.Baseline)@(wl.WebSearchAllowed ? " · web search allowed" : "")@(ProfileEditing.RejectsSensitive(wl) ? " · rejects detected sensitive data" : "") · used by @(usage.GrantedTo.Count == 0 ? "no application" : string.Join(", ", usage.GrantedTo))
    @{ var dest = WorkloadDestination.For(cfg, wl); } @@ -418,6 +418,18 @@ Allow web search (Public workloads only) + @* ADR-0019: server-side, versioned; the gateway enforces it for every caller (console and API). *@ +
    + + @{ var sensDisabled = PolicyText.IsSensitive(wp.Baseline); } + + @(sensDisabled ? "A PII/PHI workload is sensitive by declaration; its requests are always routed by the sensitive-data policy." : ProfileEditing.SensitiveActionExplained) +
    @if (!we.IsNew) { @@ -711,6 +723,7 @@ if (e.IsNew && !ConnectionRules.IsValidId(w.Id)) p.Add("Enter a workload id (letters, digits, '.', '_' or '-')."); if (string.IsNullOrWhiteSpace(w.Name)) p.Add("Enter a name."); if (w.WebSearchAllowed && !string.Equals(w.Baseline, "Public", StringComparison.Ordinal)) p.Add("Only a Public workload may use web search."); + if (ProfileEditing.RejectsSensitive(w) && PolicyText.IsSensitive(w.Baseline)) p.Add("Only a Public or Internal workload can reject detected sensitive data."); return p; } @@ -732,6 +745,8 @@ if (!ProfileEditing.IsBaseline(baseline)) return; w.Baseline = baseline; if (!string.Equals(baseline, "Public", StringComparison.Ordinal)) w.WebSearchAllowed = false; + // ADR-0019: a PII/PHI workload cannot reject "detected" sensitive data — back to the default. + if (PolicyText.IsSensitive(baseline) && ProfileEditing.RejectsSensitive(w)) w.SensitiveDataAction = ProfileEditing.ActionRoute; } /// Primary/fallback from the selectors; an empty primary is reported by RouteProblem (Save stays disabled). diff --git a/src/Covenant.Ui/Services/PlaygroundState.cs b/src/Covenant.Ui/Services/PlaygroundState.cs index 036bf1c..180ecd9 100644 --- a/src/Covenant.Ui/Services/PlaygroundState.cs +++ b/src/Covenant.Ui/Services/PlaygroundState.cs @@ -269,10 +269,9 @@ public bool SelectProfile(string? profileId) { if (Running) return false; var ok = ComposerRules.SelectProfile(Form, _workspace.Applications, profileId); - // The example's own external pin described the previous workload: back to "Let policy choose". - if (ok) DemoExamples.ResetExamplePin(Form); - // An example filled for another workload no longer describes this request (e.g. Internal coding after switching to Public). - if (ok && Form.ExampleId is not null && !string.Equals(Form.ExampleProfileId, Form.ProfileId, StringComparison.Ordinal)) Form.ExampleId = null; + // The prompt is kept. The example's own external pin is reset; the example label is kept only for an exact twin on the + // new workload (the Internal/Public sensitive pair), otherwise cleared — never a stale example claim (pure, tested). + if (ok) DemoExamples.AfterWorkloadChange(Form, Examples); PresetNote = null; Notify(); return ok; diff --git a/tests/Covenant.Tests/ContractRoundTripTests.cs b/tests/Covenant.Tests/ContractRoundTripTests.cs index 56e2855..5262b4c 100644 --- a/tests/Covenant.Tests/ContractRoundTripTests.cs +++ b/tests/Covenant.Tests/ContractRoundTripTests.cs @@ -102,7 +102,8 @@ public sealed class ContractRoundTripTests ], Profiles = [ - new WorkloadProfileConfig { Id = "public-tickets", Name = "Public tickets", Baseline = DataClassification.Public, Description = "Synthetic public text" }, + new WorkloadProfileConfig { Id = "public-tickets", Name = "Public tickets", Baseline = DataClassification.Public, Description = "Synthetic public text", + SensitiveDataAction = SensitiveDataAction.Reject }, new WorkloadProfileConfig { Id = "internal", Name = "Internal", Baseline = DataClassification.Internal }, new WorkloadProfileConfig { Id = "customer-pii", Name = "Customer PII", Baseline = DataClassification.Pii }, new WorkloadProfileConfig { Id = "clinical", Name = "Clinical", Baseline = DataClassification.Phi }, @@ -331,6 +332,8 @@ public void Host_wire_spellings_are_the_contract_vocabulary_and_the_console_read Assert.Equal(new[] { "monthly", "daily", "none" }, dto.Budgets.Select(b => b.Period)); Assert.Equal(new[] { "hard", "warn-only", "hard" }, dto.Budgets.Select(b => b.Enforcement)); Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, dto.Profiles.Select(p => p.Baseline)); + // ADR-0019: "reject" is written explicitly; the default "route" travels too, and the console keeps both on save. + Assert.Equal(new[] { "reject", "route", "route", "route" }, dto.Profiles.Select(p => p.SensitiveDataAction)); Assert.Equal(new[] { "Pii", "Phi" }, dto.Policies[2].Classifications); Assert.Equal(0.15m, dto.Connections[2].Models[0].Price!.InputPer1M); Assert.Equal(0.60m, dto.Connections[2].Models[0].Price!.OutputPer1M); @@ -504,6 +507,18 @@ public void Simulator_request_with_a_draft_candidate_and_dry_run_response_round_ Assert.Null(ui.Eligible[0].ExcludedReason); Assert.Equal("cloud destination for PII", ui.Eligible[1].ExcludedReason); Assert.Equal("PII → ollama/qwen3:8b", ui.Explanation); + Assert.Null(ui.RefusedAtStage); + + // ADR-0019: a classify-stage rejection carries the stage and the Host-computed suggestions to the console. + var rejected = JsonSerializer.Serialize(new SimulateResponse + { + DryRun = true, ConfigVersion = 7, ApplicationId = "demo-app", Profile = "public-tickets", Classification = "Pii", Baseline = "Public", + DetectedSignal = "US SSN pattern", Eligible = [], Decision = "refuse", Fallbacks = [], Reason = "rejected", + RefusedAtStage = "classify", SuggestedProfiles = ["internal"], + }, ConfigJsonContext.Default.SimulateResponse); + var uiRejected = JsonSerializer.Deserialize(rejected, UiModels.UiJsonContext.Default.SimulateResponseDto)!; + Assert.Equal("classify", uiRejected.RefusedAtStage); + Assert.Equal(["internal"], uiRejected.SuggestedProfiles!); } [Fact] diff --git a/tests/Covenant.Tests/DemoAppScopedTests.cs b/tests/Covenant.Tests/DemoAppScopedTests.cs index 844d4f9..5787bd5 100644 --- a/tests/Covenant.Tests/DemoAppScopedTests.cs +++ b/tests/Covenant.Tests/DemoAppScopedTests.cs @@ -102,12 +102,15 @@ public sealed class DemoAppScopedTests public void Each_application_lists_only_examples_its_workloads_and_routes_support() { Assert.Equal(["internal-coding"], Ids(For("engineering-assistant"))); // no research-model or public examples - Assert.Equal(["cache-repeat", "internal-research", "public-research", "sensitive-local", "sensitive-refusal"], Ids(For("research-assistant"))); - Assert.Equal(["cache-repeat", "public-writing", "sensitive-local", "sensitive-refusal"], Ids(For("communications-assistant"))); - Assert.Equal(["budget-refusal", "cache-repeat", "public-writing", "sensitive-local", "sensitive-refusal"], Ids(For("budget-demo"))); + // ADR-0019: the sensitive pair ("sensitive-local" / "sensitive-public-rejected") is offered only to an application whose + // workloads show BOTH halves (Internal routes sensitive data locally AND Public rejects it) — none in v7; see + // SensitiveDataActionUiTests for demo-app. Engineering (Internal only) gets no sensitive-data noise. + Assert.Equal(["cache-repeat", "internal-research", "public-research", "sensitive-refusal"], Ids(For("research-assistant"))); + Assert.Equal(["cache-repeat", "public-writing", "sensitive-refusal"], Ids(For("communications-assistant"))); + Assert.Equal(["budget-refusal", "cache-repeat", "public-writing", "sensitive-refusal"], Ids(For("budget-demo"))); // demo-app's Public workload searches the web and answers on the LOCAL coder: the generic web-research example and the // local-inference + governed-search example both describe it; nothing external-model-only is offered. - Assert.Equal(["cache-repeat", "public-local-research", "public-research", "sensitive-local"], Ids(For("demo-app"))); // PII stays local; no external to block + Assert.Equal(["cache-repeat", "public-local-research", "public-research"], Ids(For("demo-app"))); // Public only here; no external to block Assert.DoesNotContain("public-local-research", Ids(For("research-assistant"))); // its Public research answers on Claude Assert.DoesNotContain("budget-refusal", Ids(For("research-assistant"))); } @@ -124,7 +127,7 @@ public void A_mixed_writing_application_gets_writing_examples_not_coding_ones_on .Select(e => UiLogic.DemoExamples.ResolveFor(e, "communications-assistant", cfg, Apps(cfg), Budgets, Search())) .Where(r => r.Relevant).Select(r => r.Example.Id).OrderBy(x => x, StringComparer.Ordinal).ToArray(); - Assert.Equal(["cache-repeat", "internal-writing", "public-writing", "sensitive-local", "sensitive-refusal"], ids); // generic examples kept + Assert.Equal(["cache-repeat", "internal-writing", "public-writing", "sensitive-refusal"], ids); // generic examples kept Assert.DoesNotContain("internal-coding", ids); // same model ≠ coding work var writing = UiLogic.DemoExamples.ResolveFor(UiLogic.DemoExamples.Find("internal-writing")!, "communications-assistant", cfg, Apps(cfg), Budgets, Search()); Assert.True(writing.Ready); @@ -147,9 +150,9 @@ public void Each_application_recommends_at_most_three_task_examples_and_keeps_di var cfg = V7(); Assert.Equal(["internal-coding"], Groups(cfg, "engineering-assistant").Recommended); Assert.Equal(["internal-research"], Groups(cfg, "research-assistant").Recommended); // cloud research is optional - Assert.Equal(["cache-repeat", "public-research", "sensitive-local", "sensitive-refusal"], Groups(cfg, "research-assistant").More); + Assert.Equal(["cache-repeat", "public-research", "sensitive-refusal"], Groups(cfg, "research-assistant").More); Assert.Equal(["public-writing"], Groups(cfg, "communications-assistant").Recommended); - Assert.Equal(["cache-repeat", "sensitive-local", "sensitive-refusal"], Groups(cfg, "communications-assistant").More); + Assert.Equal(["cache-repeat", "sensitive-refusal"], Groups(cfg, "communications-assistant").More); Assert.Equal(["public-writing", "budget-refusal"], Groups(cfg, "budget-demo").Recommended); // dedicated budget app only Assert.Equal(["public-local-research"], Groups(cfg, "demo-app").Recommended); foreach (var app in new[] { "engineering-assistant", "research-assistant", "communications-assistant", "budget-demo", "demo-app" }) @@ -191,14 +194,15 @@ private static UiLogic.ExampleResolution ResolveFor(string example, string app) } [Fact] - public void The_same_sensitive_prompt_is_local_by_policy_and_blocked_only_with_an_explicit_external_pin() + public void Without_a_rejecting_public_workload_only_the_explicit_external_pin_example_is_offered() { - var local = ResolveFor("sensitive-local", "communications-assistant"); - var blocked = ResolveFor("sensitive-refusal", "communications-assistant"); + // research-assistant: Internal research + Public research (Claude, route action). The pin example is offered; + // the Internal/Public pair is not (no Public workload rejects sensitive data here — ADR-0019). + var local = ResolveFor("sensitive-local", "research-assistant"); + var blocked = ResolveFor("sensitive-refusal", "research-assistant"); Assert.Equal(local.Example.Prompt, blocked.Example.Prompt); // same synthetic input - Assert.True(local.Ready); - Assert.Null(local.ModelPin); // policy chooses → PII route → local - Assert.Contains("ollama/", local.ConfiguredRoute, StringComparison.Ordinal); + Assert.False(local.Relevant); + Assert.False(local.Ready); Assert.Equal("anthropic/" + Claude, blocked.ModelPin); // explicit external attempt Assert.Contains("Blocked by policy", blocked.Example.Expected, StringComparison.Ordinal); Assert.Contains("not a provider outage", blocked.Example.Expected, StringComparison.Ordinal); diff --git a/tests/Covenant.Tests/LegacyImportTests.cs b/tests/Covenant.Tests/LegacyImportTests.cs index 060587a..ad2cefa 100644 --- a/tests/Covenant.Tests/LegacyImportTests.cs +++ b/tests/Covenant.Tests/LegacyImportTests.cs @@ -245,8 +245,15 @@ public void Demo_seeds_use_the_restrictive_defaults() var h = new RuntimeSnapshot(hybrid); Assert.Equal("openai/gpt-4o-mini (fallback: ollama/qwen3:8b)", PolicyEngineV2.Summary(h, DataClassification.Public, "public-demo")); - foreach (var cls in new[] { DataClassification.Internal, DataClassification.Pii, DataClassification.Phi }) - Assert.Equal("ollama/qwen3:8b", PolicyEngineV2.Summary(h, cls, "public-demo")); + Assert.Equal("ollama/qwen3:8b", PolicyEngineV2.Summary(h, DataClassification.Internal, "public-demo")); + // ADR-0019: the seeded Public workload rejects detected sensitive data; the Internal workload routes it locally. + Assert.Equal(SensitiveDataAction.Reject, hybrid.Profiles.Single(p => p.Id == "public-demo").SensitiveDataAction); + Assert.Equal(SensitiveDataAction.Route, hybrid.Profiles.Single(p => p.Id == "internal-default").SensitiveDataAction); + foreach (var cls in new[] { DataClassification.Pii, DataClassification.Phi }) + { + Assert.StartsWith("refused: workload 'public-demo' rejects detected sensitive data", PolicyEngineV2.Summary(h, cls, "public-demo"), StringComparison.Ordinal); + Assert.Equal("ollama/qwen3:8b", PolicyEngineV2.Summary(h, cls, "internal-default")); + } Assert.Equal("ollama/qwen3:8b", PolicyEngineV2.Summary(new RuntimeSnapshot(local), DataClassification.Public, "public-demo")); Assert.Equal(BudgetPeriod.Monthly, hybrid.Budgets.Single().Period); Assert.Equal(3m, hybrid.Budgets.Single().CapUsd); diff --git a/tests/Covenant.Tests/SensitiveDataActionTests.cs b/tests/Covenant.Tests/SensitiveDataActionTests.cs new file mode 100644 index 0000000..931da0a --- /dev/null +++ b/tests/Covenant.Tests/SensitiveDataActionTests.cs @@ -0,0 +1,414 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0019: a workload profile states what happens when detection raises a request to PII/PHI. "reject" refuses it +/// at the classify stage — before policy, cache, rate limit, budget, web search and any provider — with the escalated class, +/// the signal label and a server-computed suggestion in evidence. "route" (default) is unchanged: PII/PHI stay local. The +/// simulator, the policy engine and execution share one rule. Each guarantee has a test that fails if it is removed. +public sealed class SensitiveDataActionTests +{ + private const string Ssn = "000-12-3456"; + + /// The V2 hybrid fixture with the demo seed's ADR-0019 shape: public-demo rejects, internal-default routes. + /// public-demo may search (search enabled and priced) and the exact cache is on, so a missing guard would show up as a + /// search call, a cache entry or a provider call. + private static CovenantConfig Cfg(SensitiveDataAction publicAction = SensitiveDataAction.Reject, bool grantInternal = true, + Func? tweak = null) + => V2.Hybrid(tweak: c => + { + var x = c with + { + Profiles = c.Profiles.Select(p => p.Id == "public-demo" ? p with { WebSearchAllowed = true, SensitiveDataAction = publicAction } : p).ToList(), + Applications = grantInternal ? c.Applications + : c.Applications.Select(a => a.Id != "demo-app" ? a : a with { GrantedProfiles = ["public-demo"], DefaultProfile = "public-demo" }).ToList(), + WebSearch = new WebSearchSettings { Enabled = true, PricePerCreditUsd = 0.008m }, + Settings = c.Settings with { CacheTtlSeconds = 300 }, + }; + return tweak is null ? x : tweak(x); + }); + + private sealed record Rig(V2Rig V2, StubChatClient Cloud, StubChatClient Local, StubSearchClient Search, ResponseCache Cache); + + private static Rig Build(CovenantConfig cfg) + { + var cloud = new StubChatClient("cloud reply"); + var local = new StubChatClient("local reply"); + var search = new StubSearchClient(); + var cache = new ResponseCache(); + var rig = V2Rig.Build(cfg, new Dictionary + { + [$"openai:{V2.CloudModel}"] = cloud, + [$"ollama:{V2.LocalTag}"] = local, + }, cache: cache, search: search); + return new Rig(rig, cloud, local, search, cache); + } + + public static TheoryData PhiVariants => new() + { + "Patient John Smith was diagnosed with type 2 diabetes last week.", + "patient jane roe has diabetes", + "My name is Jane Roe. I was diagnosed with diabetes.", + "Name: Jane Roe. Prescribed insulin for diabetes.", + "MRN: 00123456", + "{\"patient_name\":\"jane roe\",\"medication\":\"insulin\"}", + }; + + private static void AssertRejectedAtClassify(Rig rig, InferenceContext ctx, AuditEntry e) + { + Assert.True(ctx.IsDenied); + Assert.Equal("classify", ctx.StoppedAtStage); + Assert.Equal(TraceReasons.SensitiveDataRejected, ctx.DenialCode); + Assert.Equal(DenialKind.Governance, ctx.DenialKind); + Assert.Null(ctx.Policy); // policy never evaluated + Assert.Equal(0, rig.Cloud.Calls + rig.Local.Calls + rig.Search.Calls); // nothing external, nothing local + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.True(e.Classification >= DataClassification.Pii); // the escalated class is kept + Assert.Equal(DataClassification.Public, e.BaselineClassification); + Assert.True(e.ClassificationEvaluated); // a real detection, not "incomplete" + Assert.NotNull(e.Signal); + Assert.Equal("public-demo", e.ProfileId); + Assert.True(e.Attempts is null || e.Attempts.Count == 0); + Assert.Null(e.ToolCalls); + Assert.False(ctx.ServedFromCache); + Assert.Equal(0m, rig.V2.Ledger.Reserved("global")); + Assert.DoesNotContain(Ssn, e.Reason, StringComparison.Ordinal); // the reason never echoes content + } + + // ---------------------------------------------------------------- reject: every format, nothing reaches anything + + [Theory] + [MemberData(nameof(SensitiveInspectionTests.PiiVariants), MemberType = typeof(SensitiveInspectionTests))] + public async Task Public_workload_rejects_every_PII_format_at_classify_with_search_requested(string text) + { + var rig = Build(Cfg()); + var (ctx, e) = await rig.V2.RunAsync(text, profile: "public-demo", webSearch: new WebSearchRequest(WebSearchMode.Required)); + AssertRejectedAtClassify(rig, ctx, e); + Assert.Equal(DataClassification.Pii, e.Classification); + } + + [Theory] + [MemberData(nameof(PhiVariants))] + public async Task Public_workload_rejects_PHI_and_names_the_kind(string text) + { + var rig = Build(Cfg()); + var (ctx, e) = await rig.V2.RunAsync(text, profile: "public-demo"); + AssertRejectedAtClassify(rig, ctx, e); + Assert.Equal(DataClassification.Phi, e.Classification); + Assert.StartsWith("sensitive data detected (PHI", e.Reason, StringComparison.Ordinal); + } + + [Fact] + public async Task The_reason_is_clear_and_suggests_the_granted_internal_workload() + { + var rig = Build(Cfg()); + var (ctx, e) = await rig.V2.RunAsync($"Summarize this note. SSN on file: {Ssn}.", profile: "public-demo"); + AssertRejectedAtClassify(rig, ctx, e); + Assert.Contains("sensitive data detected (PII: US SSN pattern)", e.Reason, StringComparison.Ordinal); + Assert.Contains("workload 'public-demo' rejects detected sensitive data", e.Reason, StringComparison.Ordinal); + Assert.Contains("nothing was sent", e.Reason, StringComparison.Ordinal); + Assert.EndsWith("choose workload 'internal-default'.", e.Reason, StringComparison.Ordinal); + + // No granted alternative: said plainly, nothing invented. + var lone = Build(Cfg(grantInternal: false)); + var (_, le) = await lone.V2.RunAsync($"Summarize this note. SSN on file: {Ssn}.", profile: "public-demo"); + Assert.EndsWith("No other workload granted to this application accepts it.", le.Reason, StringComparison.Ordinal); + Assert.Empty(SensitiveDataRules.Suggestions(lone.V2.Snapshot, lone.V2.Snapshot.FindApplication("demo-app"), "public-demo", DataClassification.Pii)); + } + + [Fact] + public async Task A_sensitive_system_turn_is_rejected_too_and_an_explicit_cloud_pin_changes_nothing() + { + var rig = Build(Cfg()); + var ctx = new InferenceContext(new InferenceRequest("caller", + [new ChatMessage(ChatRole.System, $"Context: account holder SSN {Ssn}."), new ChatMessage(ChatRole.User, "Write a greeting.")], + "openai/" + V2.CloudModel, new AttributionTags("self-declared", "wf", "uc"), Credential: "demo-key", + RequestId: $"req_{Guid.NewGuid():n}", RequestedProfile: "public-demo")) + { + Configuration = rig.V2.Snapshot, + ConfigVersion = rig.V2.Snapshot.Version, + }; + await rig.V2.Pipeline.ExecuteAsync(ctx, default); + Assert.Equal("classify", ctx.StoppedAtStage); // before policy: the pin is never considered + Assert.Equal(TraceReasons.SensitiveDataRejected, ctx.DenialCode); + Assert.Equal(0, rig.Cloud.Calls + rig.Local.Calls); + } + + [Fact] + public async Task A_rejected_request_never_reads_or_writes_the_cache() + { + var rig = Build(Cfg()); + var prompt = $"Summarize this note. SSN on file: {Ssn}."; + var (first, _) = await rig.V2.RunAsync(prompt, profile: "public-demo"); + var (second, e) = await rig.V2.RunAsync(prompt, profile: "public-demo"); + Assert.True(first.IsDenied && second.IsDenied); + Assert.False(second.ServedFromCache); + Assert.True(e.CacheOutcome is null or "not_reached", e.CacheOutcome); // the cache stage was never reached + Assert.Equal(0, rig.Cloud.Calls + rig.Local.Calls); + } + + [Fact] + public async Task An_innocent_public_request_is_still_served_on_the_public_route() + { + var rig = Build(Cfg()); + var (ctx, e) = await rig.V2.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(DataClassification.Public, e.Classification); + Assert.Equal("openai", ctx.ServedTarget!.AdapterKey); + Assert.Equal(1, rig.Cloud.Calls); + } + + // ---------------------------------------------------------------- route (Internal / default): unchanged, local only + + [Theory] + [MemberData(nameof(PhiVariants))] + [InlineData("Summarize this note. SSN on file: " + Ssn + ".")] + [InlineData("card 4111 1111 1111 1111")] + public async Task The_internal_workload_serves_detected_sensitive_data_locally(string text) + { + var rig = Build(Cfg()); + var (ctx, e) = await rig.V2.RunAsync(text, profile: "internal-default"); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.True(e.Classification >= DataClassification.Pii); + Assert.Equal("ollama", ctx.ServedTarget!.AdapterKey); + Assert.Equal(0, rig.Cloud.Calls + rig.Search.Calls); + Assert.Equal(1, rig.Local.Calls); + } + + [Fact] + public async Task Default_route_keeps_the_previous_behaviour_for_a_public_workload() + { + // Backward compatibility: a version without the field (Route) still escalates and routes locally — never external. + var rig = Build(Cfg(publicAction: SensitiveDataAction.Route)); + var (ctx, e) = await rig.V2.RunAsync($"Summarize. SSN {Ssn}.", profile: "public-demo"); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(DataClassification.Pii, e.Classification); + Assert.Equal("ollama", ctx.ServedTarget!.AdapterKey); + Assert.Equal(0, rig.Cloud.Calls); + } + + [Fact] + public async Task A_failed_local_attempt_on_the_internal_workload_never_falls_back_externally() + { + var rig = Build(Cfg(tweak: c => c with + { + Policies = c.Policies.Select(p => p.Id != "sensitive" ? p : p with + { + Targets = [V2.T("ollama", V2.LocalTag), V2.T("openai", V2.CloudModel)], // unvalidated: lists a cloud target + Retry = new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000 }, + }).ToList(), + })); + rig.Local.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var (ctx, e) = await rig.V2.RunAsync($"Summarize. SSN {Ssn}.", profile: "internal-default"); + Assert.True(ctx.IsDenied); + Assert.Equal(0, rig.Cloud.Calls); + Assert.Single(e.Attempts!); + } + + // ---------------------------------------------------------------- fail-closed ordering + + [Fact] + public async Task Incomplete_inspection_is_still_refused_as_not_evaluated_not_as_a_rejection() + { + var rig = Build(Cfg()); + var (ctx, e) = await rig.V2.RunAsync("Summarize this ticket \uD800 please.", profile: "public-demo"); + Assert.Equal("classify", ctx.StoppedAtStage); + Assert.Equal(TraceReasons.InspectionIncomplete, ctx.DenialCode); + Assert.False(e.ClassificationEvaluated); + Assert.Equal(0, rig.Cloud.Calls + rig.Local.Calls + rig.Search.Calls); + } + + [Fact] + public void The_policy_engine_refuses_too_so_impact_previews_and_summaries_agree() + { + var snap = new RuntimeSnapshot(Cfg()); + foreach (var cls in new[] { DataClassification.Pii, DataClassification.Phi }) + { + var o = PolicyEngineV2.Evaluate(snap, cls, "public-demo", null, []); + Assert.Equal(PolicyEffect.Deny, o.Effect); + Assert.StartsWith("refused: workload 'public-demo' rejects detected sensitive data", PolicyEngineV2.Summary(snap, cls, "public-demo"), StringComparison.Ordinal); + Assert.Equal($"ollama/{V2.LocalTag}", PolicyEngineV2.Summary(snap, cls, "internal-default")); + } + Assert.Equal(PolicyEffect.Allow, PolicyEngineV2.Evaluate(snap, DataClassification.Public, "public-demo", null, []).Effect); + + // Impact preview of the migration (route → reject) shows exactly the PII/PHI rows of public-demo changing. + var before = new RuntimeSnapshot(Cfg(publicAction: SensitiveDataAction.Route)); + var rows = ImpactAnalyzer.Analyze(before, snap, _ => true).Classifications.Where(r => r.Changed).ToList(); + Assert.Equal(["Pii", "Phi"], rows.Where(r => r.Profile == "public-demo").Select(r => r.Classification).OrderByDescending(x => x).ToArray()); + Assert.DoesNotContain(rows, r => r.Profile != "public-demo"); + } + + // ---------------------------------------------------------------- simulation matches execution + + [Theory] + [InlineData("public-demo", "Summarize this note. SSN on file: " + Ssn + ".")] + [InlineData("public-demo", "Patient John Smith was diagnosed with type 2 diabetes last week.")] + [InlineData("internal-default", "Summarize this note. SSN on file: " + Ssn + ".")] + [InlineData("public-demo", V2Rig.PublicPrompt)] + public async Task Simulation_matches_execution(string profile, string prompt) + { + var rig = Build(Cfg()); + var sim = ConfigAdminApi.Simulate(rig.V2.Snapshot, new RegexDataClassifier(), + new SimulateRequest { ApplicationId = "demo-app", ProfileId = profile, Prompt = prompt }); + var (ctx, e) = await rig.V2.RunAsync(prompt, profile: profile); + + Assert.Equal(e.Classification.ToString(), sim.Classification); + Assert.Equal(e.Signal, sim.DetectedSignal); + if (ctx.IsDenied) + { + Assert.Equal("refuse", sim.Decision); + Assert.Equal(e.Reason, sim.Reason); // same rule, same words + Assert.Equal("classify", sim.RefusedAtStage); + Assert.Equal(["internal-default"], sim.SuggestedProfiles!); + } + else + { + Assert.Equal("route", sim.Decision); + Assert.Null(sim.RefusedAtStage); + Assert.Equal($"{ctx.ServedTarget!.AdapterKey}/{ctx.ServedTarget.ModelId}", sim.Primary); + } + } + + // ---------------------------------------------------------------- validation, sanitized policy, JSON compatibility + + /// Validation without the web-search block (its server-environment checks are covered by WebSearchTests). + private static ConfigValidationResult Validate(CovenantConfig c) => ConfigValidator.Validate(c with { WebSearch = null }, V2.Env()); + + [Fact] + public void Validation_accepts_reject_on_public_or_internal_and_refuses_it_on_a_sensitive_baseline() + { + Assert.True(Validate(Cfg()).IsValid); + var internalReject = Cfg(tweak: c => c with + { + Profiles = c.Profiles.Select(p => p.Id == "internal-default" ? p with { SensitiveDataAction = SensitiveDataAction.Reject } : p).ToList(), + }); + Assert.True(Validate(internalReject).IsValid); + + var phiReject = Cfg(tweak: c => c with + { + Profiles = c.Profiles.Select(p => p.Id == "phi-workload" ? p with { SensitiveDataAction = SensitiveDataAction.Reject } : p).ToList(), + }); + var v = Validate(phiReject); + var issue = Assert.Single(v.Errors, x => x.Code == "sensitive_action_requires_non_sensitive_baseline"); + Assert.Equal("profiles[2].sensitive_data_action", issue.Path); + + var undefined = Cfg(tweak: c => c with + { + Profiles = c.Profiles.Select(p => p.Id == "public-demo" ? p with { SensitiveDataAction = (SensitiveDataAction)99 } : p).ToList(), + }); + Assert.Contains(Validate(undefined).Errors, x => x.Code == "invalid_enum" && x.Path == "profiles[0].sensitive_data_action"); + + // Engine re-check: an unvalidated PHI-baseline "reject" never rejects (and never widens anything). + Assert.False(SensitiveDataRules.Rejects(new RuntimeSnapshot(phiReject), "phi-workload", DataClassification.Phi)); + } + + [Fact] + public void The_dedicated_sanitized_workload_is_unchanged() + { + var cfg = Cfg(tweak: c => c with + { + Profiles = [.. c.Profiles, new WorkloadProfileConfig { Id = "support-records", Name = "Support records", Baseline = DataClassification.Pii }], + Applications = c.Applications.Select(a => a.Id != "demo-app" ? a : a with { GrantedProfiles = [.. a.GrantedProfiles, "support-records"] }).ToList(), + Policies = [.. c.Policies, V2.Policy("sanitized-support", [DataClassification.Pii], [V2.T("openai", V2.CloudModel), V2.T("ollama", V2.LocalTag)], + profiles: ["support-records"]) with { Redaction = new RedactionPolicy { Types = ["email", "phone", "us_ssn"], Tasks = ["triage_case"] } }], + }); + Assert.True(Validate(cfg).IsValid); + var snap = new RuntimeSnapshot(cfg); + Assert.Equal(SensitiveDataAction.Route, snap.FindProfile("support-records")!.SensitiveDataAction); // default + var o = PolicyEngineV2.Evaluate(snap, DataClassification.Pii, "support-records", null, []); + Assert.Equal("openai", o.Route!.AdapterKey); + Assert.True(o.SanitizedPayloadRequired); + Assert.False(SensitiveDataRules.Rejects(snap, "support-records", DataClassification.Pii)); + // The sanitized workload is not offered as a suggestion for a rejected Public request: it is PII by declaration. + Assert.Equal(["internal-default"], SensitiveDataRules.Suggestions(snap, snap.FindApplication("demo-app"), "public-demo", DataClassification.Pii)); + } + + [Fact] + public void Older_versions_without_the_field_read_as_route_and_reject_round_trips() + { + var json = JsonSerializer.Serialize(Cfg(), ConfigJsonContext.Default.CovenantConfig); + Assert.Contains("\"sensitive_data_action\":\"reject\"", json, StringComparison.Ordinal); + Assert.Contains("\"sensitive_data_action\":\"route\"", json, StringComparison.Ordinal); + Assert.Equal(Cfg().Profiles, JsonSerializer.Deserialize(json, ConfigJsonContext.Default.CovenantConfig)!.Profiles); + + var legacy = json.Replace(",\"sensitive_data_action\":\"route\"", "", StringComparison.Ordinal) + .Replace(",\"sensitive_data_action\":\"reject\"", "", StringComparison.Ordinal); + Assert.DoesNotContain("sensitive_data_action", legacy, StringComparison.Ordinal); + var back = JsonSerializer.Deserialize(legacy, ConfigJsonContext.Default.CovenantConfig)!; + Assert.All(back.Profiles, p => Assert.Equal(SensitiveDataAction.Route, p.SensitiveDataAction)); + } +} + +/// ADR-0019 through the real Host (demo-hybrid seed): raw /v1 callers and the console get the same gateway decision. +public sealed class SensitiveDataActionHttpTests : IDisposable +{ + private readonly HybridSeedFactory _factory = new(); + + public void Dispose() => _factory.Dispose(); + + private HttpClient App(string profile) + { + var c = _factory.CreateClient(); + c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + c.DefaultRequestHeaders.Add("X-Covenant-Profile", profile); + return c; + } + + [Fact] + public async Task Raw_api_public_rejects_internal_serves_locally_and_the_preview_says_the_same() + { + const string prompt = "Summarize this note in one sentence: Customer asked to update their mailing address. SSN on file: 000-12-3456."; + var admin = _factory.CreateClient(); + + using var pub = App("public-demo"); + using var rejected = await pub.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat(prompt)); + Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode); + var body = await rejected.Content.ReadAsStringAsync(); + Assert.Contains("rejects detected sensitive data", body, StringComparison.Ordinal); + Assert.Contains("internal-default", body, StringComparison.Ordinal); + Assert.DoesNotContain("000-12-3456", body, StringComparison.Ordinal); + var re = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(rejected)); + Assert.Equal("classify", re.StoppedAtStage); + Assert.Equal(DataClassification.Pii, re.Classification); + Assert.Equal("public-demo", re.ProfileId); + Assert.Equal(0, _factory.Cloud.Calls + _factory.Local.Calls); + + var (status, sim, _) = await V2Admin.SendAsync(admin, HttpMethod.Post, "/admin/policies/simulate", + JsonSerializer.Serialize(new SimulateRequest { ApplicationId = "demo-app", ProfileId = "public-demo", Prompt = prompt }, ConfigJsonContext.Default.SimulateRequest)); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("refuse", sim.GetProperty("decision").GetString()); + Assert.Equal(re.Reason, sim.GetProperty("reason").GetString()); + + using var internalApp = App("internal-default"); + using var served = await internalApp.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat(prompt)); + Assert.Equal(HttpStatusCode.OK, served.StatusCode); + var se = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(served)); + Assert.Equal(V2.LocalTag, se.ServedByModel); + Assert.Equal(DataClassification.Pii, se.Classification); + Assert.Equal(0, _factory.Cloud.Calls); + + using var innocent = await pub.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public product announcement.")); + Assert.Equal(HttpStatusCode.OK, innocent.StatusCode); + Assert.Equal(1, _factory.Cloud.Calls); + } + + [Fact] + public async Task The_console_playground_gets_the_same_rejection() + { + using var resp = await Playground.PostAsync(_factory.CreateClient(), + Playground.Body("demo-app", "Patient John Smith was diagnosed with type 2 diabetes last week.", profile: "public-demo")); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var e = await CorrelationTestKit.LookupAsync(_factory.CreateClient(), CorrelationTestKit.HeaderId(resp)); + Assert.Equal("classify", e.StoppedAtStage); + Assert.Equal(DataClassification.Phi, e.Classification); + Assert.Equal("console", e.EntryPoint); + Assert.Equal(0, _factory.Cloud.Calls + _factory.Local.Calls); + } +} diff --git a/tests/Covenant.Tests/SensitiveDataActionUiTests.cs b/tests/Covenant.Tests/SensitiveDataActionUiTests.cs new file mode 100644 index 0000000..d494429 --- /dev/null +++ b/tests/Covenant.Tests/SensitiveDataActionUiTests.cs @@ -0,0 +1,279 @@ +using Xunit; +using UiLogic = Covenant.Ui.Logic; +using UiModels = Covenant.Ui.Models; + +namespace Covenant.Tests; + +/// ADR-0019 in the console: the demo application's recommended pair (Internal → local, Public → rejected) uses the +/// SAME neutral prompt and is visible without "More examples"; switching the workload keeps the prompt and never leaves a +/// stale example claim; previews, schemes and chips say "rejected at Classify" from the server's facts. The UI never +/// fakes the outcome — no model pin, no example-name special case: the decision is the Host's (tested in +/// SensitiveDataActionTests). +public sealed class SensitiveDataActionUiTests +{ + private const string LocalModel = "qwen3:8b"; + + /// The demo seed's shape (hybrid): public-demo rejects detected sensitive data, internal-default routes it. + private static UiModels.CovenantConfigDto Seed(string publicAction = "reject") => new() + { + Version = 3, Mode = "hybrid", + Connections = + [ + new() { Id = "ollama", Kind = "Ollama", Boundary = "Local", Enabled = true, Models = [new() { ModelId = LocalModel, Price = new() { InputPer1M = 0m, OutputPer1M = 0m } }] }, + new() { Id = "openai", Kind = "OpenAi", Boundary = "Cloud", Enabled = true, Models = [new() { ModelId = "gpt-4o-mini", Price = new() { InputPer1M = 0.15m, OutputPer1M = 0.6m } }] }, + ], + Profiles = + [ + new() { Id = "public-demo", Name = "Public demo", Baseline = "Public", SensitiveDataAction = publicAction }, + new() { Id = "internal-default", Name = "Internal (default)", Baseline = "Internal" }, // null = route + ], + Applications = + [ + new() { Id = "demo-app", Team = "platform", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-demo", "internal-default"], DefaultProfile = "internal-default" }, + ], + Policies = + [ + new() { Id = "public", Name = "public", Enabled = true, Classifications = ["Public"], Strategy = "fixed", + Targets = [new() { ConnectionId = "openai", ModelId = "gpt-4o-mini" }, new() { ConnectionId = "ollama", ModelId = LocalModel }] }, + new() { Id = "internal", Name = "internal", Enabled = true, Classifications = ["Internal"], Strategy = "fixed", Targets = [new() { ConnectionId = "ollama", ModelId = LocalModel }] }, + new() { Id = "sensitive", Name = "sensitive", Enabled = true, Classifications = ["Pii", "Phi"], Strategy = "fixed", Targets = [new() { ConnectionId = "ollama", ModelId = LocalModel }] }, + ], + Budgets = [new() { Id = "global", Scope = "global", CapUsd = 25m, Enforcement = "hard" }], + Settings = new() { CacheTtlSeconds = 300 }, + }; + + private static List Apps(UiModels.CovenantConfigDto c) => c.Applications.Select(a => new UiModels.ApplicationSummaryDto + { + Id = a.Id, Team = a.Team, Enabled = true, ConsoleTesting = true, GrantedProfiles = a.GrantedProfiles.ToList(), DefaultProfile = a.DefaultProfile, + }).ToList(); + + private static List Relevant(UiModels.CovenantConfigDto cfg) + => UiLogic.DemoExamples.All.Select(e => UiLogic.DemoExamples.ResolveFor(e, "demo-app", cfg, Apps(cfg), null, null)).Where(r => r.Relevant).ToList(); + + private static UiLogic.ExampleResolution Get(List rs, string id) => rs.Single(r => r.Example.Id == id); + + [Fact] + public void The_demo_app_gets_the_internal_local_and_public_rejected_pair_with_one_neutral_prompt() + { + var rs = Relevant(Seed()); + var local = Get(rs, "sensitive-local"); + var rejected = Get(rs, "sensitive-public-rejected"); + Assert.True(local.Ready); + Assert.True(rejected.Ready); + Assert.Equal("internal-default", local.ProfileId); // resolves INTERNAL + Assert.Equal("public-demo", rejected.ProfileId); + Assert.Null(local.ModelPin); // nothing faked by a pin + Assert.Null(rejected.ModelPin); + Assert.StartsWith("ollama/" + LocalModel, local.ConfiguredRoute, StringComparison.Ordinal); + Assert.Contains("rejects detected sensitive data", rejected.ConfiguredRoute, StringComparison.Ordinal); + + Assert.Equal(local.Example.Prompt, rejected.Example.Prompt); // the SAME request + Assert.Contains(UiLogic.DemoExamples.SyntheticSsn, local.Example.Prompt, StringComparison.Ordinal); + Assert.DoesNotContain("public", local.Example.Prompt, StringComparison.OrdinalIgnoreCase); // neutral: the workload declares + Assert.DoesNotContain("internal", local.Example.Prompt, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("ticket", local.Example.Prompt, StringComparison.OrdinalIgnoreCase); + + // The explicit-external-pin example describes a POLICY refusal; a rejecting Public workload refuses earlier. + Assert.DoesNotContain(rs, r => r.Example.Id == "sensitive-refusal"); + + // Visible without "More examples": recommended, together, first. + var groups = UiLogic.ExampleRecommendations.Split(rs); + Assert.Equal(["sensitive-local", "sensitive-public-rejected"], groups.Recommended.Take(2).Select(r => r.Example.Id).ToArray()); + Assert.True(groups.Recommended.Count <= UiLogic.ExampleRecommendations.Max); + Assert.DoesNotContain(groups.More, r => r.Example.Id.StartsWith("sensitive-", StringComparison.Ordinal) && r.Example.Id != "sensitive-refusal"); + } + + [Fact] + public void An_internal_only_application_gets_no_sensitive_pair_noise() + { + var cfg = Seed(); + cfg.Applications.Add(new() { Id = "engineering-assistant", Team = "engineering", Enabled = true, ConsoleTesting = true, + GrantedProfiles = ["internal-default"], DefaultProfile = "internal-default" }); + var ids = UiLogic.DemoExamples.All + .Select(e => UiLogic.DemoExamples.ResolveFor(e, "engineering-assistant", cfg, Apps(cfg), null, null)) + .Where(r => r.Relevant).Select(r => r.Example.Id).ToList(); + Assert.DoesNotContain("sensitive-local", ids); + Assert.DoesNotContain("sensitive-public-rejected", ids); + } + + [Fact] + public void Without_a_rejecting_public_workload_the_pair_is_not_offered() + { + var rs = Relevant(Seed(publicAction: "route")); + Assert.DoesNotContain(rs, r => r.Example.Id == "sensitive-public-rejected"); + Assert.DoesNotContain(rs, r => r.Example.Id == "sensitive-local"); // never half a pair: its text promises the rejection + } + + [Fact] + public void Flipping_the_workload_after_fill_keeps_the_prompt_and_relabels_only_an_exact_twin() + { + var cfg = Seed(); + var rs = Relevant(cfg); + var form = new UiLogic.PlaygroundForm(); + Assert.True(UiLogic.DemoExamples.ApplyTo(Get(rs, "sensitive-local"), form)); + var prompt = form.Prompt; + Assert.Equal("Example · " + Get(rs, "sensitive-local").Title, UiLogic.RequestSnapshot.Freeze(1, form, DateTimeOffset.UnixEpoch).ScenarioLabel); + + // Internal → Public: same prompt; the form is now exactly the Public example → labelled as THAT example (true claim). + Assert.True(UiLogic.ComposerRules.SelectProfile(form, Apps(cfg), "public-demo")); + UiLogic.DemoExamples.AfterWorkloadChange(form, rs); + Assert.Equal(prompt, form.Prompt); + Assert.Equal("public-demo", form.ProfileId); + Assert.Equal("sensitive-public-rejected", form.ExampleId); + Assert.Equal(UiLogic.RouteMode.Policy, form.Mode); + Assert.Equal("Example · " + Get(rs, "sensitive-public-rejected").Title, UiLogic.RequestSnapshot.Freeze(2, form, DateTimeOffset.UnixEpoch).ScenarioLabel); + + // And back. + Assert.True(UiLogic.ComposerRules.SelectProfile(form, Apps(cfg), "internal-default")); + UiLogic.DemoExamples.AfterWorkloadChange(form, rs); + Assert.Equal("sensitive-local", form.ExampleId); + + // Edited prompt, then flip: no example claim survives; the edited prompt is kept. + form.Prompt += " Also list the next step."; + Assert.True(UiLogic.ComposerRules.SelectProfile(form, Apps(cfg), "public-demo")); + UiLogic.DemoExamples.AfterWorkloadChange(form, rs); + Assert.Null(form.ExampleId); + Assert.EndsWith("Also list the next step.", form.Prompt, StringComparison.Ordinal); + Assert.Equal("Custom", UiLogic.RequestSnapshot.Freeze(3, form, DateTimeOffset.UnixEpoch).ScenarioLabel); + } + + [Fact] + public void The_example_selector_follows_a_twin_relabel_instead_of_showing_the_placeholder() + { + // Browser bug: after Internal → Public the form held the Public twin (expected outcome relabelled) while the select + // showed the placeholder and "Fill again"/"Run example" stayed. The picker now derives its value from this rule. + var cfg = Seed(); + var rs = Relevant(cfg); + var form = new UiLogic.PlaygroundForm(); + Assert.True(UiLogic.DemoExamples.ApplyTo(Get(rs, "sensitive-local"), form)); + string? picked = "sensitive-local"; // "Use example" sets the pick + Assert.Equal("sensitive-local", UiLogic.ExampleSelection.Shown(picked, form.ExampleId)); + + Assert.True(UiLogic.ComposerRules.SelectProfile(form, Apps(cfg), "public-demo")); + UiLogic.DemoExamples.AfterWorkloadChange(form, rs); + picked = UiLogic.ExampleSelection.AfterSwitch(picked, form.ExampleId); + Assert.Equal("sensitive-public-rejected", picked); // select, buttons and summary agree + Assert.Equal(form.ExampleId, UiLogic.ExampleSelection.Shown(picked, form.ExampleId)); + + // A switch that clears the example clears the selection too (placeholder, no "Fill again" for a stale example). + form.Prompt += " edited"; + Assert.True(UiLogic.ComposerRules.SelectProfile(form, Apps(cfg), "internal-default")); + UiLogic.DemoExamples.AfterWorkloadChange(form, rs); + picked = UiLogic.ExampleSelection.AfterSwitch(picked, form.ExampleId); + Assert.Null(picked); + Assert.Null(UiLogic.ExampleSelection.Shown(picked, form.ExampleId)); + + // An operator's pick that is not applied yet is kept as long as nothing switches. + Assert.Equal("cache-repeat", UiLogic.ExampleSelection.Shown("cache-repeat", null)); + Assert.Equal("cache-repeat", UiLogic.ExampleSelection.AfterSwitch("cache-repeat", "cache-repeat")); + } + + [Fact] + public void A_rejecting_workload_never_shows_the_stricter_local_rule_copy() + { + // Browser bug: the Public Reject workload still said "detection raises it and the stricter (local) rule applies" + // next to the rejection explanation. One note, consistent with the gateway. + var reject = Seed(); + var note = UiLogic.WorkloadDestination.For(reject, reject.Profiles[0]).Note; + Assert.Equal(UiLogic.WorkloadDestination.RejectNote, note); + Assert.DoesNotContain("stricter", note, StringComparison.Ordinal); + + var route = Seed(publicAction: "route"); + Assert.Equal(UiLogic.WorkloadDestination.StricterRuleNote, UiLogic.WorkloadDestination.For(route, route.Profiles[0]).Note); + + // Public routed LOCALLY + Reject: the routing fact stays, the rejection is added, the stricter-rule copy never appears. + var local = Seed(); + local.Policies[0].Targets = [new() { ConnectionId = "ollama", ModelId = LocalModel }]; + var localNote = UiLogic.WorkloadDestination.For(local, local.Profiles[0]).Note; + Assert.Contains("cloud-eligible, not cloud", localNote, StringComparison.Ordinal); + Assert.EndsWith(UiLogic.WorkloadDestination.RejectNote, localNote, StringComparison.Ordinal); + Assert.DoesNotContain("stricter", localNote, StringComparison.Ordinal); + + // The Internal (route) workload carries neither sentence. + Assert.Null(UiLogic.WorkloadDestination.For(reject, reject.Profiles[1]).Note); + } + + [Fact] + public void Flipping_a_non_twin_example_clears_the_label_and_keeps_the_prompt() + { + var cfg = Seed(); + var rs = Relevant(cfg); + var form = new UiLogic.PlaygroundForm(); + Assert.True(UiLogic.DemoExamples.ApplyTo(Get(rs, "cache-repeat"), form)); + Assert.Equal("public-demo", form.ProfileId); + var prompt = form.Prompt; + Assert.True(UiLogic.ComposerRules.SelectProfile(form, Apps(cfg), "internal-default")); + UiLogic.DemoExamples.AfterWorkloadChange(form, rs); + Assert.Null(form.ExampleId); + Assert.Equal(prompt, form.Prompt); + Assert.Equal("Custom", UiLogic.RequestSnapshot.Freeze(1, form, DateTimeOffset.UnixEpoch).ScenarioLabel); + } + + [Fact] + public void The_route_mirror_and_the_workload_editor_follow_the_rule() + { + var cfg = Seed(); + Assert.Contains("rejects detected sensitive data", UiLogic.DemoExamples.Route(cfg, "Pii", "public-demo").Refusal, StringComparison.Ordinal); + Assert.Contains("rejects detected sensitive data", UiLogic.DemoExamples.Route(cfg, "Phi", "public-demo").Refusal, StringComparison.Ordinal); + Assert.Equal("ollama", UiLogic.DemoExamples.Route(cfg, "Pii", "internal-default").Primary!.ConnectionId); + Assert.Equal("openai", UiLogic.DemoExamples.Route(cfg, "Public", "public-demo").Primary!.ConnectionId); // innocent Public unchanged + + var pub = cfg.Profiles[0]; + var internalProfile = cfg.Profiles[1]; + Assert.True(UiLogic.ProfileEditing.RejectsSensitive(pub)); + Assert.False(UiLogic.ProfileEditing.RejectsSensitive(internalProfile)); // null = route + Assert.False(UiLogic.ProfileEditing.RejectsSensitive(null)); + Assert.NotNull(UiLogic.ProfileEditing.SetBaseline(pub, "Pii")); // must switch to route first + Assert.Equal("Public", pub.Baseline); + + var pii = new UiModels.WorkloadProfileDto { Id = "records", Baseline = "Pii" }; + Assert.NotNull(UiLogic.ProfileEditing.SetSensitiveAction(pii, "reject")); + Assert.Null(pii.SensitiveDataAction); + Assert.Null(UiLogic.ProfileEditing.SetSensitiveAction(internalProfile, "reject")); + Assert.Equal("reject", internalProfile.SensitiveDataAction); + Assert.Null(UiLogic.ProfileEditing.SetSensitiveAction(internalProfile, "route")); + Assert.Equal("route", internalProfile.SensitiveDataAction); + } + + [Fact] + public void The_expected_route_shows_the_server_rejection_and_no_search_badge() + { + var form = new UiLogic.PlaygroundForm { ApplicationId = "demo-app", ProfileId = "public-demo", Prompt = UiLogic.DemoExamples.SensitivePrompt, WebSources = UiLogic.WebSourcesMode.Required }; + var result = new UiModels.SimulateResponseDto + { + DryRun = true, ConfigVersion = 3, ApplicationId = "demo-app", Profile = "public-demo", Classification = "Pii", Baseline = "Public", + DetectedSignal = "US SSN pattern", Decision = "refuse", RefusedAtStage = "classify", SuggestedProfiles = ["internal-default"], + Reason = "sensitive data detected (PII: US SSN pattern): workload 'public-demo' rejects detected sensitive data — refused before routing, cache, web search or any model; nothing was sent. To process it on an approved route, choose workload 'internal-default'.", + }; + var v = UiLogic.RouteSchemes.Expected(new UiLogic.RoutePreview(UiLogic.RoutePreview.KeyOf(form), result, null, false), form, 3, Apps(Seed()), Seed().Profiles); + Assert.Equal("ready", v.State); + Assert.Equal("Rejected — nothing would be sent", v.Destination.Line); + Assert.Equal("blocked", v.Destination.Tone); + Assert.Contains("rejected at Classify", v.Covenant.Sub, StringComparison.Ordinal); + Assert.Contains("detected: US SSN pattern", v.Covenant.Line, StringComparison.Ordinal); + Assert.Empty(v.Badges); // no search would run + } + + [Fact] + public void The_actual_route_and_chips_say_rejected_at_classify_and_keep_incomplete_distinct() + { + var form = new UiLogic.PlaygroundForm { ApplicationId = "demo-app", ProfileId = "public-demo", Prompt = UiLogic.DemoExamples.SensitivePrompt }; + var snapshot = UiLogic.RequestSnapshot.Freeze(1, form, DateTimeOffset.UnixEpoch); + UiModels.AuditEntryView Rec(bool evaluated) => new() + { + Effect = "Deny", StoppedAtStage = "classify", DenialKind = "Governance", ClassificationEvaluated = evaluated, + Classification = evaluated ? "Pii" : "Phi", BaselineClassification = "Public", Signal = evaluated ? "US SSN pattern" : "inspection incomplete", + ApplicationId = "demo-app", ProfileId = "public-demo", Attempts = [], Reason = "x", Tags = new() { Team = "platform" }, + }; + + var rejected = Rec(evaluated: true); + var scheme = UiLogic.RouteSchemes.Actual(snapshot, rejected, false, Apps(Seed()), null, Seed().Profiles); + Assert.Equal("Blocked — model not contacted", scheme.Destination.Line); + Assert.Contains("rejected at Classify", scheme.Destination.Sub, StringComparison.Ordinal); + Assert.Equal("Rejected · this workload does not accept sensitive data", UiLogic.JourneyChips.For(rejected, null, Seed().Profiles)[0].Label); + + var incomplete = Rec(evaluated: false); + Assert.DoesNotContain("rejected at Classify", UiLogic.RouteSchemes.Actual(snapshot, incomplete, false, Apps(Seed()), null, Seed().Profiles).Destination.Sub ?? "", StringComparison.Ordinal); + Assert.Equal("Refused · inspection incomplete", UiLogic.JourneyChips.For(incomplete, null, Seed().Profiles)[0].Label); + } +} diff --git a/tests/Covenant.Tests/SimulatorTests.cs b/tests/Covenant.Tests/SimulatorTests.cs index 4640fa3..7f5ba11 100644 --- a/tests/Covenant.Tests/SimulatorTests.cs +++ b/tests/Covenant.Tests/SimulatorTests.cs @@ -64,14 +64,22 @@ public async Task Dry_run_routes_public_to_cloud_without_calling_any_provider_or [Fact] public async Task Dry_run_shows_detector_escalation_and_cloud_exclusion() { - var body = await Simulate("""{"application_id":"demo-app","profile_id":"public-demo","prompt":"Public notice, SSN 123-45-6789"}"""); + // ADR-0019: the seeded Internal workload routes detected PII locally; the seeded Public workload rejects it (below). + var body = await Simulate("""{"application_id":"demo-app","profile_id":"internal-default","prompt":"Notice, SSN 123-45-6789"}"""); Assert.Equal("Pii", body.GetProperty("classification").GetString()); - Assert.Equal("Public", body.GetProperty("baseline").GetString()); + Assert.Equal("Internal", body.GetProperty("baseline").GetString()); Assert.Equal("US SSN pattern", body.GetProperty("detected_signal").GetString()); Assert.Equal($"ollama/{V2.LocalTag}", body.GetProperty("primary").GetString()); - var refused = await Simulate($$"""{"application_id":"demo-app","profile_id":"public-demo","prompt":"Public notice, SSN 123-45-6789","model":"{{V2.CloudModel}}"}"""); + var refused = await Simulate($$"""{"application_id":"demo-app","profile_id":"internal-default","prompt":"Notice, SSN 123-45-6789","model":"{{V2.CloudModel}}"}"""); Assert.Equal("refuse", refused.GetProperty("decision").GetString()); + + var rejected = await Simulate("""{"application_id":"demo-app","profile_id":"public-demo","prompt":"Public notice, SSN 123-45-6789"}"""); + Assert.Equal("refuse", rejected.GetProperty("decision").GetString()); + Assert.Equal("classify", rejected.GetProperty("refused_at_stage").GetString()); + Assert.Equal("Pii", rejected.GetProperty("classification").GetString()); + Assert.Equal("internal-default", rejected.GetProperty("suggested_profiles")[0].GetString()); + Assert.False(rejected.TryGetProperty("primary", out var primary) && primary.ValueKind == JsonValueKind.String); // no route shown Assert.Equal(0, _factory.Cloud.Calls + _factory.Local.Calls); }