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
package workflow
import (
"bytes"
"context"
"encoding/json"
"fmt"
"maps"
"sort"
"strings"
"time"
"gopkg.in/yaml.v3"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/sandbox"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/models"
)
type Action struct {
Uses string
Path string
Using string
Main string
Inputs map[string]string
Source []byte
}
type ActionResolver func(uses string) (*Action, error)
type Options struct {
Sandbox sandbox.Runner
ResolveAction ActionResolver
MaxConsoleBytes int64
MaxOutputBytes int64
}
type JobResult struct {
Status string
Outputs map[string]any
Error string
}
type Context struct {
Inputs map[string]any
Env map[string]any
Secrets map[string]string
Outputs map[string]map[string]any
Annotations map[string][]models.Annotation
Cache models.Cache
Vars map[string]any
JobResults map[string]JobResult
Console []string
Shell string
Error error
console int64
}
type Executor struct {
opts Options
Context *Context
jobFailed bool
jobDeadline time.Time
}
func New(options Options) *Executor {
return &Executor{
opts: options,
Context: &Context{
Inputs: map[string]any{},
Env: map[string]any{},
Secrets: map[string]string{},
Outputs: map[string]map[string]any{},
Annotations: map[string][]models.Annotation{},
Cache: models.Cache{},
Vars: map[string]any{},
JobResults: map[string]JobResult{},
Shell: "bash -xe",
},
}
}
func Parse(raw json.RawMessage) (*models.Workflow, error) {
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
return nil, fmt.Errorf("workflow is required")
}
var text string
if err := json.Unmarshal(trimmed, &text); err == nil {
text = strings.TrimSpace(text)
if text == "" || text == "null" {
return nil, fmt.Errorf("workflow is required")
}
var parsed models.Workflow
if err := yaml.Unmarshal([]byte(text), &parsed); err != nil {
return nil, fmt.Errorf("failed to parse workflow YAML: %w", err)
}
return &parsed, nil
}
var parsed models.Workflow
if err := yaml.Unmarshal(trimmed, &parsed); err != nil {
return nil, fmt.Errorf("failed to parse workflow: %w", err)
}
return &parsed, nil
}
func HasRunStep(raw json.RawMessage) (string, bool) {
parsed, err := Parse(raw)
if err != nil {
return "", false
}
names := make([]string, 0, len(parsed.Jobs))
for name := range parsed.Jobs {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
for _, step := range parsed.Jobs[name].Steps {
if strings.TrimSpace(step.Run) != "" {
return name, true
}
}
}
return "", false
}
func (e *Executor) Execute(ctx context.Context, request *models.Request) (*models.Result, error) {
if request == nil {
return nil, fmt.Errorf("request is required")
}
workflow, err := Parse(request.Workflow)
if err != nil {
return nil, err
}
if err := e.initializeContext(request); err != nil {
return nil, err
}
if workflow.Name != "" {
e.Context.Env["GITHUB_WORKFLOW"] = workflow.Name
}
for key, value := range workflow.Env {
evaluated, evalErr := e.evaluateExpression(ctx, fmt.Sprintf("%v", value))
if evalErr != nil {
return e.failureResult(evalErr), nil
}
e.Context.Env[key] = evaluated
}
order, err := jobOrder(workflow)
if err != nil {
return e.failureResult(err), nil
}
var firstErr error
for _, name := range order {
job := workflow.Jobs[name]
result, jobErr := e.executeJob(ctx, name, &job)
e.Context.JobResults[name] = result
if jobErr != nil && firstErr == nil {
firstErr = jobErr
}
}
if firstErr != nil {
e.Context.Error = firstErr
return e.failureResult(firstErr), nil
}
return e.successResult(), nil
}
func (e *Executor) initializeContext(request *models.Request) error {
maps.Copy(e.Context.Inputs, request.Inputs)
if request.Context != nil {
if config, ok := request.Context["config"].(map[string]any); ok {
if env, ok := config["env"].(map[string]any); ok {
maps.Copy(e.Context.Env, env)
}
}
if secrets, ok := request.Context["secrets"].(map[string]any); ok {
for key, value := range secrets {
if text, ok := value.(string); ok {
e.Context.Secrets[key] = text
}
}
}
if cacheValue, ok := request.Context["cache"]; ok && cacheValue != nil {
e.Context.Cache = decodeCache(cacheValue)
}
if vars, ok := request.Context["vars"].(map[string]any); ok {
e.Context.Vars = vars
}
}
if token := e.Context.Secrets["GITHUB_TOKEN"]; token != "" {
if _, exists := e.Context.Env["GITHUB_TOKEN"]; !exists {
e.Context.Env["GITHUB_TOKEN"] = token
}
}
e.Context.Env["CI"] = "true"
e.Context.Env["GITHUB_ACTIONS"] = "true"
return nil
}
func jobOrder(workflow *models.Workflow) ([]string, error) {
names := make([]string, 0, len(workflow.Jobs))
for name := range workflow.Jobs {
names = append(names, name)
}
sort.Strings(names)
visited := map[string]bool{}
visiting := map[string]bool{}
order := make([]string, 0, len(names))
var visit func(string) error
visit = func(name string) error {
if visited[name] {
return nil
}
if visiting[name] {
return fmt.Errorf("circular needs involving job %s", name)
}
job, ok := workflow.Jobs[name]
if !ok {
return fmt.Errorf("job %s is not defined", name)
}
visiting[name] = true
for _, need := range needsOf(job.Needs) {
if err := visit(need); err != nil {
return err
}
}
visiting[name] = false
visited[name] = true
order = append(order, name)
return nil
}
for _, name := range names {
if err := visit(name); err != nil {
return nil, err
}
}
return order, nil
}
func needsOf(value any) []string {
switch typed := value.(type) {
case string:
if typed == "" {
return nil
}
return []string{typed}
case []string:
return typed
case []any:
out := make([]string, 0, len(typed))
for _, item := range typed {
if name, ok := item.(string); ok && name != "" {
out = append(out, name)
}
}
return out
default:
return nil
}
}
func (e *Executor) executeJob(ctx context.Context, name string, job *models.WorkflowJob) (JobResult, error) {
result := JobResult{Status: "success", Outputs: map[string]any{}}
dependencyFailed := false
for _, need := range needsOf(job.Needs) {
dep, ok := e.Context.JobResults[need]
if ok && (dep.Status == "failure" || dep.Status == "skipped") {
dependencyFailed = true
}
}
e.jobFailed = dependencyFailed
if job.If != nil {
guard, err := e.evaluateGuard(ctx, job.If)
if err != nil {
result.Status = "failure"
result.Error = err.Error()
return result, fmt.Errorf("job %s: %w", name, err)
}
if !guard.run {
result.Status = "skipped"
return result, nil
}
} else if dependencyFailed {
result.Status = "skipped"
return result, nil
}
jobCtx := ctx
if job.TimeoutMinutes > 0 {
var cancel context.CancelFunc
jobCtx, cancel = context.WithTimeout(ctx, time.Duration(job.TimeoutMinutes)*time.Minute)
defer cancel()
}
e.jobDeadline = time.Time{}
if job.TimeoutMinutes > 0 {
e.jobDeadline = time.Now().Add(time.Duration(job.TimeoutMinutes) * time.Minute)
}
envSnapshot := make(map[string]any, len(e.Context.Env))
maps.Copy(envSnapshot, e.Context.Env)
for key, value := range job.Env {
evaluated, evalErr := e.evaluateExpression(ctx, fmt.Sprintf("%v", value))
if evalErr != nil {
maps.Copy(e.Context.Env, envSnapshot)
result.Status = "failure"
result.Error = evalErr.Error()
return result, fmt.Errorf("job %s: %w", name, evalErr)
}
e.Context.Env[key] = evaluated
}
err := e.executeSteps(jobCtx, job)
outputs := map[string]any{}
for outputName, expression := range job.Outputs {
value, evalErr := e.evaluateExpression(ctx, fmt.Sprintf("%v", expression))
if evalErr != nil {
outputs[outputName] = ""
continue
}
outputs[outputName] = value
}
for key := range e.Context.Env {
if _, existed := envSnapshot[key]; !existed {
delete(e.Context.Env, key)
}
}
maps.Copy(e.Context.Env, envSnapshot)
result.Outputs = outputs
if err != nil {
result.Status = "failure"
result.Error = err.Error()
return result, fmt.Errorf("job %s: %w", name, err)
}
return result, nil
}
func (e *Executor) executeSteps(ctx context.Context, job *models.WorkflowJob) error {
e.jobFailed = false
e.Context.Error = nil
var firstErr error
for index, step := range job.Steps {
if err := ctx.Err(); err != nil {
e.jobFailed = true
return err
}
stepName := fmt.Sprintf("step_%d", index+1)
if step.ID != "" {
stepName = step.ID
} else if step.Name != "" {
stepName = step.Name
}
guard, err := e.evaluateGuard(ctx, step.If)
if err != nil {
firstErr = fmt.Errorf("step %s: %w", stepName, err)
e.jobFailed = true
break
}
if e.jobFailed && !guard.always && !guard.failure {
continue
}
if !guard.run {
continue
}
if step.Shell != "" {
e.Context.Shell = step.Shell
}
env, err := e.buildStepEnv(ctx, &step)
if err != nil {
firstErr = fmt.Errorf("step %s: %w", stepName, err)
e.jobFailed = true
break
}
e.emit(fmt.Sprintf("##[group]%s", stepName))
var stepErr error
if strings.TrimSpace(step.Run) != "" {
stepErr = fmt.Errorf("this evaluator runs gha-lite policies net-only and refuses a run: step (job step %s)", stepName)
} else if step.Uses != "" {
stepErr = e.executeStepUses(ctx, &step, env)
}
e.emit("##[endgroup]")
if stepErr != nil {
e.emit(fmt.Sprintf("##[error]step %s failed: %v", stepName, stepErr))
if step.ContinueOnError {
continue
}
e.jobFailed = true
e.Context.Error = stepErr
if firstErr == nil {
firstErr = fmt.Errorf("step %s: %w", stepName, stepErr)
}
continue
}
}
if firstErr != nil {
return firstErr
}
if !e.jobDeadline.IsZero() && time.Now().After(e.jobDeadline) {
e.jobFailed = true
return fmt.Errorf("job exceeded timeout-minutes")
}
return nil
}
func (e *Executor) emit(line string) {
if e.opts.MaxConsoleBytes > 0 {
if e.Context.console >= e.opts.MaxConsoleBytes {
return
}
remaining := e.opts.MaxConsoleBytes - e.Context.console
if int64(len(line)) > remaining {
line = line[:remaining]
}
}
e.Context.Console = append(e.Context.Console, line)
e.Context.console += int64(len(line)) + 1
}
func (e *Executor) successResult() *models.Result {
outputs := models.Outputs{}
for name, result := range e.Context.JobResults {
outputs[name] = result.Outputs
}
if used, limit := e.outputBytes(outputs); limit > 0 && used > limit {
err := fmt.Errorf("workflow outputs exceed the configured limit")
e.emit("##[error]" + err.Error())
return e.failureResult(err)
}
return &models.Result{
Status: models.ExecutionComplete,
ExitStatus: models.ExitSuccess,
Outputs: outputs,
Cache: e.Context.Cache,
Annotations: e.annotationMap(),
ConsoleOutput: strings.Join(e.Context.Console, "\n"),
}
}
func (e *Executor) failureResult(err error) *models.Result {
annotations := e.annotationMap()
errors := []models.Annotation{}
if err != nil {
errors = append(errors, models.Annotation{AnnotationLevel: models.AnnotationError, Message: err.Error(), Title: err.Error()})
}
annotations["error"] = errors
return &models.Result{
Status: models.ExecutionComplete,
ExitStatus: models.ExitFailure,
Outputs: models.Outputs{},
Cache: e.Context.Cache,
Annotations: annotations,
ConsoleOutput: strings.Join(e.Context.Console, "\n"),
}
}
func (e *Executor) annotationMap() models.Annotations {
out := models.Annotations{}
for level, list := range e.Context.Annotations {
copied := make([]models.Annotation, len(list))
copy(copied, list)
out[level] = copied
}
return out
}
func (e *Executor) outputBytes(outputs models.Outputs) (int64, int64) {
if e.opts.MaxOutputBytes <= 0 {
return 0, e.opts.MaxOutputBytes
}
data, err := json.Marshal(outputs)
if err != nil {
return 0, e.opts.MaxOutputBytes
}
return int64(len(data)), e.opts.MaxOutputBytes
}
func decodeCache(value any) models.Cache {
data, err := json.Marshal(value)
if err != nil {
return models.Cache{}
}
var out models.Cache
if err := json.Unmarshal(data, &out); err != nil {
return models.Cache{}
}
if out == nil {
out = models.Cache{}
}
return out
}