-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender
More file actions
executable file
·418 lines (352 loc) · 13.4 KB
/
render
File metadata and controls
executable file
·418 lines (352 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/env bash
# Render config.yaml -> Caddyfile + docker-compose.yml
set -euo pipefail
cd "$(dirname "$0")"
CONFIG_FILE="${FIREWALL_CONFIG_FILE:-config.yaml}"
[[ -f "$CONFIG_FILE" ]] || {
echo "ERROR: config file not found: $CONFIG_FILE" >&2
exit 1
}
CONFIG_DIR="$(cd "$(dirname "$CONFIG_FILE")" && pwd)"
command -v yq >/dev/null 2>&1 || {
echo "ERROR: yq v4+ is required: https://github.com/mikefarah/yq" >&2
exit 1
}
q() {
yq -r "$1" "$CONFIG_FILE"
}
die() {
echo "ERROR: $*" >&2
exit 1
}
is_valid_name() {
[[ "$1" =~ ^[a-z0-9][a-z0-9_-]*$ ]]
}
env_syntax() {
# Convert ${VAR} to Caddy env syntax {env.VAR}
echo "$1" | sed 's/\${\([^}]*\)}/{env.\1}/g'
}
yq_apply() {
local expr="$1"
local file="$2"
local tmp
tmp="$(mktemp)"
yq -y "$expr" "$file" > "$tmp"
mv "$tmp" "$file"
}
resolve_from_config_dir() {
local path="$1"
if [[ "$path" = /* ]]; then
echo "$path"
elif [[ -f "$path" ]]; then
echo "$path"
elif [[ -f "$CONFIG_DIR/$path" ]]; then
echo "$CONFIG_DIR/$path"
else
echo "$CONFIG_DIR/$path"
fi
}
expand_team_scope() {
# Backward-compat shim: converts team_scope config into enum_overrides-style
# writes directly to the rendered spec, same output as the old apply_team_scope_policy().
local api="$1"
local policy="$2"
local rendered_spec="$3"
local cfg_root=".apis.$api.policies.$policy"
local has_team_scope
has_team_scope="$(q "$cfg_root | has(\"team_scope\")")"
[[ "$has_team_scope" == "true" ]] || return 0
local field
field="$(q "$cfg_root.team_scope.field // \"team_assignee_id\"")"
[[ "$field" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid team scope field '$field' for $api/$policy"
local ids_len
ids_len="$(q "$cfg_root.team_scope.allowed_ids // [] | length")"
(( ids_len > 0 )) || die "team_scope.allowed_ids must be a non-empty list for $api/$policy"
local team_id
while IFS= read -r team_id; do
[[ "$team_id" =~ ^[0-9]+$ ]] || die "team_scope.allowed_ids must contain integers for $api/$policy (got '$team_id')"
done < <(q "$cfg_root.team_scope.allowed_ids[]")
local names_len
names_len="$(q "$cfg_root.team_scope.allowed_names // [] | length")"
if (( names_len > 0 && names_len != ids_len )); then
die "team_scope.allowed_names length must match allowed_ids for $api/$policy"
fi
# AllowedTeamId.enum
yq_apply '.components.schemas.AllowedTeamId.enum = []' "$rendered_spec"
while IFS= read -r team_id; do
yq_apply ".components.schemas.AllowedTeamId.enum += [$team_id]" "$rendered_spec"
done < <(q "$cfg_root.team_scope.allowed_ids[]")
# AllowedTeamId.x-enumNames
yq_apply '.components.schemas.AllowedTeamId["x-enumNames"] = []' "$rendered_spec"
if (( names_len > 0 )); then
local team_name escaped_name
while IFS= read -r team_name; do
escaped_name="${team_name//\\/\\\\}"
escaped_name="${escaped_name//\"/\\\"}"
yq_apply ".components.schemas.AllowedTeamId[\"x-enumNames\"] += [\"$escaped_name\"]" "$rendered_spec"
done < <(q "$cfg_root.team_scope.allowed_names[]")
else
while IFS= read -r team_id; do
yq_apply ".components.schemas.AllowedTeamId[\"x-enumNames\"] += [\"$team_id\"]" "$rendered_spec"
done < <(q "$cfg_root.team_scope.allowed_ids[]")
fi
# TeamFilter*.field.enum
local escaped_field
escaped_field="${field//\\/\\\\}"
escaped_field="${escaped_field//\"/\\\"}"
yq_apply ".components.schemas.TeamFilterEquals.properties.field.enum = [\"$escaped_field\"]" "$rendered_spec"
yq_apply ".components.schemas.TeamFilterIn.properties.field.enum = [\"$escaped_field\"]" "$rendered_spec"
}
apply_enum_overrides() {
# Generic mechanism: reads enum_overrides from config and sets .enum / .x-enumNames
# on any schema path under components.schemas.
#
# Config syntax:
# enum_overrides:
# AllowedTeamId: # schema name
# values: [6979737, 7257201]
# names: [Support, Tickets] # optional
# TeamFilterEquals.properties.field: # dots = path traversal in spec
# values: [team_assignee_id]
#
# Keys with dots are read literally from config (bracket notation),
# then dots become path separators when writing to the spec.
local api="$1"
local policy="$2"
local rendered_spec="$3"
local cfg_root=".apis.$api.policies.$policy"
local has_overrides
has_overrides="$(q "$cfg_root | has(\"enum_overrides\")")"
[[ "$has_overrides" == "true" ]] || return 0
local override_key
while IFS= read -r override_key; do
[[ -n "$override_key" ]] || continue
# Read from config using bracket notation (key may contain dots)
local values_len
values_len="$(q "$cfg_root.enum_overrides[\"$override_key\"].values // [] | length")"
(( values_len > 0 )) || die "enum_overrides[\"$override_key\"].values must be a non-empty list for $api/$policy"
# Convert dotted key to yq path under .components.schemas
local spec_path=".components.schemas.${override_key//\./.}"
# Set .enum -- build the array from config values
yq_apply "$spec_path.enum = []" "$rendered_spec"
local val
while IFS= read -r val; do
# Try to add as number if it looks numeric, else as string
if [[ "$val" =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
yq_apply "$spec_path.enum += [$val]" "$rendered_spec"
else
local escaped_val
escaped_val="${val//\\/\\\\}"
escaped_val="${escaped_val//\"/\\\"}"
yq_apply "$spec_path.enum += [\"$escaped_val\"]" "$rendered_spec"
fi
done < <(q "$cfg_root.enum_overrides[\"$override_key\"].values[]")
# Set .x-enumNames if provided
local names_len
names_len="$(q "$cfg_root.enum_overrides[\"$override_key\"].names // [] | length")"
if (( names_len > 0 )); then
if (( names_len != values_len )); then
die "enum_overrides[\"$override_key\"].names length must match values for $api/$policy"
fi
yq_apply "$spec_path[\"x-enumNames\"] = []" "$rendered_spec"
local name escaped_name
while IFS= read -r name; do
escaped_name="${name//\\/\\\\}"
escaped_name="${escaped_name//\"/\\\"}"
yq_apply "$spec_path[\"x-enumNames\"] += [\"$escaped_name\"]" "$rendered_spec"
done < <(q "$cfg_root.enum_overrides[\"$override_key\"].names[]")
fi
done < <(q "$cfg_root.enum_overrides // {} | keys | .[]")
}
LISTEN="$(q '.listen // ":8282"')"
AUTH_HEADER="$(q '.auth.header // "X-Agent-Token"')"
NETWORK="$(q '.network // "vault"')"
WALLARM_IMAGE="$(q '.wallarm.image // "wallarm/api-firewall:v0.9.5"')"
WALLARM_SERVER_READ_BUFFER_SIZE="$(q '.wallarm.server_read_buffer_size // 65536')"
WALLARM_SERVER_WRITE_BUFFER_SIZE="$(q '.wallarm.server_write_buffer_size // 16384')"
WALLARM_READ_BUFFER_SIZE="$(q '.wallarm.read_buffer_size // 16384')"
mapfile -t AGENTS < <(q '.agents | keys | .[]')
mapfile -t APIS < <(q '.apis | keys | .[]')
[[ ${#AGENTS[@]} -gt 0 ]] || die "No agents defined in $CONFIG_FILE"
[[ ${#APIS[@]} -gt 0 ]] || die "No apis defined in $CONFIG_FILE"
# route records: agent|token|api|policy|spec|upstream
declare -a ROUTES=()
declare -A FW_SPEC_SOURCES=()
declare -A FW_SPECS=()
declare -A FW_UPSTREAMS=()
declare -A FW_RESP_VALIDATION=()
declare -A ROUTE_GUARD=()
GEN_SPEC_DIR=".generated/specs"
for api in "${APIS[@]}"; do
is_valid_name "$api" || die "Invalid API name '$api'"
upstream="$(q ".apis.$api.upstream // \"\"")"
[[ -n "$upstream" ]] || die "API '$api' missing upstream"
done
for agent in "${AGENTS[@]}"; do
is_valid_name "$agent" || die "Invalid agent name '$agent'"
token="$(q ".agents.$agent.token // \"\"")"
[[ -n "$token" ]] || die "Agent '$agent' missing token"
access_count="$(q ".agents.$agent.access | length")"
[[ "$access_count" =~ ^[0-9]+$ ]] || die "Agent '$agent' access must be a list"
(( access_count > 0 )) || die "Agent '$agent' has no access entries"
for ((idx = 0; idx < access_count; idx++)); do
api="$(q ".agents.$agent.access[$idx].api // \"\"")"
policy="$(q ".agents.$agent.access[$idx].policy // \"\"")"
[[ -n "$api" ]] || die "Agent '$agent' access[$idx] missing api"
[[ -n "$policy" ]] || die "Agent '$agent' access[$idx] missing policy"
is_valid_name "$api" || die "Invalid api '$api' in agent '$agent'"
is_valid_name "$policy" || die "Invalid policy '$policy' in agent '$agent'"
api_upstream="$(q ".apis.$api.upstream // \"\"")"
[[ -n "$api_upstream" ]] || die "Agent '$agent' references undefined api '$api'"
policy_exists="$(q ".apis.$api.policies | has(\"$policy\")")"
[[ "$policy_exists" == "true" ]] || die "Agent '$agent' references undefined policy '$policy' on api '$api'"
route_key="$agent|$api"
if [[ -n "${ROUTE_GUARD[$route_key]:-}" ]]; then
die "Duplicate route '$agent/$api'. Keep one policy per agent/api route."
fi
ROUTE_GUARD[$route_key]=1
spec="$(q ".apis.$api.policies.$policy.spec // \"\"")"
ROUTES+=("$agent|$token|$api|$policy|$spec|$api_upstream")
if [[ -n "$spec" ]]; then
spec_src="$(resolve_from_config_dir "$spec")"
[[ -f "$spec_src" ]] || die "Spec file not found for $api/$policy: $spec (resolved: $spec_src)"
fw_key="$api|$policy"
FW_SPEC_SOURCES[$fw_key]="$spec_src"
FW_UPSTREAMS[$fw_key]="$api_upstream"
resp_val="$(q ".apis.$api.policies.$policy.response_validation // \"LOG_ONLY\"")"
case "$resp_val" in
BLOCK|LOG_ONLY|DISABLE) ;;
*) die "Invalid response_validation '$resp_val' for $api/$policy (must be BLOCK, LOG_ONLY, or DISABLE)" ;;
esac
FW_RESP_VALIDATION[$fw_key]="$resp_val"
fi
done
done
mkdir -p "$GEN_SPEC_DIR"
mapfile -t FW_KEYS < <(printf "%s\n" "${!FW_SPEC_SOURCES[@]}" | sort)
for key in "${FW_KEYS[@]}"; do
IFS='|' read -r api policy <<<"$key"
source_spec="${FW_SPEC_SOURCES[$key]}"
rendered_spec="$GEN_SPEC_DIR/${api}-${policy}.yaml"
cp "$source_spec" "$rendered_spec"
expand_team_scope "$api" "$policy" "$rendered_spec"
apply_enum_overrides "$api" "$policy" "$rendered_spec"
FW_SPECS[$key]="$rendered_spec"
done
# Generate Caddyfile
{
cat <<EOF_HEADER
# Auto-generated. Edit $CONFIG_FILE, then run ./render
{
auto_https off
admin off
}
$LISTEN {
EOF_HEADER
for route in "${ROUTES[@]}"; do
IFS='|' read -r agent token api policy spec api_upstream <<<"$route"
matcher="auth_${agent}_${api}"
matcher="$(echo "$matcher" | tr '-' '_' )"
if [[ -n "$spec" ]]; then
backend="fw-${api}-${policy}:8080"
else
backend="$api_upstream"
fi
cat <<EOF_ROUTE
handle_path /$agent/$api/* {
@$matcher header $AUTH_HEADER "$(env_syntax "$token")"
handle @$matcher {
@probe header X-Agent-Firewall-Probe "1"
respond @probe 204
EOF_ROUTE
api_auth="$(q ".apis.$api.auth // \"\"")"
if [[ -n "$api_auth" ]]; then
echo " request_header Authorization \"$(env_syntax "$api_auth")\""
fi
while IFS= read -r key; do
[[ -n "$key" ]] || continue
val="$(q ".apis.$api.auth_query.$key")"
echo " uri query $key $(env_syntax "$val")"
done < <(q ".apis.$api.auth_query // {} | keys | .[]")
while IFS= read -r hdr; do
[[ -n "$hdr" ]] || continue
val="$(q ".apis.$api.headers.\"$hdr\"")"
echo " request_header $hdr \"$(env_syntax "$val")\""
done < <(q ".apis.$api.headers // {} | keys | .[]")
if [[ "$backend" == https://* ]]; then
host="${backend#https://}"
host="${host%%/*}"
cat <<EOF_PROXY
reverse_proxy $backend {
header_up Host $host
}
EOF_PROXY
else
echo " reverse_proxy $backend"
fi
cat <<'EOF_FOOTER'
}
respond "unauthorized" 401
}
EOF_FOOTER
done
echo ""
echo " respond 404"
echo "}"
} > Caddyfile
# Generate docker-compose.yml
{
cat <<'EOF_COMPOSE'
# Auto-generated. Edit source config, then run ./render
services:
router:
image: caddy:2.8.4-alpine
container_name: agent-api-firewall
restart: unless-stopped
ports: ["${VAULT_BIND:-127.0.0.1}:${VAULT_PORT:-8282}:8282"]
volumes: ["./Caddyfile:/etc/caddy/Caddyfile:ro"]
env_file: ["${FIREWALL_ENV_FILE:-.env}"]
EOF_COMPOSE
echo " networks: [$NETWORK]"
mapfile -t FW_KEYS < <(printf "%s\n" "${!FW_SPECS[@]}" | sort)
if (( ${#FW_KEYS[@]} > 0 )); then
echo " depends_on:"
for key in "${FW_KEYS[@]}"; do
IFS='|' read -r api policy <<<"$key"
echo " fw-${api}-${policy}: { condition: service_started }"
done
fi
for key in "${FW_KEYS[@]}"; do
IFS='|' read -r api policy <<<"$key"
spec="${FW_SPECS[$key]}"
upstream="${FW_UPSTREAMS[$key]}"
resp_val="${FW_RESP_VALIDATION[$key]:-LOG_ONLY}"
cat <<EOF_FW
fw-${api}-${policy}:
image: $WALLARM_IMAGE
container_name: agent-api-firewall-fw-${api}-${policy}
restart: unless-stopped
volumes: ["./$spec:/spec.yaml:ro"]
environment:
APIFW_URL: http://0.0.0.0:8080
APIFW_API_SPECS: /spec.yaml
APIFW_SERVER_URL: $upstream
APIFW_SERVER_READ_BUFFER_SIZE: "$WALLARM_SERVER_READ_BUFFER_SIZE"
APIFW_SERVER_WRITE_BUFFER_SIZE: "$WALLARM_SERVER_WRITE_BUFFER_SIZE"
APIFW_READ_BUFFER_SIZE: "$WALLARM_READ_BUFFER_SIZE"
APIFW_REQUEST_VALIDATION: BLOCK
APIFW_RESPONSE_VALIDATION: $resp_val
APIFW_CUSTOM_BLOCK_STATUS_CODE: "403"
APIFW_LOG_FORMAT: JSON
APIFW_LOG_LEVEL: INFO
networks: [$NETWORK]
EOF_FW
done
cat <<EOF_NET
networks:
$NETWORK:
EOF_NET
} > docker-compose.yml
echo "OK: generated Caddyfile + docker-compose.yml"
echo " routes: ${#ROUTES[@]}"
echo " firewall services: ${#FW_SPECS[@]}"