|
1 | | -import { verifyTokenFn } from '@/api/tokens_serverFunctions'; |
2 | 1 | import { createFileRoute } from '@tanstack/react-router' |
3 | 2 |
|
4 | 3 | async function handler({ request }) { |
5 | 4 | const url = new URL(request.url); |
6 | 5 |
|
7 | | - const isExemptPath = |
| 6 | + // OAuth/discovery paths that don't require token auth (login flow) |
| 7 | + const isOAuthPath = |
| 8 | + url.pathname.startsWith('/tfe/app/oauth2/') || |
| 9 | + url.pathname.startsWith('/tfe/oauth2/') || |
| 10 | + url.pathname === '/.well-known/terraform.json' || |
| 11 | + url.pathname === '/tfe/api/v2/motd'; |
| 12 | + |
| 13 | + // Upload paths that use signed URLs (no Bearer token) |
| 14 | + const isUploadPath = |
8 | 15 | /^\/tfe\/api\/v2\/state-versions\/[^\/]+\/upload$/.test(url.pathname) || |
9 | 16 | /^\/tfe\/api\/v2\/state-versions\/[^\/]+\/json-upload$/.test(url.pathname); |
10 | 17 |
|
11 | | - if (!isExemptPath) { |
12 | | - try { |
13 | | - const token = request.headers.get('authorization')?.split(' ')[1] |
14 | | - console.log('verifying token', token, request.url) |
15 | | - console.log(request.headers) |
16 | | - const tokenValidation = await verifyTokenFn({data: { token: token}}) |
17 | | - if (!tokenValidation.valid) { |
18 | | - return new Response('Unauthorized', { status: 401 }) |
19 | | - } |
20 | | - } catch (error) { |
21 | | - console.error('Error verifying token', error) |
22 | | - return new Response('Unauthorized', { status: 401 }) |
| 18 | + // OAuth and upload paths: forward directly to public statesman endpoints |
| 19 | + if (isOAuthPath || isUploadPath) { |
| 20 | + const outgoingHeaders = new Headers(request.headers); |
| 21 | + const originalHost = outgoingHeaders.get('host') ?? ''; |
| 22 | + if (originalHost) outgoingHeaders.set('x-forwarded-host', originalHost); |
| 23 | + outgoingHeaders.set('x-forwarded-proto', url.protocol.replace(':', '')); |
| 24 | + if (url.port) outgoingHeaders.set('x-forwarded-port', url.port); |
| 25 | + |
| 26 | + // Drop hop-by-hop headers |
| 27 | + ['host','content-length','connection','keep-alive','proxy-connection','transfer-encoding','upgrade','te','trailer','accept-encoding'] |
| 28 | + .forEach(h => outgoingHeaders.delete(h)); |
| 29 | + |
| 30 | + const response = await fetch(`${process.env.STATESMAN_BACKEND_URL}${url.pathname}${url.search}`, { |
| 31 | + method: request.method, |
| 32 | + headers: outgoingHeaders, |
| 33 | + body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.blob() : undefined |
| 34 | + }); |
| 35 | + |
| 36 | + const headers = new Headers(response.headers); |
| 37 | + headers.delete('Content-Encoding'); |
| 38 | + headers.delete('content-length'); |
| 39 | + headers.delete('transfer-encoding'); |
| 40 | + headers.delete('connection'); |
| 41 | + |
| 42 | + console.log(response.status, request.url, '(direct proxy)'); |
| 43 | + return new Response(response.body, { headers }); |
| 44 | + } |
| 45 | + |
| 46 | + // API paths: verify token service token and use webhook auth to internal routes |
| 47 | + const token = request.headers.get('authorization')?.split(' ')[1] |
| 48 | + if (!token) { |
| 49 | + return new Response('Unauthorized: No token provided', { status: 401 }) |
| 50 | + } |
| 51 | + |
| 52 | + // Verify token against TOKEN SERVICE and extract user context |
| 53 | + let userId, userEmail, orgId; |
| 54 | + try { |
| 55 | + const verifyResponse = await fetch(`${process.env.TOKENS_SERVICE_BACKEND_URL}/api/v1/tokens/verify`, { |
| 56 | + method: 'POST', |
| 57 | + headers: { |
| 58 | + 'Content-Type': 'application/json', |
| 59 | + }, |
| 60 | + body: JSON.stringify({ |
| 61 | + token: token, |
| 62 | + }), |
| 63 | + }); |
| 64 | + |
| 65 | + if (!verifyResponse.ok) { |
| 66 | + console.error('Token verification failed:', verifyResponse.status); |
| 67 | + return new Response('Unauthorized: Invalid token', { status: 401 }) |
| 68 | + } |
| 69 | + |
| 70 | + const tokenInfo = await verifyResponse.json(); |
| 71 | + if (!tokenInfo.valid) { |
| 72 | + return new Response('Unauthorized: Invalid token', { status: 401 }) |
23 | 73 | } |
| 74 | + |
| 75 | + // Extract user info from token service response |
| 76 | + userId = tokenInfo.user_id || tokenInfo.userId || 'anonymous'; |
| 77 | + userEmail = tokenInfo.email || ''; |
| 78 | + orgId = tokenInfo.org_id || tokenInfo.orgId || 'default'; |
| 79 | + |
| 80 | + console.log('Verified token service token for user:', userId, 'org:', orgId); |
| 81 | + } catch (error) { |
| 82 | + console.error('Error verifying token:', error); |
| 83 | + return new Response('Unauthorized: Token verification failed', { status: 401 }) |
24 | 84 | } |
25 | 85 |
|
| 86 | + // Use webhook auth to forward to internal TFE routes |
| 87 | + const webhookSecret = process.env.OPENTACO_ENABLE_INTERNAL_ENDPOINTS; |
| 88 | + if (!webhookSecret) { |
| 89 | + console.error('OPENTACO_ENABLE_INTERNAL_ENDPOINTS not configured'); |
| 90 | + return new Response('Internal configuration error', { status: 500 }); |
| 91 | + } |
26 | 92 |
|
27 | | - // important: we need to set these to allow the statesman backend to return the correct URL to opentofu or terraform clients |
28 | | - const outgoingHeaders = new Headers(request.headers); |
29 | | - const originalHost = outgoingHeaders.get('host') ?? ''; |
| 93 | + const outgoingHeaders = new Headers(); |
| 94 | + outgoingHeaders.set('Authorization', `Bearer ${webhookSecret}`); |
| 95 | + outgoingHeaders.set('X-User-ID', userId); |
| 96 | + outgoingHeaders.set('X-Email', userEmail); |
| 97 | + outgoingHeaders.set('X-Org-ID', orgId); |
| 98 | + |
| 99 | + const originalHost = request.headers.get('host') ?? ''; |
30 | 100 | if (originalHost) outgoingHeaders.set('x-forwarded-host', originalHost); |
31 | 101 | outgoingHeaders.set('x-forwarded-proto', url.protocol.replace(':', '')); |
32 | 102 | if (url.port) outgoingHeaders.set('x-forwarded-port', url.port); |
33 | | - // Let fetch manage these, and drop hop-by-hop headers |
34 | | - ['host','content-length','connection','keep-alive','proxy-connection','transfer-encoding','upgrade','te','trailer','accept-encoding'] |
35 | | - .forEach(h => outgoingHeaders.delete(h)); |
36 | | - |
| 103 | + |
| 104 | + // Copy other relevant headers |
| 105 | + const headersToForward = ['content-type', 'accept', 'user-agent']; |
| 106 | + headersToForward.forEach(h => { |
| 107 | + const value = request.headers.get(h); |
| 108 | + if (value) outgoingHeaders.set(h, value); |
| 109 | + }); |
37 | 110 |
|
38 | | - const response = await fetch(`${process.env.STATESMAN_BACKEND_URL}${url.pathname}${url.search}`, { |
| 111 | + // Forward to internal TFE routes with webhook auth |
| 112 | + const internalPath = url.pathname.replace('/tfe/api/v2', '/internal/tfe/api/v2'); |
| 113 | + const response = await fetch(`${process.env.STATESMAN_BACKEND_URL}${internalPath}${url.search}`, { |
39 | 114 | method: request.method, |
40 | | - headers: request.headers, |
41 | | - body: request.method !== 'GET' ? await request.blob() : undefined |
| 115 | + headers: outgoingHeaders, |
| 116 | + body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.blob() : undefined |
42 | 117 | }); |
43 | 118 |
|
44 | 119 | // important, remove all encoding headers since the fetch already decompresses the gzip |
|
0 commit comments