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
84 changes: 84 additions & 0 deletions open-sse/services/keyGroupAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Key Group Authorization Service
*
* Enforces model-level access control based on API key group membership.
* Used in the request pipeline to check if an API key's groups allow
* access to the requested model.
*
* If the API key is not in any group, all models are allowed (no restriction).
* If the API key IS in a group, model access is determined by permissions:
* - Deny rules override allow rules
* - Patterns support wildcards: "gpt-*", "claude-*", "*" for all
* - Provider-specific rules: "openai/gpt-4"
*/

import { checkKeyModelAccess, getKeyGroupsForApiKey } from "@/lib/localDb";

export interface KeyGroupAuthResult {
/** Whether the request is authorized */
authorized: boolean;
/** Human-readable reason if denied */
reason?: string;
/** Groups that apply to this key */
groups: Array<{ id: string; name: string }>;
}

/**
* Check if an API key has access to a specific model.
* This is the main entry point for the request pipeline.
*
* @param apiKeyId - The API key ID from the auth pipeline
* @param model - The model string (e.g., "gpt-4", "claude-opus-4-7")
* @param provider - Optional provider (e.g., "openai", "anthropic")
* @returns KeyGroupAuthResult
*/
export function authorizeKeyModelAccess(
apiKeyId: string | undefined,
model: string,
provider?: string,
): KeyGroupAuthResult {
if (!apiKeyId) {
// No API key = no restriction (public endpoint)
return { authorized: true, groups: [] };
}

const groups = getKeyGroupsForApiKey(apiKeyId);
if (groups.length === 0) {
// Key not in any group = no restriction
return { authorized: true, groups: [] };
}

const accessCheck = checkKeyModelAccess(apiKeyId, model, provider);

if (accessCheck.allowed) {
return {
authorized: true,
groups: groups.map((g) => ({ id: g.id, name: g.name })),
};
}

const denyReason = accessCheck.deniedBy
? `Model "${model}" is denied by group permission (pattern: ${accessCheck.deniedBy.modelPattern})`
: `Model "${model}" is not in the allowed models for your API key group(s). ` +
`Configure group permissions or contact your administrator.`;

return {
authorized: false,
reason: denyReason,
groups: groups.map((g) => ({ id: g.id, name: g.name })),
};
}

