Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Add Switch Trust settings UI in Console, backed by a DB-backed gateway API

Timo Bozsolik-Torres80a4a9e06675
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 853c9855e..52241e318 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -31,6 +31,8 @@ import {
import type {
AddServerParams,
BundledChatSignIn,
+ ClearTrustSettingsResult,
+ FetchTrustSettingsResult,
PasswordLoginParams,
RenameServerParams,
ServerConnectionStatus,
@@ -40,6 +42,8 @@ import type {
SwitchServer,
UpdateServerParams,
UpdateServerResult,
+ UpdateTrustSettingsParams,
+ UpdateTrustSettingsResult,
} from '@shared/core/switch-servers/switch-servers';
import type { JoinableWorkspaces, PendingInvitations } from '@shared/core/workspaces/invitations';
import { isWithdrawnWorkspace, type Workspace } from '@shared/core/workspaces/workspaces';
@@ -102,6 +106,11 @@ import {
updateServer,
} from './servers-store';
import { requireSwitchCloudEndpoint, switchCloudEndpoint } from './switch-cloud';
+import {
+ clearTrustSettingsOnServer,
+ fetchTrustSettingsFromServer,
+ updateTrustSettingsOnServer,
+} from './trust-settings';
/** A sign-in's own error union, as a reportable code. Never its message. */
const SIGN_IN_FAILURE: Record<LoginError['kind'], TelemetrySignInFailure> = {
@@ -508,6 +517,20 @@ export const switchServersController = createRPCController({
getAuthConfig: async (serverId: string): Promise<SwitchAuthConfig> =>
fetchAuthConfig(await requireReachableServer(serverId)),
+ /** Switch Trust's one server-global guardrails settings row. Admin-only
+ * (a deployment operator) — not scoped to a workspace, since one policy
+ * covers the whole deployment. */
+ getTrustSettings: async (serverId: string): Promise<FetchTrustSettingsResult> =>
+ fetchTrustSettingsFromServer(await requireReachableServer(serverId)),
+
+ updateTrustSettings: async (
+ params: UpdateTrustSettingsParams
+ ): Promise<UpdateTrustSettingsResult> =>
+ updateTrustSettingsOnServer(await requireReachableServer(params.serverId), params),
+
+ clearTrustSettings: async (serverId: string): Promise<ClearTrustSettingsResult> =>
+ clearTrustSettingsOnServer(await requireReachableServer(serverId)),
+
// Reported here rather than in `auth.ts`: the same functions are used to
// re-authenticate a managed server on its own and to log in while starting a
// stack, and neither of those is a person signing in.
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 775e5d37d..af9b7615b 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -57,6 +57,8 @@ import type {
SwitchUser,
TeamsTeam,
TeamsTeamsResult,
+ TrustSettings,
+ UpdateTrustSettingsParams,
} from '@shared/core/switch-servers/switch-servers';
import type {
Invitation,
@@ -370,6 +372,59 @@ export async function fetchAuthConfig(server: SwitchServer): Promise<SwitchAuthC
};
}
+type TrustSettingsJson = {
+ endpoint: string;
+ policy_id: string | null;
+ has_api_key: boolean;
+ api_key_last4: string | null;
+ enabled: boolean;
+};
+
+function mapTrustSettings(json: TrustSettingsJson): TrustSettings {
+ return {
+ endpoint: json.endpoint,
+ policyId: json.policy_id,
+ hasApiKey: json.has_api_key,
+ apiKeyLast4: json.api_key_last4,
+ enabled: json.enabled,
+ };
+}
+
+/** Switch Trust's one server-global settings row, admin-only
+ * (`GET /trust-settings`). */
+export async function fetchTrustSettings(server: SwitchServer): Promise<TrustSettings> {
+ const res = await gatewayFetch(server, '/trust-settings', { authenticated: true });
+ return mapTrustSettings((await res.json()) as TrustSettingsJson);
+}
+
+/** Save Switch Trust's settings, admin-only (`PUT /trust-settings`).
+ * `params.apiKey` left unset leaves whatever key is already stored
+ * untouched — see {@link UpdateTrustSettingsParams}. */
+export async function updateTrustSettings(
+ server: SwitchServer,
+ params: Omit<UpdateTrustSettingsParams, 'serverId'>
+): Promise<TrustSettings> {
+ const res = await gatewayFetch(server, '/trust-settings', {
+ authenticated: true,
+ method: 'PUT',
+ body: {
+ endpoint: params.endpoint,
+ policy_id: params.policyId,
+ ...(params.apiKey !== undefined ? { api_key: params.apiKey } : {}),
+ },
+ });
+ return mapTrustSettings((await res.json()) as TrustSettingsJson);
+}
+
+/** Turn Switch Trust off, admin-only (`DELETE /trust-settings`). */
+export async function clearTrustSettings(server: SwitchServer): Promise<TrustSettings> {
+ const res = await gatewayFetch(server, '/trust-settings', {
+ authenticated: true,
+ method: 'DELETE',
+ });
+ return mapTrustSettings((await res.json()) as TrustSettingsJson);
+}
+
type ServerDeclarationJson = {
version: string | null;
contracts: Record<string, { speaks: number; accepts: number }>;
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.ts
new file mode 100644
index 000000000..1b739b363
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.ts
@@ -0,0 +1,242 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const refreshSession = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+
+const managedServerHostBlocked = vi.hoisted(() => vi.fn(() => null));
+const managedServerStoppedPhase = vi.hoisted(() => vi.fn(() => null));
+const noteManagedServerUnanswered = vi.hoisted(() => vi.fn());
+
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ managedServerHostBlocked,
+ managedServerStoppedPhase,
+ noteManagedServerUnanswered,
+}));
+
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));
+
+const { fetchTrustSettingsFromServer, updateTrustSettingsOnServer, clearTrustSettingsOnServer } =
+ await import('./trust-settings');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ gatewayUrl: 'https://switch.example.com',
+ managed: false,
+} as never;
+
+const SAVE_PARAMS = {
+ endpoint: 'https://trust.example',
+ policyId: 'pol_123',
+};
+
+/** A far-from-expiry JWT, so no renewal path is exercised here. */
+function validJwt(): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function response(status: number, body: unknown): Response {
+ const text = typeof body === 'string' ? body : JSON.stringify(body);
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ json: async () => (typeof body === 'string' ? {} : body),
+ headers: { getSetCookie: () => [] },
+ text: async () => text,
+ } as unknown as Response;
+}
+
+const SETTINGS_JSON = {
+ endpoint: 'https://trust.example',
+ policy_id: 'pol_123',
+ has_api_key: true,
+ api_key_last4: '-key',
+ enabled: true,
+};
+
+const SETTINGS = {
+ endpoint: 'https://trust.example',
+ policyId: 'pol_123',
+ hasApiKey: true,
+ apiKeyLast4: '-key',
+ enabled: true,
+};
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(validJwt());
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('fetchTrustSettingsFromServer', () => {
+ it('returns the loaded settings on success', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await expect(fetchTrustSettingsFromServer(SERVER)).resolves.toEqual({
+ kind: 'loaded',
+ settings: SETTINGS,
+ });
+ });
+
+ it('maps a rejected session onto unauthenticated so the caller prompts a sign-in', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(fetchTrustSettingsFromServer(SERVER)).resolves.toEqual({
+ kind: 'unauthenticated',
+ });
+ });
+
+ it('reports a non-operator as forbidden, not a thrown error', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Admin access required' }));
+
+ await expect(fetchTrustSettingsFromServer(SERVER)).resolves.toEqual({ kind: 'forbidden' });
+ });
+
+ it('reports an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(fetchTrustSettingsFromServer(SERVER)).resolves.toMatchObject({ kind: 'error' });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(fetchTrustSettingsFromServer(SERVER)).rejects.toMatchObject({ status: 500 });
+ });
+});
+
+describe('updateTrustSettingsOnServer', () => {
+ it('returns the saved settings on success', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await expect(updateTrustSettingsOnServer(SERVER, SAVE_PARAMS)).resolves.toEqual({
+ kind: 'saved',
+ settings: SETTINGS,
+ });
+ });
+
+ it('PUTs the settings, omitting api_key when none is given', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await updateTrustSettingsOnServer(SERVER, SAVE_PARAMS);
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/trust-settings');
+ expect(init.method).toBe('PUT');
+ expect(JSON.parse(init.body)).toEqual({
+ endpoint: 'https://trust.example',
+ policy_id: 'pol_123',
+ });
+ });
+
+ it('includes api_key in the body when one is given, to replace the stored key', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await updateTrustSettingsOnServer(SERVER, { ...SAVE_PARAMS, apiKey: 'new-key' });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init.body)).toMatchObject({ api_key: 'new-key' });
+ });
+
+ it('maps a rejected session onto unauthenticated', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(updateTrustSettingsOnServer(SERVER, SAVE_PARAMS)).resolves.toEqual({
+ kind: 'unauthenticated',
+ });
+ });
+
+ it('reports a non-operator as forbidden', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Admin access required' }));
+
+ await expect(updateTrustSettingsOnServer(SERVER, SAVE_PARAMS)).resolves.toEqual({
+ kind: 'forbidden',
+ });
+ });
+
+ it('reports a rejected endpoint or timeout as invalid, with the gateway’s own sentence', async () => {
+ fetchMock.mockResolvedValue(response(422, { detail: 'endpoint must be an http(s) URL' }));
+
+ await expect(
+ updateTrustSettingsOnServer(SERVER, { ...SAVE_PARAMS, endpoint: 'not-a-url' })
+ ).resolves.toEqual({
+ kind: 'invalid',
+ message: 'endpoint must be an http(s) URL',
+ });
+ });
+
+ it('reports an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(updateTrustSettingsOnServer(SERVER, SAVE_PARAMS)).resolves.toMatchObject({
+ kind: 'error',
+ });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(updateTrustSettingsOnServer(SERVER, SAVE_PARAMS)).rejects.toMatchObject({
+ status: 500,
+ });
+ });
+});
+
+describe('clearTrustSettingsOnServer', () => {
+ it('returns the cleared settings on success', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, { ...SETTINGS_JSON, policy_id: null, has_api_key: false, enabled: false })
+ );
+
+ await expect(clearTrustSettingsOnServer(SERVER)).resolves.toEqual({
+ kind: 'cleared',
+ settings: { ...SETTINGS, policyId: null, hasApiKey: false, enabled: false },
+ });
+ });
+
+ it('DELETEs the settings', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await clearTrustSettingsOnServer(SERVER);
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/trust-settings');
+ expect(init.method).toBe('DELETE');
+ });
+
+ it('maps a rejected session onto unauthenticated', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(clearTrustSettingsOnServer(SERVER)).resolves.toEqual({ kind: 'unauthenticated' });
+ });
+
+ it('reports a non-operator as forbidden', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Admin access required' }));
+
+ await expect(clearTrustSettingsOnServer(SERVER)).resolves.toEqual({ kind: 'forbidden' });
+ });
+
+ it('reports an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(clearTrustSettingsOnServer(SERVER)).resolves.toMatchObject({ kind: 'error' });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(clearTrustSettingsOnServer(SERVER)).rejects.toMatchObject({ status: 500 });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.ts
new file mode 100644
index 000000000..0a3f71164
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.ts
@@ -0,0 +1,82 @@
+import {
+ clearTrustSettings,
+ fetchTrustSettings,
+ GatewayError,
+ updateTrustSettings,
+} from '@main/core/switch-servers/gateway-client';
+import type {
+ ClearTrustSettingsResult,
+ FetchTrustSettingsResult,
+ SwitchServer,
+ UpdateTrustSettingsParams,
+ UpdateTrustSettingsResult,
+} from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * Load Switch Trust's one server-global settings row, mapping recoverable
+ * gateway failures the same way the write paths below do — a non-operator
+ * gets `forbidden` rather than a thrown error, so the settings page can say
+ * why rather than showing a generic failure banner.
+ */
+export async function fetchTrustSettingsFromServer(
+ server: SwitchServer
+): Promise<FetchTrustSettingsResult> {
+ try {
+ return { kind: 'loaded', settings: await fetchTrustSettings(server) };
+ } catch (cause) {
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/**
+ * Save Switch Trust's settings and map recoverable gateway failures onto a
+ * typed {@link UpdateTrustSettingsResult}, mirroring `updateBridgeOnServer`.
+ *
+ * Unmapped failures still throw: an unexpected 500 is a bug, not a form error.
+ */
+export async function updateTrustSettingsOnServer(
+ server: SwitchServer,
+ params: Omit<UpdateTrustSettingsParams, 'serverId'>
+): Promise<UpdateTrustSettingsResult> {
+ try {
+ return { kind: 'saved', settings: await updateTrustSettings(server, params) };
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.kind === 'http') {
+ if (cause.status === 400 || cause.status === 422) {
+ return { kind: 'invalid', message: cause.detail ?? cause.message };
+ }
+ }
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/** Turn Switch Trust off and map recoverable gateway failures onto a typed
+ * {@link ClearTrustSettingsResult}. */
+export async function clearTrustSettingsOnServer(
+ server: SwitchServer
+): Promise<ClearTrustSettingsResult> {
+ try {
+ return { kind: 'cleared', settings: await clearTrustSettings(server) };
+ } catch (cause) {
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/** The three failure cases every Switch Trust settings call can produce —
+ * common across load, save and clear because all three sit behind the same
+ * `require_admin` gate. */
+function recoverableResult(
+ cause: unknown
+): { kind: 'unauthenticated' } | { kind: 'forbidden' } | { kind: 'error'; message: string } | null {
+ if (!(cause instanceof GatewayError)) return null;
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };
+ return null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx
new file mode 100644
index 000000000..6b5aaed7d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx
@@ -0,0 +1,236 @@
+import { observer } from 'mobx-react-lite';
+import { useEffect, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { Button } from '@renderer/lib/ui/button';
+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import type {
+ ClearTrustSettingsResult,
+ FetchTrustSettingsResult,
+ TrustSettings,
+ UpdateTrustSettingsResult,
+} from '@shared/core/switch-servers/switch-servers';
+import { switchServersStore } from './switch-servers-store';
+
+type FormState = {
+ endpoint: string;
+ policyId: string;
+ apiKey: string;
+};
+
+function formFor(settings: TrustSettings): FormState {
+ return { endpoint: settings.endpoint, policyId: settings.policyId ?? '', apiKey: '' };
+}
+
+/** The three recoverable failure kinds every Switch Trust call can produce,
+ * worded for someone filling in the form rather than for a log line. */
+function recoverableResultText(result: { kind: string; message?: string }): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Your session has expired. Sign in again.';
+ case 'forbidden':
+ return 'Only a deployment administrator can view or change Switch Trust settings.';
+ case 'invalid':
+ case 'error':
+ return result.message ?? 'Could not reach the Switch Trust settings.';
+ default:
+ return 'Could not reach the Switch Trust settings.';
+ }
+}
+
+/**
+ * Switch Trust's one server-global guardrails settings, inline on the
+ * server's Home page between Messaging apps and the admin interface link.
+ *
+ * Admin-only (a deployment operator, not a workspace admin) — one policy
+ * covers the whole deployment, not a workspace, so `switchServersStore`'s
+ * reported `user.role` is checked directly rather than through
+ * `administersWorkspaceInScope()`. Renders nothing for anyone else: there is
+ * no read-only view of this to offer, since the gateway itself refuses a
+ * non-operator's read.
+ */
+export const GuardrailsSection = observer(function GuardrailsSection({
+ serverId,
+ className,
+}: {
+ serverId: string;
+ className?: string;
+}) {
+ const isOperator = switchServersStore.statusFor(serverId)?.user?.role === 'admin';
+
+ const [settings, setSettings] = useState<TrustSettings | null>(null);
+ const [form, setForm] = useState<FormState | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const [confirmingOff, setConfirmingOff] = useState(false);
+ const [clearing, setClearing] = useState(false);
+
+ useEffect(() => {
+ if (!isOperator) return;
+ let cancelled = false;
+ setSettings(null);
+ setForm(null);
+ setLoadError(null);
+ setConfirmingOff(false);
+ rpc.switchServers.getTrustSettings(serverId).then(
+ (result: FetchTrustSettingsResult) => {
+ if (cancelled) return;
+ if (result.kind === 'loaded') {
+ setSettings(result.settings);
+ setForm(formFor(result.settings));
+ } else {
+ setLoadError(recoverableResultText(result));
+ }
+ },
+ (error: unknown) => {
+ if (!cancelled) setLoadError(failureText(error, 'Could not load Switch Trust settings.'));
+ }
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId, isOperator]);
+
+ if (!isOperator) return null;
+
+ const applyResult = (result: UpdateTrustSettingsResult | ClearTrustSettingsResult): void => {
+ if (result.kind === 'saved' || result.kind === 'cleared') {
+ setSettings(result.settings);
+ setForm(formFor(result.settings));
+ setActionError(null);
+ } else {
+ setActionError(recoverableResultText(result));
+ }
+ };
+
+ const save = async () => {
+ if (!form) return;
+ setSaving(true);
+ try {
+ applyResult(
+ await rpc.switchServers.updateTrustSettings({
+ serverId,
+ endpoint: form.endpoint.trim(),
+ policyId: form.policyId.trim() === '' ? null : form.policyId.trim(),
+ ...(form.apiKey.trim() === '' ? {} : { apiKey: form.apiKey.trim() }),
+ })
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const turnOff = async () => {
+ setClearing(true);
+ try {
+ applyResult(await rpc.switchServers.clearTrustSettings(serverId));
+ setConfirmingOff(false);
+ } finally {
+ setClearing(false);
+ }
+ };
+
+ const formValid = form !== null && form.endpoint.trim() !== '';
+
+ return (
+ <div className={className}>
+ <h3 className="text-sm font-medium text-foreground">Guardrails</h3>
+
+ {loadError && <p className="mt-2 text-xs text-destructive">{loadError}</p>}
+
+ {form && settings && (
+ <>
+ <p className="mt-1 text-xs text-foreground-muted">
+ {settings.enabled
+ ? 'Switch Trust is on: every message this server sends is checked before it goes out.'
+ : 'Switch Trust is off. Set a policy ID and an API key to turn it on.'}
+ </p>
+ <FieldGroup className="mt-3">
+ <Field>
+ <FieldLabel>Switch Trust Endpoint</FieldLabel>
+ <Input
+ value={form.endpoint}
+ onChange={(e) => setForm({ ...form, endpoint: e.target.value })}
+ spellCheck={false}
+ autoComplete="off"
+ />
+ </Field>
+ <Field>
+ <FieldLabel>
+ Guardrails Policy ID
+ <span className="ml-1 font-normal text-foreground-muted">(optional)</span>
+ </FieldLabel>
+ <Input
+ value={form.policyId}
+ onChange={(e) => setForm({ ...form, policyId: e.target.value })}
+ spellCheck={false}
+ autoComplete="off"
+ />
+ </Field>
+ <Field>
+ <FieldLabel>
+ Switch Trust API key
+ {settings.hasApiKey && (
+ <span className="ml-1 font-normal text-foreground-muted">
+ (configured, ending •••{settings.apiKeyLast4})
+ </span>
+ )}
+ </FieldLabel>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ spellCheck={false}
+ placeholder={settings.hasApiKey ? 'Leave blank to keep the current key' : ''}
+ value={form.apiKey}
+ onChange={(e) => setForm({ ...form, apiKey: e.target.value })}
+ />
+ </Field>
+ </FieldGroup>
+ {actionError && <p className="mt-2 text-xs text-destructive">{actionError}</p>}
+ <div className="mt-3 flex items-center gap-2">
+ <Button
+ size="sm"
+ onClick={() => void save()}
+ disabled={!formValid || saving || clearing}
+ >
+ {saving ? 'Saving…' : 'Save'}
+ </Button>
+ {settings.enabled &&
+ (confirmingOff ? (
+ <>
+ <span className="text-xs text-foreground-muted">Turn off Switch Trust?</span>
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={clearing}
+ onClick={() => void turnOff()}
+ >
+ {clearing ? 'Turning off…' : 'Turn off'}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={clearing}
+ onClick={() => setConfirmingOff(false)}
+ >
+ Cancel
+ </Button>
+ </>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setConfirmingOff(true)}
+ disabled={saving}
+ >
+ Turn off
+ </Button>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ );
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
index 9f256d71c..ce497b4e9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
@@ -35,6 +35,7 @@ import {
} from '@renderer/lib/ui/dropdown-menu';
import { Spinner } from '@renderer/lib/ui/spinner';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { GuardrailsSection } from './GuardrailsSection';
import { localServerStore } from './local-server-store';
import { LocalServerControls } from './LocalServerControls';
import { managedTelemetryNotice } from './managed-telemetry-notice';
@@ -374,6 +375,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {
{connected && <ServerStatTiles serverId={serverId} />}
{connected && <MessagingAppsCard serverId={serverId} />}
+ {connected && <GuardrailsSection serverId={serverId} />}
</>
)}
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index e7f406aed..3db35c76c 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -586,6 +586,64 @@ export type DeleteBridgeResult =
| { kind: 'not-found' }
| { kind: 'error'; message: string };
+/**
+ * Switch Trust's one server-global guardrails settings row
+ * (`GET /trust-settings`). One policy covers the whole deployment, not a
+ * workspace, so this has no `workspaceId` the way bridge-shaped types do.
+ *
+ * The API key is never returned by the gateway — `hasApiKey`/`apiKeyLast4`
+ * only confirm one is stored, so a form can show "configured" without ever
+ * holding the real value.
+ */
+export type TrustSettings = {
+ endpoint: string;
+ /** Null until a policy id has been saved — the check is off until then. */
+ policyId: string | null;
+ hasApiKey: boolean;
+ apiKeyLast4: string | null;
+ /** `policyId` and an API key are both set. */
+ enabled: boolean;
+};
+
+/** Outcome of loading Switch Trust's settings (`GET /trust-settings`).
+ * Admin-only (a deployment operator, not a workspace admin), so a signed-in
+ * non-operator gets `forbidden` rather than an empty form. */
+export type FetchTrustSettingsResult =
+ | { kind: 'loaded'; settings: TrustSettings }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'error'; message: string };
+
+/**
+ * Parameters for saving Switch Trust's settings (`PUT /trust-settings`).
+ * `apiKey` left unset leaves whatever key is already stored untouched, so
+ * resaving the endpoint or policy id doesn't force re-entering the secret.
+ */
+export type UpdateTrustSettingsParams = {
+ serverId: string;
+ endpoint: string;
+ policyId: string | null;
+ apiKey?: string;
+};
+
+/** Outcome of saving Switch Trust's settings. Mirrors {@link
+ * UpdateBridgeResult}'s recoverable cases. */
+export type UpdateTrustSettingsResult =
+ | { kind: 'saved'; settings: TrustSettings }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'invalid'; message: string }
+ | { kind: 'error'; message: string };
+
+/** Outcome of turning Switch Trust off (`DELETE /trust-settings`). Not
+ * `deleted`, since the row's absence is itself a valid, steady state (a
+ * deployment that has never configured it) rather than something removed. */
+export type ClearTrustSettingsResult =
+ | { kind: 'cleared'; settings: TrustSettings }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'error'; message: string };
+
/** A bridged (external) human identity on a server. The `users` dimension of an
* addressing policy keys off these ids. */
export type RemoteExternalUser = {
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 59062760a..3c22b74bd 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -547,25 +547,14 @@ class SwitchConfig(BaseSettings):
# move every deeplink along with it.
messaging_public_url: str | None = None
- # Switch Trust: a guardrails service that checks a message against a
- # policy before it is sent, blocking it on a BLOCKED verdict. Base URL,
- # no path — `/guardrails/check` (the check-only route added in
- # https://github.com/sandbox-quantum/hoot/pull/2397) is appended, the same
- # convention `otlp_endpoint`/`telemetry_endpoint` follow. Defaults to the
- # company API; override for a different deployment or a local stack.
- switch_trust_endpoint: str = "https://api.switchagents.ai"
-
- # Authenticates with Switch Trust and names which policy to run. Both
- # unset (the default) is what turns the whole feature off — see
- # `trust_enabled` — and setting one without the other is a startup error,
- # the same all-or-nothing shape as the distributed Slack/Discord app
- # config above.
- switch_trust_api_key: str | None = None
- switch_trust_policy_id: str | None = None
-
- # How long to wait on a check before giving up and letting the message
- # through unchecked (fail open — see `trust/client.py`). Short, because
- # this gates every message Switch sends.
+ # How long to wait on a Switch Trust check before giving up and letting the
+ # message through unchecked (fail open — see `trust/client.py`). Fixed at
+ # deploy time rather than DB-backed and admin-editable like the rest of
+ # Switch Trust's settings (`trust_settings` table,
+ # `gateway/trust_settings.py`): getting the endpoint, policy or key wrong
+ # locks guardrails out entirely, which an operator needs to fix without a
+ # restart, but a timeout is a tuning knob with a safe, short default that
+ # deserves one more step to change.
switch_trust_timeout_seconds: float = 2.0
# Upper bound on a single attachment an agent may post to a room (and that
@@ -970,6 +959,15 @@ class SwitchConfig(BaseSettings):
def keyring(self) -> Keyring:
return Keyring.parse(self.secret_keys, legacy_secret=self.jwt_secret_key)
+ @model_validator(mode="after")
+ def _validate_switch_trust_timeout(self) -> "SwitchConfig":
+ if self.switch_trust_timeout_seconds <= 0:
+ raise ValueError(
+ "SWITCH_TRUST_TIMEOUT_SECONDS must be positive, got "
+ f"{self.switch_trust_timeout_seconds!r}."
+ )
+ return self
+
@model_validator(mode="after")
def _validate_oauth_audience(self) -> "SwitchConfig":
if self.oauth_issuer_url and not self.oauth_audience:
@@ -1190,56 +1188,6 @@ class SwitchConfig(BaseSettings):
)
return self
- @model_validator(mode="after")
- def _validate_switch_trust(self) -> "SwitchConfig":
- required = (self.switch_trust_api_key, self.switch_trust_policy_id)
- set_count = sum(1 for value in required if value)
- if 0 < set_count < len(required):
- raise ValueError(
- "Partial Switch Trust config: set both SWITCH_TRUST_API_KEY "
- "and SWITCH_TRUST_POLICY_ID, or neither."
- )
- if self.switch_trust_endpoint != self.switch_trust_endpoint.strip():
- raise ValueError(
- "SWITCH_TRUST_ENDPOINT has leading or trailing whitespace: "
- f"{self.switch_trust_endpoint!r}."
- )
- endpoint = urlsplit(self.switch_trust_endpoint)
- if endpoint.scheme not in ("http", "https"):
- raise ValueError(
- "SWITCH_TRUST_ENDPOINT must be an http(s) URL, got "
- f"{self.switch_trust_endpoint!r}."
- )
- if not endpoint.netloc:
- raise ValueError(
- "SWITCH_TRUST_ENDPOINT must include a host, got "
- f"{self.switch_trust_endpoint!r}."
- )
- if endpoint.path.strip("/"):
- raise ValueError(
- "SWITCH_TRUST_ENDPOINT is the service's base URL and "
- "/guardrails/check is appended to it, so it must have no path "
- f"of its own. Got {self.switch_trust_endpoint!r} — drop the "
- f"{endpoint.path!r}."
- )
- if endpoint.query or endpoint.fragment:
- raise ValueError(
- "SWITCH_TRUST_ENDPOINT must be a bare base URL: a query or "
- "fragment is dropped when /guardrails/check is appended, so "
- f"it would silently never be sent. Got "
- f"{self.switch_trust_endpoint!r}."
- )
- if self.switch_trust_timeout_seconds <= 0:
- raise ValueError(
- "SWITCH_TRUST_TIMEOUT_SECONDS must be positive, got "
- f"{self.switch_trust_timeout_seconds!r}."
- )
- return self
-
- @property
- def trust_enabled(self) -> bool:
- return bool(self.switch_trust_api_key and self.switch_trust_policy_id)
-
@model_validator(mode="after")
def _validate_teams_app(self) -> "SwitchConfig":
settings = {
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 47084f516..f48def944 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -2457,6 +2457,29 @@ class FeatureFlag(Base):
)
+class TrustSettings(Base):
+ """Server-global Switch Trust guardrails configuration — one row.
+
+ No row, or one with ``policy_id``/``api_key_encrypted`` unset, means the
+ check is off (see ``switch_core.trust.client.DynamicTrustClient``). ``id``
+ is a fixed constant (``db/stores/trust_settings_store.py``) rather than a
+ generated key, since there is exactly one row by construction.
+ """
+
+ __tablename__ = "trust_settings"
+
+ id: Mapped[str] = mapped_column(Text, primary_key=True)
+ endpoint: Mapped[str] = mapped_column(Text, nullable=False)
+ policy_id: Mapped[str | None] = mapped_column(Text, nullable=True)
+ api_key_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ server_default=func.now(),
+ onupdate=func.now(),
+ nullable=False,
+ )
+
+
# ── Messages ─────────────────────────────────────────────────────────────────
diff --git a/core/switch_core/db/rls_ddl.py b/core/switch_core/db/rls_ddl.py
index b45dd8bc4..df4afcd7a 100644
--- a/core/switch_core/db/rls_ddl.py
+++ b/core/switch_core/db/rls_ddl.py
@@ -132,6 +132,11 @@ POLICY_NAME = "tenant_isolation"
# when it started, its last renewal and when it stopped. A process holds
# controller sockets for every tenant at once, so its lease belongs to none of
# them, and it holds no customer data, only that the process is alive.
+#
+# `trust_settings` is Switch Trust's one guardrails policy for the whole
+# deployment (`docs/design/switch-trust-guardrails-v1.md`'s Settings UI
+# section) — a policy that varied per tenant would be a new scoped table, not
+# a row here.
GLOBAL_TABLES = frozenset(
{
"users",
@@ -141,6 +146,7 @@ GLOBAL_TABLES = frozenset(
"telemetry_milestones",
"telemetry_snapshot_watermark",
"switch_core_processes",
+ "trust_settings",
}
)
diff --git a/core/switch_core/db/stores/trust_settings_store.py b/core/switch_core/db/stores/trust_settings_store.py
new file mode 100644
index 000000000..934c18d99
--- /dev/null
+++ b/core/switch_core/db/stores/trust_settings_store.py
@@ -0,0 +1,71 @@
+from __future__ import annotations
+
+from sqlalchemy import delete, func, select
+from sqlalchemy.dialects.postgresql import insert
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import TrustSettings
+
+_ROW_ID = "global"
+
+
+class TrustSettingsStore:
+ """Storage for Switch Trust's one server-global settings row.
+
+ No row, or one missing ``policy_id``/``api_key_encrypted``, means the
+ check is off — see ``switch_core.trust.client.DynamicTrustClient``.
+ Merge semantics (e.g. keeping the existing API key when a caller doesn't
+ supply a new one) are the caller's job; this store only ever writes the
+ exact values it's given.
+ """
+
+ async def get(self, session: AsyncSession) -> TrustSettings | None:
+ result = await session.execute(
+ select(TrustSettings).where(TrustSettings.id == _ROW_ID)
+ )
+ return result.scalar_one_or_none()
+
+ async def upsert(
+ self,
+ session: AsyncSession,
+ *,
+ endpoint: str,
+ policy_id: str | None,
+ api_key_encrypted: str | None,
+ ) -> TrustSettings:
+ stmt = (
+ insert(TrustSettings)
+ .values(
+ id=_ROW_ID,
+ endpoint=endpoint,
+ policy_id=policy_id,
+ api_key_encrypted=api_key_encrypted,
+ )
+ .on_conflict_do_update(
+ index_elements=[TrustSettings.id],
+ set_={
+ "endpoint": endpoint,
+ "policy_id": policy_id,
+ "api_key_encrypted": api_key_encrypted,
+ "updated_at": func.now(),
+ },
+ )
+ )
+ await session.execute(stmt)
+ await session.flush()
+ # Not `.returning(TrustSettings)`: a caller that already loaded this
+ # row this session (as `update_trust_settings` does, to read the
+ # existing `api_key_encrypted`) has it in the identity map, and an
+ # ORM-mapped `RETURNING` result would hand back that same stale
+ # object rather than the row this statement just wrote.
+ # `populate_existing` forces the fresh columns onto it instead.
+ result = await session.execute(
+ select(TrustSettings)
+ .where(TrustSettings.id == _ROW_ID)
+ .execution_options(populate_existing=True)
+ )
+ return result.scalar_one()
+
+ async def clear(self, session: AsyncSession) -> None:
+ await session.execute(delete(TrustSettings).where(TrustSettings.id == _ROW_ID))
+ await session.flush()
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index 44e79d9b4..9c6421ab9 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -68,6 +68,7 @@ from switch_core.gateway.teams_placements import router as teams_placements_rout
from switch_core.gateway.template_runs import router as template_runs_router
from switch_core.gateway.templates import router as templates_router
from switch_core.gateway.tenants import router as tenants_router
+from switch_core.gateway.trust_settings import router as trust_settings_router
from switch_core.keys import Purpose
from switch_core.providers.claude_verifier import ClaudeVerifier
from switch_core.providers.github import GitHubConnections
@@ -219,6 +220,7 @@ def create_gateway_app(
app.include_router(templates_router, tags=["templates"])
app.include_router(template_runs_router, tags=["templates"])
app.include_router(ecosystem_router, prefix="/ecosystem", tags=["ecosystem"])
+ app.include_router(trust_settings_router, tags=["trust-settings"])
app.include_router(
messaging_installs_router,
prefix="/messaging-apps",
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index fc61335ea..eb97e7e8e 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Annotated, Any, Literal
+from urllib.parse import urlsplit
from pydantic import (
BaseModel,
@@ -1476,3 +1477,70 @@ class BudgetResponse(BaseModel):
spent: int
resets_at: datetime
exhausted: bool
+
+
+# ── Switch Trust ──────────────────────────────────────────────────────────────
+
+
+class TrustSettingsResponse(BaseModel):
+ """Switch Trust's one server-global settings row. The API key itself is
+ never returned — `has_api_key`/`api_key_last4` only confirm one is set,
+ the way the stored secret is surfaced everywhere else in the gateway."""
+
+ endpoint: str
+ policy_id: str | None
+ has_api_key: bool
+ api_key_last4: str | None
+ enabled: bool
+
+
+class TrustSettingsUpdateRequest(BaseModel):
+ """`api_key` omitted (or null) leaves whatever key is already stored
+ untouched, so changing the endpoint or policy id doesn't force re-entering
+ the secret. Use `DELETE /trust-settings` to turn Switch Trust off.
+
+ No `timeout_seconds` here: unlike the rest of Switch Trust's settings,
+ the check timeout is fixed at deploy time (`SwitchConfig.
+ switch_trust_timeout_seconds`), not admin-editable."""
+
+ endpoint: str
+ policy_id: str | None
+ api_key: str | None = None
+
+ @model_validator(mode="after")
+ def _validate_endpoint(self) -> TrustSettingsUpdateRequest:
+ value = self.endpoint
+ if value != value.strip():
+ raise ValueError("endpoint has leading or trailing whitespace")
+ parts = urlsplit(value)
+ if parts.scheme not in ("http", "https"):
+ raise ValueError("endpoint must be an http(s) URL")
+ if not parts.netloc:
+ raise ValueError("endpoint must include a host")
+ if parts.path.strip("/"):
+ raise ValueError(
+ "endpoint is the service's base URL — /guardrails/check is "
+ "appended to it, so it must have no path of its own"
+ )
+ if parts.query or parts.fragment:
+ raise ValueError(
+ "endpoint must be a bare base URL: a query or fragment is "
+ "dropped when /guardrails/check is appended, so it would "
+ "silently never be sent"
+ )
+ return self
+
+ @model_validator(mode="after")
+ def _validate_api_key(self) -> TrustSettingsUpdateRequest:
+ if self.api_key is not None and not self.api_key.strip():
+ raise ValueError(
+ "api_key must not be blank; omit it to leave the stored key "
+ "unchanged, or use DELETE /trust-settings to turn Switch "
+ "Trust off"
+ )
+ return self
+
+ @field_validator("policy_id")
+ @classmethod
+ def _blank_policy_id_is_unset(cls, value: str | None) -> str | None:
+ return value.strip() if value and value.strip() else None
diff --git a/core/switch_core/gateway/trust_settings.py b/core/switch_core/gateway/trust_settings.py
new file mode 100644
index 000000000..f6d5d5525
--- /dev/null
+++ b/core/switch_core/gateway/trust_settings.py
@@ -0,0 +1,99 @@
+"""Switch Trust's one server-global settings row — deployment-operator only.
+
+Not tenant-scoped: `require_admin` (`users.role == "admin"`), not
+`require_tenant_admin`, gates every route here, since one guardrails policy
+covers the whole deployment rather than one tenant's traffic.
+"""
+
+from __future__ import annotations
+
+from typing import Annotated
+
+from fastapi import APIRouter, Depends
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.config import SwitchConfig
+from switch_core.db.models import TrustSettings, User
+from switch_core.db.stores.trust_settings_store import TrustSettingsStore
+from switch_core.gateway.auth import require_admin
+from switch_core.gateway.dependencies import get_config, get_session
+from switch_core.gateway.schemas import (
+ TrustSettingsResponse,
+ TrustSettingsUpdateRequest,
+)
+
+router = APIRouter()
+
+# Matches the previous env-var default (`SwitchConfig.switch_trust_endpoint`,
+# since removed) — shown until an operator saves their own.
+DEFAULT_TRUST_ENDPOINT = "https://api.switchagents.ai"
+
+
+def _to_response(
+ settings: TrustSettings | None, config: SwitchConfig
+) -> TrustSettingsResponse:
+ if settings is None:
+ return TrustSettingsResponse(
+ endpoint=DEFAULT_TRUST_ENDPOINT,
+ policy_id=None,
+ has_api_key=False,
+ api_key_last4=None,
+ enabled=False,
+ )
+ api_key_last4 = (
+ config.keyring.decrypt(settings.api_key_encrypted)[-4:]
+ if settings.api_key_encrypted
+ else None
+ )
+ return TrustSettingsResponse(
+ endpoint=settings.endpoint,
+ policy_id=settings.policy_id,
+ has_api_key=settings.api_key_encrypted is not None,
+ api_key_last4=api_key_last4,
+ enabled=bool(settings.policy_id and settings.api_key_encrypted),
+ )
+
+
[email protected]("/trust-settings")
+async def get_trust_settings(
+ session: Annotated[AsyncSession, Depends(get_session)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ _admin: Annotated[User, Depends(require_admin)],
+) -> TrustSettingsResponse:
+ settings = await TrustSettingsStore().get(session)
+ return _to_response(settings, config)
+
+
[email protected]("/trust-settings")
+async def update_trust_settings(
+ req: TrustSettingsUpdateRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ _admin: Annotated[User, Depends(require_admin)],
+) -> TrustSettingsResponse:
+ """`req.api_key` omitted leaves whatever key is already stored untouched,
+ so changing the endpoint or policy id doesn't force re-entering it."""
+ store = TrustSettingsStore()
+ existing = await store.get(session)
+ api_key_encrypted = existing.api_key_encrypted if existing else None
+ if req.api_key is not None:
+ api_key_encrypted = config.keyring.encrypt(req.api_key)
+ settings = await store.upsert(
+ session,
+ endpoint=req.endpoint,
+ policy_id=req.policy_id,
+ api_key_encrypted=api_key_encrypted,
+ )
+ await session.commit()
+ return _to_response(settings, config)
+
+
[email protected]("/trust-settings")
+async def delete_trust_settings(
+ session: Annotated[AsyncSession, Depends(get_session)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ _admin: Annotated[User, Depends(require_admin)],
+) -> TrustSettingsResponse:
+ await TrustSettingsStore().clear(session)
+ await session.commit()
+ return _to_response(None, config)
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index cb9217a59..f4d6af95d 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -561,7 +561,7 @@ async def run(config: SwitchConfig) -> None:
)
# ── Switch Trust guardrails ──────────────────────────────────────────────
- trust_client, trust_http = build_trust_client(config)
+ trust_client, trust_http = build_trust_client(session_factory, config)
# ── Resource service ─────────────────────────────────────────────────────
resource_service = ResourceService(
@@ -1027,8 +1027,7 @@ async def run(config: SwitchConfig) -> None:
# product event is the least valuable thing in it.
await protocol.sessions.aclose()
await _drain_telemetry(telemetry, message_telemetry, telemetry_http)
- if trust_http is not None:
- await trust_http.aclose()
+ await trust_http.aclose()
await observability.aclose()
# So a probe during teardown gets a 503 rather than the last
# cached answer, which may still say ready.
diff --git a/core/switch_core/migrations/versions/d5f9a3c71b84_trust_settings.py b/core/switch_core/migrations/versions/d5f9a3c71b84_trust_settings.py
new file mode 100644
index 000000000..aed6f7d2b
--- /dev/null
+++ b/core/switch_core/migrations/versions/d5f9a3c71b84_trust_settings.py
@@ -0,0 +1,38 @@
+"""trust settings: server-global Switch Trust guardrails config
+
+Revision ID: d5f9a3c71b84
+Revises: e4b7d2a91c06
+Create Date: 2026-10-09 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "d5f9a3c71b84"
+down_revision: str | None = "e4b7d2a91c06"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "trust_settings",
+ sa.Column("id", sa.Text(), nullable=False),
+ sa.Column("endpoint", sa.Text(), nullable=False),
+ sa.Column("policy_id", sa.Text(), nullable=True),
+ sa.Column("api_key_encrypted", sa.Text(), nullable=True),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.func.now(),
+ nullable=False,
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("trust_settings")
diff --git a/core/switch_core/trust/client.py b/core/switch_core/trust/client.py
index 43fdaefd8..2cfc2dc27 100644
--- a/core/switch_core/trust/client.py
+++ b/core/switch_core/trust/client.py
@@ -17,6 +17,10 @@ from dataclasses import dataclass
from typing import Any, Literal, Protocol
import httpx
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.stores.trust_settings_store import TrustSettingsStore
+from switch_core.keys import Keyring
logger = logging.getLogger(__name__)
@@ -120,6 +124,48 @@ class NullTrustClient:
return TrustCheckResult(outcome="ok", policy_id=None, policy_name=None)
+class DynamicTrustClient:
+ """Reads the one server-global ``trust_settings`` row on every call.
+
+ Unlike `HttpTrustClient`, built once at boot from fixed arguments, this
+ resolves its settings fresh each check — so a change made through the
+ gateway's settings endpoint (`gateway/trust_settings.py`) takes effect on
+ the next message, with no restart. Behaves exactly like `NullTrustClient`
+ when no row exists yet, or one is missing `policy_id`/`api_key_encrypted`.
+ """
+
+ def __init__(
+ self,
+ *,
+ session_factory: async_sessionmaker[AsyncSession],
+ store: TrustSettingsStore,
+ keyring: Keyring,
+ client: httpx.AsyncClient,
+ timeout_seconds: float,
+ ) -> None:
+ self._session_factory = session_factory
+ self._store = store
+ self._keyring = keyring
+ self._client = client
+ self._timeout_seconds = timeout_seconds
+
+ async def check(
+ self, *, role: Role, content: str, room_id: str
+ ) -> TrustCheckResult:
+ async with self._session_factory() as session:
+ settings = await self._store.get(session)
+ if settings is None or not settings.policy_id or not settings.api_key_encrypted:
+ return TrustCheckResult(outcome="ok", policy_id=None, policy_name=None)
+ http_client = HttpTrustClient(
+ base_url=settings.endpoint,
+ api_key=self._keyring.decrypt(settings.api_key_encrypted),
+ policy_id=settings.policy_id,
+ timeout_seconds=self._timeout_seconds,
+ client=self._client,
+ )
+ return await http_client.check(role=role, content=content, room_id=room_id)
+
+
class HttpTrustClient:
"""Posts to `{base_url}/guardrails/check`. One client, reused.
diff --git a/core/switch_core/trust/setup.py b/core/switch_core/trust/setup.py
index d37c53fa4..6fcbb9323 100644
--- a/core/switch_core/trust/setup.py
+++ b/core/switch_core/trust/setup.py
@@ -2,48 +2,31 @@
One function, so `main.py` does not have to know the difference between a
deployment with guardrails configured and one without — it asks for a client
-and gets one either way.
+and gets one either way, and whether it actually checks anything is decided
+per call from the `trust_settings` row (see `trust/client.py`), not at boot.
"""
from __future__ import annotations
-import logging
-
import httpx
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.config import SwitchConfig
-from switch_core.trust.client import HttpTrustClient, NullTrustClient, TrustClient
-
-logger = logging.getLogger(__name__)
+from switch_core.db.stores.trust_settings_store import TrustSettingsStore
+from switch_core.trust.client import DynamicTrustClient, TrustClient
def build_trust_client(
+ session_factory: async_sessionmaker[AsyncSession],
config: SwitchConfig,
-) -> tuple[TrustClient, httpx.AsyncClient | None]:
- """The trust client, and its HTTP client so `main` can close it.
-
- Returns a `NullTrustClient` (no request ever made) unless both
- `SWITCH_TRUST_API_KEY` and `SWITCH_TRUST_POLICY_ID` are set.
- """
- api_key = config.switch_trust_api_key
- policy_id = config.switch_trust_policy_id
- if not api_key or not policy_id:
- logger.info(
- "Switch Trust is off; messages are not checked before sending. Set "
- "SWITCH_TRUST_API_KEY and SWITCH_TRUST_POLICY_ID to turn it on."
- )
- return NullTrustClient(), None
-
+) -> tuple[TrustClient, httpx.AsyncClient]:
+ """The trust client, and its HTTP client so `main` can close it."""
http_client = httpx.AsyncClient()
- client = HttpTrustClient(
- base_url=config.switch_trust_endpoint,
- api_key=api_key,
- policy_id=policy_id,
- timeout_seconds=config.switch_trust_timeout_seconds,
+ client = DynamicTrustClient(
+ session_factory=session_factory,
+ store=TrustSettingsStore(),
+ keyring=config.keyring,
client=http_client,
- )
- logger.info(
- "Switch Trust is ON: messages are checked against %s before sending.",
- config.switch_trust_endpoint,
+ timeout_seconds=config.switch_trust_timeout_seconds,
)
return client, http_client
diff --git a/core/tests/switch_core/db/stores/test_trust_settings_store.py b/core/tests/switch_core/db/stores/test_trust_settings_store.py
new file mode 100644
index 000000000..067074038
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_trust_settings_store.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.stores.trust_settings_store import TrustSettingsStore
+
+
+class TestTrustSettingsStore:
+ async def test_absent_row_is_none(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TrustSettingsStore()
+ async with session_factory() as session:
+ assert await store.get(session) is None
+
+ async def test_upsert_then_get(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TrustSettingsStore()
+ async with session_factory() as session:
+ await store.upsert(
+ session,
+ endpoint="https://trust.example",
+ policy_id="pol_123",
+ api_key_encrypted="enc:k",
+ )
+ await session.commit()
+
+ settings = await store.get(session)
+ assert settings is not None
+ assert settings.endpoint == "https://trust.example"
+ assert settings.policy_id == "pol_123"
+ assert settings.api_key_encrypted == "enc:k"
+
+ async def test_upsert_is_idempotent_on_the_one_row(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TrustSettingsStore()
+ async with session_factory() as session:
+ await store.upsert(
+ session,
+ endpoint="https://trust.example",
+ policy_id="pol_123",
+ api_key_encrypted="enc:k",
+ )
+ await store.upsert(
+ session,
+ endpoint="https://other.example",
+ policy_id="pol_456",
+ api_key_encrypted="enc:k2",
+ )
+ await session.commit()
+
+ settings = await store.get(session)
+ assert settings is not None
+ assert settings.endpoint == "https://other.example"
+ assert settings.policy_id == "pol_456"
+ assert settings.api_key_encrypted == "enc:k2"
+
+ async def test_upsert_can_leave_the_api_key_untouched(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TrustSettingsStore()
+ async with session_factory() as session:
+ await store.upsert(
+ session,
+ endpoint="https://trust.example",
+ policy_id="pol_123",
+ api_key_encrypted="enc:k",
+ )
+ await store.upsert(
+ session,
+ endpoint="https://trust2.example",
+ policy_id="pol_123",
+ api_key_encrypted="enc:k",
+ )
+ await session.commit()
+
+ settings = await store.get(session)
+ assert settings is not None
+ assert settings.api_key_encrypted == "enc:k"
+ assert settings.endpoint == "https://trust2.example"
+
+ async def test_clear_removes_the_row(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TrustSettingsStore()
+ async with session_factory() as session:
+ await store.upsert(
+ session,
+ endpoint="https://trust.example",
+ policy_id="pol_123",
+ api_key_encrypted="enc:k",
+ )
+ await session.commit()
+
+ await store.clear(session)
+ await session.commit()
+
+ assert await store.get(session) is None
diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
index baa13508f..d423a78ea 100644
--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
@@ -179,6 +179,12 @@ _RAW_SESSION_FACTORY_MODULES = {
# and no policy (`rls_ddl.GLOBAL_TABLES`): a process serves every tenant,
# so its lease belongs to none. It touches only that table.
"switch_core.management.process_lease",
+ # `DynamicTrustClient` reads `trust_settings` on every check, including
+ # from agent- and bridge-originated sends that have no request to inherit
+ # a tenant from. A table with no tenant and no policy
+ # (`rls_ddl.GLOBAL_TABLES`): one guardrails policy covers the whole
+ # deployment, so there is no tenant for a policy to narrow on.
+ "switch_core.trust.client",
}
# Calls that end in `session_factory` but hand one back rather than open a
diff --git a/core/tests/switch_core/db/test_tenant_schema_catalogue.py b/core/tests/switch_core/db/test_tenant_schema_catalogue.py
index 1485b14e8..3eb71dd6e 100644
--- a/core/tests/switch_core/db/test_tenant_schema_catalogue.py
+++ b/core/tests/switch_core/db/test_tenant_schema_catalogue.py
@@ -112,6 +112,9 @@ class TestEveryTableIsScopedUnlessItIsNamedGlobal:
# sockets for every tenant at once, and the row says only that it
# is alive.
"switch_core_processes",
+ # Switch Trust's one guardrails policy for the whole deployment.
+ # A policy that varied per tenant would be a new scoped table.
+ "trust_settings",
}
async def test_scoped_is_everything_else(self) -> None:
diff --git a/core/tests/switch_core/gateway/test_trust_settings.py b/core/tests/switch_core/gateway/test_trust_settings.py
new file mode 100644
index 000000000..03ef9ee6d
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_trust_settings.py
@@ -0,0 +1,189 @@
+"""Switch Trust's one server-global settings row — deployment-operator only.
+
+Against real Postgres: a non-operator is refused on every route, the API key
+is never echoed back, and a PUT that omits it leaves the stored one alone.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from types import SimpleNamespace
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from pydantic import ValidationError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import TENANT_ZERO_ID, TenantMember, User
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway import dependencies as gw_deps
+from switch_core.gateway.auth import create_jwt
+from switch_core.gateway.schemas import TrustSettingsUpdateRequest
+from switch_core.gateway.trust_settings import router as trust_settings_router
+from switch_core.keys import Keyring
+
+TEST_KEYRING = Keyring.parse("test:" + "x" * 40, legacy_secret=None)
+
+_CONFIGURED_BODY = {
+ "endpoint": "https://trust.example",
+ "policy_id": "pol_123",
+ "api_key": "s3cr3t-key",
+}
+
+
+def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+ async def _session() -> AsyncIterator[AsyncSession]:
+ async with session_factory() as session:
+ yield session
+
+ app = FastAPI()
+ app.include_router(trust_settings_router)
+ app.dependency_overrides[gw_deps.get_session] = _session
+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
+ app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ keyring=TEST_KEYRING, gateway_tenant_choice_enabled=False
+ )
+ return app
+
+
+async def _add_user(
+ session_factory: async_sessionmaker[AsyncSession], *, name: str, role: str
+) -> User:
+ async with session_factory() as session:
+ user = User(name=name, email=f"{name}@example.com", role=role)
+ session.add(user)
+ await session.flush()
+ session.add(
+ TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member")
+ )
+ await session.commit()
+ return user
+
+
+def _cookies_for(user: User) -> dict[str, str]:
+ return {
+ "switch_auth": create_jwt(
+ user.id, user.email, user.role, TEST_KEYRING, TENANT_ZERO_ID
+ )
+ }
+
+
+def _client(
+ session_factory: async_sessionmaker[AsyncSession], user: User
+) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=_app(session_factory)),
+ base_url="http://test",
+ cookies=_cookies_for(user),
+ )
+
+
+async def test_a_non_admin_is_refused_every_route(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ user = await _add_user(session_factory, name="mallory", role="user")
+ async with _client(session_factory, user) as client:
+ get_resp = await client.get("/trust-settings")
+ put_resp = await client.put("/trust-settings", json=_CONFIGURED_BODY)
+ delete_resp = await client.delete("/trust-settings")
+
+ assert get_resp.status_code == 403
+ assert put_resp.status_code == 403
+ assert delete_resp.status_code == 403
+
+
+async def test_get_with_no_row_reports_off_with_the_default_endpoint(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ admin = await _add_user(session_factory, name="op", role="admin")
+ async with _client(session_factory, admin) as client:
+ resp = await client.get("/trust-settings")
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["enabled"] is False
+ assert body["has_api_key"] is False
+ assert body["api_key_last4"] is None
+ assert body["endpoint"] == "https://api.switchagents.ai"
+
+
+async def test_put_then_get_round_trips_without_exposing_the_key(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ admin = await _add_user(session_factory, name="op", role="admin")
+ async with _client(session_factory, admin) as client:
+ put_resp = await client.put("/trust-settings", json=_CONFIGURED_BODY)
+ assert put_resp.status_code == 200
+ body = put_resp.json()
+ assert body["enabled"] is True
+ assert body["has_api_key"] is True
+ assert body["api_key_last4"] == "-key"
+ assert "api_key" not in body
+
+ get_resp = await client.get("/trust-settings")
+ assert get_resp.json() == body
+
+
+async def test_put_without_api_key_leaves_the_stored_key_untouched(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ admin = await _add_user(session_factory, name="op", role="admin")
+ async with _client(session_factory, admin) as client:
+ await client.put("/trust-settings", json=_CONFIGURED_BODY)
+ resp = await client.put(
+ "/trust-settings",
+ json={
+ "endpoint": "https://trust2.example",
+ "policy_id": "pol_123",
+ },
+ )
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["endpoint"] == "https://trust2.example"
+ assert body["has_api_key"] is True
+ assert body["api_key_last4"] == "-key"
+
+
+async def test_delete_turns_it_off(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ admin = await _add_user(session_factory, name="op", role="admin")
+ async with _client(session_factory, admin) as client:
+ await client.put("/trust-settings", json=_CONFIGURED_BODY)
+ delete_resp = await client.delete("/trust-settings")
+ get_resp = await client.get("/trust-settings")
+
+ assert delete_resp.status_code == 200
+ assert delete_resp.json()["enabled"] is False
+ assert get_resp.json()["enabled"] is False
+
+
+def test_a_blank_policy_id_is_treated_as_unset() -> None:
+ req = TrustSettingsUpdateRequest(endpoint="https://trust.example", policy_id=" ")
+ assert req.policy_id is None
+
+
+def test_a_blank_api_key_is_refused_rather_than_silently_stored() -> None:
+ with pytest.raises(ValidationError):
+ TrustSettingsUpdateRequest(
+ endpoint="https://trust.example",
+ policy_id="pol_1",
+ api_key=" ",
+ )
+
+
+ "endpoint,match",
+ [
+ ("https://trust.example/guardrails/check", "no path"),
+ ("not-a-url", "http"),
+ (" https://trust.example", "whitespace"),
+ ("https://trust.example?x=1", "query"),
+ ],
+)
+def test_endpoint_shape_is_validated(endpoint: str, match: str) -> None:
+ with pytest.raises(ValidationError, match=match):
+ TrustSettingsUpdateRequest(endpoint=endpoint, policy_id="pol_1")
diff --git a/core/tests/switch_core/test_config_switch_trust.py b/core/tests/switch_core/test_config_switch_trust.py
deleted file mode 100644
index c27fd5db4..000000000
--- a/core/tests/switch_core/test_config_switch_trust.py
+++ /dev/null
@@ -1,66 +0,0 @@
-"""Half-configuring Switch Trust has to be a startup error, the same shape as
-the distributed Slack/Discord app config: setting the key without the policy
-(or the reverse) looks configured and checks nothing.
-"""
-
-import pytest
-
-from switch_core.config import SwitchConfig
-
-_BASE_KWARGS = dict(
- db_host="db",
- db_port="5432",
- db_user="postgres",
- db_password="pw",
- db_name="switch",
- id_server_name="switch.local",
- agent_registration_token="token",
- secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
- gateway_admin_email="[email protected]",
- gateway_admin_password="pw",
-)
-
-_TRUST = dict(
- switch_trust_api_key="key",
- switch_trust_policy_id="pol_123",
-)
-
-
-def _config(**overrides: object) -> SwitchConfig:
- return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]
-
-
-def test_off_by_default() -> None:
- config = _config()
- assert config.trust_enabled is False
- assert config.switch_trust_endpoint == "https://api.switchagents.ai"
-
-
-def test_setting_both_enables_it() -> None:
- assert _config(**_TRUST).trust_enabled is True
-
-
[email protected]("missing", sorted(_TRUST))
-def test_setting_only_one_raises(missing: str) -> None:
- partial = {key: value for key, value in _TRUST.items() if key != missing}
- with pytest.raises(ValueError, match="Partial Switch Trust config"):
- _config(**partial)
-
-
-def test_a_path_on_the_endpoint_is_refused() -> None:
- """The check path is appended, so a value already carrying one would be
- posted to e.g. /guardrails/check/guardrails/check."""
- with pytest.raises(ValueError, match="must have no path"):
- _config(
- **_TRUST, switch_trust_endpoint="https://trust.example/guardrails/check"
- )
-
-
-def test_an_http_endpoint_is_refused() -> None:
- with pytest.raises(ValueError, match="must be an http"):
- _config(**_TRUST, switch_trust_endpoint="not-a-url")
-
-
-def test_a_non_positive_timeout_is_refused() -> None:
- with pytest.raises(ValueError, match="SWITCH_TRUST_TIMEOUT_SECONDS"):
- _config(**_TRUST, switch_trust_timeout_seconds=0)
diff --git a/core/tests/switch_core/test_config_switch_trust_timeout.py b/core/tests/switch_core/test_config_switch_trust_timeout.py
new file mode 100644
index 000000000..21939174a
--- /dev/null
+++ b/core/tests/switch_core/test_config_switch_trust_timeout.py
@@ -0,0 +1,34 @@
+"""The Switch Trust check timeout is the one piece of its config still fixed
+at deploy time — see docs/design/switch-trust-guardrails-v1.md's Settings UI
+section for why it stayed out of the DB-backed, admin-editable settings.
+"""
+
+import pytest
+
+from switch_core.config import SwitchConfig
+
+_BASE_KWARGS = dict(
+ db_host="db",
+ db_port="5432",
+ db_user="postgres",
+ db_password="pw",
+ db_name="switch",
+ id_server_name="switch.local",
+ agent_registration_token="token",
+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ gateway_admin_email="[email protected]",
+ gateway_admin_password="pw",
+)
+
+
+def _config(**overrides: object) -> SwitchConfig:
+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]
+
+
+def test_defaults_to_two_seconds() -> None:
+ assert _config().switch_trust_timeout_seconds == 2.0
+
+
+def test_a_non_positive_timeout_is_refused() -> None:
+ with pytest.raises(ValueError, match="SWITCH_TRUST_TIMEOUT_SECONDS"):
+ _config(switch_trust_timeout_seconds=0)
diff --git a/core/tests/switch_core/trust/test_client.py b/core/tests/switch_core/trust/test_client.py
index c9527838e..fa3d52dd7 100644
--- a/core/tests/switch_core/trust/test_client.py
+++ b/core/tests/switch_core/trust/test_client.py
@@ -5,11 +5,13 @@ sites that use them.
import json
import uuid
+from dataclasses import dataclass
import httpx
import pytest
from switch_core.trust.client import (
+ DynamicTrustClient,
GuardrailBlockedError,
GuardrailsCheckError,
HttpTrustClient,
@@ -21,6 +23,96 @@ from switch_core.trust.client import (
)
+@dataclass
+class _FakeRow:
+ endpoint: str
+ policy_id: str | None
+ api_key_encrypted: str | None
+
+
+class _FakeStore:
+ def __init__(self, row: _FakeRow | None) -> None:
+ self._row = row
+
+ async def get(self, session: object) -> _FakeRow | None:
+ return self._row
+
+
+class _FakeSession:
+ async def __aenter__(self) -> "_FakeSession":
+ return self
+
+ async def __aexit__(self, *exc: object) -> bool:
+ return False
+
+
+class _FakeSessionFactory:
+ def __call__(self) -> _FakeSession:
+ return _FakeSession()
+
+
+class _FakeKeyring:
+ def decrypt(self, value: str) -> str:
+ return value.removeprefix("enc:")
+
+
+def _dynamic_client(row: _FakeRow | None, handler) -> DynamicTrustClient:
+ return DynamicTrustClient(
+ session_factory=_FakeSessionFactory(), # type: ignore[arg-type]
+ store=_FakeStore(row), # type: ignore[arg-type]
+ keyring=_FakeKeyring(), # type: ignore[arg-type]
+ client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ timeout_seconds=1.0,
+ )
+
+
+def _unreachable(request: httpx.Request) -> httpx.Response:
+ raise AssertionError("no request should be made")
+
+
+async def test_dynamic_client_behaves_like_null_with_no_row() -> None:
+ client = _dynamic_client(None, _unreachable)
+ result = await client.check(role="user", content="hi", room_id="room-1")
+ assert result.outcome == "ok"
+
+
+async def test_dynamic_client_behaves_like_null_when_policy_id_is_missing() -> None:
+ row = _FakeRow(
+ endpoint="https://trust.example",
+ policy_id=None,
+ api_key_encrypted="enc:k",
+ )
+ client = _dynamic_client(row, _unreachable)
+ result = await client.check(role="user", content="hi", room_id="room-1")
+ assert result.outcome == "ok"
+
+
+async def test_dynamic_client_checks_against_the_current_row() -> None:
+ seen: dict[str, object] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen["key"] = request.headers.get("x-flintai-api-key")
+ seen["policy"] = request.headers.get("x-guardrails-policy-id")
+ seen["url"] = str(request.url)
+ return httpx.Response(200, json={"outcome": "GUARDRAIL_RESULT_OUTCOME_OK"})
+
+ row = _FakeRow(
+ endpoint="https://trust.example",
+ policy_id="pol_123",
+ api_key_encrypted="enc:k",
+ )
+ client = _dynamic_client(row, handler)
+ result = await client.check(role="user", content="hi", room_id="room-1")
+
+ assert seen["key"] == "k"
+ assert seen["policy"] == "pol_123"
+ assert seen["url"] == "https://trust.example/guardrails/check"
+ assert result.outcome == "ok"
+
+
def _client(handler) -> HttpTrustClient:
return HttpTrustClient(
base_url="https://trust.example",
diff --git a/docs/design/switch-trust-guardrails-v1.md b/docs/design/switch-trust-guardrails-v1.md
index 6daeb2852..7948e3dc3 100644
--- a/docs/design/switch-trust-guardrails-v1.md
+++ b/docs/design/switch-trust-guardrails-v1.md
@@ -151,32 +151,14 @@ to the message it's about, rather than becoming a second thing to read.
## Config
-New fields on `SwitchConfig` (`core/switch_core/config.py`), mirroring the
-existing all-or-nothing settings groups (`_validate_slack_app`,
-`core/switch_core/config.py:986`):
-
-```python
-switch_trust_endpoint: str = "https://api.switchagents.ai"
-switch_trust_api_key: str = ""
-switch_trust_policy_id: str = ""
-switch_trust_timeout_seconds: float = 2.0
-```
-
-`switch_trust_endpoint` is a base URL; the client appends
-`/guardrails/check` — the check-only route added in
-[hoot#2397](https://github.com/sandbox-quantum/hoot/pull/2397) — rather than
-treating the configured value as the full check URL.
-
-A `trust_enabled` property returns `bool(switch_trust_api_key and
-switch_trust_policy_id)`. A `_validate_switch_trust` model validator checks
-the endpoint's URL shape (scheme/host, no path/query — mirroring
-`_validate_observability`'s OTLP check) when it's overridden from the default,
-and that `switch_trust_api_key`/`switch_trust_policy_id` are both set or both
-empty.
-
-When `trust_enabled` is false, a `NullTrustClient` is injected — mirrors
-`telemetry/sink.py`'s `NullSink`: off is a client that always allows, so no
-call site has to branch on whether the feature is on.
+v1 shipped as four env-var fields on `SwitchConfig`
+(`switch_trust_endpoint`/`switch_trust_api_key`/`switch_trust_policy_id`/
+`switch_trust_timeout_seconds`, with a `trust_enabled` property and a
+`_validate_switch_trust` validator), with `NullTrustClient` injected whenever
+`trust_enabled` was false — mirroring `telemetry/sink.py`'s `NullSink`, so no
+call site had to branch on whether the feature was on. These env vars were a
+bootstrap stopgap, never a real deployment's config, and are gone: see
+§Settings UI below for what replaced them.
## Execution plan
@@ -246,9 +228,72 @@ call site has to branch on whether the feature is on.
whole deployment. Multiple tenants wanting different policies needs a DB
table, migration, and an admin API — a materially bigger lift than the env
var config in this doc.
-- **Settings UI**: a dedicated Switch Trust section, either in the gateway
- operator dashboard or in Console's "server properties" — neither surface has
- an existing settings page to extend today, so this is new UI work in either
- home.
- **Media/attachment checks**: images and files aren't sent to Switch Trust in
v1.
+
+## Settings UI
+
+The env-var config above was always a bootstrap stopgap, not the intended
+long-term home: it requires a deploy to change, and it isn't visible from
+anywhere a deployment operator actually looks. This section replaces it with
+a DB-backed, editable settings surface — still one global policy for the whole
+deployment (no per-tenant override; that's still the bigger lift described
+above).
+
+**Storage**: a new `trust_settings` table — a single row (`endpoint`,
+`policy_id`, `api_key_encrypted`, `updated_at`), upserted in place rather than
+modeled as a list. `api_key_encrypted` is encrypted via `config.keyring`, the
+same mechanism `ProviderConnection` already uses for per-user provider
+credentials. The table starts empty — there is no migration step to carry
+over the old `SWITCH_TRUST_*` env vars, since those never had a real
+deployment depending on them. The `switch_trust_endpoint`,
+`switch_trust_api_key`, `switch_trust_policy_id` fields, `trust_enabled`
+property, and `_validate_switch_trust` validator are removed from
+`SwitchConfig` entirely; endpoint URL-shape validation moves to the new
+settings' write path.
+
+The check timeout is the one exception: `switch_trust_timeout_seconds` stays
+a `SwitchConfig` field (default 2s, validated positive), fixed at deploy time
+rather than joining the DB-backed settings. Getting the endpoint, policy or
+key wrong locks guardrails out entirely, which an operator needs to fix
+without a restart — but the timeout is a tuning knob with a safe default, not
+something to expose to day-to-day editing or surface in the settings UI.
+
+**Resolution**: `TrustClient` gains a `DynamicTrustClient` implementation that
+reads the current row on every `check()` call (via the new
+`TrustSettingsStore`) instead of a client built once at boot from static
+config, using `SwitchConfig.switch_trust_timeout_seconds` for the timeout on
+every call. No row, or an incomplete one (missing `api_key`/`policy_id`),
+behaves exactly like today's `NullTrustClient` — `outcome="ok"`, no request
+made — except decided per call rather than at startup, so a settings change
+takes effect on the next message with no restart. `trust/setup.py::build_trust_client`
+now always returns a `DynamicTrustClient` wired to the store; `NullTrustClient`
+remains for tests that want no DB involved at all.
+
+**Gateway API**: a new router, `core/switch_core/gateway/trust_settings.py`,
+deployment-scoped (no `{tenant_id}` in the path) and gated by `require_admin`
+— the existing deployment-operator check (`users.role == "admin"`), distinct
+from `require_tenant_admin` — since this setting applies to the whole
+deployment, not one tenant.
+
+- `GET /trust-settings` — `endpoint`, `policy_id`, `has_api_key`,
+ `api_key_last4`, and a derived `enabled`. The real API key is never
+ returned.
+- `PUT /trust-settings` — full update of the non-secret fields; `api_key`
+ omitted or `null` leaves the stored key untouched, so changing the endpoint
+ or policy id doesn't force re-entering the secret.
+- `DELETE /trust-settings` — clears the row, equivalent to turning guardrails
+ off.
+
+**Console UI**: a new section on the server's Home page, between "Messaging
+apps" and "Full admin interface" — not a separate view, since there's little
+enough here to configure that a full page would be a detour rather than a
+destination. Gated on the connected server's reported `user.role === "admin"`
+directly — not the broader `administersWorkspaceInScope()` helper, which also
+admits a plain workspace owner and would be too wide for a deployment-level
+setting — and hidden entirely for anyone else, since there's nothing read-only
+to show a non-operator. Labeled "Switch Trust Endpoint", "Guardrails Policy
+ID" and "Switch Trust API key" rather than the gateway's own field names, to
+read as Switch Trust's settings rather than generic form fields; the timeout
+is not surfaced at all. The key field shows "configured, ending •••1234"
+instead of ever prefilling the real value, matching the write-only API above.