Nyk commited on
Commit
97dff67
·
1 Parent(s): 8a6dc1f

fix: remove legacy auth, add login rate limiting, block SSRF metadata, parameterize migration SQL

Browse files
middleware.ts CHANGED
@@ -83,12 +83,6 @@ export function middleware(request: NextRequest) {
83
  return NextResponse.next()
84
  }
85
 
86
- // Backward compat: accept legacy cookie during migration
87
- const legacyCookie = request.cookies.get('mission-control-auth')
88
- if (safeCompare(legacyCookie?.value || '', process.env.AUTH_SECRET || '')) {
89
- return NextResponse.next()
90
- }
91
-
92
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
93
  }
94
 
@@ -97,12 +91,6 @@ export function middleware(request: NextRequest) {
97
  return NextResponse.next()
98
  }
99
 
100
- // Backward compat: accept legacy cookie
101
- const legacyCookie = request.cookies.get('mission-control-auth')
102
- if (safeCompare(legacyCookie?.value || '', process.env.AUTH_SECRET || '')) {
103
- return NextResponse.next()
104
- }
105
-
106
  // Redirect to login
107
  const loginUrl = request.nextUrl.clone()
108
  loginUrl.pathname = '/login'
 
83
  return NextResponse.next()
84
  }
85
 
 
 
 
 
 
 
86
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
87
  }
88
 
 
91
  return NextResponse.next()
92
  }
93
 
 
 
 
 
 
 
94
  // Redirect to login
95
  const loginUrl = request.nextUrl.clone()
96
  loginUrl.pathname = '/login'