/**
* Get a summary of group memberships for an API key (for dashboard display).
*/
export function getKeyGroupSummary(apiKeyId: string): {
groups: Array<{ id: string; name: string }>;
restricted: boolean;
} {
const groups = getKeyGroupsForApiKey(apiKeyId);
return {
groups: groups.map((g) => ({ id: g.id, name: g.name })),
restricted: groups.length > 0,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,21 @@ interface Combo {
// ── Status helpers ───────────────────────────────────────────────────────────

function StatusTag({ status }: { status: TargetSimulation["status"] }) {
const map: Record<TargetSimulation["status"], { label: string; variant: "success" | "error" | "warning" | "info" }> = {
const map: Record<
TargetSimulation["status"],
{ label: string; variant: "success" | "error" | "warning" | "info" }
> = {
available: { label: "Available", variant: "success" },
no_quota: { label: "No Quota", variant: "error" },
degraded: { label: "Degraded", variant: "warning" },
error: { label: "Error", variant: "error" },
unknown: { label: "Unknown", variant: "info" },
};
return <Badge variant={map[status].variant} size="sm">{map[status].label}</Badge>;
return (
<Badge variant={map[status].variant} size="sm">
{map[status].label}
</Badge>
);
}

// ── Component ────────────────────────────────────────────────────────────────
Expand All @@ -65,7 +72,7 @@ export default function ComboPlaygroundClient() {
fetch("/api/combos")
.then((r) => r.json())
.then((data) => {
const list: Combo[] = Array.isArray(data) ? data : data?.combos ?? data?.data ?? [];
const list: Combo[] = Array.isArray(data) ? data : (data?.combos ?? data?.data ?? []);
setCombos(list);
if (list.length > 0) setSelectedComboId(list[0].id);
})
Expand Down Expand Up @@ -194,8 +201,18 @@ export default function ComboPlaygroundClient() {
{i > 0 && (
<div className="flex justify-center py-1">
<div className="flex flex-col items-center text-text-muted">
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 14l-7 7m0 0l-7-7m7 7V3" />
<svg
className="w-4 h-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 14l-7 7m0 0l-7-7m7 7V3"
/>
</svg>
{result.strategy === "priority" && (
<span className="text-[10px]">fallback</span>
Expand All @@ -213,10 +230,10 @@ export default function ComboPlaygroundClient() {
t.status === "available"
? "border-green-500/30 bg-green-500/5"
: t.status === "error"
? "border-red-500/30 bg-red-500/5"
: t.status === "unknown"
? "border-yellow-500/30 bg-yellow-500/5"
: "border-border bg-surface/50"
? "border-red-500/30 bg-red-500/5"
: t.status === "unknown"
? "border-yellow-500/30 bg-yellow-500/5"
: "border-border bg-surface/50"
}`}
>
<div className="flex items-center justify-between">
Expand All @@ -234,9 +251,7 @@ export default function ComboPlaygroundClient() {
<span className="text-xs text-text-muted">
${t.estimatedCost.toFixed(6)}
</span>
<span className="text-xs text-text-muted">
{t.estimatedLatencyMs}ms
</span>
<span className="text-xs text-text-muted">{t.estimatedLatencyMs}ms</span>
{t.contextWindow && (
<span className="text-xs text-text-muted">
{(t.contextWindow / 1000).toFixed(0)}K ctx
Expand Down Expand Up @@ -301,7 +316,7 @@ export default function ComboPlaygroundClient() {
<Card>
<div className="p-8 text-center">
<p className="text-text-muted">
No combos configured yet.{' '}
No combos configured yet.{" "}
<a href="/dashboard/combos" className="text-primary hover:underline">
Create one first
</a>
Expand Down
64 changes: 64 additions & 0 deletions src/app/api/keys/groups/[id]/keys/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { NextResponse } from "next/server";
import { addKeyToGroup, removeKeyFromGroup, getGroupMembers, getKeyGroup } from "@/lib/localDb";

type RouteParams = { params: Promise<{ id: string }> };

/**
* GET /api/keys/groups/[id]/keys — List API keys in a group
*/
export async function GET(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const group = getKeyGroup(id);
if (!group) return NextResponse.json({ error: "Group not found" }, { status: 404 });
const members = getGroupMembers(id);
return NextResponse.json({ members });
} catch (error) {
return NextResponse.json({ error: "Failed to list members" }, { status: 500 });
}
}

/**
* POST /api/keys/groups/[id]/keys — Add an API key to the group
* Body: { keyId }
*/
export async function POST(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const group = getKeyGroup(id);
if (!group) return NextResponse.json({ error: "Group not found" }, { status: 404 });

const body = await request.json();
if (!body.keyId) {
return NextResponse.json({ error: "keyId is required" }, { status: 400 });
}
const added = addKeyToGroup(body.keyId, id);
if (!added) {
return NextResponse.json({ error: "Failed to add key" }, { status: 500 });
}
return NextResponse.json({ success: true }, { status: 201 });
} catch (error) {
return NextResponse.json({ error: "Failed to add key to group" }, { status: 500 });
}
}

/**
* DELETE /api/keys/groups/[id]/keys?keyId=xxx — Remove an API key from the group
*/
export async function DELETE(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const url = new URL(request.url);
const keyId = url.searchParams.get("keyId");
if (!keyId) {
return NextResponse.json({ error: "keyId query param required" }, { status: 400 });
}
const removed = removeKeyFromGroup(keyId, id);
if (!removed) {
return NextResponse.json({ error: "Key not found in group" }, { status: 404 });
}
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: "Failed to remove key from group" }, { status: 500 });
}
}
66 changes: 66 additions & 0 deletions src/app/api/keys/groups/[id]/permissions/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { NextResponse } from "next/server";
import { addGroupPermission, removeGroupPermission, getGroupPermissions, getKeyGroup } from "@/lib/localDb";

type RouteParams = { params: Promise<{ id: string }> };

/**
* GET /api/keys/groups/[id]/permissions — List permissions for a group
*/
export async function GET(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const group = getKeyGroup(id);
if (!group) return NextResponse.json({ error: "Group not found" }, { status: 404 });

const permissions = getGroupPermissions(id);
return NextResponse.json({ permissions });
} catch (error) {
return NextResponse.json({ error: "Failed to list permissions" }, { status: 500 });
}
}

/**
* POST /api/keys/groups/[id]/permissions — Add a permission rule
* Body: { modelPattern, accessType, provider? }
*/
export async function POST(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const group = getKeyGroup(id);
if (!group) return NextResponse.json({ error: "Group not found" }, { status: 404 });

const body = await request.json();
if (!body.modelPattern || !body.accessType) {
return NextResponse.json({ error: "modelPattern and accessType are required" }, { status: 400 });
}
if (body.accessType !== "allow" && body.accessType !== "deny") {
return NextResponse.json({ error: "accessType must be 'allow' or 'deny'" }, { status: 400 });
}
Comment on lines +33 to +38

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.

medium

The input validation here is performed manually. According to the Repository Style Guide (Rule 8), all inputs should be validated using Zod schemas from src/shared/validation/schemas.ts. This ensures consistent validation logic and better type safety across the API.

References
  1. Always validate inputs with Zod schemas from src/shared/validation/schemas.ts. (link)


const permission = addGroupPermission(id, body.modelPattern, body.accessType, body.provider);
return NextResponse.json({ permission }, { status: 201 });
} catch (error) {
return NextResponse.json({ error: "Failed to add permission" }, { status: 500 });
}
}

/**
* DELETE /api/keys/groups/[id]/permissions?permissionId=xxx — Remove a permission
*/
export async function DELETE(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const url = new URL(request.url);
const permissionId = url.searchParams.get("permissionId");
if (!permissionId) {
return NextResponse.json({ error: "permissionId query param required" }, { status: 400 });
}
const removed = removeGroupPermission(permissionId);
if (!removed) {
return NextResponse.json({ error: "Permission not found" }, { status: 404 });
}
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: "Failed to remove permission" }, { status: 500 });
}
}
68 changes: 68 additions & 0 deletions src/app/api/keys/groups/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { NextResponse } from "next/server";
import {
getKeyGroupWithPermissions,
updateKeyGroup,
deleteKeyGroup,
getGroupMembers,
addGroupPermission,
removeGroupPermission,
addKeyToGroup,
removeKeyFromGroup,
} from "@/lib/localDb";

type RouteParams = { params: Promise<{ id: string }> };

/**
* GET /api/keys/groups/[id] — Get group details with permissions and members
*/
export async function GET(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const group = getKeyGroupWithPermissions(id);
if (!group) {
return NextResponse.json({ error: "Group not found" }, { status: 404 });
}
const members = getGroupMembers(id);
return NextResponse.json({ group, members });
} catch (error) {
return NextResponse.json({ error: "Failed to get group" }, { status: 500 });
}
}

/**
* PUT /api/keys/groups/[id] — Update a group
*/
export async function PUT(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const body = await request.json();
const updates: { name?: string; description?: string; isActive?: boolean } = {};
if (body.name !== undefined) updates.name = body.name;
if (body.description !== undefined) updates.description = body.description;
if (body.isActive !== undefined) updates.isActive = body.isActive;

const group = updateKeyGroup(id, updates);
if (!group) {
return NextResponse.json({ error: "Group not found" }, { status: 404 });
}
return NextResponse.json({ group });
} catch (error) {
return NextResponse.json({ error: "Failed to update group" }, { status: 500 });
}
}

/**
* DELETE /api/keys/groups/[id] — Delete a group
*/
export async function DELETE(request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const deleted = deleteKeyGroup(id);
if (!deleted) {
return NextResponse.json({ error: "Group not found" }, { status: 404 });
}
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: "Failed to delete group" }, { status: 500 });
}
}
Loading