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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions apps/api/src/routes/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ import type { ServerTypes } from "@/vars.js";
export const organization = new OpenAPIHono<ServerTypes>();

// Define schemas directly with Zod instead of using createSelectSchema
const providerCompliancePolicySchema = z.object({
enabled: z.boolean(),
requireSoc2: z.boolean().optional(),
requireIso27001: z.boolean().optional(),
requireSoc2OrIso27001: z.boolean().optional(),
requireGdpr: z.boolean().optional(),
blockApiTraining: z.boolean().optional(),
blockPromptLogging: z.boolean().optional(),
});

const organizationSchema = z.object({
id: z.string(),
createdAt: z.date(),
Expand All @@ -39,6 +49,7 @@ const organizationSchema = z.object({
plan: z.enum(["free", "pro", "enterprise"]),
planExpiresAt: z.date().nullable(),
retentionLevel: z.enum(["retain", "none"]),
providerCompliancePolicy: providerCompliancePolicySchema.nullable(),
status: z.enum(["active", "inactive", "deleted"]).nullable(),
autoTopUpEnabled: z.boolean(),
autoTopUpThreshold: z.string().nullable(),
Expand Down Expand Up @@ -96,6 +107,9 @@ const updateOrganizationSchema = z.object({
billingTaxId: z.string().optional(),
billingNotes: z.string().optional(),
retentionLevel: z.enum(["retain", "none"]).optional(),
providerCompliancePolicy: providerCompliancePolicySchema
.nullable()
.optional(),
autoTopUpEnabled: z.boolean().optional(),
autoTopUpThreshold: z.number().min(5).optional(),
autoTopUpAmount: z
Expand Down Expand Up @@ -444,6 +458,7 @@ organization.openapi(updateOrganization, async (c) => {
billingTaxId,
billingNotes,
retentionLevel,
providerCompliancePolicy,
autoTopUpEnabled,
autoTopUpThreshold,
autoTopUpAmount,
Expand Down Expand Up @@ -491,6 +506,24 @@ organization.openapi(updateOrganization, async (c) => {
});
}

// Provider compliance policies are an enterprise feature managed by owners
// and admins (matching the Guardrails settings page).
if (providerCompliancePolicy !== undefined) {
if (userOrganization.organization?.plan !== "enterprise") {
throw new HTTPException(403, {
message: "Provider compliance policies require an enterprise plan",
});
}
if (
userOrganization.role !== "owner" &&
userOrganization.role !== "admin"
) {
throw new HTTPException(403, {
message: "Only owners and admins can manage compliance policies",
});
}
}

const updateData: any = {};
if (name !== undefined) {
updateData.name = name;
Expand All @@ -513,6 +546,9 @@ organization.openapi(updateOrganization, async (c) => {
if (retentionLevel !== undefined) {
updateData.retentionLevel = retentionLevel;
}
if (providerCompliancePolicy !== undefined) {
updateData.providerCompliancePolicy = providerCompliancePolicy;
Comment on lines +549 to +550

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Invalidate cached organizations on policy updates

Saving the new policy through this route updates the organization with the uncached db client, while the gateway reads organizations through the cached cdb path in findOrganizationById; only cached-client mutations trigger RedisCache.onMutate and SWR invalidation. If an admin enables a stricter policy after the org was cached, the gateway can continue using the old providerCompliancePolicy until the cache expires, allowing non-compliant traffic during that window.

Useful? React with 👍 / 👎.

}
if (autoTopUpEnabled !== undefined) {
updateData.autoTopUpEnabled = autoTopUpEnabled;
if (autoTopUpEnabled && !userOrganization.organization?.autoTopUpEnabled) {
Expand Down Expand Up @@ -577,6 +613,16 @@ organization.openapi(updateOrganization, async (c) => {
new: retentionLevel,
};
}
if (
providerCompliancePolicy !== undefined &&
JSON.stringify(oldOrg.providerCompliancePolicy ?? null) !==
JSON.stringify(providerCompliancePolicy ?? null)
) {
changes.providerCompliancePolicy = {
old: oldOrg.providerCompliancePolicy,
new: providerCompliancePolicy,
};
}
if (
autoTopUpEnabled !== undefined &&
autoTopUpEnabled !== oldOrg.autoTopUpEnabled
Expand Down
34 changes: 34 additions & 0 deletions apps/api/src/routes/video.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { z } from "zod";
import { userHasOrganizationAccess } from "@/utils/authorization.js";

import { db } from "@llmgateway/db";
import { buildSignedGatewayVideoLogContentUrl } from "@llmgateway/shared/video-access";

import type { ServerTypes } from "@/vars.js";

Expand Down Expand Up @@ -42,6 +43,15 @@ const videoJobResponseSchema = z.object({
details: z.unknown().optional(),
})
.nullable(),
content: z
.array(
z.object({
type: z.literal("video"),
url: z.string(),
mime_type: z.string().nullable().optional(),
}),
)
.optional(),
});

const getVideoStatus = createRoute({
Expand Down Expand Up @@ -92,6 +102,29 @@ video.openapi(getVideoStatus, async (c) => {
throw new HTTPException(404, { message: "Video not found" });
}

let content:
| { type: "video"; url: string; mime_type?: string | null }[]
| undefined;
if (job.status === "completed") {
const log = await db.query.log.findFirst({
where: {
requestId: { eq: job.requestId },
},
Comment on lines +110 to +112

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Scope signed content lookup to the job

For completed jobs this query finds the first log with the same requestId across the whole log table, then signs that log's content URL. Video requestId is taken from caller-supplied x-request-id and is only indexed, not unique, so if two jobs share a request id maliciously or accidentally, a user authorized for their own job can receive a signed URL for another project/org's log. Include at least job.projectId/job.organizationId in the log lookup before signing.

Useful? React with 👍 / 👎.

columns: {
id: true,
},
});
Comment on lines +109 to +116

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Scope the log lookup to the same project (or organization), not only requestId.

findFirst on requestId alone can resolve the wrong log record if IDs collide/reuse. That can generate a signed URL for unrelated content. Include projectId (or organizationId) in the lookup predicate.

Suggested fix
 		const log = await db.query.log.findFirst({
 			where: {
 				requestId: { eq: job.requestId },
+				projectId: { eq: job.projectId },
 			},
 			columns: {
 				id: true,
 			},
 		});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const log = await db.query.log.findFirst({
where: {
requestId: { eq: job.requestId },
},
columns: {
id: true,
},
});
const log = await db.query.log.findFirst({
where: {
requestId: { eq: job.requestId },
projectId: { eq: job.projectId },
},
columns: {
id: true,
},
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/api/src/routes/video.ts` around lines 109 - 116, The log lookup in the
db.query.log.findFirst call at apps/api/src/routes/video.ts (lines 109-116) only
filters by requestId, which can cause ID collisions across different projects or
organizations. To fix this security issue, add projectId or organizationId to
the where clause predicate alongside the requestId filter. Retrieve the
appropriate scoping ID from the job object or request context and include it in
the findFirst query to ensure the log record belongs to the correct project or
organization.

if (log) {
content = [
{
type: "video" as const,
url: buildSignedGatewayVideoLogContentUrl(log.id),
mime_type: job.contentType ?? null,
},
];
}
}

return c.json(
{
id: job.id,
Expand All @@ -107,6 +140,7 @@ video.openapi(getVideoStatus, async (c) => {
completed_at: toUnixTimestamp(job.completedAt),
expires_at: toUnixTimestamp(job.expiresAt),
error: job.error ?? null,
content,
},
200,
);
Expand Down
65 changes: 65 additions & 0 deletions apps/docs/content/features/compliance.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
title: Compliance
description: Restrict routing to providers that meet your compliance requirements (SOC 2, ISO 27001, GDPR, no prompt training, no prompt logging)
icon: BadgeCheck
---

import { Callout } from "fumadocs-ui/components/callout";

# Provider Compliance Policies

Provider compliance policies let you guarantee that requests are only ever routed to providers that meet your organization's regulatory requirements. When a request would be routed to a provider that doesn't meet the policy, the gateway blocks it **before any data leaves the gateway**.

<Callout type="info">
Provider compliance policies are available on the [**Enterprise
plan**](https://llmgateway.io/enterprise) for organization owners and admins.
</Callout>

## Requirements

Enable a policy under **Settings → Compliance** in the dashboard and toggle the requirements you need:

| Requirement | A provider is allowed when… |
| -------------------------- | ----------------------------------- |
| **SOC 2 (Type 2)** | it holds a SOC 2 certification |
| **ISO 27001** | it holds an ISO 27001 certification |
| **SOC 2 or ISO 27001** | it holds either SOC 2 or ISO 27001 |
| **GDPR compliant** | it is GDPR compliant |
| **No training on prompts** | it does not train on API prompts |
| **No prompt logging** | it does not log prompts |

Every requirement is **fail-closed**: a provider passes only if its published data policy explicitly satisfies the requirement. If an attribute is unknown for a provider, that provider is treated as non-compliant.

The settings page shows a live preview of which providers are allowed and which are blocked under the current policy, so you can see the impact before saving.

## Enforcement

When no available provider for a model meets the policy — or a pinned provider is non-compliant — the gateway returns a `403`:

```json
{
"error": {
"message": "This request was blocked by your organization's provider compliance policy. No available provider for deepseek-v3.2 meets the required certifications. Contact your LLMGateway admin to adjust the policy."
}
}
```

This applies to both routing modes:

- **Automatic routing** — non-compliant providers are removed from the candidate set, and the request is blocked if none remain.
- **Pinned providers** — a request such as `deepseek/deepseek-v3.2` is blocked when that specific provider does not meet the policy.

Each block is recorded as a **security event** so administrators can review what was rejected and why.

## Access Control

Only organization **owners** and **admins** can view and change the compliance policy.

## Related

- [Data Retention](/features/data-retention) — control whether request and response payloads are stored.
- [Guardrails](/features/guardrails) — detect and block harmful or sensitive content.

## Get Started

Provider compliance policies are an Enterprise feature. [Contact us](https://llmgateway.io/enterprise) to enable Enterprise for your organization.
35 changes: 33 additions & 2 deletions apps/docs/content/features/video-generation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ LLMGateway currently supports a focused subset of the OpenAI video API.
| `seconds` | number | yes | Duration in seconds. Supported values depend on the model (see below) |
| `size` | string | no | `widthxheight`, limited to the sizes supported by the selected model and provider |
| `audio` | boolean | no | Whether to include audio in the output (default `true`). Only honored when the model supports both audio and silent output |
| `image` | object | no | Optional first frame for image-to-video generation |
| `last_frame` | object | no | Optional ending frame when `image` is provided |
| `image` | object | no | Optional first frame for image-to-video generation (see first/last frame inputs below) |
| `last_frame` | object | no | Optional ending frame when `image` is provided (see first/last frame inputs below) |
| `reference_images` | array | no | One to three provider-specific image inputs |
| `input_reference` | object | no | Alias for one or more `reference_images` |
| `reference_videos` | array | no | One to three reference video HTTPS URLs (Seedance 2.0 only, see below) |
Expand All @@ -56,6 +56,37 @@ LLMGateway currently supports a focused subset of the OpenAI video API.

Requests return `400` when the selected provider cannot serve the requested `size` or `seconds`. Seedance derives `aspect_ratio` from the requested `size` (16:9 for landscape, 9:16 for portrait).

### First/last frame inputs

Frame inputs interpolate a video between a starting frame and an optional ending frame. You provide the first frame as `image` and, optionally, the ending frame as `last_frame`. The gateway tags each one with the correct role for the provider, so you don't set roles yourself.

| Field | Required | Accepted input | Available on |
| ------------ | ------------------ | -------------------------------- | ---------------------------------------------------------------------------------------- |
| `image` | for frame mode | HTTPS URL **or** base64 data URL | **Seedance 2.0** (`bytedance`), Veo 3.1 (`google-vertex`, `avalanche`), `minimax`, `xai` |
| `last_frame` | no (needs `image`) | HTTPS URL **or** base64 data URL | **Seedance 2.0** (`bytedance`), Veo 3.1 (`google-vertex`, `avalanche`) |

#### Rules and limits

- **Seedance scope.** Frame inputs are supported on **Seedance 2.0** and **Seedance 2.0 Fast** (`seedance-2-0`, `seedance-2-0-fast`). Sending `image`/`last_frame` to Seedance 1.5 Pro or any other ByteDance model returns a `400`.
- **`last_frame` requires `image`.** Providing `last_frame` without `image` returns a `400`.
- **Not combinable with references.** First/last frame inputs (`image`, `last_frame`) cannot be combined with reference inputs (`reference_images`, `input_reference`, `reference_videos`, `reference_audios`).

#### Example (Seedance 2.0)

```bash
curl -X POST "https://api.llmgateway.io/v1/videos" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "seedance-2-0",
"prompt": "Morph smoothly from the first frame into the last frame",
"seconds": 5,
"size": "1280x720",
"image": { "image_url": "https://example.com/first-frame.png" },
"last_frame": { "image_url": "https://example.com/last-frame.png" }
}'
```

### Reference-guided generation (Seedance 2.0)

Seedance 2.0 (`seedance-2-0`, `seedance-2-0-fast`) can generate a video that is guided by reference **images**, **videos**, and **audio** — sometimes called omni-reference. You attach references as top-level fields in the same `POST /v1/videos` payload; the gateway forwards each one to the provider tagged with the correct role, so you don't set roles yourself.
Expand Down
96 changes: 84 additions & 12 deletions apps/gateway/src/anthropic/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,52 @@ const anthropicMessageSchema = z.object({
.optional(),
});

const anthropicToolSchema = z.object({
// Standard Anthropic "custom" tools: a name plus a JSON schema describing the
// parameters the model should produce.
const anthropicCustomToolSchema = z.object({
type: z.literal("custom").optional(),
name: z.string(),
description: z.string(),
description: z.string().optional(),
input_schema: z.record(z.unknown()),
cache_control: z
.object({
type: z.enum(["ephemeral"]),
ttl: z.enum(["5m", "1h"]).optional(),
})
.nullish(),
});

// Anthropic server-side tools (e.g. web_search_20250305, code_execution_*).
// These are executed by Anthropic, carry a versioned `type` instead of an
// `input_schema`, and must not be validated as custom tools.
const anthropicServerToolSchema = z.object({
type: z.string(),
Comment on lines +109 to +110

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject custom tools before server-tool parsing

Because this server-tool schema accepts any string type, an Anthropic custom tool such as { type: "custom", name: "..." } that is missing or misspells input_schema no longer fails validation: it matches this branch, then the mapper treats custom as an unsupported server tool and silently drops it. That turns malformed tool requests into normal model calls without tools instead of returning the expected 400, so constrain this schema to real server-tool types or explicitly exclude custom.

Useful? React with 👍 / 👎.

name: z.string(),
max_uses: z.number().optional(),
allowed_domains: z.array(z.string()).optional(),
blocked_domains: z.array(z.string()).optional(),
Comment on lines +113 to +114

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add mutual-exclusion validation for Anthropic server tool domain filters

Line 113 and Line 114 currently permit both allowed_domains and blocked_domains. This should be rejected at schema validation to avoid ambiguous server-tool routing behavior.

Suggested fix
-const anthropicServerToolSchema = z.object({
-	type: z.string(),
-	name: z.string(),
-	max_uses: z.number().optional(),
-	allowed_domains: z.array(z.string()).optional(),
-	blocked_domains: z.array(z.string()).optional(),
-	user_location: z
-		.object({
-			type: z.literal("approximate").optional(),
-			city: z.string().optional(),
-			region: z.string().optional(),
-			country: z.string().optional(),
-			timezone: z.string().optional(),
-		})
-		.optional(),
-	cache_control: z
-		.object({
-			type: z.enum(["ephemeral"]),
-			ttl: z.enum(["5m", "1h"]).optional(),
-		})
-		.nullish(),
-});
+const anthropicServerToolSchema = z
+	.object({
+		type: z.string(),
+		name: z.string(),
+		max_uses: z.number().optional(),
+		allowed_domains: z.array(z.string()).optional(),
+		blocked_domains: z.array(z.string()).optional(),
+		user_location: z
+			.object({
+				type: z.literal("approximate").optional(),
+				city: z.string().optional(),
+				region: z.string().optional(),
+				country: z.string().optional(),
+				timezone: z.string().optional(),
+			})
+			.optional(),
+		cache_control: z
+			.object({
+				type: z.enum(["ephemeral"]),
+				ttl: z.enum(["5m", "1h"]).optional(),
+			})
+			.nullish(),
+	})
+	.superRefine((tool, ctx) => {
+		if (tool.allowed_domains && tool.blocked_domains) {
+			ctx.addIssue({
+				code: z.ZodIssueCode.custom,
+				message:
+					"allowed_domains and blocked_domains are mutually exclusive",
+				path: ["allowed_domains"],
+			});
+		}
+	});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
allowed_domains: z.array(z.string()).optional(),
blocked_domains: z.array(z.string()).optional(),
const anthropicServerToolSchema = z
.object({
type: z.string(),
name: z.string(),
max_uses: z.number().optional(),
allowed_domains: z.array(z.string()).optional(),
blocked_domains: z.array(z.string()).optional(),
user_location: z
.object({
type: z.literal("approximate").optional(),
city: z.string().optional(),
region: z.string().optional(),
country: z.string().optional(),
timezone: z.string().optional(),
})
.optional(),
cache_control: z
.object({
type: z.enum(["ephemeral"]),
ttl: z.enum(["5m", "1h"]).optional(),
})
.nullish(),
})
.superRefine((tool, ctx) => {
if (tool.allowed_domains && tool.blocked_domains) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"allowed_domains and blocked_domains are mutually exclusive",
path: ["allowed_domains"],
});
}
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/gateway/src/anthropic/anthropic.ts` around lines 113 - 114, The schema
currently allows both `allowed_domains` and `blocked_domains` fields to be
optionally set simultaneously, which creates ambiguous behavior for server-tool
routing. Add mutual-exclusion validation to the schema to ensure that only one
of these two fields can be provided at a time. Use Zod's .refine() or
.superRefine() method on the parent schema object to validate that either
`allowed_domains` is set XOR `blocked_domains` is set, but not both. The
validation should reject requests where both fields are populated with values.

user_location: z
.object({
type: z.literal("approximate").optional(),
city: z.string().optional(),
region: z.string().optional(),
country: z.string().optional(),
timezone: z.string().optional(),
})
.optional(),
cache_control: z
.object({
type: z.enum(["ephemeral"]),
ttl: z.enum(["5m", "1h"]).optional(),
})
.nullish(),
});

const anthropicToolSchema = z.union([
anthropicCustomToolSchema,
anthropicServerToolSchema,
]);

const anthropicRequestSchema = z.object({
model: z.string().openapi({
description: "The model to use for completion",
Expand Down Expand Up @@ -522,17 +562,49 @@ anthropic.openapi(messages, async (c) => {
}
}

// Transform tools if provided
// Transform tools if provided. Custom tools map to OpenAI function tools;
// Anthropic server-side tools (e.g. web_search_20250305) carry a versioned
// `type` and no `input_schema`, so they're translated to the internal
// `web_search` tool the chat completions endpoint understands. Server tools
// we can't represent are dropped (with a warning) rather than rejected.
let openaiTools;
if (anthropicRequest.tools) {
openaiTools = anthropicRequest.tools.map((tool) => ({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.input_schema,
},
}));
openaiTools = anthropicRequest.tools
.map((tool) => {
if ("input_schema" in tool) {
return {
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.input_schema,
},
};
}

if (tool.type.startsWith("web_search")) {
return {
type: "web_search",
...(tool.max_uses !== undefined ? { max_uses: tool.max_uses } : {}),
...(tool.user_location
? { user_location: tool.user_location }
: {}),
...(tool.allowed_domains
? { allowed_domains: tool.allowed_domains }
: {}),
...(tool.blocked_domains
? { blocked_domains: tool.blocked_domains }
: {}),
};
}

logger.warn("Dropping unsupported Anthropic server tool", {
type: tool.type,
name: tool.name,
});
return null;
})
.filter((tool): tool is NonNullable<typeof tool> => tool !== null);
}

// Build OpenAI request
Expand All @@ -544,7 +616,7 @@ anthropic.openapi(messages, async (c) => {
stream: anthropicRequest.stream,
};

if (openaiTools) {
if (openaiTools && openaiTools.length > 0) {
openaiRequest.tools = openaiTools;
}

Expand Down
Loading
Loading