chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,114 @@
/**
* @vitest-environment node
*/
import { createMockRequest } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockFlags,
mockDbLimit,
mockCheckInternalApiKey,
mockCheckServerSideUsageLimits,
mockCheckOrgMemberUsageLimit,
} = vi.hoisted(() => ({
mockFlags: { isHosted: true },
mockDbLimit: vi.fn(),
mockCheckInternalApiKey: vi.fn(),
mockCheckServerSideUsageLimits: vi.fn(),
mockCheckOrgMemberUsageLimit: vi.fn(),
}))
vi.mock('@sim/db', () => ({
db: {
select: () => ({ from: () => ({ where: () => ({ limit: mockDbLimit }) }) }),
},
}))
vi.mock('@/lib/billing/calculations/usage-monitor', () => ({
checkServerSideUsageLimits: mockCheckServerSideUsageLimits,
checkOrgMemberUsageLimit: mockCheckOrgMemberUsageLimit,
}))
vi.mock('@/lib/copilot/request/http', () => ({
checkInternalApiKey: mockCheckInternalApiKey,
}))
vi.mock('@/lib/copilot/request/otel', () => ({
withIncomingGoSpan: (
_headers: unknown,
_span: unknown,
_attrs: unknown,
fn: (span: { setAttribute: () => void; setAttributes: () => void }) => unknown
) => fn({ setAttribute: vi.fn(), setAttributes: vi.fn() }),
}))
vi.mock('@/lib/core/config/env-flags', () => ({
get isHosted() {
return mockFlags.isHosted
},
}))
import { POST } from '@/app/api/copilot/api-keys/validate/route'
function request(body: Record<string, unknown>) {
return createMockRequest('POST', body, { 'x-api-key': 'internal' })
}
describe('POST /api/copilot/api-keys/validate — per-member enforcement', () => {
beforeEach(() => {
vi.clearAllMocks()
mockFlags.isHosted = true
mockCheckInternalApiKey.mockReturnValue({ success: true })
mockDbLimit.mockResolvedValue([{ id: 'user-1' }])
mockCheckServerSideUsageLimits.mockResolvedValue({
isExceeded: false,
currentUsage: 0,
limit: 100,
})
mockCheckOrgMemberUsageLimit.mockResolvedValue({
isExceeded: false,
currentUsage: 0,
limit: null,
})
})
it('returns 402 when the pooled/personal limit is exceeded (existing behavior)', async () => {
mockCheckServerSideUsageLimits.mockResolvedValue({
isExceeded: true,
currentUsage: 200,
limit: 100,
})
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(402)
expect(mockCheckOrgMemberUsageLimit).not.toHaveBeenCalled()
})
it('returns 402 when the per-member org-workspace cap is exceeded', async () => {
mockCheckOrgMemberUsageLimit.mockResolvedValue({
isExceeded: true,
currentUsage: 5,
limit: 4,
})
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(402)
expect(mockCheckOrgMemberUsageLimit).toHaveBeenCalledWith('user-1', 'ws-1')
})
it('returns 200 when under both limits', async () => {
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(200)
})
it('rejects with 400 when workspaceId is omitted (contract-required, fail closed)', async () => {
const res = await POST(request({ userId: 'user-1' }))
expect(res.status).toBe(400)
expect(mockCheckOrgMemberUsageLimit).not.toHaveBeenCalled()
})
it('skips the per-member check when not hosted', async () => {
mockFlags.isHosted = false
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(200)
expect(mockCheckOrgMemberUsageLimit).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,144 @@
import { db } from '@sim/db'
import { user } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { validateCopilotApiKeyContract } from '@/lib/api/contracts/copilot'
import { parseRequest, validationErrorResponse } from '@/lib/api/server'
import {
checkOrgMemberUsageLimit,
checkServerSideUsageLimits,
} from '@/lib/billing/calculations/usage-monitor'
import { CopilotValidateOutcome } from '@/lib/copilot/generated/trace-attribute-values-v1'
import { TraceAttr } from '@/lib/copilot/generated/trace-attributes-v1'
import { TraceSpan } from '@/lib/copilot/generated/trace-spans-v1'
import { checkInternalApiKey } from '@/lib/copilot/request/http'
import { withIncomingGoSpan } from '@/lib/copilot/request/otel'
import { isHosted } from '@/lib/core/config/env-flags'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
const logger = createLogger('CopilotApiKeysValidate')
/**
* Incoming-from-Go: extracts traceparent so this handler's work shows up as
* a child of the Go-side `sim.validate_api_key` span in the same trace. If
* there's no traceparent (manual curl / browser), the helper falls back to a
* new root span.
*/
export const POST = withRouteHandler((req: NextRequest) =>
withIncomingGoSpan(
req.headers,
TraceSpan.CopilotAuthValidateApiKey,
{
[TraceAttr.HttpMethod]: 'POST',
[TraceAttr.HttpRoute]: '/api/copilot/api-keys/validate',
},
async (span) => {
try {
const auth = checkInternalApiKey(req)
if (!auth.success) {
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.InternalAuthFailed
)
span.setAttribute(TraceAttr.HttpStatusCode, 401)
return new NextResponse(null, { status: 401 })
}
const parsed = await parseRequest(
validateCopilotApiKeyContract,
req,
{},
{
validationErrorResponse: (error) => {
logger.warn('Invalid validation request', { errors: error.issues })
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.InvalidBody
)
span.setAttribute(TraceAttr.HttpStatusCode, 400)
return validationErrorResponse(error, 'userId is required')
},
invalidJsonResponse: () => {
logger.warn('Invalid validation request: invalid JSON')
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.InvalidBody
)
span.setAttribute(TraceAttr.HttpStatusCode, 400)
return NextResponse.json(
{ error: 'userId is required', details: [] },
{ status: 400 }
)
},
}
)
if (!parsed.success) return parsed.response
const { userId, workspaceId } = parsed.data.body
span.setAttribute(TraceAttr.UserId, userId)
const [existingUser] = await db.select().from(user).where(eq(user.id, userId)).limit(1)
if (!existingUser) {
logger.warn('[API VALIDATION] userId does not exist', { userId })
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.UserNotFound)
span.setAttribute(TraceAttr.HttpStatusCode, 403)
return NextResponse.json({ error: 'User not found' }, { status: 403 })
}
logger.info('[API VALIDATION] Validating usage limit', { userId })
const { isExceeded, currentUsage, limit } = await checkServerSideUsageLimits(userId)
span.setAttributes({
[TraceAttr.BillingUsageCurrent]: currentUsage,
[TraceAttr.BillingUsageLimit]: limit,
[TraceAttr.BillingUsageExceeded]: isExceeded,
})
logger.info('[API VALIDATION] Usage limit validated', {
userId,
currentUsage,
limit,
isExceeded,
})
if (isExceeded) {
logger.info('[API VALIDATION] Usage exceeded', { userId, currentUsage, limit })
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.UsageExceeded)
span.setAttribute(TraceAttr.HttpStatusCode, 402)
return new NextResponse(null, { status: 402 })
}
// Per-member org-workspace cap (hosted-only). Blocks the mothership/copilot
// chat request itself when the user is over their personal credit limit for
// the org that owns this workspace, independent of the pooled org limit.
// workspaceId is contract-required, so the gate can't be silently skipped.
if (isHosted) {
const memberCheck = await checkOrgMemberUsageLimit(userId, workspaceId)
if (memberCheck.isExceeded) {
logger.info('[API VALIDATION] Per-member org usage limit exceeded', {
userId,
workspaceId,
currentUsage: memberCheck.currentUsage,
limit: memberCheck.limit,
})
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.UsageExceeded
)
span.setAttribute(TraceAttr.HttpStatusCode, 402)
return new NextResponse(null, { status: 402 })
}
}
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.Ok)
span.setAttribute(TraceAttr.HttpStatusCode, 200)
return new NextResponse(null, { status: 200 })
} catch (error) {
logger.error('Error validating usage limit', { error })
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.InternalError)
span.setAttribute(TraceAttr.HttpStatusCode, 500)
return NextResponse.json({ error: 'Failed to validate usage' }, { status: 500 })
}
}
)
)