fix(cloud): harden edge gateways, api-server ssrf, supabase fail-closed quota, and web/admin lifecycle
This commit is contained in:
parent
2a009e421a
commit
c68e81e0aa
46 changed files with 2553 additions and 294 deletions
|
|
@ -7,7 +7,8 @@
|
|||
"dev": "next dev --port 3001",
|
||||
"build": "next build",
|
||||
"start": "next start --port 3001",
|
||||
"typecheck": "next typegen && tsc --noEmit"
|
||||
"typecheck": "next typegen && tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "*",
|
||||
|
|
|
|||
|
|
@ -3,21 +3,33 @@
|
|||
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import { createServerClient, type CookieOptions } from '@supabase/ssr'
|
||||
import { resolveAdminCallbackOrigin, safeAdminRedirectPath } from '@/lib/admin-url-safety'
|
||||
|
||||
export async function GET(request: NextRequest): Promise<NextResponse> {
|
||||
const { searchParams, origin } = new URL(request.url)
|
||||
const { searchParams } = new URL(request.url)
|
||||
const origin = resolveAdminCallbackOrigin(
|
||||
request.url,
|
||||
process.env.ADMIN_PUBLIC_ORIGIN ?? process.env.NEXT_PUBLIC_ADMIN_ORIGIN,
|
||||
)
|
||||
const code = searchParams.get('code')
|
||||
const nextPath = safeAdminRedirectPath(searchParams.get('next'))
|
||||
|
||||
if (!code) {
|
||||
return NextResponse.redirect(`${origin}/login?error=no_code`)
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
|
||||
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY?.trim()
|
||||
if (!supabaseUrl || !supabaseAnonKey) {
|
||||
return NextResponse.redirect(`${origin}/login?error=auth_unavailable`)
|
||||
}
|
||||
|
||||
// 쿠키를 수집할 배열
|
||||
const cookiesToSet: Array<{ name: string; value: string; options: CookieOptions }> = []
|
||||
|
||||
const supabase = createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ?? '',
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
|
||||
supabaseUrl,
|
||||
supabaseAnonKey,
|
||||
{
|
||||
cookies: {
|
||||
getAll() {
|
||||
|
|
@ -33,11 +45,11 @@ export async function GET(request: NextRequest): Promise<NextResponse> {
|
|||
const { error } = await supabase.auth.exchangeCodeForSession(code)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(error.message)}`)
|
||||
return NextResponse.redirect(`${origin}/login?error=oauth_callback_failed`)
|
||||
}
|
||||
|
||||
// 세션 교환 성공 후 response 생성 + 수집된 쿠키 적용
|
||||
const response = NextResponse.redirect(`${origin}/`)
|
||||
const response = NextResponse.redirect(`${origin}${nextPath}`)
|
||||
for (const { name, value, options } of cookiesToSet) {
|
||||
response.cookies.set({ name, value, ...options })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,13 +9,14 @@ import GoogleIcon from '@mui/icons-material/Google'
|
|||
import LockOutlinedIcon from '@mui/icons-material/LockOutlined'
|
||||
import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds'
|
||||
import { C, FONT_SANS, FONT_MONO, primaryButtonSx } from '@/lib/console-theme'
|
||||
import { safeAdminRedirectPath } from '@/lib/admin-url-safety'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
|
||||
function LoginForm(): React.ReactElement {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const redirectPath = searchParams.get('redirect') || '/'
|
||||
const redirectPath = safeAdminRedirectPath(searchParams.get('redirect'))
|
||||
|
||||
const [usernameOrEmail, setUsernameOrEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
// apps/admin/src/components/subscription-form.tsx
|
||||
// 구독 생성/수정 공용 폼
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
TextField,
|
||||
|
|
@ -17,6 +17,7 @@ import {
|
|||
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
|
||||
import { d3roPalette, d3roFontMono } from '@d3ro/ui/theme'
|
||||
import { callAdminApi } from '@/lib/admin-api'
|
||||
import { parseOptionalIsoDate } from '@/lib/admin-url-safety'
|
||||
|
||||
type Tier = 'free' | 'pro' | 'pro_plus'
|
||||
type SubStatus = 'active' | 'canceled' | 'past_due' | 'expired'
|
||||
|
|
@ -44,10 +45,24 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript
|
|||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSubmit = async (): Promise<void> => {
|
||||
if (!memo.trim()) return
|
||||
|
||||
const parsedEnd = parseOptionalIsoDate(periodEnd)
|
||||
if (!parsedEnd.ok) {
|
||||
setError(parsedEnd.message)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
setSuccess(false)
|
||||
|
|
@ -60,31 +75,36 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript
|
|||
userId,
|
||||
tier,
|
||||
status,
|
||||
currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined,
|
||||
currentPeriodEnd: parsedEnd.iso,
|
||||
adminNote: adminNote || undefined,
|
||||
memo: memo.trim(),
|
||||
}),
|
||||
})
|
||||
} else {
|
||||
await callAdminApi(`admin-subscriptions?userId=${userId}`, {
|
||||
await callAdminApi(`admin-subscriptions?userId=${encodeURIComponent(userId)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({
|
||||
tier,
|
||||
status,
|
||||
currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined,
|
||||
currentPeriodEnd: parsedEnd.iso,
|
||||
overageCredits,
|
||||
adminNote: adminNote || undefined,
|
||||
memo: memo.trim(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
if (!mountedRef.current) return
|
||||
setSuccess(true)
|
||||
setMemo('')
|
||||
onSuccess()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Operation failed')
|
||||
if (mountedRef.current) {
|
||||
setError(err instanceof Error ? err.message : 'Operation failed')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (mountedRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
70
apps/admin/src/lib/admin-url-safety.ts
Normal file
70
apps/admin/src/lib/admin-url-safety.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
const STATIC_ASSET_EXT_RE =
|
||||
/\.(?:ico|png|jpg|jpeg|gif|svg|webp|woff2?|ttf|eot|css|js|map|txt|xml|webmanifest)$/i
|
||||
|
||||
function hasUnsafeControlOrBackslash(value: string): boolean {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
const code = value.charCodeAt(i)
|
||||
if (code <= 0x1f || code === 0x7f || code === 0x5c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 콘솔 내부 경로만 허용한다.
|
||||
* `//evil.example`, `https://evil.example`, `/\evil.example`, 제어문자는 `/`로 폴백한다.
|
||||
*/
|
||||
export function safeAdminRedirectPath(value: string | null | undefined): string {
|
||||
if (!value || !value.startsWith('/') || value.startsWith('//') || hasUnsafeControlOrBackslash(value)) {
|
||||
return '/'
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(value, 'https://d3ro-admin.local')
|
||||
if (parsed.origin !== 'https://d3ro-admin.local' || parsed.pathname.startsWith('//')) {
|
||||
return '/'
|
||||
}
|
||||
} catch {
|
||||
return '/'
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** 정적 에셋 확장자 경로만 인증 우회 정적 경로로 간주한다. `/api/*`는 절대 면제하지 않는다. */
|
||||
export function isStaticAssetPath(pathname: string): boolean {
|
||||
if (pathname.startsWith('/_next/') || pathname === '/_next') return true
|
||||
if (pathname.startsWith('/static/') || pathname === '/static') return true
|
||||
if (pathname.startsWith('/api/') || pathname === '/api') return false
|
||||
return STATIC_ASSET_EXT_RE.test(pathname)
|
||||
}
|
||||
|
||||
/** 관리자 OAuth 콜백 리다이렉트 기준 origin을 반환한다. 설정값이 유효하면 우선한다. */
|
||||
export function resolveAdminCallbackOrigin(requestUrl: string, configuredOrigin?: string): string {
|
||||
const configured = configuredOrigin?.trim()
|
||||
if (configured) {
|
||||
try {
|
||||
const parsed = new URL(configured)
|
||||
if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
|
||||
return parsed.origin
|
||||
}
|
||||
} catch {
|
||||
// 잘못된 설정값은 요청 URL origin으로 폴백한다.
|
||||
}
|
||||
}
|
||||
return new URL(requestUrl).origin
|
||||
}
|
||||
|
||||
/** 선택적 날짜 입력을 ISO-8601 문자열로 검증·변환한다. */
|
||||
export function parseOptionalIsoDate(
|
||||
raw: string,
|
||||
): { ok: true; iso: string | undefined } | { ok: false; message: string } {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed) {
|
||||
return { ok: true, iso: undefined }
|
||||
}
|
||||
const timestamp = Date.parse(trimmed)
|
||||
if (!Number.isFinite(timestamp)) {
|
||||
return { ok: false, message: '올바른 종료일 형식이 아닙니다.' }
|
||||
}
|
||||
return { ok: true, iso: new Date(timestamp).toISOString() }
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
// D3RO Voice — Industrial Grade Admin Route & Security Guard
|
||||
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import { isStaticAssetPath, safeAdminRedirectPath } from '@/lib/admin-url-safety'
|
||||
import { verifyEdgeSession } from '@/lib/edge-session'
|
||||
|
||||
const PUBLIC_PATHS = [
|
||||
|
|
@ -15,15 +16,15 @@ const PUBLIC_PATHS = [
|
|||
export async function proxy(request: NextRequest): Promise<NextResponse> {
|
||||
const { pathname } = request.nextUrl
|
||||
const isPublic = PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(path + '/'))
|
||||
const isStatic =
|
||||
pathname.startsWith('/_next') || pathname.startsWith('/static') || pathname.includes('.')
|
||||
const isStatic = isStaticAssetPath(pathname)
|
||||
|
||||
const sessionCookie = request.cookies.get('d3ro_admin_session')?.value
|
||||
const isAuthenticated = sessionCookie ? (await verifyEdgeSession(sessionCookie)) !== null : false
|
||||
|
||||
if (!isAuthenticated && !isPublic && !isStatic) {
|
||||
const loginUrl = new URL('/login', request.url)
|
||||
if (pathname !== '/') loginUrl.searchParams.set('redirect', pathname)
|
||||
const safeRedirect = safeAdminRedirectPath(pathname)
|
||||
if (safeRedirect !== '/') loginUrl.searchParams.set('redirect', safeRedirect)
|
||||
const redirectResponse = NextResponse.redirect(loginUrl)
|
||||
addSecurityHeaders(redirectResponse)
|
||||
return redirectResponse
|
||||
|
|
|
|||
123
apps/admin/tests/admin-security.test.ts
Normal file
123
apps/admin/tests/admin-security.test.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { NextRequest } from 'next/server'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
isStaticAssetPath,
|
||||
parseOptionalIsoDate,
|
||||
resolveAdminCallbackOrigin,
|
||||
safeAdminRedirectPath,
|
||||
} from '@/lib/admin-url-safety'
|
||||
|
||||
const mockCreateServerClient = vi.fn()
|
||||
const mockExchangeCodeForSession = vi.fn()
|
||||
|
||||
vi.mock('@supabase/ssr', () => ({
|
||||
createServerClient: (...args: unknown[]) => {
|
||||
mockCreateServerClient(...args)
|
||||
return {
|
||||
auth: {
|
||||
exchangeCodeForSession: (code: string) => mockExchangeCodeForSession(code),
|
||||
},
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Admin 라우트 가드 및 OAuth 콜백 보안', () => {
|
||||
const originalSupabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const originalSupabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
const originalAdminOrigin = process.env.ADMIN_PUBLIC_ORIGIN
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = originalSupabaseUrl
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = originalSupabaseAnonKey
|
||||
process.env.ADMIN_PUBLIC_ORIGIN = originalAdminOrigin
|
||||
})
|
||||
|
||||
it('proxy_점포함동적경로나API경로미인증접근_정적으로우회하지않고로그인으로차단한다', async () => {
|
||||
const { proxy } = await import('@/proxy')
|
||||
|
||||
const dottedUserRoute = new NextRequest('https://admin.chanpaca.net/users/john.doe')
|
||||
const userRes = await proxy(dottedUserRoute)
|
||||
expect(userRes.status).toBe(307)
|
||||
expect(userRes.headers.get('location')).toBe(
|
||||
'https://admin.chanpaca.net/login?redirect=%2Fusers%2Fjohn.doe',
|
||||
)
|
||||
|
||||
const dottedApiRoute = new NextRequest('https://admin.chanpaca.net/api/audit.export')
|
||||
const apiRes = await proxy(dottedApiRoute)
|
||||
expect(apiRes.status).toBe(307)
|
||||
expect(apiRes.headers.get('location')).toBe(
|
||||
'https://admin.chanpaca.net/login?redirect=%2Fapi%2Faudit.export',
|
||||
)
|
||||
|
||||
const staticAsset = new NextRequest('https://admin.chanpaca.net/static/logo.png')
|
||||
const staticRes = await proxy(staticAsset)
|
||||
expect(staticRes.status).toBe(200)
|
||||
expect(isStaticAssetPath('/api/logo.png')).toBe(false)
|
||||
expect(isStaticAssetPath('/_next/static/chunk.js')).toBe(true)
|
||||
})
|
||||
|
||||
it('safeAdminRedirectPath_외부URL이나프로토콜상대경로_루트로폴백한다', () => {
|
||||
expect(safeAdminRedirectPath('https://evil.example/phish')).toBe('/')
|
||||
expect(safeAdminRedirectPath('//evil.example/phish')).toBe('/')
|
||||
expect(safeAdminRedirectPath('/\\evil.example')).toBe('/')
|
||||
expect(safeAdminRedirectPath('/users\r\n')).toBe('/')
|
||||
expect(safeAdminRedirectPath('/users/123?tab=billing')).toBe('/users/123?tab=billing')
|
||||
})
|
||||
|
||||
it('parseOptionalIsoDate_유효하지않은날짜입력_예외없이오류를반환한다', () => {
|
||||
expect(parseOptionalIsoDate('')).toEqual({ ok: true, iso: undefined })
|
||||
expect(parseOptionalIsoDate('2026-12-31')).toEqual({
|
||||
ok: true,
|
||||
iso: '2026-12-31T00:00:00.000Z',
|
||||
})
|
||||
expect(parseOptionalIsoDate('invalid-date-value')).toEqual({
|
||||
ok: false,
|
||||
message: '올바른 종료일 형식이 아닙니다.',
|
||||
})
|
||||
})
|
||||
|
||||
it('authCallback_GET_Supabase환경변수누락시_빈문자클라이언트생성없이실패닫힘으로리다이렉트한다', async () => {
|
||||
delete process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
delete process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('https://admin.chanpaca.net/auth/callback?code=fake-oauth-code')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
expect(mockCreateServerClient).not.toHaveBeenCalled()
|
||||
expect(res.headers.get('location')).toBe('https://admin.chanpaca.net/login?error=auth_unavailable')
|
||||
})
|
||||
|
||||
it('authCallback_GET_세션교환실패시_원시에러노출없이고정코드로리다이렉트한다', async () => {
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'public-anon-example'
|
||||
mockExchangeCodeForSession.mockResolvedValue({
|
||||
error: { message: 'internal error http://10.0.0.5:5432' },
|
||||
})
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('https://admin.chanpaca.net/auth/callback?code=fake-oauth-code')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
const location = res.headers.get('location') ?? ''
|
||||
expect(location).toBe('https://admin.chanpaca.net/login?error=oauth_callback_failed')
|
||||
expect(location).not.toContain('10.0.0.5')
|
||||
})
|
||||
|
||||
it('authCallback_GET_공개origin설정과위험한next파라미터_공개도메인루트로만이동한다', async () => {
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'public-anon-example'
|
||||
process.env.ADMIN_PUBLIC_ORIGIN = 'https://admin.chanpaca.net/ignored-path'
|
||||
mockExchangeCodeForSession.mockResolvedValue({ error: null })
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('http://127.0.0.1:3001/auth/callback?code=ok-code&next=//evil.example')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
expect(res.headers.get('location')).toBe('https://admin.chanpaca.net/')
|
||||
expect(
|
||||
resolveAdminCallbackOrigin('http://127.0.0.1:3001/auth/callback', 'javascript:alert(1)'),
|
||||
).toBe('http://127.0.0.1:3001')
|
||||
})
|
||||
})
|
||||
19
apps/admin/vitest.config.ts
Normal file
19
apps/admin/vitest.config.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import path from 'node:path'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
esbuild: {
|
||||
jsx: 'automatic',
|
||||
},
|
||||
test: {
|
||||
globals: false,
|
||||
environment: 'node',
|
||||
include: ['tests/**/*.test.{ts,tsx}'],
|
||||
testTimeout: 10000,
|
||||
},
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue