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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@
- `src/types/budgets/` - Budget definitions, assignments (user, team, API key) and spend evaluation
- `ledger.rs` - `BudgetLedger`: one Tokio actor reserves estimated cost at admission, reconciles once to actual cost, and refunds on drop; web chat and the gateway both reserve through `BudgetLedger::reserve_for_model`, never through their own checks, once per upstream request (web chat reserves again before every tool step, and a refused step saves the answer so far)
- `repository.rs` - `Budget::evaluate`/`status_for`/`checks` load effective budgets for a `BudgetSubject` (optional user, optional key)
- `src/types/guard/` - Guardrails (HEN-139, slice 1): admin rules check prompts before they reach a model and block or only log them
- `rule.rs` - `GuardRule` (`guard_rules`; `triggers` and `action` are serde-tagged JSONB, `stage` is `input` only, `version` bumps on every change) and `guard_rule_assignments` (everyone, team, user or key; a user's rules include their teams' unless the request names a team). New rules start in `monitor`; `on_error` defaults to `block` for block rules (fail closed) and `allow` otherwise. Every change is audited (`target_type = guard_rule`)
- `classifier.rs` - the check model's type picks the strategy: `decision` models get a predicate (or a choice over the policy's categories plus `none`) through `OmniferenceEngine::decision`, `chat` models a strict JSON schema (`matched`, `category`, `confidence`, `reason`). The prompt is sent apart from the instructions, billed to the subject's user as `guard` (reserved through `rag::reserve`), or to the admin as `guard_test`
- `evaluate.rs` - `prompt_text` (web chat: the new user message only; gateway: all system and user text; nothing when the last message is not the user's, so tool steps are not checked again), `evaluate` (rules in parallel, each with its own timeout; any trigger matching at its threshold makes the rule match), `decide` (block beats log only, then priority; monitor rules only count in tests with `include_monitor`)
- `middleware.rs` - `GuardMiddleware`, registered in `build_engine` before `ProviderRoutingMiddleware`; skips `oxide_request_type` `guard`, `guard_test` and `title`; a block is `AdapterError::Forbidden { code: "guard_blocked" }` with the rule's message or `guard.blocked`, plus the reason unless `show_reason_to_user` is off
- `events.rs` - one `guard_events` row per checked rule: score, label, reason and error cut to 300 characters, latency; never prompt text
- `testing.rs` - `POST /api/v1/admin/guard/test` (`admin.guard.test`) runs `all` rules for a simulated subject and source, chosen `ids` or an unsaved `draft` through the same evaluation without acting on it
- Routes in `src/routes/admin/guard.rs` under `/api/v1/admin/guard/rules` (`admin.guard.view` / `admin.guard.edit`); validation failures are `GuardError` rendered as `ValidationFailed` with `details.reason` (`guard.error.<reason>`)
- `src/types/gateway/` - Gateway rate limiting and credentials, re-exported through `crate::types::*`
- `limiter.rs` - Admission owned by one Tokio actor; bounded admission and unbounded release/reconciliation channels replace shared locking
- `policy.rs` - Team and key rate rules, validated policies (`GatewayRatePolicy::from_stored`), and `GatewayLimitError`
Expand Down
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* What happens when a rule matches.
*/
export type GuardAction = { "type": "block", message: string | null, } | { "type": "log_only" };
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardMode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* Enforce acts on a hit; monitor only records it.
*/
export type GuardMode = "enforce" | "monitor";
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardOnError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* What a rule does when its check fails or times out.
*/
export type GuardOnError = "allow" | "block";
10 changes: 10 additions & 0 deletions frontend/types/generated/GuardPolicy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* The admin's description of what a rule catches; it becomes the check model's instructions.
*/
export type GuardPolicy = { description: string, positive_examples: Array<string>, negative_examples: Array<string>,
/**
* When set, the check also names which of these categories matched.
*/
categories: Array<string>, };
13 changes: 13 additions & 0 deletions frontend/types/generated/GuardRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardAction } from "./GuardAction";
import type { GuardMode } from "./GuardMode";
import type { GuardOnError } from "./GuardOnError";
import type { GuardSource } from "./GuardSource";
import type { GuardStage } from "./GuardStage";
import type { GuardTrigger } from "./GuardTrigger";

