forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.sh
More file actions
executable file
·3038 lines (2918 loc) · 119 KB
/
Copy pathdeploy.sh
File metadata and controls
executable file
·3038 lines (2918 loc) · 119 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
#!/usr/bin/env bash
# Deploy the rider assistant as an immutable Lambda version behind a live alias.
#
# ./infra/deploy.sh # stage, verify, promote, then print the URL
#
# Requires the AWS CLI with credentials that may manage IAM, Lambda, and
# CloudWatch Logs. Region comes from AWS_REGION (default us-west-2, matching
# CI). See ADR 0018 for the one-time unqualified-route migration and rollback
# state machine.
set -euo pipefail
REGION="${AWS_REGION:-us-west-2}"
FN="${FPA_FUNCTION_NAME:-fare-policy-assistant-demo}"
LIVE_ALIAS="${FPA_LIVE_ALIAS:-live}"
ROLLBACK_ALIAS="${FPA_ROLLBACK_ALIAS:-rollback}"
LEGACY_IDENTITY_ROLLBACK_VERSION="${FPA_LEGACY_IDENTITY_ROLLBACK_VERSION:-}"
LOG_GROUP="/aws/lambda/$FN"
LOGGING_CONFIG="LogFormat=JSON,ApplicationLogLevel=INFO,SystemLogLevel=WARN,LogGroup=$LOG_GROUP"
ROLE_NAME="$FN-role"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD="${FPA_BUILD_DIR:-$ROOT/infra/build}"
BUNDLE="$BUILD/bundle"
PROMOTION_BUILD="$BUILD/promotion"
PROMOTION_RUNTIME_EVIDENCE="$BUILD/promotion-runtime.json"
PROMOTION_RUN_POINTER="$BUILD/promotion-run-path"
EVAL_BUNDLE_POINTER="$BUILD/promotion-evidence-pointer.json"
PROMOTION_RUNS_ROOT="${FPA_PROMOTION_RUNS_ROOT:-$ROOT/evals/runs}"
API_ID="${FPA_API_ID:-}"
SOURCE_REVISION="$(git -C "$ROOT" rev-parse HEAD)"
[[ "$SOURCE_REVISION" =~ ^[0-9a-f]{40}$ ]] || {
echo "source revision is not a full lowercase Git object id" >&2
exit 2
}
if [[ -n "$(git -C "$ROOT" status --porcelain --untracked-files=normal)" ]]; then
echo "working tree is dirty; refusing a false source/release identity" >&2
echo "commit the complete release before deploying" >&2
exit 2
fi
for required_command in aws chmod cmp curl find install jq mktemp mv openssl uv; do
command -v "$required_command" >/dev/null 2>&1 || {
echo "$required_command is required" >&2
exit 2
}
done
sha256_hex() {
local digest
digest="$(openssl dgst -sha256 <"$1")"
digest="${digest##* }"
[[ "$digest" =~ ^[0-9a-f]{64}$ ]] || {
echo "could not compute SHA-256 for $1" >&2
return 1
}
printf '%s\n' "$digest"
}
if [[ -n "$LEGACY_IDENTITY_ROLLBACK_VERSION" \
&& ! "$LEGACY_IDENTITY_ROLLBACK_VERSION" =~ ^[1-9][0-9]*$ ]]; then
echo "FPA_LEGACY_IDENTITY_ROLLBACK_VERSION must be a numeric published version" >&2
exit 2
fi
ACCOUNT="$(aws sts get-caller-identity --query Account --output text)"
# ── cost allocation ──────────────────────────────────────────────────────────
# `project` is the cost-allocation tag key activated in Cost Explorer. Anything
# created without it lands in the account's untagged bucket, where the
# `fare-demo` budget and any per-project report cannot see this deployment's
# spend at all. There is no CDK/Terraform layer here (ADR 0004) -- this script is
# the whole deployment -- so tagging is applied by the script itself: on create
# where the API supports it, and re-applied idempotently at the end of every
# deploy so resources created before this existed get labelled on the next run
# rather than staying invisible forever.
#
# The value is the portfolio project name, which is deliberately NOT the repo
# name (`fare-policy-assistant`) or the function name: it is the key the budget
# and the cross-repo cost report group on, so it must stay stable even if the
# function is renamed. `tests/test_deploy_tagging.py` guards that.
PROJECT_TAG=fare-assistant
# Same pair in the two shorthand forms the AWS CLI uses: Lambda, Logs and API
# Gateway take a `key=value` map; IAM, SNS and CloudWatch take a list of
# Key=/Value= structs. Keeping both here means the value is written once.
PROJECT_TAG_MAP="project=$PROJECT_TAG"
PROJECT_TAG_LIST="Key=project,Value=$PROJECT_TAG"
# Hard ceiling on parallel Bedrock spend: at most this many containers run at
# once, no matter how many requests arrive. Every other rate figure below is
# derived from it so the two never drift out of sync (see ADR 0004 amendment,
# "a true cross-container rate limit" / roadmap P1 item 4).
RESERVED_CONCURRENCY=2
# API Gateway stage throttle, tuned to that ceiling: sustained rate equals the
# concurrency ceiling (a container answers a request in a few seconds, so
# admitting more than RESERVED_CONCURRENCY requests/sec would just queue and
# eventually 429/timeout at the Lambda layer instead of the gateway layer);
# burst allows one short spike above steady-state (e.g. two riders loading the
# page and asking at the same moment) to queue briefly rather than bounce.
# This is the actual cross-container ceiling: it is enforced by API Gateway
# before any container runs, so it holds identically whether the request lands
# on a warm container, a cold start, or a container that no longer exists by
# the time the next request arrives -- unlike the handler's in-memory budget
# (web/handler.py), which resets per container and is not shared across them.
THROTTLE_RATE_LIMIT="$RESERVED_CONCURRENCY"
THROTTLE_BURST_LIMIT=$((RESERVED_CONCURRENCY * 2 + 1))
# Everything above is an AGGREGATE ceiling: it bounds what the service spends in
# total but says nothing about who spends it, so one actor sustaining 2 rps
# starves every real rider at no cost to itself. The table below is the shared
# state behind the per-caller limiter and the spend breaker that fix that
# (web/ratelimit.py, ADR 0025). Quotas themselves are release inputs in
# src/assistant/config.py, not deploy-time settings, so a change to them is a
# reviewed release with a new config version rather than a console edit.
#
# Why a table and not AWS WAF, which is the usual answer: WAF cannot attach to
# an API Gateway *HTTP* API at all. It protects CloudFront, ALB, AppSync,
# Cognito, App Runner, Verified Access, Amplify, and API Gateway REST APIs --
# HTTP APIs are absent from the list, and the REST-vs-HTTP comparison table
# says so outright. Buying WAF here would mean first putting CloudFront in
# front of the API or migrating to a REST API, and would cost a $5/month web
# ACL plus $1/month per rule before serving a single request: roughly 30% of
# this project's entire $20/month budget, to protect a service whose model
# spend rounds to a few dollars. See ADR 0025 for the full comparison.
#
# The table is deliberately outside the immutable-release boundary: it holds
# operational counters and one operator-flippable breaker row, never release
# state. Nothing in it survives its TTL, and losing the whole table degrades
# the service to exactly the posture it had before this existed.
RATE_LIMIT_TABLE="${FPA_RATE_LIMIT_TABLE:-$FN-limits}"
# CloudWatch JSON metric contracts. Keep the legacy handler/call/feedback
# filters through one rollback-compatible release; the additive v2 filters
# consume structured application events emitted by JSON/INFO Lambda logging.
HANDLER_ERROR_V2_FILTER='{ $.event = "handler_error" }'
FEEDBACK_DOWN_V2_FILTER='{ $.event = "feedback" && $.verdict = "down" }'
GENAI_CALL_FILTER='{ $.event = "genai_call" && $.completion_recorded IS TRUE }'
MODEL_COST_FILTER='{ $.event = "genai_call" && $.cost_estimate_available IS TRUE && $.estimated_cost_usd = * }'
UNPRICED_MODEL_FILTER='{ $.event = "genai_call" && $.completion_recorded IS TRUE && $.cost_estimate_available IS FALSE }'
MODEL_DURATION_FILTER='{ $.event = "genai_call" && $.model_duration_ms = * }'
ANSWER_DURATION_FILTER='{ $.event = "answer_request" && $.duration_ms = * }'
# Preserve operator-owned Lambda settings from the actual live version. AWS
# replaces the entire Variables map on update, so constructing it from only
# this script's three controls would silently erase settings such as
# FPA_EMBED_ANCESTORS. Once the alias exists, never inherit from mutable
# $LATEST: a failed candidate must not poison the next release.
FUNCTION_EXISTS=false
if EXISTING_LAMBDA_ENV="$(
aws lambda get-function-configuration --function-name "$FN" --region "$REGION" \
--query 'Environment.Variables' --output json 2>&1
)"; then
FUNCTION_EXISTS=true
elif [[ "$EXISTING_LAMBDA_ENV" == *"ResourceNotFoundException"* ]]; then
# A confirmed missing function is the only safe case for starting with an
# empty environment. Authentication, authorization, and network failures
# must abort rather than masquerade as a first deploy.
EXISTING_LAMBDA_ENV='{}'
else
echo "could not read existing Lambda environment; refusing to deploy:" >&2
echo "$EXISTING_LAMBDA_ENV" >&2
exit 1
fi
assert_unweighted_alias() {
local alias_json="$1"
local alias_name="$2"
jq -e '((.RoutingConfig.AdditionalVersionWeights // {}) | length) == 0' \
<<<"$alias_json" >/dev/null || {
echo "Lambda alias $alias_name has weighted routing; refusing deterministic release" >&2
exit 1
}
}
EMPTY_ALIAS_ROUTING='{"AdditionalVersionWeights":{}}'
PROMOTION_GUARD_ACTIVE=false
PROMOTION_GUARD_EXPECTED_VERSION=""
PROMOTION_GUARD_EXPECTED_REVISION=""
PROMOTION_GUARD_EXPECTED_DESCRIPTION=""
PROMOTION_GUARD_RESTORE_VERSION=""
PROMOTION_GUARD_RESTORE_DESCRIPTION=""
ROLLBACK_POINTER_GUARD_ACTIVE=false
ROLLBACK_POINTER_GUARD_EXPECTED_VERSION=""
ROLLBACK_POINTER_GUARD_EXPECTED_REVISION=""
ROLLBACK_POINTER_GUARD_EXPECTED_DESCRIPTION=""
ROLLBACK_POINTER_GUARD_RESTORE_VERSION=""
ROLLBACK_POINTER_GUARD_RESTORE_DESCRIPTION=""
# Once live has moved, every abnormal exit must attempt a compare-and-swap
# restore until the public route has passed smoke. The version and RevisionId
# checks prevent this cleanup from overwriting a concurrent operator change.
restore_unverified_live() {
local current_alias
local current_version
local current_revision
local current_description
local restored_alias
[[ "$PROMOTION_GUARD_ACTIVE" == "true" ]] || return 0
PROMOTION_GUARD_ACTIVE=false
if ! current_alias="$(
aws lambda get-alias \
--function-name "$FN" --name "$LIVE_ALIAS" --region "$REGION" --output json
)"; then
echo "CRITICAL: could not inspect live while restoring an unverified release" >&2
return 1
fi
current_version="$(jq -r '.FunctionVersion // ""' <<<"$current_alias")"
current_revision="$(jq -r '.RevisionId // ""' <<<"$current_alias")"
current_description="$(jq -r '.Description // ""' <<<"$current_alias")"
if [[ "$current_version" == "$PROMOTION_GUARD_RESTORE_VERSION" \
&& "$current_description" == "$PROMOTION_GUARD_RESTORE_DESCRIPTION" ]]; then
if ! jq -e '((.RoutingConfig.AdditionalVersionWeights // {}) | length) == 0' \
<<<"$current_alias" >/dev/null; then
echo "CRITICAL: live returned to the prior primary version but still has weighted routing" >&2
return 1
fi
return 0
fi
if [[ "$current_version" != "$PROMOTION_GUARD_EXPECTED_VERSION" \
|| "$current_description" != "$PROMOTION_GUARD_EXPECTED_DESCRIPTION" \
|| ( -n "$PROMOTION_GUARD_EXPECTED_REVISION" \
&& "$current_revision" != "$PROMOTION_GUARD_EXPECTED_REVISION" ) ]]; then
echo "WARNING: live changed after promotion; automatic restore did not overwrite it" >&2
return 1
fi
if ! restored_alias="$(
aws lambda update-alias \
--function-name "$FN" \
--name "$LIVE_ALIAS" \
--function-version "$PROMOTION_GUARD_RESTORE_VERSION" \
--revision-id "$current_revision" \
--routing-config "$EMPTY_ALIAS_ROUTING" \
--description "$PROMOTION_GUARD_RESTORE_DESCRIPTION" \
--region "$REGION" \
--output json
)"; then
echo "CRITICAL: compare-and-swap restore of live failed" >&2
return 1
fi
if ! jq -e \
--arg version "$PROMOTION_GUARD_RESTORE_VERSION" \
--arg description "$PROMOTION_GUARD_RESTORE_DESCRIPTION" '
.FunctionVersion == $version
and (.Description // "") == $description
and ((.RoutingConfig.AdditionalVersionWeights // {}) | length) == 0
' <<<"$restored_alias" >/dev/null; then
echo "CRITICAL: restored live alias failed target/routing verification" >&2
return 1
fi
echo "restored unverified live version $current_version -> $PROMOTION_GUARD_RESTORE_VERSION" >&2
}
restore_previous_rollback_pointer() {
local current_alias
local current_version
local current_revision
local current_description
local restored_alias
[[ "$ROLLBACK_POINTER_GUARD_ACTIVE" == "true" ]] || return 0
ROLLBACK_POINTER_GUARD_ACTIVE=false
if ! current_alias="$(
aws lambda get-alias \
--function-name "$FN" --name "$ROLLBACK_ALIAS" \
--region "$REGION" --output json
)"; then
echo "WARNING: could not inspect the rollback pointer during release cleanup" >&2
return 1
fi
current_version="$(jq -r '.FunctionVersion // ""' <<<"$current_alias")"
current_revision="$(jq -r '.RevisionId // ""' <<<"$current_alias")"
current_description="$(jq -r '.Description // ""' <<<"$current_alias")"
if [[ "$current_version" == "$ROLLBACK_POINTER_GUARD_RESTORE_VERSION" \
&& "$current_description" == "$ROLLBACK_POINTER_GUARD_RESTORE_DESCRIPTION" ]]; then
if ! jq -e '((.RoutingConfig.AdditionalVersionWeights // {}) | length) == 0' \
<<<"$current_alias" >/dev/null; then
echo "WARNING: rollback pointer returned to its prior target but still has weighted routing" >&2
return 1
fi
return 0
fi
if [[ "$current_version" != "$ROLLBACK_POINTER_GUARD_EXPECTED_VERSION" \
|| "$current_description" != "$ROLLBACK_POINTER_GUARD_EXPECTED_DESCRIPTION" \
|| ( -n "$ROLLBACK_POINTER_GUARD_EXPECTED_REVISION" \
&& "$current_revision" != "$ROLLBACK_POINTER_GUARD_EXPECTED_REVISION" ) ]]; then
echo "WARNING: rollback pointer changed concurrently; cleanup did not overwrite it" >&2
return 1
fi
if ! restored_alias="$(
aws lambda update-alias \
--function-name "$FN" \
--name "$ROLLBACK_ALIAS" \
--function-version "$ROLLBACK_POINTER_GUARD_RESTORE_VERSION" \
--revision-id "$current_revision" \
--routing-config "$EMPTY_ALIAS_ROUTING" \
--description "$ROLLBACK_POINTER_GUARD_RESTORE_DESCRIPTION" \
--region "$REGION" \
--output json
)"; then
echo "WARNING: compare-and-swap restore of the rollback pointer failed" >&2
return 1
fi
if ! jq -e \
--arg version "$ROLLBACK_POINTER_GUARD_RESTORE_VERSION" \
--arg description "$ROLLBACK_POINTER_GUARD_RESTORE_DESCRIPTION" '
.FunctionVersion == $version
and (.Description // "") == $description
and ((.RoutingConfig.AdditionalVersionWeights // {}) | length) == 0
' <<<"$restored_alias" >/dev/null; then
echo "WARNING: restored rollback pointer failed target/routing verification" >&2
return 1
fi
}
release_exit_guard() {
local status=$?
local guard_was_active=false
trap - EXIT INT TERM
if [[ "$PROMOTION_GUARD_ACTIVE" == "true" ]]; then
guard_was_active=true
restore_unverified_live || true
fi
if [[ "$ROLLBACK_POINTER_GUARD_ACTIVE" == "true" ]]; then
guard_was_active=true
restore_previous_rollback_pointer || true
fi
if [[ "$guard_was_active" == "true" && "$status" == "0" ]]; then
status=1
fi
exit "$status"
}
trap release_exit_guard EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
HAS_LIVE_ALIAS=false
LIVE_ALIAS_JSON=""
BASELINE_LIVE_VERSION=""
BASELINE_LIVE_REVISION=""
BASELINE_LIVE_DESCRIPTION=""
if [[ "$FUNCTION_EXISTS" == "true" ]]; then
if LIVE_ALIAS_JSON="$(
aws lambda get-alias \
--function-name "$FN" --name "$LIVE_ALIAS" --region "$REGION" --output json 2>&1
)"; then
HAS_LIVE_ALIAS=true
assert_unweighted_alias "$LIVE_ALIAS_JSON" "$LIVE_ALIAS"
LIVE_VERSION="$(jq -r '.FunctionVersion' <<<"$LIVE_ALIAS_JSON")"
LIVE_REVISION="$(jq -r '.RevisionId // ""' <<<"$LIVE_ALIAS_JSON")"
[[ "$LIVE_VERSION" =~ ^[1-9][0-9]*$ ]] || {
echo "$LIVE_ALIAS must target a numbered version, not $LIVE_VERSION" >&2
exit 1
}
[[ -n "$LIVE_REVISION" ]] || {
echo "$LIVE_ALIAS has no revision id; refusing an unguarded release" >&2
exit 1
}
BASELINE_LIVE_VERSION="$LIVE_VERSION"
BASELINE_LIVE_REVISION="$LIVE_REVISION"
BASELINE_LIVE_DESCRIPTION="$(jq -r '.Description // ""' <<<"$LIVE_ALIAS_JSON")"
EXISTING_LAMBDA_ENV="$(
aws lambda get-function-configuration \
--function-name "$FN" --qualifier "$LIVE_VERSION" --region "$REGION" \
--query 'Environment.Variables' --output json
)"
elif [[ "$LIVE_ALIAS_JSON" != *"ResourceNotFoundException"* ]]; then
echo "could not inspect Lambda alias $LIVE_ALIAS; refusing to deploy:" >&2
echo "$LIVE_ALIAS_JSON" >&2
exit 1
fi
fi
lambda_env_value() {
(
cd "$ROOT"
FPA_DEPLOY_EXISTING_LAMBDA_ENV="$EXISTING_LAMBDA_ENV" \
FPA_DEPLOY_ENV_KEY="$1" \
uv run python -c '
import json
import os
raw = json.loads(os.environ["FPA_DEPLOY_EXISTING_LAMBDA_ENV"] or "{}")
values = raw if isinstance(raw, dict) else {}
print(values.get(os.environ["FPA_DEPLOY_ENV_KEY"], ""))
'
)
}
EXISTING_DISABLED_DOC_IDS="$(lambda_env_value FPA_DISABLED_DOC_IDS)"
EXISTING_HISTORY_HMAC_KEY="$(lambda_env_value FPA_HISTORY_HMAC_KEY)"
EXISTING_RATE_LIMIT_HMAC_KEY="$(lambda_env_value FPA_RATE_LIMIT_HMAC_KEY)"
# Production evidence controls. The currently reviewed bundle is pinned by its
# deterministic corpus identity. ``yolobus-fares`` is contained by default
# because the committed fare period ended 2026-06-30; remove it only after the
# replacement source has been reviewed, ingested, evaluated, and approved.
PINNED_CORPUS_VERSION="${FPA_PINNED_CORPUS_VERSION:-$(cd "$ROOT" && uv run python -c 'from assistant.corpus import corpus_version; print(corpus_version())')}"
if [[ ${FPA_DISABLED_DOC_IDS+x} ]]; then
DISABLED_DOC_IDS="$FPA_DISABLED_DOC_IDS"
elif [[ -n "$EXISTING_DISABLED_DOC_IDS" ]]; then
DISABLED_DOC_IDS="$EXISTING_DISABLED_DOC_IDS"
else
DISABLED_DOC_IDS="yolobus-fares"
fi
if [[ ${FPA_HISTORY_HMAC_KEY+x} ]]; then
HISTORY_HMAC_KEY="$FPA_HISTORY_HMAC_KEY"
elif [[ -n "$EXISTING_HISTORY_HMAC_KEY" ]]; then
HISTORY_HMAC_KEY="$EXISTING_HISTORY_HMAC_KEY"
else
HISTORY_HMAC_KEY="$(openssl rand -hex 32)"
fi
# The secret that keys every caller digest. It is inherited across deploys, the
# same way the history key is, so a release does not silently reset every
# in-flight counter -- but unlike the history key it is safe to rotate at any
# moment: the worst case is that one 60-second window's counters are abandoned
# and callers start a fresh window early. Rotating it is also the fastest way to
# make an existing table's contents permanently unlinkable to any address.
# It is NOT recorded in the release descriptor, deliberately: the descriptor is
# public release identity, and the identity of a secret that protects rider
# addresses does not belong in it even as a digest.
if [[ ${FPA_RATE_LIMIT_HMAC_KEY+x} ]]; then
RATE_LIMIT_HMAC_KEY="$FPA_RATE_LIMIT_HMAC_KEY"
elif [[ -n "$EXISTING_RATE_LIMIT_HMAC_KEY" ]]; then
RATE_LIMIT_HMAC_KEY="$EXISTING_RATE_LIMIT_HMAC_KEY"
else
RATE_LIMIT_HMAC_KEY="$(openssl rand -hex 32)"
fi
if [[ ! "$PINNED_CORPUS_VERSION" =~ ^[0-9a-f]{12}$ ]]; then
echo "invalid corpus pin: expected a 12-character lowercase hex digest" >&2
exit 2
fi
if [[ -n "$DISABLED_DOC_IDS" && ! "$DISABLED_DOC_IDS" =~ ^[a-z0-9-]+(,[a-z0-9-]+)*$ ]]; then
echo "invalid disabled document list: expected comma-separated document ids" >&2
exit 2
fi
if [[ ! "$HISTORY_HMAC_KEY" =~ ^[0-9a-f]{64}$ ]]; then
echo "invalid history signing key: expected a 64-character lowercase hex secret" >&2
exit 2
fi
if [[ ! "$RATE_LIMIT_HMAC_KEY" =~ ^[0-9a-f]{64}$ ]]; then
echo "invalid caller-digest key: expected a 64-character lowercase hex secret" >&2
exit 2
fi
if [[ ! "$RATE_LIMIT_TABLE" =~ ^[A-Za-z0-9._-]{3,255}$ ]]; then
echo "invalid rate-limit table name: expected a valid DynamoDB table name" >&2
exit 2
fi
if [[ -n "$DISABLED_DOC_IDS" ]]; then
(
cd "$ROOT"
FPA_DEPLOY_DISABLED_DOC_IDS="$DISABLED_DOC_IDS" uv run python -c '
import os
from assistant.ingest import load_chunks
requested = set(os.environ["FPA_DEPLOY_DISABLED_DOC_IDS"].split(","))
known = {chunk.doc_id for chunk in load_chunks()}
unknown = sorted(requested - known)
if unknown:
raise SystemExit("unknown disabled document id(s): " + ", ".join(unknown))
'
)
fi
LAMBDA_ENV="$(
cd "$ROOT"
FPA_DEPLOY_EXISTING_LAMBDA_ENV="$EXISTING_LAMBDA_ENV" \
FPA_DEPLOY_PINNED_CORPUS_VERSION="$PINNED_CORPUS_VERSION" \
FPA_DEPLOY_DISABLED_DOC_IDS="$DISABLED_DOC_IDS" \
FPA_DEPLOY_HISTORY_HMAC_KEY="$HISTORY_HMAC_KEY" \
FPA_DEPLOY_RATE_LIMIT_TABLE="$RATE_LIMIT_TABLE" \
FPA_DEPLOY_RATE_LIMIT_HMAC_KEY="$RATE_LIMIT_HMAC_KEY" \
uv run python -c '
import hashlib
import json
import os
raw = json.loads(os.environ["FPA_DEPLOY_EXISTING_LAMBDA_ENV"] or "{}")
values = raw if isinstance(raw, dict) else {}
history_key = os.environ["FPA_DEPLOY_HISTORY_HMAC_KEY"]
history_key_id = hashlib.sha256(
b"fare-assistant.history-key-id.v1\0" + history_key.encode("ascii")
).hexdigest()
for derived_key in (
"FPA_ARTIFACT_CODE_SHA256",
"FPA_CONFIG_VERSION",
"FPA_PINNED_CONTENT_VERSION",
"FPA_PINNED_SNAPSHOT_VERSION",
"FPA_RELEASE_VERSION",
"FPA_SOURCE_REVISION",
):
values.pop(derived_key, None)
values.update(
{
"FPA_PINNED_CORPUS_VERSION": os.environ["FPA_DEPLOY_PINNED_CORPUS_VERSION"],
"FPA_DISABLED_DOC_IDS": os.environ["FPA_DEPLOY_DISABLED_DOC_IDS"],
"FPA_HISTORY_HMAC_KEY": history_key,
"FPA_HISTORY_HMAC_KEY_ID": history_key_id,
"FPA_RATE_LIMIT_TABLE": os.environ["FPA_DEPLOY_RATE_LIMIT_TABLE"],
"FPA_RATE_LIMIT_HMAC_KEY": os.environ["FPA_DEPLOY_RATE_LIMIT_HMAC_KEY"],
}
)
print(json.dumps({"Variables": values}, separators=(",", ":")))
'
)"
# Return the newest numbered version whose complete versioned configuration
# matches a staged candidate. ListVersionsByFunction omits RuntimeVersionConfig,
# so it is only a code-hash shortlist; every possible match is re-read through
# GetFunctionConfiguration before reuse. This makes interrupted releases
# retryable without freezing an older managed-runtime patch by accident.
exact_published_version() {
local candidate_config="$1"
local versions_json="$2"
local candidate_sha
local version
local version_config
candidate_sha="$(jq -r '.CodeSha256' <<<"$candidate_config")"
for version in $(
jq -r --arg sha "$candidate_sha" '
[.Versions[]
| select((.Version | test("^[1-9][0-9]*$")) and .CodeSha256 == $sha)
| (.Version | tonumber)]
| sort
| reverse[]
' <<<"$versions_json"
); do
version_config="$(
aws lambda get-function-configuration \
--function-name "$FN" --qualifier "$version" \
--region "$REGION" --output json
)"
if same_versioned_release_config "$candidate_config" "$version_config"; then
printf '%s\n' "$version"
return 0
fi
done
return 0
}
# Produce a fail-closed view of configuration that this release does not
# intentionally manage. Unknown future fields stay in the view, so a new AWS
# versioned setting cannot silently hitchhike from mutable $LATEST. Derived
# status/identity fields and the fields explicitly rewritten below are omitted.
unmanaged_config_snapshot() {
local config_json="$1"
(
cd "$ROOT"
FPA_DEPLOY_CONFIG_JSON="$config_json" uv run python -c '
import json
import os
config = json.loads(os.environ["FPA_DEPLOY_CONFIG_JSON"])
managed_or_derived = {
"Architectures",
"CodeSha256",
"CodeSize",
"ConfigSha256",
"Description",
"Environment",
"FunctionArn",
"FunctionName",
"Handler",
"LastModified",
"LastUpdateStatus",
"LastUpdateStatusReason",
"LastUpdateStatusReasonCode",
"LoggingConfig",
"MasterArn",
"MemorySize",
"RevisionId",
"Role",
"Runtime",
"RuntimeVersionConfig",
"SigningJobArn",
"SigningProfileVersionArn",
"State",
"StateReason",
"StateReasonCode",
"Timeout",
"Version",
}
snapshot = {
key: value
for key, value in config.items()
if key not in managed_or_derived
}
snapshot["Layers"] = snapshot.get("Layers") or []
snapshot["FileSystemConfigs"] = snapshot.get("FileSystemConfigs") or []
snapshot["KMSKeyArn"] = snapshot.get("KMSKeyArn") or ""
snapshot["DeadLetterConfig"] = snapshot.get("DeadLetterConfig") or {"TargetArn": ""}
snapshot["TracingConfig"] = snapshot.get("TracingConfig") or {"Mode": "PassThrough"}
snapshot["EphemeralStorage"] = snapshot.get("EphemeralStorage") or {"Size": 512}
vpc = snapshot.get("VpcConfig") or {}
snapshot["VpcConfig"] = {
"SubnetIds": sorted(vpc.get("SubnetIds") or []),
"SecurityGroupIds": sorted(vpc.get("SecurityGroupIds") or []),
"Ipv6AllowedForDualStack": bool(vpc.get("Ipv6AllowedForDualStack", False)),
}
snap_start = snapshot.get("SnapStart") or {}
snapshot["SnapStart"] = {"ApplyOn": snap_start.get("ApplyOn", "None")}
print(json.dumps(snapshot, sort_keys=True, separators=(",", ":")))
'
)
}
assert_same_unmanaged_config() {
local reviewed_json="$1"
local candidate_json="$2"
local context="$3"
local reviewed_snapshot
local candidate_snapshot
reviewed_snapshot="$(unmanaged_config_snapshot "$reviewed_json")"
candidate_snapshot="$(unmanaged_config_snapshot "$candidate_json")"
if [[ "$reviewed_snapshot" != "$candidate_snapshot" ]]; then
echo "$context has unmanaged versioned-configuration drift" >&2
(
cd "$ROOT"
FPA_DEPLOY_REVIEWED_SNAPSHOT="$reviewed_snapshot" \
FPA_DEPLOY_CANDIDATE_SNAPSHOT="$candidate_snapshot" \
uv run python -c '
import json
import os
reviewed = json.loads(os.environ["FPA_DEPLOY_REVIEWED_SNAPSHOT"])
candidate = json.loads(os.environ["FPA_DEPLOY_CANDIDATE_SNAPSHOT"])
changed = sorted(
key
for key in reviewed.keys() | candidate.keys()
if reviewed.get(key) != candidate.get(key)
)
print("changed unmanaged fields: " + ", ".join(changed), file=__import__("sys").stderr)
'
)
echo "review and reconcile those settings against the immutable live version before deploying" >&2
exit 1
fi
}
assert_managed_release_config() {
local config_json="$1"
local context="$2"
local expected_revision="${3:-}"
if ! jq -e \
--arg code_sha "$LOCAL_CODE_SHA" \
--arg log_group "$LOG_GROUP" \
--arg role "$ROLE_ARN" \
--arg revision "$expected_revision" \
--argjson environment "$LAMBDA_ENV" '
.CodeSha256 == $code_sha
and .Runtime == "python3.12"
and .Role == $role
and .Handler == "web.handler.handler"
and .Timeout == 25
and .MemorySize == 512
and .Environment == $environment
and .PackageType == "Zip"
and .Architectures == ["arm64"]
and .LoggingConfig == {
"LogFormat": "JSON",
"ApplicationLogLevel": "INFO",
"SystemLogLevel": "WARN",
"LogGroup": $log_group
}
and ($revision == "" or .RevisionId == $revision)
' <<<"$config_json" >/dev/null; then
echo "$context does not match the locally built artifact and complete managed configuration" >&2
exit 1
fi
}
normalized_release_config() {
local config_json="$1"
(
cd "$ROOT"
FPA_DEPLOY_RELEASE_CONFIG="$config_json" uv run python -c '
import json
import os
config = json.loads(os.environ["FPA_DEPLOY_RELEASE_CONFIG"])
non_behavioral = {
"CodeSize",
"ConfigSha256",
"Description",
"FunctionArn",
"FunctionName",
"LastModified",
"LastUpdateStatus",
"LastUpdateStatusReason",
"LastUpdateStatusReasonCode",
"MasterArn",
"RevisionId",
"SigningJobArn",
"SigningProfileVersionArn",
"State",
"StateReason",
"StateReasonCode",
"Version",
}
snapshot = {
key: value
for key, value in config.items()
if key not in non_behavioral
}
snapshot["Layers"] = snapshot.get("Layers") or []
snapshot["FileSystemConfigs"] = snapshot.get("FileSystemConfigs") or []
snapshot["KMSKeyArn"] = snapshot.get("KMSKeyArn") or ""
snapshot["DeadLetterConfig"] = snapshot.get("DeadLetterConfig") or {"TargetArn": ""}
snapshot["TracingConfig"] = snapshot.get("TracingConfig") or {"Mode": "PassThrough"}
snapshot["EphemeralStorage"] = snapshot.get("EphemeralStorage") or {"Size": 512}
vpc = snapshot.get("VpcConfig") or {}
snapshot["VpcConfig"] = {
"SubnetIds": sorted(vpc.get("SubnetIds") or []),
"SecurityGroupIds": sorted(vpc.get("SecurityGroupIds") or []),
"Ipv6AllowedForDualStack": bool(vpc.get("Ipv6AllowedForDualStack", False)),
}
snap_start = snapshot.get("SnapStart") or {}
snapshot["SnapStart"] = {"ApplyOn": snap_start.get("ApplyOn", "None")}
logging = snapshot.get("LoggingConfig") or {}
snapshot["LoggingConfig"] = {
"LogFormat": logging.get("LogFormat", "Text"),
"LogGroup": logging.get("LogGroup", "/aws/lambda/" + config["FunctionName"]),
**(
{"ApplicationLogLevel": logging["ApplicationLogLevel"]}
if "ApplicationLogLevel" in logging
else {}
),
**(
{"SystemLogLevel": logging["SystemLogLevel"]}
if "SystemLogLevel" in logging
else {}
),
}
print(json.dumps(snapshot, sort_keys=True, separators=(",", ":")))
'
)
}
same_versioned_release_config() {
local first_snapshot
local second_snapshot
first_snapshot="$(normalized_release_config "$1")"
second_snapshot="$(normalized_release_config "$2")"
[[ "$first_snapshot" == "$second_snapshot" ]]
}
# ── stable alias and one-time route migration ───────────────────────────────
ALIAS_ARN="arn:aws:lambda:$REGION:$ACCOUNT:function:$FN:$LIVE_ALIAS"
UNQUALIFIED_ARN="arn:aws:lambda:$REGION:$ACCOUNT:function:$FN"
ALIAS_INTEGRATION_URI="arn:aws:apigateway:$REGION:lambda:path/2015-03-31/functions/$ALIAS_ARN/invocations"
UNQUALIFIED_INTEGRATION_URI="arn:aws:apigateway:$REGION:lambda:path/2015-03-31/functions/$UNQUALIFIED_ARN/invocations"
API_EXISTS=false
INTEGRATION_ID=""
INTEGRATION_URI=""
discover_api() {
local api_ids
local api_count
if [[ -n "$API_ID" ]]; then
aws apigatewayv2 get-api --api-id "$API_ID" --region "$REGION" >/dev/null
API_EXISTS=true
return
fi
api_ids="$(
aws apigatewayv2 get-apis --region "$REGION" \
--query "Items[?Name=='$FN'].ApiId" --output json
)"
api_count="$(jq 'length' <<<"$api_ids")"
if [[ "$api_count" == "0" ]]; then
API_EXISTS=false
elif [[ "$api_count" == "1" ]]; then
API_ID="$(jq -r '.[0]' <<<"$api_ids")"
API_EXISTS=true
else
echo "found multiple HTTP APIs named $FN; set FPA_API_ID explicitly" >&2
exit 1
fi
}
refresh_integration() {
local integrations
local integration_count
INTEGRATION_ID=""
INTEGRATION_URI=""
[[ "$API_EXISTS" == "true" ]] || return
integrations="$(
aws apigatewayv2 get-integrations \
--api-id "$API_ID" --region "$REGION" --query Items --output json
)"
integration_count="$(jq 'length' <<<"$integrations")"
[[ "$integration_count" == "1" ]] || {
echo "expected exactly one integration on HTTP API $API_ID" >&2
exit 1
}
INTEGRATION_ID="$(jq -r '.[0].IntegrationId' <<<"$integrations")"
INTEGRATION_URI="$(jq -r '.[0].IntegrationUri' <<<"$integrations")"
}
integration_targets_live_alias() {
[[ "$INTEGRATION_URI" == "$ALIAS_ARN" \
|| "$INTEGRATION_URI" == "$ALIAS_INTEGRATION_URI" ]]
}
integration_targets_unqualified_function() {
[[ "$INTEGRATION_URI" == "$UNQUALIFIED_ARN" \
|| "$INTEGRATION_URI" == "$UNQUALIFIED_INTEGRATION_URI" ]]
}
ensure_alias_permission() {
local source_arn="arn:aws:execute-api:$REGION:$ACCOUNT:$API_ID/*"
local alias_before
local alias_after
local alias_before_snapshot
local alias_after_snapshot
local alias_before_version
local alias_before_revision
local permission_revision
local policy_response
alias_before="$(
aws lambda get-alias \
--function-name "$FN" --name "$LIVE_ALIAS" --region "$REGION" --output json
)"
assert_unweighted_alias "$alias_before" "$LIVE_ALIAS"
alias_before_version="$(jq -r '.FunctionVersion // ""' <<<"$alias_before")"
alias_before_revision="$(jq -r '.RevisionId // ""' <<<"$alias_before")"
[[ "$alias_before_version" =~ ^[1-9][0-9]*$ && -n "$alias_before_revision" ]] || {
echo "$LIVE_ALIAS has no guarded numbered target for API permission setup" >&2
exit 1
}
if [[ -n "$BASELINE_LIVE_VERSION" \
&& ( "$alias_before_version" != "$BASELINE_LIVE_VERSION" \
|| "$alias_before_revision" != "$BASELINE_LIVE_REVISION" ) ]]; then
echo "live alias changed before API permission setup; refusing to mix release baselines" >&2
exit 1
fi
alias_before_snapshot="$(
jq -S -c '{
AliasArn,
Name,
FunctionVersion,
Description: (.Description // ""),
RoutingConfig: {
AdditionalVersionWeights:
(.RoutingConfig.AdditionalVersionWeights // {})
}
}' <<<"$alias_before"
)"
BASELINE_LIVE_VERSION="$alias_before_version"
BASELINE_LIVE_REVISION="$alias_before_revision"
if policy_response="$(
aws lambda get-policy \
--function-name "$FN" --qualifier "$LIVE_ALIAS" \
--region "$REGION" --output json 2>&1
)"; then
if jq -e \
--arg source "$source_arn" \
--arg resource "$ALIAS_ARN" '
.Policy
| fromjson
| any(.Statement[];
.Sid == "apigw-live"
and .Effect == "Allow"
and .Action == "lambda:InvokeFunction"
and .Resource == $resource
and .Principal.Service == "apigateway.amazonaws.com"
and .Condition.ArnLike["AWS:SourceArn"] == $source)
' <<<"$policy_response" >/dev/null; then
return
fi
if jq -e '
.Policy
| fromjson
| any(.Statement[]; .Sid == "apigw-live")
' <<<"$policy_response" >/dev/null; then
echo "alias policy statement apigw-live exists but does not match the reviewed API permission" >&2
echo "remove or repair that statement explicitly before deploying" >&2
exit 1
fi
elif [[ "$policy_response" != *"ResourceNotFoundException"* ]]; then
echo "could not inspect the $LIVE_ALIAS alias policy:" >&2
echo "$policy_response" >&2
exit 1
fi
# A qualified resource-policy mutation advances the same revision reported
# by GetAlias/GetPolicy. Guard the write with the pre-policy revision, then
# adopt only the new revision that both APIs report for unchanged routing.
aws lambda add-permission \
--function-name "$FN" \
--qualifier "$LIVE_ALIAS" \
--statement-id apigw-live \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-account "$ACCOUNT" \
--source-arn "$source_arn" \
--revision-id "$alias_before_revision" \
--region "$REGION" >/dev/null
policy_response="$(
aws lambda get-policy \
--function-name "$FN" --qualifier "$LIVE_ALIAS" \
--region "$REGION" --output json
)"
jq -e \
--arg source "$source_arn" \
--arg resource "$ALIAS_ARN" '
.Policy
| fromjson
| any(.Statement[];
.Sid == "apigw-live"
and .Effect == "Allow"
and .Action == "lambda:InvokeFunction"
and .Resource == $resource
and .Principal.Service == "apigateway.amazonaws.com"
and .Condition.ArnLike["AWS:SourceArn"] == $source)
' <<<"$policy_response" >/dev/null || {
echo "alias permission apigw-live was not installed with the reviewed scope" >&2
exit 1
}
permission_revision="$(jq -r '.RevisionId // ""' <<<"$policy_response")"
[[ -n "$permission_revision" ]] || {
echo "alias permission installation returned no revision id" >&2
exit 1
}
alias_after="$(
aws lambda get-alias \
--function-name "$FN" --name "$LIVE_ALIAS" --region "$REGION" --output json
)"
assert_unweighted_alias "$alias_after" "$LIVE_ALIAS"
alias_after_snapshot="$(
jq -S -c '{
AliasArn,
Name,
FunctionVersion,
Description: (.Description // ""),
RoutingConfig: {
AdditionalVersionWeights:
(.RoutingConfig.AdditionalVersionWeights // {})
}
}' <<<"$alias_after"
)"
if [[ "$alias_after_snapshot" != "$alias_before_snapshot" \
|| "$(jq -r '.RevisionId // ""' <<<"$alias_after")" != "$permission_revision" ]]; then
echo "live alias changed outside the guarded API permission mutation" >&2
exit 1
fi
LIVE_VERSION="$alias_before_version"
LIVE_REVISION="$permission_revision"
BASELINE_LIVE_VERSION="$alias_before_version"
BASELINE_LIVE_REVISION="$permission_revision"
}
remove_unqualified_api_permission() {
local removal
local remaining_policy
if ! removal="$(
aws lambda remove-permission \
--function-name "$FN" --statement-id apigw \
--region "$REGION" 2>&1
)"; then
[[ "$removal" == *"ResourceNotFoundException"* ]] || {
echo "alias route is live, but the old unqualified permission could not be removed:" >&2
echo "$removal" >&2
exit 1
}
fi
if remaining_policy="$(
aws lambda get-policy \
--function-name "$FN" --region "$REGION" --output json 2>&1
)"; then
if jq -e '.Policy | fromjson | any(.Statement[]; .Sid == "apigw")' \
<<<"$remaining_policy" >/dev/null; then
echo "old unqualified API Gateway permission is still present" >&2
exit 1
fi
elif [[ "$remaining_policy" != *"ResourceNotFoundException"* ]]; then
echo "could not verify removal of the old unqualified permission:" >&2
echo "$remaining_policy" >&2
exit 1
fi
}
ensure_initial_rollback_alias() {
local target_version="$1"
local description="$2"
local rollback_json
local rollback_version
local rollback_revision
if rollback_json="$(
aws lambda get-alias \
--function-name "$FN" --name "$ROLLBACK_ALIAS" \
--region "$REGION" --output json 2>&1
)"; then