src/app/api/auth/login/route.ts CHANGED
@@ -3,8 +3,27 @@ import { authenticateUser, createSession } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
  import { getMcSessionCookieOptions } from '@/lib/session-cookie'
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  export async function POST(request: Request) {
7
  try {
 
 
 
 
 
8
  const { username, password } = await request.json()
9
 
10
  if (!username || !password) {
 
3
  import { logAuditEvent } from '@/lib/db'
4
  import { getMcSessionCookieOptions } from '@/lib/session-cookie'
5
 
6
+ // Rate limiting: 5 attempts per minute per IP
7
+ const loginAttempts = new Map<string, { count: number; resetAt: number }>()
8
+
9
+ function checkRateLimit(ip: string): boolean {
10
+ const now = Date.now()
11
+ const entry = loginAttempts.get(ip)
12
+ if (!entry || now > entry.resetAt) {
13
+ loginAttempts.set(ip, { count: 1, resetAt: now + 60_000 })
14
+ return true
15
+ }
16
+ entry.count++
17
+ return entry.count <= 5
18
+ }
19
+
20
  export async function POST(request: Request) {
21
  try {
22
+ const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'
23
+ if (!checkRateLimit(ip)) {
24
+ return NextResponse.json({ error: 'Too many login attempts. Try again in a minute.' }, { status: 429 })
25
+ }
26
+
27
  const { username, password } = await request.json()
28
 
29
  if (!username || !password) {
src/app/api/gateways/health/route.ts CHANGED
@@ -22,6 +22,20 @@ interface HealthResult {
22
  error?: string
23
  }
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  /**
26
  * POST /api/gateways/health - Server-side health probe for all gateways
27
  * Probes gateways from the server where loopback addresses are reachable.
@@ -33,53 +47,57 @@ export async function POST(request: NextRequest) {
33
  const db = getDatabase()
34
  const gateways = db.prepare("SELECT * FROM gateways ORDER BY is_primary DESC, name ASC").all() as GatewayEntry[]
35
 
36
- const results: HealthResult[] = await Promise.all(
37
- gateways.map(async (gw) => {
38
- const start = Date.now()
39
- try {
40
- const controller = new AbortController()
41
- const timeout = setTimeout(() => controller.abort(), 5000)
 
 
 
42
 
43
- const probeUrl = "http://" + gw.host + ":" + gw.port + "/"
44
- const res = await fetch(probeUrl, {
45
- signal: controller.signal,
46
- })
47
- clearTimeout(timeout)
48
 
49
- const latency = Date.now() - start
50
- const status = res.ok ? "online" : "error"
 
 
51
 
52
- db.prepare(
53
- "UPDATE gateways SET status = ?, latency = ?, last_seen = (unixepoch()), updated_at = (unixepoch()) WHERE id = ?"
54
- ).run(status, latency, gw.id)
55
 
56
- return {
57
- id: gw.id,
58
- name: gw.name,
59
- status: status as "online" | "error",
60
- latency,
61
- agents: [],
62
- sessions_count: 0,
63
- }
64
- } catch (err: any) {
65
- const latency = Date.now() - start
66
 
67
- db.prepare(
68
- "UPDATE gateways SET status = ?, latency = NULL, updated_at = (unixepoch()) WHERE id = ?"
69
- ).run("offline", gw.id)
 
 
 
 
 
 
 
 
 
70
 
71
- return {
72
- id: gw.id,
73
- name: gw.name,
74
- status: "offline" as const,
75
- latency: null,
76
- agents: [],
77
- sessions_count: 0,
78
- error: err.name === "AbortError" ? "timeout" : (err.message || "connection failed"),
79
- }
80
- }
81
- })
82
- )
83
 
84
  return NextResponse.json({ results, probed_at: Date.now() })
85
  }
 
22
  error?: string
23
  }
24
 
25
+ function isBlockedUrl(urlStr: string): boolean {
26
+ try {
27
+ const url = new URL(urlStr)
28
+ const hostname = url.hostname
29
+ // Block link-local / cloud metadata endpoints
30
+ if (hostname.startsWith('169.254.')) return true
31
+ // Block well-known cloud metadata hostnames
32
+ if (hostname === 'metadata.google.internal') return true
33
+ return false
34
+ } catch {
35
+ return true // Block malformed URLs
36
+ }
37
+ }
38
+
39
  /**
40
  * POST /api/gateways/health - Server-side health probe for all gateways
41
  * Probes gateways from the server where loopback addresses are reachable.
 
47
  const db = getDatabase()
48
  const gateways = db.prepare("SELECT * FROM gateways ORDER BY is_primary DESC, name ASC").all() as GatewayEntry[]
49
 
50
+ const results: HealthResult[] = []
51
+
52
+ for (const gw of gateways) {
53
+ const probeUrl = "http://" + gw.host + ":" + gw.port + "/"
54
+
55
+ if (isBlockedUrl(probeUrl)) {
56
+ results.push({ id: gw.id, name: gw.name, status: 'error', latency: null, agents: [], sessions_count: 0, error: 'Blocked URL' })
57
+ continue
58
+ }
59
 
60
+ const start = Date.now()
61
+ try {
62
+ const controller = new AbortController()
63
+ const timeout = setTimeout(() => controller.abort(), 5000)
 
64
 
65
+ const res = await fetch(probeUrl, {
66
+ signal: controller.signal,
67
+ })
68
+ clearTimeout(timeout)
69
 
70
+ const latency = Date.now() - start
71
+ const status = res.ok ? "online" : "error"
 
72
 
73
+ db.prepare(
74
+ "UPDATE gateways SET status = ?, latency = ?, last_seen = (unixepoch()), updated_at = (unixepoch()) WHERE id = ?"
75
+ ).run(status, latency, gw.id)
 
 
 
 
 
 
 
76
 
77
+ results.push({
78
+ id: gw.id,
79
+ name: gw.name,
80
+ status: status as "online" | "error",
81
+ latency,
82
+ agents: [],
83
+ sessions_count: 0,
84
+ })
85
+ } catch (err: any) {
86
+ db.prepare(
87
+ "UPDATE gateways SET status = ?, latency = NULL, updated_at = (unixepoch()) WHERE id = ?"
88
+ ).run("offline", gw.id)
89
 
90
+ results.push({
91
+ id: gw.id,
92
+ name: gw.name,
93
+ status: "offline" as const,
94
+ latency: null,
95
+ agents: [],
96
+ sessions_count: 0,
97
+ error: err.name === "AbortError" ? "timeout" : (err.message || "connection failed"),
98
+ })
99
+ }
100
+ }
 
101
 
102
  return NextResponse.json({ results, probed_at: Date.now() })
103
  }
src/lib/migrations.ts CHANGED
@@ -348,14 +348,14 @@ const migrations: Migration[] = [
348
  String(process.env.MC_DEFAULT_OWNER_GATEWAY || process.env.MC_DEFAULT_GATEWAY_NAME || 'primary').trim() ||
349
  'primary'
350
 
351
- db.exec(`
352
  UPDATE tenants
353
  SET owner_gateway = COALESCE(
354
  (SELECT name FROM gateways ORDER BY is_primary DESC, id ASC LIMIT 1),
355
- '${defaultGatewayName.replace(/'/g, "''")}'
356
  )
357
  WHERE owner_gateway IS NULL OR trim(owner_gateway) = ''
358
- `)
359
 
360
  db.exec(`CREATE INDEX IF NOT EXISTS idx_tenants_owner_gateway ON tenants(owner_gateway)`)
361
  }
 
348
  String(process.env.MC_DEFAULT_OWNER_GATEWAY || process.env.MC_DEFAULT_GATEWAY_NAME || 'primary').trim() ||
349
  'primary'
350
 
351
+ db.prepare(`
352
  UPDATE tenants
353
  SET owner_gateway = COALESCE(
354
  (SELECT name FROM gateways ORDER BY is_primary DESC, id ASC LIMIT 1),
355
+ ?
356
  )
357
  WHERE owner_gateway IS NULL OR trim(owner_gateway) = ''
358
+ `).run(defaultGatewayName)
359
 
360
  db.exec(`CREATE INDEX IF NOT EXISTS idx_tenants_owner_gateway ON tenants(owner_gateway)`)
361
  }