export type GuardRule = { id: string, name: string, description: string | null, enabled: boolean, mode: GuardMode, priority: number, triggers: Array<GuardTrigger>, action: GuardAction, on_error: GuardOnError, timeout_ms: number, applies_to: Array<GuardSource>, show_reason_to_user: boolean, stage: GuardStage,
/**
* Bumped on every change, so an event names the rule as it was.
*/
version: number, created_at: string, updated_at: string, };
23 changes: 23 additions & 0 deletions frontend/types/generated/GuardRuleInput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardAction } from "./GuardAction";
import type { GuardMode } from "./GuardMode";
import type { GuardOnError } from "./GuardOnError";
import type { GuardSource } from "./GuardSource";
import type { GuardTrigger } from "./GuardTrigger";

/**
* The editable part of a rule: the body of a create or update, and an unsaved draft to test.
*/
export type GuardRuleInput = { name: string, description?: string, enabled: boolean,
/**
* New rules only observe until an admin switches them to enforce.
*/
mode: GuardMode, priority: number,
/**
* Any one matching trigger makes the rule match.
*/
triggers: Array<GuardTrigger>, action: GuardAction,
/**
* Defaults to block for block rules (fail closed) and allow otherwise.
*/
on_error?: GuardOnError, timeout_ms: number, applies_to: Array<GuardSource>, show_reason_to_user: boolean, };
17 changes: 17 additions & 0 deletions frontend/types/generated/GuardRuleResult.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardAction } from "./GuardAction";
import type { GuardMode } from "./GuardMode";
import type { GuardStrategy } from "./GuardStrategy";

/**
* What one rule found.
*/
export type GuardRuleResult = { rule_id: string, rule_name: string, mode: GuardMode, trigger_type: string, matched: boolean, score: number | null, threshold: number | null, label: string | null, reason: string | null, model_id: string | null, strategy: GuardStrategy | null, latency_ms: number,
/**
* Why the check failed; the rule's `on_error` then decides.
*/
error: string | null,
/**
* What the rule does with this result: its action on a match, a block when it failed and fails closed.
*/
action: GuardAction | null, };
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* Where a request came from.
*/
export type GuardSource = "web_chat" | "gateway";
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardStage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* What a rule checks: the prompt (`input`). Checking answers (`output`) is prepared for but not offered yet.
*/
export type GuardStage = "input";
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* How a check model is asked, which follows from its model type.
*/
export type GuardStrategy = "decision" | "structured_output";
6 changes: 6 additions & 0 deletions frontend/types/generated/GuardSubject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* Who a request is for; web chat has a user, a gateway request a key, its team and usually its owner.
*/
export type GuardSubject = { user_id?: string, team_id?: string, api_key_id?: string, };
7 changes: 7 additions & 0 deletions frontend/types/generated/GuardTestMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardTestRole } from "./GuardTestRole";

/**
* A message of the simulated conversation.
*/
export type GuardTestMessage = { role: GuardTestRole, content: string, };
14 changes: 14 additions & 0 deletions frontend/types/generated/GuardTestOutcome.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

/**
* What would happen to the request.
*/
export type GuardTestOutcome = {
/**
* `block` or `log_only`; none when the request would pass unnoticed.
*/
action: string | null, rule_id: string | null, rule_name: string | null,
/**
* The message the user would see when blocked.
*/
message: string | null, };
18 changes: 18 additions & 0 deletions frontend/types/generated/GuardTestRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardSource } from "./GuardSource";
import type { GuardSubject } from "./GuardSubject";
import type { GuardTestMessage } from "./GuardTestMessage";
import type { GuardTestRules } from "./GuardTestRules";

/**
* Body of `POST /api/v1/admin/guard/test`.
*/
export type GuardTestRequest = {
/**
* The conversation; the last message is the one being sent.
*/
messages: Array<GuardTestMessage>, system_prompt?: string, subject?: GuardSubject, source: GuardSource, rules: GuardTestRules,
/**
* Whether monitor rules count for the outcome, to show what they would do once enforced.
*/
include_monitor: boolean, };
9 changes: 9 additions & 0 deletions frontend/types/generated/GuardTestResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardRuleResult } from "./GuardRuleResult";
import type { GuardTestOutcome } from "./GuardTestOutcome";

