Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
40 changes: 40 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,7 @@ const updateOrganizationSchema = z.object({
billingTaxId: z.string().optional(),
billingNotes: z.string().optional(),
retentionLevel: z.enum(["retain", "none"]).optional(),
providerCompliancePolicy: providerCompliancePolicySchema.optional(),
autoTopUpEnabled: z.boolean().optional(),
autoTopUpThreshold: z.number().min(5).optional(),
autoTopUpAmount: z
Expand Down Expand Up @@ -444,6 +456,7 @@ organization.openapi(updateOrganization, async (c) => {
billingTaxId,
billingNotes,
retentionLevel,
providerCompliancePolicy,
autoTopUpEnabled,
autoTopUpThreshold,
autoTopUpAmount,
Expand Down Expand Up @@ -491,6 +504,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 +544,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 +611,12 @@ organization.openapi(updateOrganization, async (c) => {
new: retentionLevel,
};
}
if (providerCompliancePolicy !== undefined) {
changes.providerCompliancePolicy = {
old: oldOrg.providerCompliancePolicy,
new: providerCompliancePolicy,
};
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (
autoTopUpEnabled !== undefined &&
autoTopUpEnabled !== oldOrg.autoTopUpEnabled
Expand Down
94 changes: 94 additions & 0 deletions apps/gateway/src/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,100 @@ describe("api", () => {
expect(logs[0].finishReason).toBe("stop");
});

test("/v1/chat/completions blocks providers failing the compliance policy", async () => {
// OpenAI's dataPolicy has promptLogging: true, so blockPromptLogging removes
// it. gpt-4o's only other (azure) mapping is deactivated, leaving no provider.
await db
.update(tables.organization)
.set({
plan: "enterprise",
providerCompliancePolicy: { enabled: true, blockPromptLogging: true },
})
.where(eq(tables.organization.id, "org-id"));

await db.insert(tables.apiKey).values({
id: "token-id-compliance-block",
token: "real-token-compliance-block",
projectId: "project-id",
description: "Test API Key",
createdBy: "user-id",
});

await db.insert(tables.providerKey).values({
id: "provider-key-id-compliance-block",
token: "sk-test-key",
provider: "openai",
organizationId: "org-id",
baseUrl: mockServerUrl,
});

const res = await app.request("/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer real-token-compliance-block",
"x-no-fallback": "true",
},
body: JSON.stringify({
model: "openai/gpt-4o",
messages: [{ role: "user", content: "Hello compliance!" }],
}),
});

expect(res.status).toBe(403);
const json = await res.json();
expect(json.error.message).toContain("provider compliance policy");

const violations = await db.query.guardrailViolation.findMany({
where: { organizationId: { eq: "org-id" } },
});
expect(violations.some((v) => v.category === "provider_compliance")).toBe(
true,
);
});

test("/v1/chat/completions allows providers meeting the compliance policy", async () => {
// OpenAI's dataPolicy has soc2: true, so a requireSoc2 policy lets it through.
await db
.update(tables.organization)
.set({
plan: "enterprise",
providerCompliancePolicy: { enabled: true, requireSoc2: true },
})
.where(eq(tables.organization.id, "org-id"));

await db.insert(tables.apiKey).values({
id: "token-id-compliance-allow",
token: "real-token-compliance-allow",
projectId: "project-id",
description: "Test API Key",
createdBy: "user-id",
});

await db.insert(tables.providerKey).values({
id: "provider-key-id-compliance-allow",
token: "sk-test-key",
provider: "openai",
organizationId: "org-id",
baseUrl: mockServerUrl,
});

const res = await app.request("/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer real-token-compliance-allow",
"x-no-fallback": "true",
},
body: JSON.stringify({
model: "openai/gpt-4o",
messages: [{ role: "user", content: "Hello compliant!" }],
}),
});

expect(res.status).toBe(200);
});

test("/v1/chat/completions rejects unsupported service tiers", async () => {
await db.insert(tables.apiKey).values({
id: "token-id-unsupported-service-tier",
Expand Down
68 changes: 68 additions & 0 deletions apps/gateway/src/chat/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ import {
getProviderDefinition,
getRegionSpecificEnvVarName,
getProviderEnvValue,
isProviderCompliant,
} from "@llmgateway/models";
import {
detectCodingAgentFromReferer,
Expand Down Expand Up @@ -2415,6 +2416,70 @@ chat.openapi(completions, async (c) => {
)
: routingExpandedModelProviders;

// Enterprise provider compliance guardrails: drop providers that do not meet
// the org's required certifications/data policies, and block the request when
// none remain. Applied after every (re)computation of the IAM-filtered arrays.
const compliancePolicy =
organization.plan === "enterprise" &&
organization.providerCompliancePolicy?.enabled
? organization.providerCompliancePolicy
: undefined;

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 Enforce compliance outside chat completions

This policy is only wired into the chat completions router, but other gateway endpoints still send user content directly to providers without any isProviderCompliant check; I checked apps/gateway/src/embeddings/embeddings.ts, apps/gateway/src/speech/speech.ts, apps/gateway/src/moderations/moderations.ts, and apps/gateway/src/videos/videos.ts, and they each load the organization then resolve provider keys independently. For an Enterprise org that enables a policy such as blockPromptLogging, /v1/embeddings or speech/video requests can still reach a non-compliant provider, which contradicts the new guarantee that requests are blocked before data leaves the gateway.

Useful? React with 👍 / 👎.


const filterCompliantProviders = <T extends { providerId: string }>(
list: T[],
): T[] => {
if (!compliancePolicy) {
return list;
}
return list.filter((p) => {
const definition = getProviderDefinition(p.providerId);
return definition
? isProviderCompliant(definition, compliancePolicy)
: false;
});
};

const enforceCompliancePolicy = async () => {
if (!compliancePolicy) {
return;
}
iamFilteredModelProviders = filterCompliantProviders(
iamFilteredModelProviders,
);
expandedIamFilteredModelProviders = filterCompliantProviders(
expandedIamFilteredModelProviders,
);
// A pinned provider (e.g. "deepseek/...") is selected directly rather than
// from the filtered array, so check it explicitly. Auto/unpinned routing
// relies on the emptiness check below.
const pinnedDefinition =
usedProvider && usedProvider !== "llmgateway" && usedProvider !== "custom"
? getProviderDefinition(usedProvider)
: undefined;
const pinnedBlocked =
pinnedDefinition !== undefined &&
!isProviderCompliant(pinnedDefinition, compliancePolicy);
if (iamFilteredModelProviders.length === 0 || pinnedBlocked) {
try {
await logViolation(
project.organizationId,
{
ruleId: "provider_compliance",
ruleName: "Provider compliance policy",
category: "provider_compliance",
action: "block",
},
{ apiKeyId: apiKey.id, model: requestedModel },
);
} catch {
// Silently ignore logging failures
}

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

Don’t silently drop compliance security-event failures.

A 403 can be returned with no provider_compliance event if logViolation fails here, and the catch leaves no diagnostic. At minimum, log the failure so audit gaps are visible.

Suggested fix
-			} catch {
-				// Silently ignore logging failures
+			} catch (error) {
+				logger.error("Failed to log provider compliance violation", {
+					error: toError(error),
+					organizationId: project.organizationId,
+					apiKeyId: apiKey.id,
+					model: requestedModel,
+				});
 			}
📝 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
try {
await logViolation(
project.organizationId,
{
ruleId: "provider_compliance",
ruleName: "Provider compliance policy",
category: "provider_compliance",
action: "block",
},
{ apiKeyId: apiKey.id, model: requestedModel },
);
} catch {
// Silently ignore logging failures
}
try {
await logViolation(
project.organizationId,
{
ruleId: "provider_compliance",
ruleName: "Provider compliance policy",
category: "provider_compliance",
action: "block",
},
{ apiKeyId: apiKey.id, model: requestedModel },
);
} catch (error) {
logger.error("Failed to log provider compliance violation", {
error: toError(error),
organizationId: project.organizationId,
apiKeyId: apiKey.id,
model: requestedModel,
});
}
🤖 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/chat/chat.ts` around lines 2463 - 2476, The catch block for
the logViolation function call in the provider compliance check is silently
ignoring failures without any logging, which makes audit gaps invisible and
difficult to diagnose. Replace the empty catch block (currently just containing
a comment) with actual error logging. Log the caught error to ensure that when
logViolation fails, the failure is recorded and visible in audit logs for
diagnostic purposes.

throw new HTTPException(403, {
message: `This request was blocked by your organization's provider compliance policy. No available provider for ${modelInfo.id} meets the required certifications. Contact your LLMGateway admin to adjust the policy.`,
});
}
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if (isDevPlanRestricted) {
iamFilteredModelProviders = iamFilteredModelProviders.filter(
providerSupportsCachedInput,
Expand All @@ -2428,6 +2493,8 @@ chat.openapi(completions, async (c) => {
}
}

await enforceCompliancePolicy();

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 Defer compliance checks for auto routing

For model: "auto", this check runs before the auto-routing block resolves a real upstream model/provider, so modelInfo.providers is still the synthetic llmgateway provider from llmgatewayModels. Because that provider's policy metadata has certifications/GDPR set to false, enabling common policies like requireSoc2 or requireGdpr filters the only synthetic provider out and returns 403 before auto-routing can pick a compliant provider such as OpenAI/Anthropic. Skip this pre-auto check or apply compliance while selecting auto candidates instead.

Useful? React with 👍 / 👎.


// Validate the custom provider against the database if one was requested
if (requestedProvider === "custom" && customProviderName) {
const customProviderKey = await findCustomProviderKey(
Expand Down Expand Up @@ -2881,6 +2948,7 @@ chat.openapi(completions, async (c) => {
expandedIamFilteredModelProviders =
expandedIamFilteredModelProviders.filter(providerSupportsCachedInput);
}
await enforceCompliancePolicy();
} else if (
(usedProvider === "llmgateway" && usedInternalModel === "custom") ||
usedInternalModel === "custom"
Expand Down
6 changes: 6 additions & 0 deletions apps/gateway/src/lib/rate-limit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ describe("Rate Limiting", () => {
trialEndDate: null,
isTrialActive: false,
retentionLevel: "retain" as const,
providerCompliancePolicy: null,
status: "active" as const,
referralEarnings: "0",
referralBonusEnabled: false,
Expand Down Expand Up @@ -175,6 +176,7 @@ describe("Rate Limiting", () => {
trialEndDate: null,
isTrialActive: false,
retentionLevel: "retain" as const,
providerCompliancePolicy: null,
status: "active" as const,
referralEarnings: "0",
referralBonusEnabled: false,
Expand Down Expand Up @@ -256,6 +258,7 @@ describe("Rate Limiting", () => {
trialEndDate: null,
isTrialActive: false,
retentionLevel: "retain" as const,
providerCompliancePolicy: null,
status: "active" as const,
referralEarnings: "0",
referralBonusEnabled: false,
Expand Down Expand Up @@ -331,6 +334,7 @@ describe("Rate Limiting", () => {
trialEndDate: null,
isTrialActive: false,
retentionLevel: "retain" as const,
providerCompliancePolicy: null,
status: "active" as const,
referralEarnings: "0",
referralBonusEnabled: false,
Expand Down Expand Up @@ -414,6 +418,7 @@ describe("Rate Limiting", () => {
trialEndDate: null,
isTrialActive: false,
retentionLevel: "retain" as const,
providerCompliancePolicy: null,
status: "active" as const,
referralEarnings: "0",
referralBonusEnabled: false,
Expand Down Expand Up @@ -497,6 +502,7 @@ describe("Rate Limiting", () => {
trialEndDate: null,
isTrialActive: false,
retentionLevel: "retain" as const,
providerCompliancePolicy: null,
status: "active" as const,
referralEarnings: "0",
referralBonusEnabled: false,
Expand Down
Loading
Loading