Repository navigation
Expand file tree
/
Copy pathentrypoint.sh
More file actions
1859 lines (1740 loc) · 85.9 KB
/
Copy pathentrypoint.sh
File metadata and controls
1859 lines (1740 loc) · 85.9 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
set -e
configure_output_routing() {
if [ "${AWF_CAPTURE_COMMAND_OUTPUT:-}" = "1" ]; then
# Preserve the container streams for command bytes and keep AWF setup
# diagnostics out of both captured streams.
exec 3>&1 4>&2
exec >/dev/null 2>&1
return
fi
if [ "${AWF_COMMAND_STDOUT_ONLY:-}" != "1" ]; then
return
fi
# Keep entrypoint diagnostics off the command's stdout. File descriptor 3
# preserves the original stdout exclusively for the user command.
exec 3>&1
exec 1>&2
}
run_command_with_stdout() {
if [ "${AWF_CAPTURE_COMMAND_OUTPUT:-}" = "1" ]; then
"$@" >&3 2>&4 3>&- 4>&-
elif [ "${AWF_COMMAND_STDOUT_ONLY:-}" = "1" ]; then
"$@" >&3 3>&-
else
"$@"
fi
}
print_banner() {
echo "[entrypoint] Agentic Workflow Firewall - Agent Container"
echo "[entrypoint] =================================="
}
setup_user_identity() {
# Adjust awfuser UID/GID to match host user at runtime
# This ensures file ownership is correct regardless of whether using GHCR images or local builds
HOST_UID=${AWF_USER_UID:-$(id -u awfuser)}
HOST_GID=${AWF_USER_GID:-$(id -g awfuser)}
CURRENT_UID=$(id -u awfuser)
CURRENT_GID=$(id -g awfuser)
# Validate UID/GID values to prevent security issues
if ! [[ "$HOST_UID" =~ ^[0-9]+$ ]]; then
echo "[entrypoint][ERROR] Invalid AWF_USER_UID: must be numeric"
exit 1
fi
if ! [[ "$HOST_GID" =~ ^[0-9]+$ ]]; then
echo "[entrypoint][ERROR] Invalid AWF_USER_GID: must be numeric"
exit 1
fi
# Prevent setting UID/GID to 0 (root) which defeats the privilege drop
if [ "$HOST_UID" -eq 0 ]; then
echo "[entrypoint][ERROR] Invalid AWF_USER_UID: cannot be 0 (root)"
exit 1
fi
if [ "$HOST_GID" -eq 0 ]; then
echo "[entrypoint][ERROR] Invalid AWF_USER_GID: cannot be 0 (root)"
exit 1
fi
if [ "$CURRENT_UID" != "$HOST_UID" ] || [ "$CURRENT_GID" != "$HOST_GID" ]; then
echo "[entrypoint] Adjusting awfuser UID:GID from $CURRENT_UID:$CURRENT_GID to $HOST_UID:$HOST_GID"
# Check if target GID is already in use by another group
EXISTING_GROUP=$(getent group "$HOST_GID" 2>/dev/null | cut -d: -f1 || true)
if [ -n "$EXISTING_GROUP" ] && [ "$EXISTING_GROUP" != "awfuser" ]; then
echo "[entrypoint][WARN] Target GID $HOST_GID is already used by group '$EXISTING_GROUP'. Skipping GID change."
else
# Change GID first (must be done before UID change)
if ! groupmod -g "$HOST_GID" awfuser 2>/dev/null; then
echo "[entrypoint][ERROR] Failed to change GID of awfuser to $HOST_GID"
exit 1
fi
fi
# Check if target UID is already in use by another user
EXISTING_USER=$(getent passwd "$HOST_UID" 2>/dev/null | cut -d: -f1 || true)
if [ -n "$EXISTING_USER" ] && [ "$EXISTING_USER" != "awfuser" ]; then
echo "[entrypoint][WARN] Target UID $HOST_UID is already used by user '$EXISTING_USER'. Skipping UID change."
else
# Change UID
if ! usermod -u "$HOST_UID" awfuser 2>/dev/null; then
echo "[entrypoint][ERROR] Failed to change UID of awfuser to $HOST_UID"
exit 1
fi
fi
# Fix ownership of awfuser's home directory
chown -R awfuser:awfuser /home/awfuser 2>/dev/null || true
echo "[entrypoint] UID/GID adjustment complete"
fi
}
configure_dns() {
# Configure DNS to use only Docker's embedded DNS (127.0.0.11)
# Docker embedded DNS handles all name resolution:
# - Container names (e.g., squid-proxy) → resolved directly
# - External domains → forwarded to upstream DNS servers configured via docker-compose dns: field
# No external DNS servers are listed in resolv.conf to prevent DNS-based data exfiltration
echo "[entrypoint] Configuring DNS..."
if [ -f /etc/resolv.conf ]; then
# Backup original resolv.conf
cp /etc/resolv.conf /etc/resolv.conf.orig
if [ "$AWF_DOH_ENABLED" = "true" ] && [ -n "$AWF_DOH_PROXY_IP" ]; then
# DNS-over-HTTPS mode: use DoH proxy as the DNS resolver
{
echo "# Generated by awf entrypoint (DNS-over-HTTPS mode)"
echo "# Docker embedded DNS for service name resolution (squid-proxy, etc.)"
echo "nameserver 127.0.0.11"
echo "# DNS-over-HTTPS proxy for encrypted internet domain resolution"
echo "nameserver $AWF_DOH_PROXY_IP"
echo "options ndots:0"
} > /etc/resolv.conf
echo "[entrypoint] DNS configured with Docker embedded DNS (127.0.0.11) and DoH proxy ($AWF_DOH_PROXY_IP)"
else
# Simplified security model: Docker embedded DNS only
# Docker embedded DNS at 127.0.0.11 handles all resolution
# It forwards to upstream servers configured via docker-compose dns: field
# No external DNS servers listed to prevent DNS-based data exfiltration
{
echo "# Generated by awf entrypoint"
echo "# Docker embedded DNS handles all resolution (forwards to upstream via docker-compose dns: config)"
echo "nameserver 127.0.0.11"
echo "options ndots:0"
} > /etc/resolv.conf
echo "[entrypoint] DNS configured with Docker embedded DNS (127.0.0.11) only"
fi
fi
}
configure_ssl_certs() {
# Update CA certificates if SSL Bump is enabled
# The CA certificate is mounted at /usr/local/share/ca-certificates/awf-ca.crt
if [ "${AWF_SSL_BUMP_ENABLED}" = "true" ]; then
echo "[entrypoint] SSL Bump mode detected - updating CA certificates..."
if [ -f /usr/local/share/ca-certificates/awf-ca.crt ]; then
update-ca-certificates 2>/dev/null
AWF_CA_PATH="/usr/local/share/ca-certificates/awf-ca.crt"
# Set NODE_EXTRA_CA_CERTS so Node.js tools (Yarn 4, Corepack, npm) trust the AWF CA.
# Node.js uses its own CA bundle, not the system CA store updated by update-ca-certificates.
export NODE_EXTRA_CA_CERTS="$AWF_CA_PATH"
# SSL_CERT_FILE is respected by curl, git, Python requests, Ruby, and most
# OpenSSL-based tools that don't use the system CA store updated above.
export SSL_CERT_FILE="$AWF_CA_PATH"
export REQUESTS_CA_BUNDLE="$AWF_CA_PATH"
echo "[entrypoint] CA certificates updated for SSL Bump"
echo "[entrypoint] NODE_EXTRA_CA_CERTS set to $NODE_EXTRA_CA_CERTS"
echo "[entrypoint] ⚠️ WARNING: HTTPS traffic will be intercepted for URL inspection"
else
echo "[entrypoint][WARN] SSL Bump enabled but CA certificate not found"
fi
fi
}
wait_for_iptables() {
# Wait for iptables init container to complete setup
# The awf-iptables-init container shares our network namespace and runs
# setup-iptables.sh, then writes a ready signal file. This ensures the agent
# container NEVER needs NET_ADMIN capability.
#
# In network-isolation (topology) mode there is no iptables-init container —
# egress is enforced by Docker network topology — so skip the handshake.
# Likewise for runtimes whose network stack can't be governed by host-netns
# iptables (e.g. gVisor's isolated netstack): AWF_SKIP_IPTABLES_INIT is set and
# egress relies on the HTTP_PROXY/HTTPS_PROXY env vars instead.
if [ "${AWF_NETWORK_ISOLATION:-}" = "1" ] || [ "${AWF_SKIP_IPTABLES_INIT:-}" = "1" ]; then
echo "[entrypoint] iptables-init skipped (proxy-based egress): skipping init container wait"
else
echo "[entrypoint] Waiting for iptables initialization from init container..."
INIT_TIMEOUT=300 # 300 * 0.1s = 30 seconds
INIT_ELAPSED=0
INIT_SIGNAL_DIR="${AWF_INIT_SIGNAL_DIR:-/run/awf-init}"
LEGACY_INIT_SIGNAL_DIR="/tmp/awf-init"
while [ ! -f "${INIT_SIGNAL_DIR}/ready" ] && [ ! -f "${LEGACY_INIT_SIGNAL_DIR}/ready" ]; do
if [ "$INIT_ELAPSED" -ge "$INIT_TIMEOUT" ]; then
echo "[entrypoint][ERROR] Timed out waiting for iptables init container after 30s"
if [ -f "${INIT_SIGNAL_DIR}/output.log" ]; then
echo "[entrypoint] Init container output:"
cat "${INIT_SIGNAL_DIR}/output.log"
elif [ -f "${LEGACY_INIT_SIGNAL_DIR}/output.log" ]; then
echo "[entrypoint] Init container output:"
cat "${LEGACY_INIT_SIGNAL_DIR}/output.log"
else
echo "[entrypoint] No init container output log found"
fi
exit 1
fi
sleep 0.1
INIT_ELAPSED=$((INIT_ELAPSED + 1))
done
echo "[entrypoint] iptables initialization complete"
fi
}
check_service_health() {
# Run API proxy health checks (verifies credential isolation and connectivity)
# This must run AFTER iptables setup (which allows api-proxy traffic) but BEFORE user command
# If health check fails, the script exits with non-zero code and prevents agent from running
/usr/local/bin/api-proxy-health-check.sh || exit 1
# Run CLI proxy liveness check (fail-fast when DIFC proxy / Docker is unavailable)
# This prevents unbounded in-agent retries on connection-refused errors (e.g. when
# awmg-cli-proxy is not running). Must run BEFORE the user command so the agent
# never starts into a broken proxy environment.
if [ -n "$AWF_CLI_PROXY_URL" ]; then
echo "[entrypoint] Checking CLI proxy liveness at $AWF_CLI_PROXY_URL..."
# Extract host and port from the URL (format: http://IP:PORT)
CLI_PROXY_HOST=$(echo "$AWF_CLI_PROXY_URL" | sed -E 's|^https?://([^:/]+).*|\1|')
CLI_PROXY_PORT=$(echo "$AWF_CLI_PROXY_URL" | sed -E 's|^https?://[^:]+:([0-9]+).*|\1|')
if timeout 5 bash -c "cat < /dev/null > /dev/tcp/${CLI_PROXY_HOST}/${CLI_PROXY_PORT}" 2>/dev/null; then
echo "[entrypoint] ✓ CLI proxy is reachable at $AWF_CLI_PROXY_URL"
else
echo "[entrypoint][ERROR] CLI proxy at $AWF_CLI_PROXY_URL is not reachable"
echo "[entrypoint][ERROR] The DIFC proxy (awmg-cli-proxy) may be unavailable or Docker may be down"
echo "[entrypoint][ERROR] Failing fast to prevent unbounded in-agent retries on connection-refused errors"
exit 1
fi
fi
}
configure_claude_api_key() {
# Configure Claude Code API key helper
# This ensures the apiKeyHelper is properly configured in the config files
# The config files must exist before Claude Code starts for authentication to work
# We write to BOTH paths for compatibility:
# - ~/.claude.json (legacy path, used by older Claude Code versions)
# - ~/.claude/settings.json (used by Claude Code v2.1.81+)
# In chroot mode, we write to /host$HOME/... so files are accessible after chroot
if [ -n "$CLAUDE_CODE_API_KEY_HELPER" ]; then
echo "[entrypoint] Claude Code API key helper configured: $CLAUDE_CODE_API_KEY_HELPER"
# In chroot mode, write to /host path so files are accessible after chroot transition
if [ "${AWF_CHROOT_ENABLED}" = "true" ]; then
LEGACY_CONFIG_FILE="/host$HOME/.claude.json"
SETTINGS_DIR="/host$HOME/.claude"
else
LEGACY_CONFIG_FILE="$HOME/.claude.json"
SETTINGS_DIR="$HOME/.claude"
fi
SETTINGS_FILE="$SETTINGS_DIR/settings.json"
# Helper: write or validate apiKeyHelper in a config file
write_api_key_helper() {
local config_file="$1"
local label="$2"
if [ -f "$config_file" ]; then
if grep -q '"apiKeyHelper"' "$config_file"; then
CONFIGURED_HELPER=$(grep -o '"apiKeyHelper":"[^"]*"' "$config_file" | cut -d'"' -f4)
if [ "$CONFIGURED_HELPER" != "$CLAUDE_CODE_API_KEY_HELPER" ]; then
# Overwrite stale path (e.g. a previous run's chroot-adjusted path)
echo "[entrypoint] Updating apiKeyHelper in $label (was: $CONFIGURED_HELPER)"
if AWF_CONFIG_FILE="$config_file" AWF_KEY_HELPER="$CLAUDE_CODE_API_KEY_HELPER" \
node -e "
const fs = require('fs');
const f = process.env.AWF_CONFIG_FILE;
const obj = JSON.parse(fs.readFileSync(f, 'utf8'));
obj.apiKeyHelper = process.env.AWF_KEY_HELPER;
fs.writeFileSync(f, JSON.stringify(obj) + '\n');
" 2>/dev/null; then
chmod 666 "$config_file"
echo "[entrypoint] ✓ Updated apiKeyHelper in $label"
else
echo "{\"apiKeyHelper\":\"$CLAUDE_CODE_API_KEY_HELPER\"}" > "$config_file"
chmod 666 "$config_file"
echo "[entrypoint] ✓ Wrote apiKeyHelper to $label (overwrite fallback)"
fi
else
echo "[entrypoint] ✓ $label apiKeyHelper validated"
fi
else
echo "[entrypoint] $label exists but missing apiKeyHelper, merging..."
# Use node to safely add apiKeyHelper to existing JSON without losing other fields
# (e.g. hasCompletedOnboarding, session tokens, user preferences)
if AWF_CONFIG_FILE="$config_file" AWF_KEY_HELPER="$CLAUDE_CODE_API_KEY_HELPER" \
node -e "
const fs = require('fs');
const file = process.env.AWF_CONFIG_FILE;
const helper = process.env.AWF_KEY_HELPER;
let obj = {};
try { obj = JSON.parse(fs.readFileSync(file, 'utf8')); } catch(e) {}
obj.apiKeyHelper = helper;
fs.writeFileSync(file, JSON.stringify(obj) + '\n');
" 2>/dev/null; then
chmod 666 "$config_file"
echo "[entrypoint] ✓ Merged apiKeyHelper into $label"
else
# Fallback if node is unavailable or the file is not valid JSON
echo "{\"apiKeyHelper\":\"$CLAUDE_CODE_API_KEY_HELPER\"}" > "$config_file"
chmod 666 "$config_file"
echo "[entrypoint] ✓ Wrote apiKeyHelper to $label (overwrite fallback)"
fi
fi
else
echo "[entrypoint] Creating $label with apiKeyHelper..."
echo "{\"apiKeyHelper\":\"$CLAUDE_CODE_API_KEY_HELPER\"}" > "$config_file"
chmod 666 "$config_file"
echo "[entrypoint] ✓ Created $label with apiKeyHelper: $CLAUDE_CODE_API_KEY_HELPER"
fi
}
# Write to legacy path (~/.claude.json)
write_api_key_helper "$LEGACY_CONFIG_FILE" "$LEGACY_CONFIG_FILE"
# Write to settings path (~/.claude/settings.json) for Claude Code v2.1.81+
mkdir -p "$SETTINGS_DIR"
chmod 777 "$SETTINGS_DIR" 2>/dev/null || true
write_api_key_helper "$SETTINGS_FILE" "$SETTINGS_FILE"
fi
}
configure_jvm_proxy() {
# Pre-seed JVM build tool proxy configuration
# Java build tools (Maven, Gradle, sbt) do not honor HTTP_PROXY/HTTPS_PROXY env vars
# and need explicit proxy configuration files
if [ -n "$HTTP_PROXY" ]; then
# Determine proxy host and port for JVM tools.
# Prefer SQUID_PROXY_HOST/SQUID_PROXY_PORT (set by docker-manager.ts) over parsing HTTP_PROXY,
# since HTTP_PROXY parsing is brittle (doesn't handle https://, credentials, IPv6, etc.)
if [ -n "$SQUID_PROXY_HOST" ] && [ -n "$SQUID_PROXY_PORT" ]; then
PROXY_HOST="$SQUID_PROXY_HOST"
PROXY_PORT="$SQUID_PROXY_PORT"
else
# Fallback: extract from HTTP_PROXY (format: http://HOST:PORT)
PROXY_HOST="${HTTP_PROXY#http://}"
PROXY_HOST="${PROXY_HOST#https://}"
PROXY_HOST="${PROXY_HOST#*@}" # strip credentials if present
PROXY_PORT="${PROXY_HOST##*:}" # extract port after last colon
PROXY_HOST="${PROXY_HOST%:*}" # strip port
PROXY_PORT="${PROXY_PORT:-3128}" # default port
fi
# Determine path prefix for config files (chroot-aware, same pattern as .claude.json)
if [ "${AWF_CHROOT_ENABLED}" = "true" ]; then
JVM_HOME_PREFIX="/host${HOME}"
else
JVM_HOME_PREFIX="${HOME}"
fi
echo "[entrypoint] Pre-seeding JVM build tool proxy configuration (${PROXY_HOST}:${PROXY_PORT})..."
# Maven proxy config (~/.m2/settings.xml)
# Only create if the file does not already exist, to avoid clobbering user-provided settings
if ! mkdir -p "${JVM_HOME_PREFIX}/.m2" 2>/dev/null || [ ! -w "${JVM_HOME_PREFIX}/.m2" ]; then
echo "[entrypoint] ⚠ Cannot write ${JVM_HOME_PREFIX}/.m2 (read-only home); skipping Maven proxy config"
elif [ ! -f "${JVM_HOME_PREFIX}/.m2/settings.xml" ]; then
if cat > "${JVM_HOME_PREFIX}/.m2/settings.xml" << MAVEN_EOF
<settings>
<proxies>
<proxy>
<id>awf-http</id>
<active>true</active>
<protocol>http</protocol>
<host>${PROXY_HOST}</host>
<port>${PROXY_PORT}</port>
</proxy>
<proxy>
<id>awf-https</id>
<active>true</active>
<protocol>https</protocol>
<host>${PROXY_HOST}</host>
<port>${PROXY_PORT}</port>
</proxy>
</proxies>
</settings>
MAVEN_EOF
then
chown awfuser:awfuser "${JVM_HOME_PREFIX}/.m2/settings.xml" 2>/dev/null || true
echo "[entrypoint] ✓ Created Maven proxy config (${JVM_HOME_PREFIX}/.m2/settings.xml)"
else
echo "[entrypoint] ⚠ Failed to write ${JVM_HOME_PREFIX}/.m2/settings.xml; skipping Maven proxy config"
fi
else
echo "[entrypoint] ✓ Maven settings.xml already exists, skipping proxy config creation"
fi
# Gradle proxy config (~/.gradle/gradle.properties)
# Only create if the file does not already exist, to avoid clobbering user-provided settings
# (e.g., org.gradle.jvmargs, build cache settings, private repo credentials)
if ! mkdir -p "${JVM_HOME_PREFIX}/.gradle" 2>/dev/null || [ ! -w "${JVM_HOME_PREFIX}/.gradle" ]; then
echo "[entrypoint] ⚠ Cannot write ${JVM_HOME_PREFIX}/.gradle (read-only home); skipping Gradle proxy config"
elif [ ! -f "${JVM_HOME_PREFIX}/.gradle/gradle.properties" ]; then
if cat > "${JVM_HOME_PREFIX}/.gradle/gradle.properties" << GRADLE_EOF
systemProp.http.proxyHost=${PROXY_HOST}
systemProp.http.proxyPort=${PROXY_PORT}
systemProp.https.proxyHost=${PROXY_HOST}
systemProp.https.proxyPort=${PROXY_PORT}
GRADLE_EOF
then
chown awfuser:awfuser "${JVM_HOME_PREFIX}/.gradle/gradle.properties" 2>/dev/null || true
echo "[entrypoint] ✓ Created Gradle proxy config (${JVM_HOME_PREFIX}/.gradle/gradle.properties)"
else
echo "[entrypoint] ⚠ Failed to write ${JVM_HOME_PREFIX}/.gradle/gradle.properties; skipping Gradle proxy config"
fi
else
echo "[entrypoint] ✓ Gradle gradle.properties already exists, skipping proxy config creation"
fi
# sbt/JVM proxy config via JAVA_TOOL_OPTIONS
# This covers sbt and any JVM tool that reads standard system properties
# Also set nonProxyHosts from NO_PROXY to prevent JVM tools from proxying localhost traffic
NON_PROXY_RAW="${NO_PROXY:-${no_proxy:-}}"
JVM_PROXY_FLAGS="-Dhttp.proxyHost=${PROXY_HOST} -Dhttp.proxyPort=${PROXY_PORT} -Dhttps.proxyHost=${PROXY_HOST} -Dhttps.proxyPort=${PROXY_PORT}"
if [ -n "$NON_PROXY_RAW" ]; then
# Convert comma-separated NO_PROXY to Java's pipe-separated nonProxyHosts format
NON_PROXY_HOSTS=$(printf '%s' "$NON_PROXY_RAW" | tr ',' '|' | tr -d ' ')
JVM_PROXY_FLAGS="${JVM_PROXY_FLAGS} -Dhttp.nonProxyHosts=${NON_PROXY_HOSTS} -Dhttps.nonProxyHosts=${NON_PROXY_HOSTS}"
echo "[entrypoint] ✓ Set JAVA_TOOL_OPTIONS with proxy and nonProxyHosts flags"
else
echo "[entrypoint] ✓ Set JAVA_TOOL_OPTIONS with proxy flags"
fi
export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:-} ${JVM_PROXY_FLAGS}"
fi
}
warn_codex_auto_model() {
if [ -z "${OPENAI_BASE_URL:-}" ]; then
return
fi
local CODEX_MODEL="${GH_AW_MODEL_AGENT_CODEX:-}"
if [ -z "${CODEX_MODEL}" ]; then
return
fi
local ENGINE_NAME="${GH_AW_AWF_ENGINE_NAME:-${GH_AW_ENGINE_ID:-}}"
case "${ENGINE_NAME}:${CODEX_MODEL}" in
[Cc][Oo][Dd][Ee][Xx]:[Aa][Uu][Tt][Oo])
echo "[entrypoint][WARN] Codex model 'auto' is not supported with AWF api-proxy/API-key routing."
echo "[entrypoint][WARN] Codex resolves 'auto' through ChatGPT-authenticated remote model metadata; API-key auth cannot access that catalog."
echo "[entrypoint][WARN] Set an explicit Codex model in workflow frontmatter (for example, model: gpt-5-codex) before running under AWF."
;;
esac
}
log_environment_details() {
# Print proxy environment
echo "[entrypoint] Proxy configuration:"
echo "[entrypoint] HTTP_PROXY=$HTTP_PROXY"
echo "[entrypoint] HTTPS_PROXY=$HTTPS_PROXY"
# Print network information
echo "[entrypoint] Network information:"
echo "[entrypoint] IP address: $(hostname -I)"
echo "[entrypoint] Hostname: $(hostname)"
# Configure git safe directories for awfuser
# Use runuser instead of su to avoid PAM session issues
runuser -u awfuser -- git config --global --add safe.directory '*' 2>/dev/null || true
echo "[entrypoint] =================================="
}
determine_capabilities_to_drop() {
# Determine which capabilities to drop
# - CAP_NET_ADMIN is NOT present (never granted to agent container - iptables setup
# is handled by the separate awf-iptables-init container)
# - CAP_SYS_CHROOT is dropped when chroot mode is enabled (prevents user code from using chroot)
# - CAP_SYS_ADMIN is dropped when chroot mode is enabled (was needed for mounting procfs)
if [ "${AWF_CHROOT_ENABLED}" = "true" ]; then
CAPS_TO_DROP="cap_sys_chroot,cap_sys_admin"
echo "[entrypoint] Chroot mode enabled - dropping CAP_SYS_CHROOT and CAP_SYS_ADMIN"
else
# In non-chroot mode, no capabilities need to be dropped
# NET_ADMIN is never granted (init container handles iptables)
# SYS_CHROOT and SYS_ADMIN are only needed/dropped in chroot mode
CAPS_TO_DROP=""
echo "[entrypoint] No capabilities to drop (NET_ADMIN never granted to agent)"
fi
}
# Function to unset sensitive tokens from the entrypoint's environment
# This prevents tokens from being accessible via /proc/1/environ after the agent has started
unset_sensitive_tokens() {
# List of sensitive token environment variables (matches one-shot-token library defaults)
local SENSITIVE_TOKENS=(
# GitHub tokens
"COPILOT_GITHUB_TOKEN"
"GITHUB_TOKEN"
"GH_TOKEN"
"GITHUB_API_TOKEN"
"GITHUB_PAT"
"GH_ACCESS_TOKEN"
"GITHUB_PERSONAL_ACCESS_TOKEN"
# OpenAI tokens
"OPENAI_API_KEY"
"OPENAI_KEY"
# Anthropic/Claude tokens
"ANTHROPIC_API_KEY"
"ANTHROPIC_AUTH_TOKEN"
"CLAUDE_API_KEY"
"CLAUDE_CODE_OAUTH_TOKEN"
# Codex tokens
"CODEX_API_KEY"
# Copilot BYOK provider tokens
"COPILOT_PROVIDER_API_KEY"
)
echo "[entrypoint] Unsetting sensitive tokens from parent shell environment..." >&2
for token in "${SENSITIVE_TOKENS[@]}"; do
if [ -n "${!token}" ]; then
unset "$token"
echo "[entrypoint] Unset $token from /proc/1/environ" >&2
fi
done
}
# Space-separated list of gh-aw handoff subdirectory names; names must not
# contain spaces because relax_gh_aw_shared_permissions iterates by word.
GH_AW_HOST_HANDOFF_DIRS="memory-validation"
# Relax permissions on host-shared gh-aw scratch handoff directories after the
# agent command has finished.
#
# AWF remaps the agent's UID/GID to match the host user (see
# setup_user_identity), so new files the agent creates under /tmp/gh-aw
# ordinarily belong to that same host user. However this function runs as a
# defense-in-depth measure for cases where the effective UID/GID still ends
# up mismatched from whatever identity a later host-side step runs as (for
# example gh-aw's post-agent validateMemoryStep, which writes a validation
# marker under /tmp/gh-aw/memory-validation after the container has exited).
# Without this, that step can fail with EACCES even though the directory
# tree looks otherwise fine.
#
# We only add the group-write bit (not world-writable), and only to the shared
# handoff root plus known host-side handoff subdirectories, to avoid materially
# widening access on multi-user self-hosted runners or payload-bearing audit
# files elsewhere in the gh-aw tree. Combined with the ownership transfer
# already performed before the command ran, this covers the common case where
# the host step shares the same primary group as the mapped agent user.
#
# This must run here (as root, still in the container's own filesystem view)
# rather than after the `chroot ... capsh` invocation in run_chroot_command,
# because that invocation ends with `exec capsh`, which replaces the chroot
# shell's process image entirely — any code placed after it in
# run_chroot_command would never execute.
relax_gh_aw_shared_permissions() {
local gh_aw_dir=""
if [ -e /host/tmp/gh-aw ] || [ -L /host/tmp/gh-aw ]; then
gh_aw_dir="/host/tmp/gh-aw"
elif [ -e /tmp/gh-aw ] || [ -L /tmp/gh-aw ]; then
gh_aw_dir="/tmp/gh-aw"
else
return 0
fi
if ! relax_gh_aw_handoff_dir "${gh_aw_dir}"; then
return 0
fi
local handoff_subdir
for handoff_subdir in ${GH_AW_HOST_HANDOFF_DIRS}; do
relax_gh_aw_handoff_dir "${gh_aw_dir}/${handoff_subdir}"
done
return 0
}
relax_gh_aw_handoff_dir() {
local handoff_dir="$1"
if [ ! -e "${handoff_dir}" ]; then
return 0
fi
if [ ! -d "${handoff_dir}" ] || [ -L "${handoff_dir}" ]; then
echo "[entrypoint][WARN] Skipping unsafe gh-aw handoff path ${handoff_dir}" >&2
return 1
fi
if chmod g+rwx "${handoff_dir}" 2>/dev/null; then
echo "[entrypoint] Relaxed ${handoff_dir} group permissions for host-side post-processing" >&2
return 0
else
echo "[entrypoint][WARN] Failed to relax ${handoff_dir} group permissions" >&2
return 1
fi
}
# Run a command with signal handling, one-shot token protection, and clean exit.
# Usage: run_agent_with_token_protection <command> [args...]
# The command is launched in the background so that sensitive tokens can be unset
# from the parent shell's environment once the agent has had time to cache them.
run_agent_with_token_protection() {
# Setup signal handler to forward signals to agent process and perform cleanup
cleanup_and_exit() {
SIGNAL="$1"
EXIT_CODE=143
if [ "$SIGNAL" = "INT" ]; then
EXIT_CODE=130 # Standard exit code for SIGINT
fi
trap - TERM INT
if [ -n "$AGENT_PID" ]; then
kill "-$SIGNAL" "$AGENT_PID" 2>/dev/null || true
wait "$AGENT_PID" 2>/dev/null || true
fi
relax_gh_aw_shared_permissions
exit "$EXIT_CODE"
}
trap 'cleanup_and_exit TERM' TERM
trap 'cleanup_and_exit INT' INT
# SECURITY: Run agent command in background, then unset tokens from parent shell
# This prevents tokens from being accessible via /proc/1/environ after agent starts
# The one-shot-token library caches tokens in the agent process, so agent can still read them
"$@" &
AGENT_PID=$!
# Wait for agent to initialize and cache tokens (up to 1 second)
# The one-shot-token LD_PRELOAD library caches tokens in ~100ms during process init.
# Poll every 100ms so fast commands (e.g. 'echo ok') don't pay the full wait.
for _i in 1 2 3 4 5 6 7 8 9 10; do
kill -0 "$AGENT_PID" 2>/dev/null || break
sleep 0.1
done
# Unset all sensitive tokens from parent shell environment
unset_sensitive_tokens
# Wait for agent command to complete and capture its exit code
EXIT_CODE=0
wait "$AGENT_PID" || EXIT_CODE=$?
trap - TERM INT
relax_gh_aw_shared_permissions
exit $EXIT_CODE
}
log_execution_context() {
echo "[entrypoint] Switching to awfuser (UID: $(id -u awfuser), GID: $(id -g awfuser))"
echo "[entrypoint] Executing command: $@"
echo ""
}
# ---------------------------------------------------------------------------
# Chroot setup helpers — called from run_chroot_command()
# ---------------------------------------------------------------------------
mount_host_procfs() {
# Mount a container-scoped procfs at /host/proc
# This provides dynamic /proc/self/exe resolution (required by .NET CLR, JVM, and other
# runtimes that read /proc/self/exe to find themselves). A static bind mount of /proc/self
# always resolves to the parent shell's exe, causing runtime failures.
# Security: This procfs is container-scoped (only shows container processes, not host).
# SYS_ADMIN capability (required for mount) is dropped before user code runs.
# SECURITY: hidepid=2 prevents awfuser from reading other processes' /proc/[pid]/environ,
# which is critical because PID 1 (entrypoint) may briefly hold auth tokens before
# unset_sensitive_tokens() clears them. Without hidepid=2, the agent could race to read
# /proc/1/environ and extract credentials. Also blocks access via /dev/fd → /proc/self/fd
# symlink traversal paths.
mkdir -p /host/proc
if mount -t proc -o nosuid,nodev,noexec,hidepid=2 proc /host/proc; then
echo "[entrypoint] Mounted procfs at /host/proc (nosuid,nodev,noexec,hidepid=2)"
else
echo "[entrypoint][ERROR] Failed to mount procfs at /host/proc"
echo "[entrypoint][ERROR] This is required for Java, .NET, and other runtimes that read /proc/self/exe"
echo "[entrypoint][ERROR] Ensure the container has SYS_ADMIN capability (it will be dropped before user code runs)"
exit 1
fi
}
mount_host_cgroupfs() {
# Bind-mount the container's own (real, pre-chroot) cgroup subtree at /host/sys/fs/cgroup,
# read-only, so pids.max/pids.current (and other cgroup limits) are visible to tools
# running inside the chroot.
#
# Without this, /host/sys/fs/cgroup only shows whatever the host's read-only bind mount of
# /sys exposes (from the "system" mount policy), which is the host's raw cgroupfs view, not
# the container's own delegated cgroup. That view is typically unreadable/misleading from
# inside an unprivileged container, so tools like the JVM can't discover the real pids
# ceiling and size thread pools accordingly, leading to confusing
# "unable to create native thread" / "Cannot create worker GC thread" failures instead of a
# clear signal that the process ceiling was hit. See: --pids-limit (default 1000).
#
# This is best-effort: if the bind mount fails (e.g. cgroup not delegated, unsupported
# runtime), we continue without it rather than aborting the whole command.
mkdir -p /host/sys/fs/cgroup
if mount --bind /sys/fs/cgroup /host/sys/fs/cgroup 2>/dev/null; then
if mount -o remount,ro,bind /host/sys/fs/cgroup 2>/dev/null; then
echo "[entrypoint] Bind-mounted container cgroup subtree at /host/sys/fs/cgroup (ro)"
else
echo "[entrypoint][WARN] Could not remount /host/sys/fs/cgroup read-only; removing mount"
if umount /host/sys/fs/cgroup 2>/dev/null; then
echo "[entrypoint][WARN] pids.max/pids.current will not be visible inside the sandbox"
else
echo "[entrypoint][ERROR] Could not remove writable cgroup mount; refusing to start sandbox command"
exit 1
fi
fi
else
echo "[entrypoint][WARN] Could not bind-mount cgroup subtree at /host/sys/fs/cgroup"
echo "[entrypoint][WARN] pids.max/pids.current will not be visible inside the sandbox"
fi
}
copy_preload_libs() {
# Copy one-shot-token library to host filesystem for LD_PRELOAD in chroot
# This prevents tokens from being read multiple times by malicious code
# Staged under /run/awf-lib, which lives on the container's own writable
# rootfs. /tmp cannot be used: it is bind-mounted from the host and
# filesystem.allowWrite may narrow it to read-only, which would silently
# disable this protection.
# Sets ONE_SHOT_TOKEN_LIB (empty string if unavailable or incompatible)
ONE_SHOT_TOKEN_LIB=""
if [ -f /usr/local/lib/one-shot-token.so ]; then
# Create the library directory on the container rootfs (always writable)
if mkdir -p /host/run/awf-lib 2>/dev/null; then
# Copy the library and verify it exists after copying
if cp /usr/local/lib/one-shot-token.so /host/run/awf-lib/one-shot-token.so 2>/dev/null && \
[ -f /host/run/awf-lib/one-shot-token.so ]; then
# Probe compatibility with the host's dynamic linker before committing to LD_PRELOAD.
# Run the probe inside chroot /host so the ELF interpreter and all library paths
# (e.g. /lib/ld-musl-*.so.1 on Alpine) resolve against the host filesystem, not
# the container's. This avoids false negatives where the container's glibc
# interpreter would accept the .so even though the host loader cannot.
if chroot /host /bin/sh -c 'LD_PRELOAD=/run/awf-lib/one-shot-token.so /bin/true' 2>/dev/null; then
ONE_SHOT_TOKEN_LIB="/run/awf-lib/one-shot-token.so"
echo "[entrypoint] One-shot token library copied to chroot at ${ONE_SHOT_TOKEN_LIB}"
else
echo "[entrypoint][WARN] one-shot-token.so failed to load on host dynamic linker (host libc incompatibility, e.g. musl/Alpine)"
echo "[entrypoint][WARN] Token protection will be disabled (tokens may be readable multiple times)"
rm -f /host/run/awf-lib/one-shot-token.so 2>/dev/null || true
fi
else
# The library exists but could not be staged. Continuing would silently
# drop a security control, so fail closed instead.
echo "[entrypoint][ERROR] Could not copy one-shot-token library to /run/awf-lib" >&2
echo "[entrypoint][ERROR] Refusing to start without one-shot token protection" >&2
exit 1
fi
else
echo "[entrypoint][ERROR] Could not create /run/awf-lib directory" >&2
echo "[entrypoint][ERROR] Refusing to start without one-shot token protection" >&2
exit 1
fi
fi
}
copy_browser_libs() {
# Stage the Chromium/Playwright runtime shared libraries baked into the image
# (containers/agent/Dockerfile: BROWSER_PKGS) so they are visible inside the
# chroot. Installing the packages into the image's /usr is not sufficient on
# its own: AWF_CHROOT_ENABLED=true chroots to /host, and buildSystemMounts()
# bind-mounts the runner's own /usr, /lib, etc. over the image's, shadowing
# anything installed in this layer.
#
# The Dockerfile records the manifest of .so files owned by those packages
# (including their transitive dependencies, e.g. fontconfig/freetype/harfbuzz)
# at /usr/local/share/awf/browser-libs.manifest. We copy each one, preserving
# its original directory structure, under /run/awf-lib/browser-libs -- which
# lives on the container's own writable rootfs (not bind-mounted) -- and point
# LD_LIBRARY_PATH at the resulting directories.
#
# Sets BROWSER_LD_LIBRARY_PATH (empty string if unavailable or nothing to stage).
BROWSER_LD_LIBRARY_PATH=""
MANIFEST="/usr/local/share/awf/browser-libs.manifest"
if [ -s "$MANIFEST" ]; then
STAGE_ROOT="/host/run/awf-lib/browser-libs"
if mkdir -p "$STAGE_ROOT" 2>/dev/null; then
LIB_DIRS=""
while IFS= read -r lib; do
[ -z "$lib" ] && continue
[ -f "$lib" ] || continue
dest="${STAGE_ROOT}${lib}"
dest_dir="$(dirname "$dest")"
if mkdir -p "$dest_dir" 2>/dev/null && cp -a "$lib" "$dest" 2>/dev/null; then
rel_dir="$(dirname "$lib")"
case " $LIB_DIRS " in
*" $rel_dir "*) ;;
*) LIB_DIRS="$LIB_DIRS $rel_dir" ;;
esac
else
echo "[entrypoint][WARN] Could not stage browser runtime library $lib" >&2
fi
done < "$MANIFEST"
if [ -n "$LIB_DIRS" ]; then
for rel_dir in $LIB_DIRS; do
BROWSER_LD_LIBRARY_PATH="${BROWSER_LD_LIBRARY_PATH:+$BROWSER_LD_LIBRARY_PATH:}/run/awf-lib/browser-libs${rel_dir}"
done
echo "[entrypoint] Chromium/Playwright runtime libraries staged for chroot at ${STAGE_ROOT}"
fi
else
echo "[entrypoint][WARN] Could not create ${STAGE_ROOT}; Chromium/Playwright browsers may fail to launch" >&2
fi
fi
}
copy_agent_helper_scripts() {
# Copy get-claude-key.sh and gh CLI proxy wrapper to chroot-accessible paths.
# Both scripts are baked into the Docker image but shadowed by host bind mounts
# inside chroot. They are copied to /run/awf-lib/ -- on the container's own
# writable rootfs, not the host-bound /tmp which filesystem.allowWrite may
# narrow to read-only -- so they remain accessible after the chroot activates.
# Sets CHROOT_KEY_HELPER; may update AWF_HOST_PATH.
# Copy get-claude-key.sh to chroot-accessible path
# The script is baked into the Docker image at /usr/local/bin/, but the chroot
# bind-mounts the host's /usr (read-only), shadowing the container's copy.
# We must copy it to /run/awf-lib/ (container rootfs) before the chroot activates.
CHROOT_KEY_HELPER=""
if [ -n "$CLAUDE_CODE_API_KEY_HELPER" ] && [ -f "$CLAUDE_CODE_API_KEY_HELPER" ]; then
if mkdir -p /host/run/awf-lib 2>/dev/null; then
CHROOT_KEY_HELPER="/run/awf-lib/$(basename "$CLAUDE_CODE_API_KEY_HELPER")"
if cp "$CLAUDE_CODE_API_KEY_HELPER" "/host${CHROOT_KEY_HELPER}" 2>/dev/null && \
chmod +x "/host${CHROOT_KEY_HELPER}" 2>/dev/null; then
echo "[entrypoint] Claude key helper copied to chroot at ${CHROOT_KEY_HELPER}"
# Update apiKeyHelper in config files to use the chroot-accessible path
for cfg in "/host$HOME/.claude.json" "/host$HOME/.claude/settings.json"; do
if [ -f "$cfg" ] && grep -q '"apiKeyHelper"' "$cfg" 2>/dev/null; then
if AWF_CFG="$cfg" AWF_NEW="$CHROOT_KEY_HELPER" \
node -e "
const fs = require('fs');
const f = process.env.AWF_CFG;
const obj = JSON.parse(fs.readFileSync(f, 'utf8'));
obj.apiKeyHelper = process.env.AWF_NEW;
fs.writeFileSync(f, JSON.stringify(obj) + '\n');
" 2>/dev/null; then
echo "[entrypoint] ✓ Updated apiKeyHelper path in $cfg"
fi
fi
done
CLAUDE_CODE_API_KEY_HELPER="$CHROOT_KEY_HELPER"
else
echo "[entrypoint][WARN] Could not copy get-claude-key.sh to chroot"
echo "[entrypoint][WARN] Claude Code API key helper may not work in chroot mode"
CHROOT_KEY_HELPER=""
fi
fi
fi
# Activate gh CLI proxy wrapper when CLI proxy sidecar is enabled.
# The wrapper at /usr/local/bin/gh-cli-proxy-wrapper.sh (baked into the image)
# is copied to /run/awf-lib/gh so it is accessible inside the chroot at a
# location that takes precedence over the host's /usr/bin/gh mount.
if [ -n "$AWF_CLI_PROXY_URL" ] && [ -f /usr/local/bin/gh-cli-proxy-wrapper.sh ]; then
if mkdir -p /host/run/awf-lib 2>/dev/null && \
cp /usr/local/bin/gh-cli-proxy-wrapper.sh /host/run/awf-lib/gh 2>/dev/null && \
chmod +x /host/run/awf-lib/gh 2>/dev/null; then
# The chroot will see this as /run/awf-lib/gh (the /host prefix is the bind mount)
echo "[entrypoint] gh CLI proxy wrapper installed at /run/awf-lib/gh (inside chroot)"
# Prepend /run/awf-lib to PATH so the wrapper takes precedence over host gh
export AWF_HOST_PATH="/run/awf-lib:${AWF_HOST_PATH:-$PATH}"
else
# The CLI proxy is enabled, so an unwrapped gh would bypass credential
# mediation entirely. Fail closed rather than silently downgrade.
echo "[entrypoint][ERROR] Could not install gh CLI proxy wrapper at /run/awf-lib/gh" >&2
echo "[entrypoint][ERROR] Refusing to start with an unmediated gh CLI" >&2
exit 1
fi
fi
}
copy_dind_runner_binary() {
# In split-filesystem DinD setups with --docker-host-path-prefix pointing at
# a shared /tmp root, docker-manager stages the invoking CLI binary under
# /tmp/awf-runner-bin/<name>. Copy it into /run/awf-lib so the chrooted PATH
# can resolve the expected command name (copilot, claude, etc.) without
# requiring manual bootstrap copies into the daemon's /usr/local/bin.
# Sets STAGED_RUNNER_BINARY_CHROOT; may update AWF_HOST_PATH.
STAGED_RUNNER_BINARY_CHROOT=""
if [ -n "${AWF_STAGED_RUNNER_BINARY_NAME:-}" ]; then
if [[ ! "${AWF_STAGED_RUNNER_BINARY_NAME}" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]*$ ]]; then
echo "[entrypoint][WARN] Ignoring invalid AWF_STAGED_RUNNER_BINARY_NAME=${AWF_STAGED_RUNNER_BINARY_NAME}"
elif [ -f "/tmp/awf-runner-bin/${AWF_STAGED_RUNNER_BINARY_NAME}" ]; then
if mkdir -p /host/run/awf-lib 2>/dev/null; then
if cp "/tmp/awf-runner-bin/${AWF_STAGED_RUNNER_BINARY_NAME}" "/host/run/awf-lib/${AWF_STAGED_RUNNER_BINARY_NAME}" 2>/dev/null && \
chmod +x "/host/run/awf-lib/${AWF_STAGED_RUNNER_BINARY_NAME}" 2>/dev/null; then
STAGED_RUNNER_BINARY_CHROOT="/run/awf-lib/${AWF_STAGED_RUNNER_BINARY_NAME}"
case ":${AWF_HOST_PATH:-$PATH}:" in
*":/run/awf-lib:"*) ;;
*) export AWF_HOST_PATH="/run/awf-lib:${AWF_HOST_PATH:-$PATH}" ;;
esac
echo "[entrypoint] Runner binary staged for chroot at ${STAGED_RUNNER_BINARY_CHROOT}"
else
echo "[entrypoint][WARN] Could not stage runner binary ${AWF_STAGED_RUNNER_BINARY_NAME} into chroot"
fi
fi
fi
fi
# When chroot.binariesSourcePath is configured, the firewall mounts the runner-bin
# overlay at /host/tmp/awf-runner-bin (inside chroot: /tmp/awf-runner-bin).
# Prepend it to AWF_HOST_PATH so the chrooted PATH resolves runner-installed binaries
# (e.g. copilot, claude) even when they are absent from /usr/local/bin in the staged
# host filesystem. This is the primary mechanism for ARC/DinD runners where the
# runner-installed binaries live on the runner's /tmp emptyDir, not in /usr.
if [ -d /host/tmp/awf-runner-bin ]; then
case ":${AWF_HOST_PATH:-$PATH}:" in
*":/tmp/awf-runner-bin:"*) ;;
*) export AWF_HOST_PATH="/tmp/awf-runner-bin:${AWF_HOST_PATH:-$PATH}" ;;
esac
echo "[entrypoint] Runner binaries overlay detected at /tmp/awf-runner-bin; prepended to PATH"
fi
}
resolve_chroot_binary_path() {
# Resolve a binary name to a chroot-absolute path by searching the same
# directories the chroot PATH will contain: $GITHUB_PATH entries (written by
# setup-* actions, including tool-cache activations), AWF_HOST_PATH, the
# AWF-staged binary directories, and the standard system directories.
# Prints the chroot path on success; returns 1 when the binary is not found.
local name="$1"
local search_path=""
local entry=""
if [ -n "${GITHUB_PATH:-}" ] && [ -f "/host${GITHUB_PATH}" ]; then
while IFS= read -r entry; do
entry="${entry%$'\r'}" # strip trailing CR (Windows-style CRLF files)
[ -z "${entry}" ] && continue
search_path="${search_path}${entry}:"
done < "/host${GITHUB_PATH}"
fi
if [ -n "${AWF_HOST_PATH:-}" ]; then
search_path="${search_path}${AWF_HOST_PATH}:"
fi
search_path="${search_path}/tmp/awf-runner-bin:/run/awf-lib:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
local dir=""
local IFS=':'
for dir in ${search_path}; do
case "${dir}" in
/*) ;;
*) continue ;;
esac
if [ -f "/host${dir}/${name}" ] && [ -x "/host${dir}/${name}" ]; then
printf '%s\n' "${dir}/${name}"
return 0
fi
done
return 1
}
prepare_usr_local_bin_overlay() {
# Stage a writable replacement for the chroot's /usr/local/bin.
#
# The host /usr tree is bind-mounted read-only at /host/usr, so a missing
# /usr/local/bin/<tool> entry cannot simply be created. Instead we bind-mount
# the original directory to a second location that stays reachable inside the
# chroot (a unique /tmp/awf-usr-local-bin-orig-XXXXXX directory, read-only) and
# build a symlink farm in /tmp/awf-usr-local-bin-XXXXXX that mirrors every
# existing entry. The farm is later bind-mounted over /host/usr/local/bin so
# both the original binaries and the AWF-created shims resolve.
#
# Sets USR_LOCAL_BIN_OVERLAY_DIR, USR_LOCAL_BIN_ORIG_DIR and
# USR_LOCAL_BIN_OVERLAY_READY=1 on success. No host filesystem content is
# modified.
if [ "${USR_LOCAL_BIN_OVERLAY_READY}" = "1" ]; then
return 0
fi
if [ ! -d /host/usr/local/bin ]; then
return 1
fi
# Unique staging directories per container run: a fixed name could be reused
# by a concurrent AWF container or left stale by a previous run on the same
# host /tmp, which would shadow /usr/local/bin with outdated symlinks.
local overlay_host_dir="" orig_host_dir=""
overlay_host_dir="$(mktemp -d /host/tmp/awf-usr-local-bin-XXXXXX 2>/dev/null || true)"
orig_host_dir="$(mktemp -d /host/tmp/awf-usr-local-bin-orig-XXXXXX 2>/dev/null || true)"
if [ -z "${overlay_host_dir}" ] || [ -z "${orig_host_dir}" ]; then
rmdir "${overlay_host_dir:-/nonexistent}" "${orig_host_dir:-/nonexistent}" 2>/dev/null || true
return 1
fi
USR_LOCAL_BIN_OVERLAY_DIR="${overlay_host_dir#/host}"
USR_LOCAL_BIN_ORIG_DIR="${orig_host_dir#/host}"
if ! mount --bind /host/usr/local/bin "/host${USR_LOCAL_BIN_ORIG_DIR}" 2>/dev/null; then
rmdir "${overlay_host_dir}" "${orig_host_dir}" 2>/dev/null || true
USR_LOCAL_BIN_OVERLAY_DIR=""
USR_LOCAL_BIN_ORIG_DIR=""
return 1
fi
# Install the teardown here — from this point on there is a bind mount and two
# staging directories that must be removed however the container exits.
trap cleanup_usr_local_bin_overlay EXIT
USR_LOCAL_BIN_OVERLAY_READY=1
mount -o remount,ro,bind "/host${USR_LOCAL_BIN_ORIG_DIR}" 2>/dev/null || \
echo "[entrypoint][WARN] Could not remount ${USR_LOCAL_BIN_ORIG_DIR} read-only"
populate_usr_local_bin_farm
chown 0:0 "/host${USR_LOCAL_BIN_OVERLAY_DIR}" 2>/dev/null || true
chmod 0755 "/host${USR_LOCAL_BIN_OVERLAY_DIR}" 2>/dev/null || true
return 0
}
populate_usr_local_bin_farm() {
# Mirror every entry of the real /usr/local/bin into the staging farm as a
# symlink. Uses USR_LOCAL_BIN_OVERLAY_DIR / USR_LOCAL_BIN_ORIG_DIR.
local entry="" base="" real="" target=""
# Iterate the original directory (the overlay is not mounted yet) so relative
# symlinks resolve against their real location rather than the staging path.
# The dotfile globs are required as well: * skips hidden entries, which would
# otherwise disappear from /usr/local/bin once the overlay is activated.
for entry in /host/usr/local/bin/* /host/usr/local/bin/.[!.]* /host/usr/local/bin/..?*; do
[ -e "${entry}" ] || continue
base="$(basename "${entry}")"