export type GuardTestResponse = { outcome: GuardTestOutcome, results: Array<GuardRuleResult>,
/**
* The delay the user would notice: the slowest rule, as rules run in parallel.
*/
latency_ms: number, };
3 changes: 3 additions & 0 deletions frontend/types/generated/GuardTestRole.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.

export type GuardTestRole = "user" | "assistant";
7 changes: 7 additions & 0 deletions frontend/types/generated/GuardTestRules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardRuleInput } from "./GuardRuleInput";

/**
* Which rules a test runs.
*/
export type GuardTestRules = "all" | { "ids": Array<string> } | { "draft": GuardRuleInput };
7 changes: 7 additions & 0 deletions frontend/types/generated/GuardTrigger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { GuardPolicy } from "./GuardPolicy";

/**
* Checks a prompt and scores how well it matches (0–1).
*/
export type GuardTrigger = { "type": "classifier", model_id: string, policy: GuardPolicy, threshold: number, };
4 changes: 4 additions & 0 deletions frontend/types/generated/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export const ADMIN_ROLES_VIEW = 'admin.roles.view';
export const ADMIN_ROLES_EDIT = 'admin.roles.edit';
export const ADMIN_RAG_VIEW = 'admin.rag.view';
export const ADMIN_RAG_EDIT = 'admin.rag.edit';
export const ADMIN_GUARD_VIEW = 'admin.guard.view';
export const ADMIN_GUARD_EDIT = 'admin.guard.edit';
export const ADMIN_GUARD_TEST = 'admin.guard.test';
export const ADMIN_GUARD_EVENTS_VIEW = 'admin.guard.events.view';
export const SETTINGS_APPEARANCE_EDIT = 'settings.appearance.edit';
export const SETTINGS_KNOWLEDGE_EDIT = 'settings.knowledge.edit';
export const SETTINGS_PRESETS_EDIT = 'settings.presets.edit';
Expand Down
101 changes: 101 additions & 0 deletions migrations/20251226000000_initial_schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6082,3 +6082,104 @@ INSERT INTO i18n_translations (language, key_path, value) VALUES
('en', 'chat.errors.context_too_large', 'This chat with its attached files is about {tokens} tokens, more than the model''s context window of {limit}. Remove a file or use a knowledge base instead.'),
('de', 'chat.errors.context_too_large', 'Dieser Chat ist mit den angehängten Dateien etwa {tokens} Tokens lang, mehr als das Kontextfenster des Modells von {limit}. Entferne eine Datei oder nutze stattdessen eine Wissensdatenbank.')
ON CONFLICT (language, key_path) DO NOTHING;


-- ============= Guardrails =============

-- A rule checks prompts before they reach a model; see src/types/guard.
CREATE TABLE IF NOT EXISTS guard_rules (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
description TEXT,
enabled BOOLEAN NOT NULL DEFAULT true,
mode TEXT NOT NULL DEFAULT 'monitor' CHECK (mode IN ('enforce', 'monitor')),
priority INTEGER NOT NULL DEFAULT 0,
triggers JSONB NOT NULL,
action JSONB NOT NULL,
on_error TEXT NOT NULL CHECK (on_error IN ('allow', 'block')),
timeout_ms INTEGER NOT NULL DEFAULT 3000 CHECK (timeout_ms BETWEEN 100 AND 30000),
applies_to TEXT[] NOT NULL DEFAULT '{web_chat,gateway}',
show_reason_to_user BOOLEAN NOT NULL DEFAULT true,
-- Responses ('output') are prepared for but not checked in v1.
stage TEXT NOT NULL DEFAULT 'input' CHECK (stage IN ('input')),
version INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Who a rule applies to; a row without any target is everyone.
CREATE TABLE IF NOT EXISTS guard_rule_assignments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
rule_id UUID NOT NULL REFERENCES guard_rules(id) ON DELETE CASCADE,
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
team_id UUID REFERENCES teams(id) ON DELETE CASCADE,
api_key_id UUID REFERENCES gateway_api_keys(id) ON DELETE CASCADE,
assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT guard_rule_assignments_one_target CHECK (num_nonnulls(user_id, team_id, api_key_id) <= 1)
);
CREATE INDEX IF NOT EXISTS idx_guard_rule_assignments_rule ON guard_rule_assignments(rule_id);

