forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_check_public_build_contract.py
More file actions
817 lines (726 loc) · 33.2 KB
/
Copy pathtest_check_public_build_contract.py
File metadata and controls
817 lines (726 loc) · 33.2 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
#!/usr/bin/env python3
"""Fixtures for the public-build contract, source preflight, and browser smoke."""
from __future__ import annotations
import base64
import importlib.util
import json
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[2]
STATIC_PATH = ROOT / ".github" / "scripts" / "check_public_build_contract.py"
PREFLIGHT_PATH = ROOT / ".github" / "scripts" / "preflight_public_build_config.py"
SMOKE_PATH = ROOT / ".github" / "scripts" / "smoke_public_build_browser.py"
RUNTIME_PREFLIGHT_PATH = ROOT / ".github" / "scripts" / "preflight_public_build_runtime.py"
def load_module(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise RuntimeError(f"cannot load {path}")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
STATIC = load_module("check_public_build_contract", STATIC_PATH)
PREFLIGHT = load_module("preflight_public_build_config", PREFLIGHT_PATH)
SMOKE = load_module("smoke_public_build_browser", SMOKE_PATH)
RUNTIME_PREFLIGHT = load_module("preflight_public_build_runtime", RUNTIME_PREFLIGHT_PATH)
def fixture_contract() -> dict:
return {
"schema_version": 4,
"configuration": {
"source": "repository_config",
"path": "config/public-build-values.json",
"environments": ["development", "prod"],
},
"targets": {
"fake": {
"service": "fake-service",
"dockerfile": "web/fake/Dockerfile",
"workflow": ".github/workflows/gcp_fake.yml",
"deployment": {
"region": "us-central1",
"build_context": ".",
"platforms": ["linux/amd64"],
"flags": [],
"runtime_secrets": {"FAKE_RUNTIME_SECRET": "FAKE_RUNTIME_SECRET:latest"},
"preserve_runtime_secrets": [],
"runtime_env_vars": {},
"remove_runtime_secrets": [],
},
"canary_component": "web/fake/public-build-canary.tsx",
"inputs": [
{
"name": "FAKE_PUBLIC_INPUT",
"required": True,
"source": "repository_config",
"allowed_scopes": ["repository"],
}
],
"candidate_acceptance": {
"command": [
"python3",
".github/scripts/smoke_public_build_browser.py",
"--target",
"fake",
"--base-url",
"{base_url}",
],
"marker": "fake:ready",
},
"traffic_promotion": "candidate_after_browser_acceptance",
}
},
}
def fixture_values(value: str = "configured") -> dict:
return {
"schema_version": 1,
"environments": {
"development": {"values": {"FAKE_PUBLIC_INPUT": value}},
"prod": {"values": {"FAKE_PUBLIC_INPUT": value}},
},
}
class PublicBuildContractFixture(unittest.TestCase):
def setUp(self) -> None:
self.temp_dir = tempfile.TemporaryDirectory(prefix="omi-public-build-contract-")
self.root = Path(self.temp_dir.name)
self.write_json("config/public-build-contract.json", fixture_contract())
self.write_json("config/public-build-values.json", fixture_values())
self.write_json(
"config/deployment-setting-classification.json",
{"kinds": {"public_build": ["FAKE_PUBLIC_INPUT"]}},
)
self.write(
"web/fake/Dockerfile",
"""ARG FAKE_PUBLIC_INPUT
ENV OMI_REQUIRED_PUBLIC_BUILD_INPUTS="FAKE_PUBLIC_INPUT"
RUN for name in $OMI_REQUIRED_PUBLIC_BUILD_INPUTS; do value="$(printenv "$name" || true)"; test -n "$value"; done
""",
)
self.write(
".github/workflows/gcp_fake.yml",
"""steps:
- uses: ./.github/actions/deploy-public-build
""",
)
self.write(
"web/fake/public-build-canary.tsx",
'<span data-omi-public-build-canary="fake:ready" />\n',
)
self.write(
".github/workflows/public-build-config-preflight.yml",
"""on:
pull_request:
workflow_dispatch:
""",
)
def tearDown(self) -> None:
self.temp_dir.cleanup()
def write(self, relative_path: str, contents: str) -> None:
path = self.root / relative_path
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(contents, encoding="utf-8")
def write_json(self, relative_path: str, value: object) -> None:
self.write(relative_path, json.dumps(value))
def target(self):
return STATIC.load_contract(self.root / "config/public-build-contract.json").targets["fake"]
def errors(self) -> list[str]:
return STATIC.validate_target(self.root, self.target(), {"FAKE_PUBLIC_INPUT"})
def test_accepts_centralized_public_build_deployment(self) -> None:
self.assertEqual(self.errors(), [])
def test_rejects_direct_build_or_deploy_wiring(self) -> None:
self.write(
".github/workflows/gcp_fake.yml",
(self.root / ".github/workflows/gcp_fake.yml").read_text(encoding="utf-8")
+ " - uses: docker/build-push-action@v7\n",
)
self.assertIn("bypasses centralized public-build deployment", "\n".join(self.errors()))
def test_rejects_missing_declared_build_context(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["build_context"] = "web/missing"
self.write_json("config/public-build-contract.json", contract)
self.assertIn("Docker build context is missing", "\n".join(self.errors()))
def test_rejects_scheduled_public_build_reconciliation(self) -> None:
self.write(
".github/workflows/public-build-config-preflight.yml",
"""on:
pull_request:
workflow_dispatch:
schedule:
- cron: '* * * * *'
""",
)
self.assertIn("must not schedule drift checks", "\n".join(STATIC.validate_jit_preflight_workflow(self.root)))
def test_rejects_overlap_across_runtime_binding_groups(self) -> None:
binding_groups = {
"runtime_secrets": {"SHARED_RUNTIME_BINDING": "shared-runtime-binding:latest"},
"preserve_runtime_secrets": ["SHARED_RUNTIME_BINDING"],
"runtime_env_vars": {"SHARED_RUNTIME_BINDING": "reviewed.example"},
"remove_runtime_secrets": ["SHARED_RUNTIME_BINDING"],
}
group_names = tuple(binding_groups)
for index, left in enumerate(group_names):
for right in group_names[index + 1 :]:
with self.subTest(left=left, right=right):
contract = fixture_contract()
deployment = contract["targets"]["fake"]["deployment"]
for name in group_names:
deployment[name] = {} if name in {"runtime_secrets", "runtime_env_vars"} else []
deployment[left] = binding_groups[left]
deployment[right] = binding_groups[right]
self.write_json("config/public-build-contract.json", contract)
with self.assertRaisesRegex(ValueError, "runtime binding groups cannot overlap"):
self.target()
def test_rejects_runtime_env_values_that_cannot_be_rendered_as_action_input(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["runtime_env_vars"] = {"FAKE_RUNTIME_CONFIG": "one,two"}
self.write_json("config/public-build-contract.json", contract)
with self.assertRaisesRegex(
ValueError, "runtime_env_vars must map environment names to non-empty deploy-safe values"
):
self.target()
def test_runtime_env_vars_must_be_classified_as_reviewed_config(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["runtime_env_vars"] = {"FAKE_RUNTIME_CONFIG": "reviewed.example"}
self.write_json("config/public-build-contract.json", contract)
self.assertEqual(
STATIC.validate_target(self.root, self.target(), {"FAKE_PUBLIC_INPUT"}, {"FAKE_RUNTIME_CONFIG"}),
[],
)
self.assertEqual(
STATIC.validate_target(self.root, self.target(), {"FAKE_PUBLIC_INPUT"}),
["fake: runtime env FAKE_RUNTIME_CONFIG is not classified config"],
)
def test_runtime_preflight_rejects_literal_binding(self) -> None:
service = {
"template": {
"containers": [
{
"env": [
{"name": "FAKE_RUNTIME_SECRET", "value": "not-a-secret-reference"},
]
}
]
}
}
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service),
[
"fake: runtime binding FAKE_RUNTIME_SECRET is a literal; expected Secret Manager "
"FAKE_RUNTIME_SECRET:latest"
],
)
def test_runtime_preflight_accepts_absent_or_matching_binding(self) -> None:
matching_service = {
"template": {
"containers": [
{
"env": [
{
"name": "FAKE_RUNTIME_SECRET",
"valueSource": {"secretKeyRef": {"secret": "FAKE_RUNTIME_SECRET", "version": "latest"}},
}
]
}
]
}
}
self.assertEqual(RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), {"template": {}}), [])
self.assertEqual(RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), matching_service), [])
def test_runtime_preflight_accepts_v1_secret_binding(self) -> None:
service = {
"spec": {
"template": {
"spec": {
"containers": [
{
"env": [
{
"name": "FAKE_RUNTIME_SECRET",
"valueFrom": {"secretKeyRef": {"name": "FAKE_RUNTIME_SECRET", "key": "latest"}},
}
]
}
]
}
}
}
}
self.assertEqual(RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service), [])
def test_runtime_preflight_normalizes_v1_and_v2_secret_binding_shapes(self) -> None:
v1_service = {
"spec": {
"template": {
"spec": {
"containers": [
{
"env": [
{
"name": "FAKE_RUNTIME_SECRET",
"valueFrom": {"secretKeyRef": {"name": "legacy-secret", "key": "7"}},
}
]
}
]
}
}
}
}
v2_service = {
"template": {
"containers": [
{
"env": [
{
"name": "FAKE_RUNTIME_SECRET",
"valueSource": {"secretKeyRef": {"secret": "legacy-secret", "version": "7"}},
}
]
}
]
}
}
expected = {"FAKE_RUNTIME_SECRET": RUNTIME_PREFLIGHT.RuntimeBinding("secret", "legacy-secret:7")}
self.assertEqual(RUNTIME_PREFLIGHT.current_bindings(v1_service), expected)
self.assertEqual(RUNTIME_PREFLIGHT.current_bindings(v2_service), expected)
def test_runtime_preflight_fails_closed_for_malformed_or_ambiguous_secret_binding_shapes(self) -> None:
malformed_sources = (
{"valueFrom": {"secretKeyRef": {"name": "legacy-secret"}}},
{"valueFrom": {"secretKeyRef": {"key": "7"}}},
{"valueSource": {"secretKeyRef": {"secret": "legacy-secret"}}},
{"valueSource": {"secretKeyRef": {"version": "7"}}},
{"valueSource": {"secretKeyRef": {"secret": "legacy-secret", "version": 7}}},
{"valueFrom": {"secretKeyRef": {"secret": "legacy-secret", "version": "7"}}},
{"valueSource": {"secretKeyRef": {"name": "legacy-secret", "key": "7"}}},
{
"valueSource": {
"secretKeyRef": {
"name": "legacy-secret",
"key": "7",
"secret": "other-secret",
"version": "8",
}
}
},
{
"valueSource": {
"secretKeyRef": {"secret": "legacy-secret", "version": "7"},
"configMapKeyRef": {"name": "other-source"},
}
},
{
"valueFrom": {"secretKeyRef": {"name": "legacy-secret", "key": "7"}},
"valueSource": {"secretKeyRef": {"secret": "other-secret", "version": "8"}},
},
{
"value": "literal",
"valueFrom": {"secretKeyRef": {"name": "legacy-secret", "key": "7"}},
},
{
"value": "literal",
"valueSource": {"secretKeyRef": {"secret": "legacy-secret", "version": "7"}},
},
)
for source in malformed_sources:
with self.subTest(source=source):
service = {"template": {"containers": [{"env": [{"name": "FAKE_RUNTIME_SECRET", **source}]}]}}
self.assertEqual(
RUNTIME_PREFLIGHT.current_bindings(service),
{"FAKE_RUNTIME_SECRET": RUNTIME_PREFLIGHT.RuntimeBinding("invalid")},
)
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service),
["fake-service: runtime binding FAKE_RUNTIME_SECRET has an ambiguous or malformed value source"],
)
def test_runtime_preflight_rejects_disabled_secret_version(self) -> None:
original = RUNTIME_PREFLIGHT._gcloud_json
RUNTIME_PREFLIGHT._gcloud_json = lambda _args: {"state": "DISABLED"}
try:
errors = RUNTIME_PREFLIGHT.validate_secret_versions(target=self.target(), project_id="fake-project")
finally:
RUNTIME_PREFLIGHT._gcloud_json = original
self.assertEqual(
errors,
[
"fake-service: runtime binding FAKE_RUNTIME_SECRET requires enabled Secret Manager version "
"FAKE_RUNTIME_SECRET:latest"
],
)
def test_runtime_preflight_reports_service_and_binding_for_an_unavailable_secret_version(self) -> None:
original = RUNTIME_PREFLIGHT._gcloud_json
def missing_version(_args):
raise RUNTIME_PREFLIGHT.RuntimePreflightError("resource not found", category="not_found")
RUNTIME_PREFLIGHT._gcloud_json = missing_version
try:
errors = RUNTIME_PREFLIGHT.validate_secret_versions(target=self.target(), project_id="fake-project")
finally:
RUNTIME_PREFLIGHT._gcloud_json = original
self.assertEqual(
errors,
[
"fake-service: runtime binding FAKE_RUNTIME_SECRET requires Secret Manager version "
"FAKE_RUNTIME_SECRET:latest, but it is unavailable (resource not found)"
],
)
def test_runtime_preflight_accepts_an_enabled_secret_version(self) -> None:
original = RUNTIME_PREFLIGHT._gcloud_json
RUNTIME_PREFLIGHT._gcloud_json = lambda _args: {"state": "ENABLED"}
try:
errors = RUNTIME_PREFLIGHT.validate_secret_versions(target=self.target(), project_id="fake-project")
finally:
RUNTIME_PREFLIGHT._gcloud_json = original
self.assertEqual(errors, [])
def test_runtime_preflight_rejects_a_live_secret_binding_missing_from_the_deployment_contract(self) -> None:
service = {
"template": {
"containers": [
{
"env": [
{
"name": "STALE_RUNTIME_SECRET",
"valueSource": {"secretKeyRef": {"secret": "stale-secret", "version": "latest"}},
}
]
}
]
}
}
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service),
["fake-service: secret binding STALE_RUNTIME_SECRET is missing from the deployment contract"],
)
def test_runtime_preflight_allows_a_live_secret_binding_rendered_for_removal(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["remove_runtime_secrets"] = ["STALE_RUNTIME_SECRET"]
self.write_json("config/public-build-contract.json", contract)
service = {
"template": {
"containers": [
{
"env": [
{
"name": "STALE_RUNTIME_SECRET",
"valueSource": {"secretKeyRef": {"secret": "stale-secret", "version": "latest"}},
}
]
}
]
}
}
self.assertEqual(RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service), [])
def test_runtime_preflight_preserves_the_live_secret_reference_without_guessing_it(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["preserve_runtime_secrets"] = ["PRESERVED_RUNTIME_SECRET"]
self.write_json("config/public-build-contract.json", contract)
service = {
"template": {
"containers": [
{
"env": [
{
"name": "PRESERVED_RUNTIME_SECRET",
"valueSource": {"secretKeyRef": {"secret": "legacy-secret", "version": "7"}},
}
]
}
]
}
}
self.assertEqual(RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service), [])
calls: list[list[str]] = []
original = RUNTIME_PREFLIGHT._gcloud_json
def enabled(arguments):
calls.append(arguments)
return {"state": "ENABLED"}
RUNTIME_PREFLIGHT._gcloud_json = enabled
try:
errors = RUNTIME_PREFLIGHT.validate_preserved_secret_versions(
target=self.target(), service=service, project_id="fake-project"
)
finally:
RUNTIME_PREFLIGHT._gcloud_json = original
self.assertEqual(errors, [])
self.assertIn("--secret=legacy-secret", calls[0])
self.assertIn("7", calls[0])
def test_runtime_preflight_rejects_a_disabled_preserved_secret_version(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["preserve_runtime_secrets"] = ["PRESERVED_RUNTIME_SECRET"]
self.write_json("config/public-build-contract.json", contract)
service = {
"template": {
"containers": [
{
"env": [
{
"name": "PRESERVED_RUNTIME_SECRET",
"valueSource": {"secretKeyRef": {"secret": "legacy-secret", "version": "7"}},
}
]
}
]
}
}
original = RUNTIME_PREFLIGHT._gcloud_json
RUNTIME_PREFLIGHT._gcloud_json = lambda _args: {"state": "DISABLED"}
try:
errors = RUNTIME_PREFLIGHT.validate_preserved_secret_versions(
target=self.target(), service=service, project_id="fake-project"
)
finally:
RUNTIME_PREFLIGHT._gcloud_json = original
self.assertEqual(
errors,
[
"fake-service: runtime binding PRESERVED_RUNTIME_SECRET requires enabled Secret Manager version "
"legacy-secret:7"
],
)
def test_runtime_preflight_rejects_missing_or_literal_preserved_secret(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["preserve_runtime_secrets"] = ["PRESERVED_RUNTIME_SECRET"]
self.write_json("config/public-build-contract.json", contract)
literal_service = {
"template": {"containers": [{"env": [{"name": "PRESERVED_RUNTIME_SECRET", "value": "not-a-secret"}]}]}
}
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), {"template": {}}),
[
"fake: preserved runtime secret PRESERVED_RUNTIME_SECRET is absent; expected an enabled Secret Manager binding"
],
)
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), literal_service),
[
"fake: preserved runtime secret PRESERVED_RUNTIME_SECRET is a literal; expected an enabled Secret Manager binding"
],
)
def test_runtime_preflight_rejects_a_literal_secret_union_for_a_preserved_binding(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["preserve_runtime_secrets"] = ["PRESERVED_RUNTIME_SECRET"]
self.write_json("config/public-build-contract.json", contract)
service = {
"template": {
"containers": [
{
"env": [
{
"name": "PRESERVED_RUNTIME_SECRET",
"value": "literal",
"valueSource": {"secretKeyRef": {"secret": "legacy-secret", "version": "7"}},
}
]
}
]
}
}
self.assertEqual(
RUNTIME_PREFLIGHT.current_bindings(service),
{"PRESERVED_RUNTIME_SECRET": RUNTIME_PREFLIGHT.RuntimeBinding("invalid")},
)
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service),
["fake-service: runtime binding PRESERVED_RUNTIME_SECRET has an ambiguous or malformed value source"],
)
def test_runtime_preflight_requires_a_live_service_to_preserve_secret_bindings(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["preserve_runtime_secrets"] = ["PRESERVED_RUNTIME_SECRET"]
self.write_json("config/public-build-contract.json", contract)
original_validate = RUNTIME_PREFLIGHT.validate_secret_versions
original_load = RUNTIME_PREFLIGHT.load_current_service
RUNTIME_PREFLIGHT.validate_secret_versions = lambda **_kwargs: []
RUNTIME_PREFLIGHT.load_current_service = lambda **_kwargs: None
try:
errors = RUNTIME_PREFLIGHT.preflight(target=self.target(), project_id="fake-project")
finally:
RUNTIME_PREFLIGHT.validate_secret_versions = original_validate
RUNTIME_PREFLIGHT.load_current_service = original_load
self.assertEqual(
errors,
["fake: cannot preserve runtime secrets because current Cloud Run service fake-service is absent"],
)
def test_runtime_preflight_rejects_secret_where_reviewed_runtime_config_will_be_applied(self) -> None:
contract = fixture_contract()
contract["targets"]["fake"]["deployment"]["runtime_env_vars"] = {"FAKE_RUNTIME_CONFIG": "reviewed.example"}
self.write_json("config/public-build-contract.json", contract)
service = {
"template": {
"containers": [
{
"env": [
{
"name": "FAKE_RUNTIME_CONFIG",
"valueSource": {"secretKeyRef": {"secret": "incorrect", "version": "latest"}},
}
]
}
]
}
}
self.assertEqual(
RUNTIME_PREFLIGHT.validate_current_bindings(self.target(), service),
["fake: runtime config FAKE_RUNTIME_CONFIG is a Secret Manager binding; expected a literal value"],
)
def test_personas_contract_reconciles_the_failed_live_runtime_bindings(self) -> None:
# Static deployment-contract fixture: the handler must consume the
# reviewed linkedin-api8 host for its documented profile-data endpoint
# while the API key stays a runtime secret.
contract = STATIC.load_contract(ROOT / "config" / "public-build-contract.json")
personas = contract.targets["personas"]
self.assertNotIn("LINKEDIN_API_HOST", personas.deployment.runtime_secrets)
self.assertEqual(personas.deployment.runtime_secrets["LINKEDIN_API_KEY"], "NEXT_PUBLIC_LINKEDIN_API_KEY:latest")
self.assertEqual(
personas.deployment.runtime_env_vars,
{"LINKEDIN_RAPIDAPI_HOST": "linkedin-api8.p.rapidapi.com"},
)
self.assertEqual(
personas.deployment.preserve_runtime_secrets,
("REDIS_HOST", "REDIS_PASSWORD", "NEXT_PUBLIC_OMI_APP_ID", "NEXT_PUBLIC_OMI_API_KEY"),
)
self.assertEqual(
personas.deployment.remove_runtime_secrets,
(
"LINKEDIN_API_HOST",
"NEXT_PUBLIC_FIREBASE_API_KEY",
"NEXT_PUBLIC_FIREBASE_APP_ID",
"NEXT_PUBLIC_FIREBASE_VAPID_KEY",
"NEXT_PUBLIC_MIXPANEL_TOKEN",
"NEXT_PUBLIC_RAPIDAPI_KEY",
"NEXT_PUBLIC_RAPIDAPI_HOST",
"NEXT_PUBLIC_LINKEDIN_API_KEY",
"CLAUDE_API_KEY",
),
)
live_bindings = {
name: {"valueSource": {"secretKeyRef": {"secret": reference.rsplit(":", 1)[0], "version": "latest"}}}
for name, reference in personas.deployment.runtime_secrets.items()
}
live_bindings.update(
{
"REDIS_HOST": {"valueSource": {"secretKeyRef": {"secret": "legacy-redis-host", "version": "9"}}},
"REDIS_PASSWORD": {
"valueSource": {"secretKeyRef": {"secret": "legacy-redis-password", "version": "4"}}
},
"NEXT_PUBLIC_OMI_APP_ID": {
"valueSource": {"secretKeyRef": {"secret": "legacy-app-id", "version": "2"}}
},
"NEXT_PUBLIC_OMI_API_KEY": {
"valueSource": {"secretKeyRef": {"secret": "legacy-api-key", "version": "6"}}
},
"LINKEDIN_API_HOST": {
"valueSource": {"secretKeyRef": {"secret": "NEXT_PUBLIC_LINKEDIN_API_HOST", "version": "latest"}}
},
**{
name: {"valueSource": {"secretKeyRef": {"secret": f"retired-{name.lower()}", "version": "latest"}}}
for name in personas.deployment.remove_runtime_secrets
if name != "LINKEDIN_API_HOST"
},
}
)
service = {
"template": {
"containers": [{"env": [{"name": name, **binding} for name, binding in live_bindings.items()]}]
}
}
self.assertEqual(RUNTIME_PREFLIGHT.validate_current_bindings(personas, service), [])
calls: list[list[str]] = []
original = RUNTIME_PREFLIGHT._gcloud_json
def enabled(arguments):
calls.append(arguments)
return {"state": "ENABLED"}
RUNTIME_PREFLIGHT._gcloud_json = enabled
try:
self.assertEqual(RUNTIME_PREFLIGHT.validate_secret_versions(target=personas, project_id="fake-project"), [])
finally:
RUNTIME_PREFLIGHT._gcloud_json = original
self.assertNotIn(
"--secret=NEXT_PUBLIC_LINKEDIN_API_HOST",
[argument for call in calls for argument in call],
)
route = (ROOT / "web/personas-open-source/src/app/api/social-profile/route.ts").read_text(encoding="utf-8")
self.assertIn("process.env.LINKEDIN_RAPIDAPI_HOST", route)
self.assertNotIn("process.env.LINKEDIN_API_HOST", route)
self.assertIn("headers = rapidApiHeaders(linkedinApiKey, linkedinRapidApiHost);", route)
self.assertIn(
"https://${linkedinRapidApiHost}/profile-data-connection-count-posts?username=${encodeURIComponent(", route
)
readme = (ROOT / "web/personas-open-source/README.md").read_text(encoding="utf-8")
self.assertIn("/rockapis-rockapis-default/api/linkedin-api8", readme)
self.assertIn("LINKEDIN_RAPIDAPI_HOST=linkedin-api8.p.rapidapi.com", readme)
def test_rejects_a_required_value_missing_from_reviewed_source(self) -> None:
contract = STATIC.load_contract(self.root / "config/public-build-contract.json")
values = STATIC.parse_values_document(fixture_values(value=""), source="fixture")
self.assertEqual(
STATIC.validate_values(contract, values, contract.targets.values(), "prod"),
["fake: required input FAKE_PUBLIC_INPUT is missing or empty in prod"],
)
def test_preflight_blocks_an_absent_newly_referenced_input_before_build(self) -> None:
original = PREFLIGHT.request_remote_values
PREFLIGHT.request_remote_values = lambda **_kwargs: STATIC.parse_values_document(
fixture_values(value=""), source="fixture"
)
try:
result = PREFLIGHT.main(
[
"--target",
"fake",
"--environment",
"prod",
"--repository",
"owner/repo",
"--ref",
"deadbeef",
"--token",
"token",
"--contract",
str(self.root / "config/public-build-contract.json"),
]
)
finally:
PREFLIGHT.request_remote_values = original
self.assertEqual(result, 1)
def test_rejects_workflow_variable_bypass(self) -> None:
self.write(
".github/workflows/gcp_fake.yml",
(self.root / ".github/workflows/gcp_fake.yml").read_text(encoding="utf-8")
+ "FAKE_PUBLIC_INPUT=${{ vars.FAKE_PUBLIC_INPUT }}\n",
)
self.assertIn("bypasses repository_config", "\n".join(self.errors()))
def test_rejects_missing_client_canary(self) -> None:
self.write("web/fake/public-build-canary.tsx", "<span />\n")
self.assertIn("must expose fake browser canary", "\n".join(self.errors()))
def test_remote_preflight_decodes_reviewed_configuration_without_printing_values(self) -> None:
remote = json.dumps(fixture_values()).encode("utf-8")
class Response:
def read(self) -> bytes:
return json.dumps({"encoding": "base64", "content": base64.b64encode(remote).decode("ascii")}).encode(
"utf-8"
)
def __enter__(self):
return self
def __exit__(self, *_args) -> None:
return None
original = PREFLIGHT.urllib.request.urlopen
PREFLIGHT.urllib.request.urlopen = lambda *_args, **_kwargs: Response()
try:
values = PREFLIGHT.request_remote_values(
repository="owner/repo", ref="deadbeef", config_path="config/public-build-values.json", token="token"
)
finally:
PREFLIGHT.urllib.request.urlopen = original
self.assertEqual(values["prod"]["FAKE_PUBLIC_INPUT"], "configured")
def test_browser_smoke_requires_the_ready_marker(self) -> None:
original = SMOKE.render_candidate
SMOKE.render_candidate = lambda **_kwargs: '<span data-omi-public-build-canary="fake:ready" />'
try:
SMOKE.smoke(
target="fake",
base_url="https://candidate.example",
contract_path=self.root / "config/public-build-contract.json",
environment={"OMI_BROWSER_BIN": "fake-browser"},
)
finally:
SMOKE.render_candidate = original
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()