Repository navigation
feat(auth): API key groups with model-level permissions #2673
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
diegosouzapw
merged 2 commits into
diegosouzapw:release/v3.8.3
from
herjarsa:pr-key-groups
May 24, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } | ||
|
|
||
| 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 }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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