kong-entrypoint.sh49 lines · main
1#!/bin/bash
2# Custom entrypoint for Kong that builds Lua expressions for request-transformer
3# and performs environment variable substitution in the declarative config.
4
5# Build Lua expressions for translating opaque API keys to asymmetric JWTs.
6# When opaque keys are not configured (empty env vars), expressions fall through
7# to legacy-only behavior - just passing apikey as-is.
8#
9# Full expression logic (when opaque keys are configured):
10# 1. If Authorization header exists and is NOT an sb_ key -> pass through (user session JWT)
11# 2. If apikey matches secret key -> set service_role asymmetric JWT internal "API key"
12# 3. If apikey matches publishable key -> set anon asymmetric JWT internal "API key"
13# 4. Fallback: pass apikey as-is (legacy HS256 JWT)
14
15if [ -n "$BRIVEN_SECRET_KEY" ] && [ -n "$BRIVEN_PUBLISHABLE_KEY" ]; then
16 # Opaque keys configured -> full translation expressions
17 export LUA_AUTH_EXPR="\$((headers.authorization ~= nil and headers.authorization:sub(1, 10) ~= 'Bearer sb_' and headers.authorization) or (headers.apikey == '$BRIVEN_SECRET_KEY' and 'Bearer $SERVICE_ROLE_KEY_ASYMMETRIC') or (headers.apikey == '$BRIVEN_PUBLISHABLE_KEY' and 'Bearer $ANON_KEY_ASYMMETRIC') or headers.apikey)"
18
19 # Realtime WebSocket: reads from query_params.apikey (briven-js sends apikey
20 # via query string), outputs to x-api-key header which Realtime checks first.
21 export LUA_RT_WS_EXPR="\$((query_params.apikey == '$BRIVEN_SECRET_KEY' and '$SERVICE_ROLE_KEY_ASYMMETRIC') or (query_params.apikey == '$BRIVEN_PUBLISHABLE_KEY' and '$ANON_KEY_ASYMMETRIC') or query_params.apikey)"
22else
23 # Legacy API keys, not sb_ API keys -> pass apikey through unchanged
24 export LUA_AUTH_EXPR="\$((headers.authorization ~= nil and headers.authorization:sub(1, 10) ~= 'Bearer sb_' and headers.authorization) or headers.apikey)"
25 export LUA_RT_WS_EXPR="\$(query_params.apikey)"
26fi
27
28# Substitute environment variables in the Kong declarative config.
29# Uses awk instead of eval/echo to preserve YAML quoting (eval strips double
30# quotes, breaking "Header: value" patterns that YAML parses as mappings).
31awk '{
32 result = ""
33 rest = $0
34 while (match(rest, /\$[A-Za-z_][A-Za-z_0-9]*/)) {
35 varname = substr(rest, RSTART + 1, RLENGTH - 1)
36 if (varname in ENVIRON) {
37 result = result substr(rest, 1, RSTART - 1) ENVIRON[varname]
38 } else {
39 result = result substr(rest, 1, RSTART + RLENGTH - 1)
40 }
41 rest = substr(rest, RSTART + RLENGTH)
42 }
43 print result rest
44}' /home/kong/temp.yml > "$KONG_DECLARATIVE_CONFIG"
45
46# Remove empty key-auth credentials (unconfigured opaque keys)
47sed -i '/^[[:space:]]*- key:[[:space:]]*$/d' "$KONG_DECLARATIVE_CONFIG"
48
49exec /entrypoint.sh kong docker-start