This repository has been archived by the owner on Nov 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
policy_engine.py
executable file
·2722 lines (2381 loc) · 90.3 KB
/
policy_engine.py
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 python
"""
Implement GitHub Actions workflow evaluation as step towards workflow based
policy engine. TODO Receipts with attestations for SLSA L4.
```mermaid
graph TD
subgraph Tool_Catalog[Tool Catalog]
subgraph Third_Party[3rd Party Catalog - Open Source / External OpenAPI Endpoints]
run_kubernetes_get_pod[kubectl get pod]
run_kubernetes_delete_deployment[kubectl delete deploy $deployment_name]
end
subgraph Second_Party[2nd Party Catalog - Org Local OpenAPI Endpoints]
query_org_database[Query Org Database]
end
query_org_database --> tool_catalog_list_tools
run_kubernetes_get_pod --> tool_catalog_list_tools
run_kubernetes_delete_deployment --> tool_catalog_list_tools
tool_catalog_list_tools[#47;tools#47;list]
end
subgraph llm_provider_Endpoint[LLM Endpoint - https://api.openai.com/v1/]
llm_provider_completions_endpoint[#47;chat#47;completions]
llm_provider_completions_endpoint --> query_org_database
llm_provider_completions_endpoint --> run_kubernetes_get_pod
llm_provider_completions_endpoint --> run_kubernetes_delete_deployment
end
subgraph Transparency_Service[Transparency Service]
Transparency_Service_Statement_Submission_Endpoint[POST #47;entries]
Transparency_Service_Policy_Engine[Decide admicability per Registration Policy]
Transparency_Service_Receipt_Endpoint[GET #47;receipts#47;urn...qnGmr1o]
Transparency_Service_Statement_Submission_Endpoint --> Transparency_Service_Policy_Engine
Transparency_Service_Policy_Engine --> Transparency_Service_Receipt_Endpoint
end
subgraph LLM_Proxy[LLM Proxy]
llm_proxy_completions_endpoint[#47;chat#47;completions]
intercept_tool_definitions[Intercept tool definitions to LLM]
add_tool_definitions[Add tools from tool catalog to tool definitions]
make_modified_request_to_llm_provider[Make modified request to llm_provider]
validate_llm_reponse_tool_calls[Validate LLM reponse tool calls]
llm_proxy_completions_endpoint --> intercept_tool_definitions
intercept_tool_definitions --> add_tool_definitions
tool_catalog_list_tools --> add_tool_definitions
add_tool_definitions --> make_modified_request_to_llm_provider
make_modified_request_to_llm_provider --> llm_provider_completions_endpoint
llm_provider_completions_endpoint --> validate_llm_reponse_tool_calls
validate_llm_reponse_tool_calls --> Transparency_Service_Statement_Submission_Endpoint
Transparency_Service_Receipt_Endpoint --> validate_llm_reponse_tool_calls
validate_llm_reponse_tool_calls --> llm_proxy_completions_endpoint
end
subgraph AI_Agent[AI Agent]
langchain_agent[langchain.ChatOpenAI] --> llm_proxy_completions_endpoint
end
llm_proxy_completions_endpoint -->|Return proxied response| langchain_agent
```
Testing with token auth (fine grained tokens required for status checks):
NO_CELERY=1 GITHUB_TOKEN=$(gh auth token) nodemon -e py --exec 'clear; python -m pytest -s -vv scitt_emulator/policy_engine.py; test 1'
Testing with GitHub App auth:
LIFESPAN_CONFIG_1=github_app.yaml LIFESPAN_CALLBACK_1=scitt_emulator.policy_engine:lifespan_github_app_gidgethub nodemon -e py --exec 'clear; pytest -s -vv scitt_emulator/policy_engine.py; test 1'
**github_app.yaml**
```yaml
app_id: 1234567
private_key: |
-----BEGIN RSA PRIVATE KEY-----
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
-----END RSA PRIVATE KEY-----
```
Usage with Celery:
Terminal 1:
```bash
nodemon --signal SIGKILL -e py --exec 'clear; ./scitt_emulator/policy_engine.py --lifespan scitt_emulator.policy_engine:lifespan_github_app_gidgethub github_app.yaml api --workers 1 --bind 0.0.0.0:8080; test 1'
```
Terminal 2:
nodemon -e py --exec 'clear; ./scitt_emulator/policy_engine.py --lifespan scitt_emulator.policy_engine:lifespan_github_app_gidgethub github_app.yaml worker; test 1'
Usage without Celery:
Terminal 1:
```bash
GITHUB_TOKEN=$(gh auth token) NO_CELERY=1 ./scitt_emulator/policy_engine.py --workers 1
```
**request.yml**
```yaml
context:
config:
env:
GITHUB_REPOSITORY: "scitt-community/scitt-api-emulator"
GITHUB_API: "https://api.github.com/"
GITHUB_ACTOR: "aliceoa"
GITHUB_ACTOR_ID: "1234567"
secrets:
MY_SECRET: "test-secret"
workflow: |
on:
push:
branches:
- main
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
```
In another terminal request exec via curl:
```bash
jsonschema -i <(cat request.yml | python -c 'import json, yaml, sys; print(json.dumps(yaml.safe_load(sys.stdin.read()), indent=4, sort_keys=True))') <(python -c 'import json, scitt_emulator.policy_engine; print(json.dumps(scitt_emulator.policy_engine.PolicyEngineRequest.model_json_schema(), indent=4, sort_keys=True))')
TASK_ID=$(curl -X POST -H "Content-Type: application/json" -d @<(cat request.yml | python -c 'import json, yaml, sys; print(json.dumps(yaml.safe_load(sys.stdin.read()), indent=4, sort_keys=True))') http://localhost:8080/request/create | jq -r .detail.id)
curl http://localhost:8080/request/status/$TASK_ID | jq
TASK_ID=$(curl -X POST http://localhost:8080/webhook/github -d '{"after": "a1b70ee3b0343adc24e3b75314262e43f5c79cc2", "repository": {"full_name": "pdxjohnny/scitt-api-emulator"}, "sender": {"login": "pdxjohnny"}}' -H "X-GitHub-Event: push" -H "X-GitHub-Delivery: 42" -H "Content-Type: application/json" | jq -r .detail.id)
curl http://localhost:8080/request/status/$TASK_ID | jq
```
Or you can use the builtin client (workflow.yml is 'requests.yml'.workflow):
**workflow.yml**
```yaml
on:
push:
branches:
- main
workflow_dispatch:
file_paths:
description: 'File paths to download'
default: '[]'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- env:
FILE_PATHS: ${{ github.event.inputs.file_paths }}
GITHUB_TOKEN: ${{ github.token }}
shell: python -u {0}
run: |
import os
import json
import pathlib
from github import Github
file_paths = json.loads(os.environ["FILE_PATHS"])
g = Github(os.environ["GITHUB_TOKEN"])
upstream = g.get_repo(os.environ["GITHUB_REPOSITORY"])
for file_path in file_paths:
file_path = pathlib.Path("./" + file_path)
pygithub_fileobj = upstream.get_contents(
str(file_path),
)
content = pygithub_fileobj.decoded_content
file_path.write_bytes(content)
```
Pass inputs or more context with `--input` and `--context`.
```bash
TASK_ID=$(python -u ./scitt_emulator/policy_engine.py client --endpoint http://localhost:8080 create --repository pdxjohnny/scitt-api-emulator --workflow workflow.yml --input file_paths '["/README.md"]' | tee >(jq 1>/dev/stderr) | jq -r .detail.id)
python -u ./scitt_emulator/policy_engine.py client --endpoint http://localhost:8080 status --task-id "${TASK_ID}" | tee >(jq -r .detail.annotations.error[] 1>&2) | jq
```
"""
import os
import io
import sys
import json
import time
import enum
import uuid
import copy
import shlex
import types
import atexit
import asyncio
import pathlib
import zipfile
import tarfile
import inspect
import logging
import argparse
import tempfile
import textwrap
import datetime
import importlib
import traceback
import itertools
import subprocess
import contextlib
import contextvars
import urllib.request
import multiprocessing
import concurrent.futures
from typing import (
Union,
Callable,
Optional,
Tuple,
List,
Dict,
Any,
Annotated,
Self,
Iterator,
)
import yaml
import snoop
import pytest
import aiohttp
import gidgethub.apps
import gidgethub.aiohttp
import gunicorn.app.base
from celery import Celery, current_app as celery_current_app
from celery.result import AsyncResult
from fastapi import FastAPI, Request
from pydantic import (
BaseModel,
PlainSerializer,
Field,
model_validator,
field_validator,
)
from fastapi.testclient import TestClient
logger = logging.getLogger(__name__)
def entrypoint_style_load(
*args: str, relative: Optional[Union[str, pathlib.Path]] = None
) -> Iterator[Any]:
"""
Load objects given the entrypoint formatted path to the object. Roughly how
the python stdlib docs say entrypoint loading works.
"""
# Push current directory into front of path so we can run things
# relative to where we are in the shell
if relative is not None:
if relative == True:
relative = os.getcwd()
# str() in case of Path object
sys.path.insert(0, str(relative))
try:
for entry in args:
modname, qualname_separator, qualname = entry.partition(":")
obj = importlib.import_module(modname)
for attr in qualname.split("."):
if hasattr(obj, "__getitem__"):
obj = obj[attr]
else:
obj = getattr(obj, attr)
yield obj
finally:
if relative is not None:
sys.path.pop(0)
class PolicyEngineCompleteExitStatuses(enum.Enum):
SUCCESS = "success"
FAILURE = "failure"
class PolicyEngineComplete(BaseModel, extra="forbid"):
id: str
exit_status: PolicyEngineCompleteExitStatuses
outputs: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
annotations: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
class PolicyEngineStatuses(enum.Enum):
SUBMITTED = "submitted"
IN_PROGRESS = "in_progress"
COMPLETE = "complete"
UNKNOWN = "unknown"
INPUT_VALIDATION_ERROR = "input_validation_error"
class PolicyEngineStatusUpdateJobStep(BaseModel, extra="forbid"):
status: PolicyEngineStatuses
metadata: Dict[str, str]
outputs: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
class PolicyEngineStatusUpdateJob(BaseModel, extra="forbid"):
steps: Dict[str, PolicyEngineStatusUpdateJobStep]
class PolicyEngineInProgress(BaseModel, extra="forbid"):
id: str
status_updates: Dict[str, PolicyEngineStatusUpdateJob]
class PolicyEngineSubmitted(BaseModel, extra="forbid"):
id: str
class PolicyEngineUnknown(BaseModel, extra="forbid"):
id: str
class PolicyEngineInputValidationError(BaseModel):
msg: str
loc: List[str]
type: str
url: Optional[str] = None
input: Optional[str] = None
class PolicyEngineStatus(BaseModel, extra="forbid"):
status: PolicyEngineStatuses
detail: Union[
PolicyEngineSubmitted,
PolicyEngineInProgress,
PolicyEngineComplete,
PolicyEngineUnknown,
List[PolicyEngineInputValidationError],
]
@model_validator(mode="before")
@classmethod
def model_validate_detail(cls, data: Any) -> Any:
if data and isinstance(data, dict):
if "status" not in data:
data["status"] = PolicyEngineStatuses.INPUT_VALIDATION_ERROR.value
if isinstance(data["status"], PolicyEngineStatuses):
data["status"] = data["status"].value
detail_class = DETAIL_CLASS_MAPPING[data["status"]]
data["detail"] = detail_class.model_validate(data["detail"])
return data
DETAIL_CLASS_MAPPING = {
PolicyEngineStatuses.SUBMITTED.value: PolicyEngineSubmitted,
PolicyEngineStatuses.IN_PROGRESS.value: PolicyEngineInProgress,
PolicyEngineStatuses.COMPLETE.value: PolicyEngineComplete,
PolicyEngineStatuses.UNKNOWN.value: PolicyEngineUnknown,
PolicyEngineStatuses.INPUT_VALIDATION_ERROR.value: types.SimpleNamespace(
model_validate=lambda detail: list(map(PolicyEngineInputValidationError.model_validate, detail)),
),
}
class PolicyEngineWorkflowJobStep(BaseModel, extra="forbid"):
id: Optional[str] = None
# TODO Alias doesn't seem to be working here
# if_condition: Optional[str] = Field(default=None, alias="if")
# TODO Implement step if conditionals, YAML load output of eval_js
if_condition: Optional[Union[str, bool, int]] = Field(default=None)
name: Optional[str] = None
uses: Optional[str] = None
shell: Optional[str] = None
# TODO Alias doesn't seem to be working here
# with_inputs: Optional[Dict[str, Any]] = Field(default_factory=lambda: {}, alias="with")
with_inputs: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
env: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
run: Optional[str] = None
@model_validator(mode="before")
@classmethod
def fix_hyphen_keys(cls, data: Any) -> Any:
if data and isinstance(data, dict):
for find, replace in [
("if", "if_condition"),
("with", "with_inputs"),
]:
if find in data:
data[replace] = data[find]
del data[find]
return data
class PolicyEngineWorkflowJob(BaseModel, extra="forbid"):
runs_on: Union[str, List[str], Dict[str, Any]] = Field(
default_factory=lambda: [],
)
steps: Optional[List[PolicyEngineWorkflowJobStep]] = Field(
default_factory=lambda: [],
)
@model_validator(mode="before")
@classmethod
def fix_hyphen_keys(cls, data: Any) -> Any:
if data and isinstance(data, dict):
for find, replace in [("runs-on", "runs_on")]:
if find in data:
data[replace] = data[find]
del data[find]
return data
class PolicyEngineWorkflow(BaseModel, extra="forbid"):
name: Optional[str] = None
on: Union[List[str], Dict[str, Any]] = Field(
default_factory=lambda: [],
)
jobs: Optional[Dict[str, PolicyEngineWorkflowJob]] = Field(
default_factory=lambda: {},
)
@model_validator(mode="before")
@classmethod
def fix_yaml_on_parsed_as_bool(cls, data: Any) -> Any:
if data and isinstance(data, dict):
for check in [1, True]:
if check in data:
data["on"] = data[check]
del data[check]
return data
class PolicyEngineRequest(BaseModel, extra="forbid"):
# Inputs should come from json-ld @context instance
inputs: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
workflow: Union[str, dict, PolicyEngineWorkflow] = Field(
default_factory=lambda: PolicyEngineWorkflow()
)
context: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
stack: Optional[Dict[str, Any]] = Field(default_factory=lambda: {})
@field_validator("workflow")
@classmethod
def parse_workflow_github_actions(cls, workflow, _info):
if isinstance(workflow, str):
workflow = yaml.safe_load(workflow)
if isinstance(workflow, dict):
workflow = PolicyEngineWorkflow.model_validate(workflow)
return workflow
@field_validator("context")
@classmethod
def parse_context_set_secrets_if_not_set(cls, context, _info):
context.setdefault("secrets", {})
return context
celery_app = Celery(
"tasks",
backend=os.environ.get("CELERY_BACKEND", "redis://localhost"),
broker=os.environ.get("CELERY_BROKER", "redis://localhost"),
broker_connection_retry_on_startup=True,
)
def number_of_workers():
return (multiprocessing.cpu_count() * 2) + 1
def _no_celery_task(func, bind=False, no_celery_async=None):
async def asyncio_delay(*args):
nonlocal bind
nonlocal no_celery_async
if no_celery_async is None:
raise Exception(
"Must specify async def version of task via @celery_task decorator keyword argument no_celery_async"
)
task_id = str(uuid.uuid4())
if bind:
mock_celery_task_bind_self = types.SimpleNamespace(
request=types.SimpleNamespace(
id=task_id,
)
)
args = [mock_celery_task_bind_self] + list(args)
task = asyncio.create_task(no_celery_async(*args))
async def async_no_celery_try_set_state(task_id):
request = fastapi_current_request.get()
async with request.state.no_celery_async_results_lock:
no_celery_try_set_state(
request.state.no_celery_async_results[task_id],
)
task.add_done_callback(
lambda _task: asyncio.create_task(
async_no_celery_try_set_state(task_id)
),
)
request = fastapi_current_request.get()
async with request.state.no_celery_async_results_lock:
results = request.state.no_celery_async_results
results[task_id] = {
"state": "PENDING",
"result": None,
"future": None,
"task": task,
}
no_celery_try_set_state(results[task_id])
return types.SimpleNamespace(id=task_id)
func.asyncio_delay = asyncio_delay
return func
def no_celery_task(*args, **kwargs):
if kwargs:
def wrap(func):
return _no_celery_task(func, **kwargs)
return wrap
return _no_celery_task(*args)
def no_celery_try_set_state(state):
task = state["task"]
future = state["future"]
if task is not None:
if not task.done():
state["state"] = "PENDING"
else:
exception = task.exception()
if exception is not None:
state["result"] = exception
state["state"] = "FAILURE"
else:
state["state"] = "SUCCESS"
state["result"] = task.result()
elif future is not None:
exception = future.exception(timeout=0)
if exception is not None:
state["result"] = exception
state["state"] = "FAILURE"
elif not future.done():
state["state"] = "PENDING"
else:
state["state"] = "SUCCESS"
state["result"] = future.result()
class NoCeleryAsyncResult:
def __init__(self, task_id, *, app=None):
self.task_id = task_id
@property
def state(self):
request = fastapi_current_request.get()
results = request.state.no_celery_async_results
if self.task_id not in results:
return "UNKNOWN"
state = results[self.task_id]
no_celery_try_set_state(state)
return state["state"]
def get(self):
result = fastapi_current_request.get().state.no_celery_async_results[
self.task_id
]["result"]
if isinstance(result, Exception):
raise result
return result
def _make_celery_task_asyncio_delay(app, func, **kwargs):
async def asyncio_delay(*args):
nonlocal func
return func.delay(*args)
if kwargs:
func = app.task(**kwargs)(func)
else:
func = app.task(func)
func.asyncio_delay = asyncio_delay
return func
def make_celery_task_asyncio_delay(app):
def celery_task_asyncio_delay(*args, **kwargs):
if kwargs:
def wrap(func):
return _make_celery_task_asyncio_delay(app, func, **kwargs)
return wrap
return _make_celery_task_asyncio_delay(app, *args, **kwargs)
return celery_task_asyncio_delay
if int(os.environ.get("NO_CELERY", "0")):
AsyncResult = NoCeleryAsyncResult
celery_task = no_celery_task
else:
celery_task = make_celery_task_asyncio_delay(celery_app)
def download_step_uses_from_url(
context,
request,
step,
step_uses_org_repo,
step_uses_version,
step_download_url,
):
stack = request.context["stack"][-1]
exit_stack = stack["exit_stack"]
if "cachedir" in stack:
downloads_path = stack["cachedir"]
else:
downloads_path = exit_stack.enter_context(
tempfile.TemporaryDirectory(dir=stack.get("tempdir", None)),
)
downloads_path = pathlib.Path(downloads_path)
# TODO(security) MoM of hashes? stat as well? How to validate on disk?
compressed_path = pathlib.Path(
downloads_path, step_uses_org_repo, "compressed.zip"
)
extracted_tmp_path = pathlib.Path(
downloads_path, step_uses_org_repo, "extracted_tmp"
)
extracted_path = pathlib.Path(
downloads_path, step_uses_org_repo, "extracted"
)
compressed_path.parent.mkdir(parents=True, exist_ok=True)
headers = {}
github_token = stack["secrets"].get("GITHUB_TOKEN", "")
if github_token:
headers["Authorization"] = f"Bearer {github_token}"
request = urllib.request.Request(
step_download_url,
headers=headers,
)
if not compressed_path.is_file():
request = exit_stack.enter_context(urllib.request.urlopen(request))
compressed_path.write_bytes(request.read())
if not extracted_path.is_dir():
zipfileobj = exit_stack.enter_context(zipfile.ZipFile(compressed_path))
zipfileobj.extractall(extracted_tmp_path)
# Rename uplevel from repo-vYXZ name as archive into extracted/
list(extracted_tmp_path.glob("*"))[0].rename(extracted_path)
stack.setdefault("steps", {})
stack["steps"].setdefault("extracted_path", {})
stack["steps"]["extracted_path"][step.uses] = extracted_path
# https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables
stack["env"]["GITHUB_ACTION_PATH"] = str(extracted_path.resolve())
return extracted_path.resolve()
def download_step_uses(context, request, step):
exception = None
step_uses_org_repo, step_uses_version = step.uses.split("@")
# TODO refs/heads/
for step_download_url in [
f"https://github.com/{step_uses_org_repo}/archive/refs/tags/{step_uses_version}.zip",
f"https://github.com/{step_uses_org_repo}/archive/{step_uses_version}.zip",
f"https://github.com/{step_uses_org_repo}/archive/refs/heads/{step_uses_version}.zip",
]:
try:
return download_step_uses_from_url(
context,
request,
step,
step_uses_org_repo,
step_uses_version,
step_download_url,
)
except Exception as error:
exception = error
raise exception
def transform_property_accessors(js_code):
transformed_code = ""
index = 0
while index < len(js_code):
if js_code[index] in ('"', "'"):
# If within a string, find the closing quote
quote = js_code[index]
end_quote_index = js_code.find(quote, index + 1)
if end_quote_index == -1:
# If no closing quote is found, break the loop
break
else:
# Append the string as is
transformed_code += js_code[index : end_quote_index + 1]
index = end_quote_index + 1
elif js_code[index].isspace():
# If whitespace, just append it
transformed_code += js_code[index]
index += 1
elif js_code[index] == ".":
# Replace dot with bracket notation if not within a string
transformed_code += "['"
prop_end_index = index + 1
while (
prop_end_index < len(js_code)
and js_code[prop_end_index].isalnum()
or js_code[prop_end_index] == "_"
or js_code[prop_end_index] == "-"
):
prop_end_index += 1
transformed_code += js_code[index + 1 : prop_end_index]
transformed_code += "']"
index = prop_end_index
else:
# Just append characters as is
transformed_code += js_code[index]
index += 1
return transformed_code
def _evaluate_using_javascript(context, request, code_block):
stack = request.context["stack"][-1]
exit_stack = stack["exit_stack"]
tempdir = exit_stack.enter_context(
tempfile.TemporaryDirectory(dir=stack.get("tempdir", None)),
)
github_context = {
**{
input_key.lower().replace(
"github_", "", 1
): evaluate_using_javascript(
context,
request,
input_value,
)
for input_key, input_value in stack["env"].items()
if input_key.startswith("GITHUB_")
},
**{
"token": stack["secrets"].get("GITHUB_TOKEN", ""),
"event": {
"inputs": request.context["inputs"],
},
},
}
runner_context = {
"debug": stack.get("debug", 1),
}
steps_context = stack["outputs"]
# TODO secrets_context
# Find property accessors in dot notation and replace dot notation
# with bracket notation. Avoids replacements within strings.
code_block = transform_property_accessors(code_block)
javascript_path = pathlib.Path(tempdir, "check_output.js")
# TODO vars and env contexts
javascript_path.write_text(
textwrap.dedent(
r"""
function always() { return "__GITHUB_ACTIONS_ALWAYS__"; }
const github = """
+ json.dumps(github_context, sort_keys=True)
+ """;
const runner = """
+ json.dumps(runner_context, sort_keys=True)
+ """;
const steps = """
+ json.dumps(steps_context, sort_keys=True)
+ """;
const result = ("""
+ code_block
+ """);
console.log(result)
"""
).strip()
)
output = subprocess.check_output(
[context.state.deno, "repl", "-q", f"--eval-file={javascript_path.resolve()}"],
stdin=request.context["devnull"],
cwd=stack["workspace"],
).decode()
if output.startswith(
f'Error in --eval-file file "{javascript_path.resolve()}"'
):
raise Exception(
output
+ ("-" * 100)
+ "\n"
+ javascript_path.read_text()
+ ("-" * 100)
+ "\n"
)
return output.strip()
def evaluate_using_javascript(context, request, code_block):
if code_block is None:
return ""
# TODO Not startswith, search for each and run deno
if not isinstance(code_block, str) or "${{" not in code_block:
return str(code_block)
result = ""
start_idx = 0
end_idx = 0
while "${{" in code_block[start_idx:]:
# Find the starting index of "${{"
start_idx = code_block.index("${{", start_idx)
result += code_block[end_idx:start_idx]
# Find the ending index of "}}"
end_idx = code_block.index("}}", start_idx) + 2
# Extract the data between "${{" and "}}"
data = code_block[start_idx + 3 : end_idx - 2]
# Call evaluate_using_javascript() with the extracted data
evaluated_data = _evaluate_using_javascript(context, request, data)
# Append the evaluated data to the result
result += code_block[start_idx + 3 : end_idx - 2].replace(
data, str(evaluated_data)
)
# Move the start index to the next position after the match
start_idx = end_idx
result += code_block[start_idx:]
return result
@pytest.mark.asyncio
@pytest.mark.parametrize(
"template,should_be",
[
[
"${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com>",
"aliceoa <1234567+aliceoa@users.noreply.github.com>",
],
[
"${{ github.actor_id + \" \" + 'https://github.com' + '/' + github.actor }}",
"1234567 https://github.com/aliceoa",
],
],
)
async def test_evaluate_using_javascript(template, should_be):
context = make_default_policy_engine_context()
request = PolicyEngineRequest(
context={
"config": {
"env": {
"GITHUB_ACTOR": "aliceoa",
"GITHUB_ACTOR_ID": "1234567",
},
},
}
)
async with async_celery_setup_workflow(context, request) as (context, request):
evaluated = evaluate_using_javascript(
context,
request,
template,
)
assert evaluated == should_be
def step_parse_outputs_github_actions(context, step, step_outputs_string):
outputs = {}
current_output_key = None
current_output_delimiter = None
current_output_value = ""
for line in step_outputs_string.split("\n"):
if "=" in line:
current_output_key, current_output_value = line.split(
"=", maxsplit=1
)
outputs[current_output_key] = current_output_value
elif "<<" in line:
current_output_key, current_output_delimiter = line.split(
"<<", maxsplit=1
)
elif current_output_delimiter:
if line.startswith(current_output_delimiter):
outputs[current_output_key] = current_output_value[:-1]
current_output_key = None
current_output_delimiter = None
current_output_value = ""
else:
current_output_value += line + "\n"
return outputs
def step_build_default_inputs(context, request, action_yaml_obj, step):
return {
f"INPUT_{input_key.upper()}": evaluate_using_javascript(
context, request, input_value["default"]
)
for input_key, input_value in action_yaml_obj.get("inputs", {}).items()
if "default" in input_value
}
def step_build_env(context, request, step):
return {
input_key: evaluate_using_javascript(context, request, input_value)
for input_key, input_value in step.env.items()
}
def step_build_inputs(context, request, step):
return {
f"INPUT_{input_key.upper()}": evaluate_using_javascript(
context, request, input_value
)
for input_key, input_value in step.with_inputs.items()
}
def step_io_output_github_actions(context, request):
stack = request.context["stack"][-1]
step_tempdir = stack["exit_stack"].enter_context(
tempfile.TemporaryDirectory(dir=stack.get("tempdir", None)),
)
step_outputs_path = pathlib.Path(step_tempdir, "output.txt")
step_env_path = pathlib.Path(step_tempdir, "env.txt")
step_outputs_path.write_text("")
step_env_path.write_text("")
return {
"GITHUB_OUTPUT": str(step_outputs_path.resolve()),
"GITHUB_ENV": str(step_env_path.resolve()),
"GITHUB_WORKSPACE": stack["workspace"],
}
def step_io_update_stack_output_and_env_github_actions(context, request, step):
stack = request.context["stack"][-1]
outputs = step_parse_outputs_github_actions(
context,
step,
pathlib.Path(stack["env"]["GITHUB_OUTPUT"]).read_text(),
)
context_env_updates = step_parse_outputs_github_actions(
context,
step,
pathlib.Path(stack["env"]["GITHUB_ENV"]).read_text(),
)
if step.id:
stack["outputs"].setdefault(step.id, {})
stack["outputs"][step.id]["outputs"] = outputs
stack["env"].update(context_env_updates)
def execute_step_uses(context, request, step):
stack = request.context["stack"][-1]
extracted_path = stack["steps"]["extracted_path"][step.uses]
action_yaml_path = list(extracted_path.glob("action.*"))[0]
action_yaml_obj = yaml.safe_load(action_yaml_path.read_text())
stack["env"].update(
{
**step_io_output_github_actions(context, request),
**step_build_default_inputs(
context, request, action_yaml_obj, step
),
}
)
if action_yaml_obj["runs"]["using"].startswith("node"):
env = copy.deepcopy(os.environ)
env.update(stack["env"])
cmd = [
context.state.nodejs,
extracted_path.joinpath(action_yaml_obj["runs"]["main"]),
]
tee_proc = subprocess.Popen(
["tee", stack["console_output"]],
stdin=subprocess.PIPE,
)
try:
completed_proc = subprocess.run(
cmd,
cwd=stack["workspace"],
stdin=request.context["devnull"],
stdout=tee_proc.stdin,
stderr=tee_proc.stdin,
env=env,
)
step_io_update_stack_output_and_env_github_actions(
context,
request,