From 3317a31c2256a9bba5c872bb11abed17d9fbd0dc Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 14 Nov 2026 07:15:46 +0000 Subject: [PATCH] fix(actions): resolve `$/` steps against the job's workflow source (#40075) GitHub resolves `uses: $/{path}` against the repository and commit of the job's workflow file, not the triggering ones. When those differ, as with reusable workflows from elsewhere or owner and global workflows: - such steps are pinned to `self:{repo}/{path}@{sha}` in the runner payload - `$/` steps with expressions in their path fail the run as an invalid workflow, as they can't be pinned safely and GitHub rejects them too Same-source jobs keep `$/`, so older runners are unaffected. Assisted-by: Claude Code:claude-opus-5-5 --------- Co-authored-by: Zettat123 --- services/actions/context.go | 29 ++++++++------ services/actions/reusable_workflow.go | 27 +++++++++++++ services/actions/reusable_workflow_test.go | 12 ++++++ services/actions/task.go | 40 +++++++++++++++++-- services/actions/task_test.go | 36 ++++++++++++----- .../actions_reusable_workflow_test.go | 29 ++++++++++++++ 6 files changed, 147 insertions(+), 26 deletions(-) diff --git a/services/actions/context.go b/services/actions/context.go index b6da48a676c..5342d88eae3 100644 --- a/services/actions/context.go +++ b/services/actions/context.go @@ -40,19 +40,7 @@ func GenerateGiteaContext(ctx context.Context, run *actions_model.ActionRun, att event := map[string]any{} _ = json.Unmarshal([]byte(run.EventPayload), &event) - baseRef := "" - headRef := "" - ref := run.Ref - sha := run.CommitSHA - if pullPayload, err := run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { - baseRef = pullPayload.PullRequest.Base.Ref - headRef = pullPayload.PullRequest.Head.Ref - if run.TriggerEvent == actions_module.GithubEventPullRequestTarget { - ref, sha = git.BranchPrefix+pullPayload.PullRequest.Base.Ref, pullPayload.PullRequest.Base.Sha - } else if run.TriggerEvent == actions_module.GithubEventPullRequest && !pullPayload.PullRequest.HasMerged && pullPayload.PullRequest.MergedCommitID != nil { - ref, sha = git.MergeRefNameFromPullIndex(pullPayload.PullRequest.Index).String(), *pullPayload.PullRequest.MergedCommitID - } - } + baseRef, headRef, ref, sha := runRefs(run) refName := git.RefName(ref) refType := refName.RefType() @@ -147,6 +135,21 @@ func GenerateGiteaContext(ctx context.Context, run *actions_model.ActionRun, att return gitContext } +// runRefs returns the run's `github.base_ref`, `github.head_ref`, `github.ref` and `github.sha`. +func runRefs(run *actions_model.ActionRun) (baseRef, headRef, ref, sha string) { + ref, sha = run.Ref, run.CommitSHA + if pullPayload, err := run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { + baseRef = pullPayload.PullRequest.Base.Ref + headRef = pullPayload.PullRequest.Head.Ref + if run.TriggerEvent == actions_module.GithubEventPullRequestTarget { + ref, sha = git.BranchPrefix+pullPayload.PullRequest.Base.Ref, pullPayload.PullRequest.Base.Sha + } else if run.TriggerEvent == actions_module.GithubEventPullRequest && !pullPayload.PullRequest.HasMerged && pullPayload.PullRequest.MergedCommitID != nil { + ref, sha = git.MergeRefNameFromPullIndex(pullPayload.PullRequest.Index).String(), *pullPayload.PullRequest.MergedCommitID + } + } + return baseRef, headRef, ref, sha +} + type TaskNeed struct { Result actions_model.Status Outputs map[string]string diff --git a/services/actions/reusable_workflow.go b/services/actions/reusable_workflow.go index 5a2d6c66145..b5171812f6a 100644 --- a/services/actions/reusable_workflow.go +++ b/services/actions/reusable_workflow.go @@ -111,6 +111,9 @@ func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun, if err != nil { return err } + if err := checkSelfRepoStepExpressions(run, source, workflow); err != nil { + return err + } for _, id := range slices.Sorted(maps.Keys(workflow.Jobs)) { uses := workflow.Jobs[id].Uses if uses == "" { @@ -142,6 +145,22 @@ func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun, return validate(content, &actions_model.ActionRunJob{WorkflowSourceRepoID: run.WorkflowRepoID, WorkflowSourceCommitSHA: run.WorkflowCommitSHA}, 0) } +// checkSelfRepoStepExpressions rejects `$/` steps with expressions that runnerWorkflowPayload can't pin to the workflow's source. +func checkSelfRepoStepExpressions(run *actions_model.ActionRun, source *actions_model.ActionRunJob, workflow *model.Workflow) error { + for _, id := range slices.Sorted(maps.Keys(workflow.Jobs)) { + for _, step := range workflow.Jobs[id].Steps { + if !strings.HasPrefix(step.Uses, "$/") || !strings.Contains(step.Uses, "${{") { + continue + } + if _, runnerResolves := selfRepoSourceCommit(run, source); runnerResolves { + return nil + } + return fmt.Errorf("job %s: `uses: %s` cannot use expressions in a workflow from another repository or commit", id, step.Uses) + } + } + return nil +} + func errCallLevelExceeded(uses string) error { return fmt.Errorf("reusable workflow call exceeds the maximum nesting level of %d at %q", MaxReusableCallLevels, uses) } @@ -296,6 +315,14 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action if _, err := jobparser.ValidateWorkflowStatic(source.content); err != nil { return fmt.Errorf("invalid called workflow: %w", err) } + // run creation checked it too, but a branch or tag may have moved since, and a rerun expands again + calledWorkflow, err := jobparser.ReadWorkflow(source.content) + if err == nil { + err = checkSelfRepoStepExpressions(run, &actions_model.ActionRunJob{WorkflowSourceRepoID: source.repoID, WorkflowSourceCommitSHA: source.commitSHA}, calledWorkflow) + } + if err != nil { + return fmt.Errorf("invalid called workflow: %w", err) + } // 4. Parse the called workflow's spec (used by both secret validation and input evaluation). wcSpec, err := jobparser.ParseWorkflowCallConfig(source.content) diff --git a/services/actions/reusable_workflow_test.go b/services/actions/reusable_workflow_test.go index b32a6b664ab..c436f029b71 100644 --- a/services/actions/reusable_workflow_test.go +++ b/services/actions/reusable_workflow_test.go @@ -245,6 +245,18 @@ func TestLoadReusableWorkflowSourceFailsAlikeForMissingAndPrivateRepo(t *testing } } +func TestValidateCalledWorkflowsRejectsCrossSourceSelfRepoExpressions(t *testing.T) { + content := []byte("on: push\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - uses: $/${{ vars.ACTION }}\n") + require.NoError(t, validateCalledWorkflows(t.Context(), &actions_model.ActionRun{RepoID: 1, WorkflowRepoID: 1, WorkflowCommitSHA: "abc", CommitSHA: "abc"}, content)) + for _, run := range []*actions_model.ActionRun{ + {RepoID: 1, WorkflowRepoID: 2, WorkflowCommitSHA: "abc", CommitSHA: "abc"}, + {RepoID: 1, WorkflowRepoID: 1, WorkflowCommitSHA: "abc", CommitSHA: "def", IsScopedRun: true}, // a scoped source triggering itself off its default branch + } { + assert.EqualError(t, validateCalledWorkflows(t.Context(), run, content), + "job build: `uses: $/${{ vars.ACTION }}` cannot use expressions in a workflow from another repository or commit") + } +} + func TestCheckRunJobLimit(t *testing.T) { require.NoError(t, unittest.PrepareTestDatabase()) diff --git a/services/actions/task.go b/services/actions/task.go index 519014107f5..c435bfc75ae 100644 --- a/services/actions/task.go +++ b/services/actions/task.go @@ -7,12 +7,16 @@ import ( "context" "errors" "fmt" + "path" + "strings" "sync" "time" + "gitea.dev/actionslib/pkg/model" runnerv1 "gitea.dev/actionslib/runner/v1" actions_model "gitea.dev/models/actions" "gitea.dev/models/db" + repo_model "gitea.dev/models/repo" secret_model "gitea.dev/models/secret" "gitea.dev/modules/actions/jobparser" "gitea.dev/modules/graceful" @@ -159,7 +163,7 @@ func buildRunnerTask(ctx context.Context, t *actions_model.ActionTask) (*runnerv return nil, nil, fmt.Errorf("generateTaskContext: %w", err) } - payload, err := runnerWorkflowPayload(job) + payload, err := runnerWorkflowPayload(ctx, job) if err != nil { return nil, nil, fmt.Errorf("runnerWorkflowPayload: %w", err) } @@ -174,19 +178,49 @@ func buildRunnerTask(ctx context.Context, t *actions_model.ActionTask) (*runnerv }, job, nil } -// runnerWorkflowPayload sets the job `if:` to `always()`, as Gitea has decided it and a runner must not re-evaluate it. -func runnerWorkflowPayload(job *actions_model.ActionRunJob) ([]byte, error) { +// runnerWorkflowPayload sets the job `if:` to `always()` as Gitea has decided it, and pins `$/` steps to the job's workflow source, which a runner doesn't know. +func runnerWorkflowPayload(ctx context.Context, job *actions_model.ActionRunJob) ([]byte, error) { swf, parsedJob, err := jobparser.ParseRawSingleWorkflow(job.WorkflowPayload) if err != nil { return nil, err } parsedJob.If = yaml.Node{Kind: yaml.ScalarNode, Value: "always()"} + var source *repo_model.Repository + var sourceSHA string + for _, step := range parsedJob.Steps { + uses, err := model.ParseActionUses(step.Uses) + if err != nil || uses.Kind != model.ActionUsesSelfRepo || strings.Contains(step.Uses, "${{") { + continue + } + if source == nil { + var runnerResolves bool + if sourceSHA, runnerResolves = selfRepoSourceCommit(job.Run, job); runnerResolves { + break + } + source, err = repo_model.GetRepositoryByID(ctx, job.WorkflowSourceRepoID) + if repo_model.IsErrRepoNotExist(err) { + break + } + if err != nil { + return nil, err + } + } + step.Uses = "self:" + path.Join(source.FullName(), uses.Path) + "@" + sourceSHA + } if err := swf.SetJob(job.JobID, parsedJob); err != nil { return nil, err } return swf.Marshal() } +// selfRepoSourceCommit returns the commit `$/` steps of a workflow from source must resolve at, +// and whether a runner resolves them there by itself, as it uses `github.repository` at `github.sha`. +func selfRepoSourceCommit(run *actions_model.ActionRun, source *actions_model.ActionRunJob) (sha string, runnerResolves bool) { + sha = resolveSameRepoWorkflowSourceCommit(run, source) + _, _, _, runSHA := runRefs(run) + return sha, source.WorkflowSourceRepoID == run.RepoID && sha == runSHA +} + func generateTaskContext(ctx context.Context, t *actions_model.ActionTask) (*structpb.Struct, error) { giteaRuntimeToken, err := CreateAuthorizationToken(t.ID, t.Job.RunID, t.JobID) if err != nil { diff --git a/services/actions/task_test.go b/services/actions/task_test.go index 89786ec608e..11cba6a6474 100644 --- a/services/actions/task_test.go +++ b/services/actions/task_test.go @@ -75,15 +75,31 @@ func TestReleaseTaskForRunnerCleanup(t *testing.T) { } func TestRunnerWorkflowPayload(t *testing.T) { - payload, err := runnerWorkflowPayload(&actions_model.ActionRunJob{ - JobID: "build", - WorkflowPayload: []byte("name: ci\njobs:\n build:\n if: false\n steps:\n - run: echo\n"), - }) - require.NoError(t, err) + require.NoError(t, unittest.PrepareTestDatabase()) + for _, tc := range []struct { + repoID, sourceRepoID int64 + sha, want string + }{ + {1, 1, "abc", "$/.gitea/actions/build"}, + {1, 1, "def", "self:user2/repo1/.gitea/actions/build@abc"}, + {2, 1, "abc", "self:user2/repo1/.gitea/actions/build@abc"}, + {2, 0, "abc", "$/.gitea/actions/build"}, + } { + payload, err := runnerWorkflowPayload(t.Context(), &actions_model.ActionRunJob{ + JobID: "build", + RepoID: tc.repoID, + Run: &actions_model.ActionRun{RepoID: tc.repoID, CommitSHA: tc.sha}, + WorkflowSourceRepoID: tc.sourceRepoID, + WorkflowSourceCommitSHA: "abc", + WorkflowPayload: []byte("name: ci\njobs:\n build:\n if: false\n steps:\n - uses: $/${{ inputs.action }}\n - uses: $/.gitea/actions/build\n"), + }) + require.NoError(t, err) - swf, parsedJob, err := jobparser.ParseRawSingleWorkflow(payload) - require.NoError(t, err) - assert.Equal(t, "ci", swf.Name) - assert.Equal(t, "always()", parsedJob.If.Value) - assert.Len(t, parsedJob.Steps, 1) + swf, parsedJob, err := jobparser.ParseRawSingleWorkflow(payload) + require.NoError(t, err) + assert.Equal(t, "ci", swf.Name) + assert.Equal(t, "always()", parsedJob.If.Value) + assert.Equal(t, "$/${{ inputs.action }}", parsedJob.Steps[0].Uses) + assert.Equal(t, tc.want, parsedJob.Steps[1].Uses) + } } diff --git a/tests/integration/actions_reusable_workflow_test.go b/tests/integration/actions_reusable_workflow_test.go index ccbe6f1d621..b1537b46e3e 100644 --- a/tests/integration/actions_reusable_workflow_test.go +++ b/tests/integration/actions_reusable_workflow_test.go @@ -660,6 +660,35 @@ jobs: assert.Contains(t, summary.Content, "secret token is required, but not provided while calling") }) + t.Run("Callee changed after run creation is checked again on expansion", func(t *testing.T) { + libRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: createActionsTestRepo(t, user2Token, "self-repo-steps-lib", false).ID}) + libPath := ".gitea/workflows/lib.yml" + libFile := createWorkflowFile(t, user2Token, libRepo.OwnerName, libRepo.Name, libPath, getWorkflowCreateFileOptions(user2, libRepo.DefaultBranch, "create lib", + "on: workflow_call\njobs:\n inner:\n runs-on: ubuntu-latest\n steps:\n - run: echo\n")) + + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: createActionsTestRepo(t, user2Token, "self-repo-steps-caller", false).ID}) + runner := newMockRunner() + runner.registerAsRepoRunner(t, repo.OwnerName, repo.Name, "mock-runner", []string{"ubuntu-latest"}, false) + createRepoWorkflowFile(t, user2, user2Token, repo, ".gitea/workflows/caller.yaml", + "on: push\njobs:\n plain_job:\n runs-on: ubuntu-latest\n steps:\n - run: echo\n call:\n needs: plain_job\n uses: user2/self-repo-steps-lib/"+libPath+"@main\n") + plainTask := runner.fetchTask(t) + + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", libRepo.OwnerName, libRepo.Name, libPath), &api.UpdateFileOptions{ + SHA: libFile.Content.SHA, + FileOptions: api.FileOptions{BranchName: libRepo.DefaultBranch, Message: "use a dynamic $/ step"}, + ContentBase64: base64.StdEncoding.EncodeToString([]byte("on: workflow_call\njobs:\n inner:\n runs-on: ubuntu-latest\n steps:\n - uses: $/${{ vars.ACTION }}\n")), + }).AddTokenAuth(user2Token) + MakeRequest(t, req, http.StatusOK) + runner.execTask(t, plainTask, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS}) + + _, _, run := getTaskAndJobAndRunByTaskID(t, plainTask.Id) + call := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: run.ID, JobID: "call"}) + assert.Equal(t, actions_model.StatusFailure, call.Status) + summary, err := actions_model.GetActionRunJobSummary(t.Context(), repo.ID, run.ID, call.RunAttemptID, call.ID, 0) + require.NoError(t, err) + assert.Contains(t, summary.Content, "job inner: `uses: $/${{ vars.ACTION }}` cannot use expressions in a workflow from another repository or commit") + }) + t.Run("Fork PR with secrets: inherit does not leak base repo secrets", func(t *testing.T) { // user2 owns the base repo, configures a secret, and registers a reusable workflow that declares a required secret. // The caller workflow uses `secrets: inherit`.