-- One row per rule checked on a request. Never holds prompt text.
CREATE TABLE IF NOT EXISTS guard_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
request_id UUID,
chat_id UUID,
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
team_id UUID REFERENCES teams(id) ON DELETE SET NULL,
api_key_id UUID REFERENCES gateway_api_keys(id) ON DELETE SET NULL,
rule_id UUID REFERENCES guard_rules(id) ON DELETE SET NULL,
rule_version INTEGER NOT NULL,
trigger_type TEXT NOT NULL,
score DOUBLE PRECISION,
label TEXT,
reason TEXT,
action TEXT NOT NULL,
matched BOOLEAN NOT NULL,
mode TEXT NOT NULL CHECK (mode IN ('enforce', 'monitor')),
stage TEXT NOT NULL,
original_model_id UUID,
classifier_model_id UUID,
latency_ms INTEGER NOT NULL,
error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_guard_events_created_at ON guard_events(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_guard_events_rule ON guard_events(rule_id, created_at DESC);

INSERT INTO permissions (name, description) VALUES
('admin.guard.view', 'View guardrail rules'),
('admin.guard.edit', 'Create, change and delete guardrail rules'),
('admin.guard.test', 'Test guardrail rules against sample prompts'),
('admin.guard.events.view', 'View guardrail events')
ON CONFLICT (name) DO NOTHING;

INSERT INTO i18n_translations (language, key_path, value) VALUES
('en', 'roles.group.admin_guard', 'Guardrails'),
('de', 'roles.group.admin_guard', 'Guardrails'),
('en', 'roles.permission.admin.guard.view', 'View guardrail rules'),
('de', 'roles.permission.admin.guard.view', 'Guardrail-Regeln ansehen'),
('en', 'roles.permission.admin.guard.edit', 'Create, change and delete guardrail rules'),
('de', 'roles.permission.admin.guard.edit', 'Guardrail-Regeln anlegen, ändern und löschen'),
('en', 'roles.permission.admin.guard.test', 'Test guardrail rules against sample prompts'),
('de', 'roles.permission.admin.guard.test', 'Guardrail-Regeln mit Beispiel-Prompts testen'),
('en', 'roles.permission.admin.guard.events.view', 'View guardrail events'),
('de', 'roles.permission.admin.guard.events.view', 'Guardrail-Ereignisse ansehen'),
('en', 'guard.blocked', 'This message was blocked by a security rule.'),
('de', 'guard.blocked', 'Diese Nachricht wurde durch eine Sicherheitsregel blockiert.'),
('en', 'guard.blocked_reason', 'Reason: {reason}'),
('de', 'guard.blocked_reason', 'Begründung: {reason}'),
('en', 'guard.error.invalid_name', 'The rule needs a name.'),
('de', 'guard.error.invalid_name', 'Die Regel braucht einen Namen.'),
('en', 'guard.error.no_trigger', 'The rule needs at least one trigger.'),
('de', 'guard.error.no_trigger', 'Die Regel braucht mindestens einen Auslöser.'),
('en', 'guard.error.threshold_range', 'The threshold must be between 0 and 1.'),
('de', 'guard.error.threshold_range', 'Der Schwellwert muss zwischen 0 und 1 liegen.'),
('en', 'guard.error.timeout_range', 'The timeout must be between 100 and 30000 ms.'),
('de', 'guard.error.timeout_range', 'Der Timeout muss zwischen 100 und 30000 ms liegen.'),
('en', 'guard.error.invalid_policy', 'The policy needs a description.'),
('de', 'guard.error.invalid_policy', 'Die Richtlinie braucht eine Beschreibung.'),
('en', 'guard.error.invalid_source', 'The rule must apply to the web chat, the gateway or both.'),
('de', 'guard.error.invalid_source', 'Die Regel muss für den Web-Chat, das Gateway oder beide gelten.'),
('en', 'guard.error.model_unavailable', 'The check model is missing, turned off, or neither a chat nor a decision model.'),
('de', 'guard.error.model_unavailable', 'Das Prüf-Modell fehlt, ist deaktiviert oder ist weder ein Chat- noch ein Decision-Modell.')
ON CONFLICT (language, key_path) DO NOTHING;
Loading
Loading