mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
enhance(actions)!: run pull_request_target workflows from the default branch (#40440)
Like GitHub since December 2025, `pull_request_target` workflows now run from the default branch whatever the pull request targets, so an outdated workflow on a release branch can't run with secrets. `github.ref`, `github.sha` and local reusable workflows follow it, while branch filters still match the base. Runs now record that ref, so runs from older versions keep the base on rerun. Breaking: pull requests targeting a non-default branch now run the default branch's `pull_request_target` workflows, so workflows that only exist on that branch stop running and `actions/checkout` without `ref` checks out the default branch. Ref: https://github.blog/changelog/2025-11-07-actions-pull_request_target-and-environment-branch-protections-changes/ Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
1 parent
e03fcadc69
commit
e1d2e94ab0
13 files changed
+129
-285
No files matched your search
@@ -448,6 +448,7 @@ func prepareMigrationTasks() []*migration {
|
||||
newMigration(369, "Add runner_name to action_task", v29.AddRunnerNameToActionTask),
|
||||
newMigration(370, "Change raw_concurrency of action_run and action_run_job to TEXT on MSSQL", v29.ChangeActionsRawConcurrencyToText),
|
||||
newMigration(371, "Add hash_sha256 column to attachment", v29.AddHashSHA256ToAttachment),
|
||||
newMigration(372, "Add workflow_ref to action_run", v29.AddWorkflowRefToActionRun),
|
||||
}
|
||||
return preparedMigrations
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v29
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.dev/modelmigration/base"
|
||||
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func AddWorkflowRefToActionRun(_ context.Context, x base.EngineMigration) error {
|
||||
type ActionRun struct {
|
||||
WorkflowRef string `xorm:"VARCHAR(255) NOT NULL DEFAULT ''"`
|
||||
}
|
||||
_, err := x.SyncWithOptions(xorm.SyncOptions{
|
||||
IgnoreDropIndices: true,
|
||||
IgnoreConstrains: true,
|
||||
}, new(ActionRun))
|
||||
return err
|
||||
}
|
||||
@@ -57,6 +57,7 @@ type ActionRun struct {
|
||||
// Always filled (repo-level run = the repo itself; scoped run = the source repo).
|
||||
WorkflowRepoID int64 `xorm:"NOT NULL DEFAULT 0"`
|
||||
WorkflowCommitSHA string `xorm:"VARCHAR(64) NOT NULL DEFAULT ''"`
|
||||
WorkflowRef string `xorm:"VARCHAR(255) NOT NULL DEFAULT ''"` // the default branch ref a pull_request_target run read its workflow from, empty for scoped and older runs
|
||||
|
||||
IsScopedRun bool `xorm:"NOT NULL DEFAULT false"` // IsScopedRun explicitly classifies scoped runs.
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ func GetSecretsOfTask(ctx context.Context, task *actions_model.ActionTask) (map[
|
||||
|
||||
if task.Job.Run.IsForkPullRequest && task.Job.Run.TriggerEvent != actions_module.GithubEventPullRequestTarget {
|
||||
// ignore secrets for fork pull request, except GITHUB_TOKEN and GITEA_TOKEN which are automatically generated.
|
||||
// for the tasks triggered by pull_request_target event, they could access the secrets because they will run in the context of the base branch
|
||||
// for the tasks triggered by pull_request_target event, they could access the secrets because they will run in the context of the default branch
|
||||
// see the documentation: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target
|
||||
return baseSecrets, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package actions
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"cmp"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
@@ -248,7 +249,8 @@ func ViewWorkflowFile(ctx *context_module.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
commit, err := ctx.Repo.GitRepo.GetCommit(ctx, run.CommitSHA)
|
||||
workflowCommitSHA := cmp.Or(run.WorkflowCommitSHA, run.CommitSHA)
|
||||
commit, err := ctx.Repo.GitRepo.GetCommit(ctx, workflowCommitSHA)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
@@ -260,7 +262,7 @@ func ViewWorkflowFile(ctx *context_module.Context) {
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name() == run.WorkflowID {
|
||||
ctx.Redirect(fmt.Sprintf("%s/src/commit/%s/%s/%s", ctx.Repo.RepoLink, url.PathEscape(run.CommitSHA), util.PathEscapeSegments(rpath), util.PathEscapeSegments(run.WorkflowID)))
|
||||
ctx.Redirect(fmt.Sprintf("%s/src/commit/%s/%s/%s", ctx.Repo.RepoLink, url.PathEscape(workflowCommitSHA), util.PathEscapeSegments(rpath), util.PathEscapeSegments(run.WorkflowID)))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,16 +135,22 @@ 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`.
|
||||
// runRefs returns the run's `github.base_ref`, `github.head_ref`, `github.ref` and `github.sha`, never the PR head for pull_request_target.
|
||||
func runRefs(run *actions_model.ActionRun) (baseRef, headRef, ref, sha string) {
|
||||
ref, sha = run.Ref, run.CommitSHA
|
||||
if run.TriggerEvent != actions_module.GithubEventPullRequestTarget {
|
||||
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
|
||||
pr := pullPayload.PullRequest
|
||||
baseRef, headRef = pr.Base.Ref, pr.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
|
||||
if run.WorkflowRef == "" { // scoped and older runs keep the base
|
||||
ref, sha = git.BranchPrefix+baseRef, pr.Base.Sha
|
||||
} else {
|
||||
ref, sha = run.WorkflowRef, run.WorkflowCommitSHA
|
||||
}
|
||||
} else if run.TriggerEvent == actions_module.GithubEventPullRequest && !pr.HasMerged && pr.MergedCommitID != nil {
|
||||
ref, sha = git.MergeRefNameFromPullIndex(pr.Index).String(), *pr.MergedCommitID
|
||||
}
|
||||
}
|
||||
return baseRef, headRef, ref, sha
|
||||
|
||||
@@ -404,41 +404,41 @@ func TestFindTaskNeeds(t *testing.T) {
|
||||
func TestGenerateGiteaContext(t *testing.T) {
|
||||
payload := api.PullRequestPayload{
|
||||
PullRequest: &api.PullRequest{
|
||||
Base: &api.PRBranchInfo{
|
||||
Name: "owner:main",
|
||||
Ref: "main",
|
||||
Sha: "1234567890abcdef",
|
||||
},
|
||||
Head: &api.PRBranchInfo{
|
||||
Name: "fork:feature",
|
||||
Ref: "feature",
|
||||
Sha: "fedcba0987654321",
|
||||
},
|
||||
Base: &api.PRBranchInfo{Ref: "release", Sha: "base-sha"},
|
||||
Head: &api.PRBranchInfo{Sha: "head-sha"},
|
||||
},
|
||||
}
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
assert.NoError(t, err)
|
||||
|
||||
run := &actions_model.ActionRun{
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
TriggerEvent: string(actions_module.GithubEventPullRequestTarget),
|
||||
EventPayload: string(payloadBytes),
|
||||
TriggerUser: &user_model.User{Name: "test-user"},
|
||||
Repo: &repo_model.Repository{Name: "test-repo", OwnerName: "test-owner"},
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
TriggerEvent: actions_module.GithubEventPullRequestTarget,
|
||||
EventPayload: string(payloadBytes),
|
||||
TriggerUser: &user_model.User{Name: "test-user"},
|
||||
Repo: &repo_model.Repository{Name: "test-repo", OwnerName: "test-owner"},
|
||||
CommitSHA: "head-sha",
|
||||
WorkflowCommitSHA: "default-sha",
|
||||
WorkflowRef: "refs/heads/main",
|
||||
}
|
||||
|
||||
giteaCtx := GenerateGiteaContext(t.Context(), run, nil, nil)
|
||||
|
||||
assert.Equal(t, "refs/heads/main", giteaCtx["ref"])
|
||||
assert.Equal(t, "main", giteaCtx["ref_name"])
|
||||
assert.Equal(t, "default-sha", giteaCtx["sha"])
|
||||
assert.Equal(t, "release", giteaCtx["base_ref"])
|
||||
|
||||
run.TriggerEvent, run.Ref = string(actions_module.GithubEventPullRequest), "refs/pull/1/head"
|
||||
run.WorkflowRef = ""
|
||||
_, _, ref, sha := runRefs(run)
|
||||
assert.Equal(t, [2]string{"refs/heads/release", "base-sha"}, [2]string{ref, sha})
|
||||
|
||||
run.TriggerEvent, run.Ref = actions_module.GithubEventPullRequest, "refs/pull/1/head"
|
||||
assert.Equal(t, "branch", GenerateGiteaContext(t.Context(), run, nil, nil)["ref_type"])
|
||||
|
||||
payload.PullRequest.Index, payload.PullRequest.MergedCommitID = 1, new("merge-sha")
|
||||
payloadBytes, err = json.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
run.EventPayload, run.CommitSHA = string(payloadBytes), "head-sha"
|
||||
run.EventPayload = string(payloadBytes)
|
||||
giteaCtx = GenerateGiteaContext(t.Context(), run, nil, nil)
|
||||
assert.Equal(t, "refs/pull/1/merge", giteaCtx["ref"])
|
||||
assert.Equal(t, "merge-sha", giteaCtx["sha"])
|
||||
|
||||
@@ -11,10 +11,8 @@ import (
|
||||
"strings"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
actions_module "gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/log"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/util"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
@@ -104,22 +102,6 @@ func calledWorkflowInputs(ctx context.Context, run *actions_model.ActionRun, cal
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
// pullRequestTargetBaseSHA returns the base branch commit of a pull_request_target run, and whether the run is one.
|
||||
func pullRequestTargetBaseSHA(run *actions_model.ActionRun) (string, bool) {
|
||||
if run.TriggerEvent != actions_module.GithubEventPullRequestTarget {
|
||||
return "", false
|
||||
}
|
||||
payload, err := run.GetPullRequestEventPayload()
|
||||
if err != nil {
|
||||
log.Error("run %d: get pull request event payload: %v", run.ID, err)
|
||||
return "", false
|
||||
}
|
||||
if payload.PullRequest == nil || payload.PullRequest.Base == nil || payload.PullRequest.Base.Sha == "" {
|
||||
return "", false
|
||||
}
|
||||
return payload.PullRequest.Base.Sha, true
|
||||
}
|
||||
|
||||
// evaluateJobIf evaluates a job's `if:`. An invalid `if:` skips the job and is reported in its summary.
|
||||
func evaluateJobIf(ctx context.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt, job *actions_model.ActionRunJob, vars map[string]string, allNeedsSucceed bool) (bool, error) {
|
||||
shouldStart, err := resolveJobIf(ctx, run, attempt, job, vars, allNeedsSucceed)
|
||||
|
||||
@@ -9,10 +9,6 @@ import (
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/models/unittest"
|
||||
actions_module "gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/json"
|
||||
api "gitea.dev/modules/structs"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -87,42 +83,3 @@ func TestReusableChildInputs(t *testing.T) {
|
||||
assert.Equal(t, map[string]any{"original_event_name": "push", "inputs": inputs}, gitCtx["gitea_workflow_call"])
|
||||
})
|
||||
}
|
||||
|
||||
func TestPullRequestTargetBaseSHA(t *testing.T) {
|
||||
prPayload := func(baseSHA string) string {
|
||||
payload, err := json.Marshal(api.PullRequestPayload{
|
||||
PullRequest: &api.PullRequest{
|
||||
Base: &api.PRBranchInfo{Sha: baseSHA},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return string(payload)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
triggerEvent string
|
||||
payload string
|
||||
wantSHA string
|
||||
}{
|
||||
{"pull_request_target with base SHA", actions_module.GithubEventPullRequestTarget, prPayload("base-sha"), "base-sha"},
|
||||
{"non pull_request_target trigger", actions_module.GithubEventPullRequest, prPayload("base-sha"), ""},
|
||||
{"missing base SHA", actions_module.GithubEventPullRequestTarget, prPayload(""), ""},
|
||||
{"invalid payload", actions_module.GithubEventPullRequestTarget, "{", ""},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, ok := pullRequestTargetBaseSHA(&actions_model.ActionRun{
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
TriggerEvent: test.triggerEvent,
|
||||
EventPayload: test.payload,
|
||||
})
|
||||
if test.wantSHA != "" {
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, test.wantSHA, got)
|
||||
} else {
|
||||
assert.False(t, ok)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -210,8 +210,6 @@ func notify(ctx context.Context, input *notifyInput) error {
|
||||
}
|
||||
}
|
||||
|
||||
var detectedWorkflows []*actions_module.DetectedWorkflow
|
||||
var filteredWorkflows []*actions_module.DetectedWorkflow
|
||||
actionsConfig := input.Repo.MustGetUnit(ctx, unit_model.TypeActions).ActionsConfig()
|
||||
workflows, schedules, filtered, invalid, err := actions_module.DetectWorkflows(ctx, gitRepo, workflowCommit,
|
||||
input.Event,
|
||||
@@ -230,56 +228,32 @@ func notify(ctx context.Context, input *notifyInput) error {
|
||||
len(schedules),
|
||||
)
|
||||
|
||||
for _, wf := range workflows {
|
||||
if actionsConfig.IsWorkflowDisabled(wf.EntryName) {
|
||||
log.Trace("repo %s has disable workflows %s", input.Repo.FullName(), wf.EntryName)
|
||||
continue
|
||||
}
|
||||
|
||||
if wf.TriggerEvent.Name != actions_module.GithubEventPullRequestTarget {
|
||||
detectedWorkflows = append(detectedWorkflows, wf)
|
||||
appendEnabled := func(dst, src []*actions_module.DetectedWorkflow, isTarget bool) []*actions_module.DetectedWorkflow {
|
||||
for _, wf := range src {
|
||||
if actionsConfig.IsWorkflowDisabled(wf.EntryName) {
|
||||
log.Trace("repo %s has disable workflows %s", input.Repo.FullName(), wf.EntryName)
|
||||
} else if (wf.TriggerEvent.Name == actions_module.GithubEventPullRequestTarget) == isTarget {
|
||||
dst = append(dst, wf)
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
detectedWorkflows, filteredWorkflows := appendEnabled(nil, workflows, false), appendEnabled(nil, filtered, false)
|
||||
|
||||
for _, wf := range filtered {
|
||||
if actionsConfig.IsWorkflowDisabled(wf.EntryName) {
|
||||
log.Trace("repo %s has disable workflows %s", input.Repo.FullName(), wf.EntryName)
|
||||
continue
|
||||
if input.PullRequest != nil && input.Event.IsPullRequest() {
|
||||
// like GitHub, pull_request_target reads workflows from the default branch whatever the base
|
||||
defaultCommit := baseCommit
|
||||
if input.PullRequest.BaseBranch != input.Repo.DefaultBranch {
|
||||
if defaultCommit, err = gitRepo.GetBranchCommit(ctx, input.Repo.DefaultBranch); err != nil {
|
||||
return fmt.Errorf("notify: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if wf.TriggerEvent.Name != actions_module.GithubEventPullRequestTarget {
|
||||
filteredWorkflows = append(filteredWorkflows, wf)
|
||||
}
|
||||
}
|
||||
|
||||
if input.PullRequest != nil {
|
||||
// detect pull_request_target workflows
|
||||
baseWorkflows, _, baseFiltered, _, err := actions_module.DetectWorkflows(ctx, gitRepo, baseCommit, input.Event, input.Payload, false)
|
||||
targetWorkflows, _, targetFiltered, _, err := actions_module.DetectWorkflows(ctx, gitRepo, defaultCommit, input.Event, input.Payload, false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DetectWorkflows: %w", err)
|
||||
}
|
||||
if len(baseWorkflows) == 0 {
|
||||
log.Trace("repo %s with commit %s couldn't find pull_request_target workflows", input.Repo.FullName(), baseCommit.ID)
|
||||
} else {
|
||||
for _, wf := range baseWorkflows {
|
||||
if actionsConfig.IsWorkflowDisabled(wf.EntryName) {
|
||||
log.Trace("repo %s has disable workflows %s", input.Repo.FullName(), wf.EntryName)
|
||||
continue
|
||||
}
|
||||
if wf.TriggerEvent.Name == actions_module.GithubEventPullRequestTarget {
|
||||
detectedWorkflows = append(detectedWorkflows, wf)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, wf := range baseFiltered {
|
||||
if actionsConfig.IsWorkflowDisabled(wf.EntryName) {
|
||||
log.Trace("repo %s has disable workflows %s", input.Repo.FullName(), wf.EntryName)
|
||||
continue
|
||||
}
|
||||
if wf.TriggerEvent.Name == actions_module.GithubEventPullRequestTarget {
|
||||
filteredWorkflows = append(filteredWorkflows, wf)
|
||||
}
|
||||
}
|
||||
detectedWorkflows = appendEnabled(detectedWorkflows, targetWorkflows, true)
|
||||
filteredWorkflows = appendEnabled(filteredWorkflows, targetFiltered, true)
|
||||
}
|
||||
|
||||
if shouldDetectSchedules {
|
||||
@@ -440,6 +414,7 @@ func buildApproveAndInsertRun(
|
||||
Status: actions_model.StatusWaiting,
|
||||
WorkflowRepoID: workflowRepoID,
|
||||
WorkflowCommitSHA: dwf.SourceCommitSHA,
|
||||
WorkflowRef: util.Iif(!isScopedRun && dwf.TriggerEvent.Name == actions_module.GithubEventPullRequestTarget, git.BranchPrefix+input.Repo.DefaultBranch, ""),
|
||||
IsScopedRun: isScopedRun,
|
||||
}
|
||||
|
||||
@@ -594,7 +569,7 @@ func ifNeedApprovalWith(
|
||||
hasMergedPR func(context.Context, int64, int64) (bool, error),
|
||||
) (bool, error) {
|
||||
// 1. don't need approval if it's not a fork PR
|
||||
// 2. don't need approval if the event is `pull_request_target` since the workflow will run in the context of base branch
|
||||
// 2. don't need approval if the event is `pull_request_target` since the workflow will run in the context of the default branch
|
||||
// see https://docs.github.com/en/actions/managing-workflow-runs/approving-workflow-runs-from-public-forks#about-workflow-runs-from-public-forks
|
||||
if !run.IsForkPullRequest || run.TriggerEvent == actions_module.GithubEventPullRequestTarget {
|
||||
return false, nil
|
||||
|
||||
@@ -171,16 +171,13 @@ func errCallLevelExceeded(uses string) error {
|
||||
}
|
||||
|
||||
// resolveSameRepoWorkflowSourceCommit returns the commit to read a same-repo reusable workflow from.
|
||||
// pull_request_target runs must resolve local `uses:` at the PR base commit, not a stored head SHA.
|
||||
func resolveSameRepoWorkflowSourceCommit(run *actions_model.ActionRun, caller *actions_model.ActionRunJob) string {
|
||||
// only a SHA copied from the run row can be the polluted head one; a SHA resolved from a `uses:` ref is right by construction
|
||||
if run.IsScopedRun || caller.WorkflowSourceRepoID != run.RepoID || caller.WorkflowSourceCommitSHA != run.WorkflowCommitSHA {
|
||||
if run.TriggerEvent != actions_module.GithubEventPullRequestTarget || run.IsScopedRun || caller.WorkflowSourceRepoID != run.RepoID || caller.WorkflowSourceCommitSHA != run.WorkflowCommitSHA {
|
||||
return caller.WorkflowSourceCommitSHA
|
||||
}
|
||||
if baseSHA, ok := pullRequestTargetBaseSHA(run); ok && baseSHA != caller.WorkflowSourceCommitSHA {
|
||||
return baseSHA
|
||||
}
|
||||
return caller.WorkflowSourceCommitSHA
|
||||
_, _, _, sha := runRefs(run)
|
||||
return sha
|
||||
}
|
||||
|
||||
// readWorkflowFromRepo loads a workflow file from `repo` at `refOrSHA`.
|
||||
|
||||
@@ -14,9 +14,7 @@ import (
|
||||
"gitea.dev/models/unittest"
|
||||
actions_module "gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/test"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
|
||||
@@ -330,74 +328,35 @@ func TestUndoExpansion(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestResolveSameRepoWorkflowSourceCommit(t *testing.T) {
|
||||
prtRun := func(baseSHA string) *actions_model.ActionRun {
|
||||
payload, err := json.Marshal(api.PullRequestPayload{
|
||||
PullRequest: &api.PullRequest{
|
||||
Base: &api.PRBranchInfo{Sha: baseSHA},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
// a run recorded before the fix points at the PR head commit
|
||||
prtRun := func(workflowSHA string) *actions_model.ActionRun {
|
||||
return &actions_model.ActionRun{
|
||||
ID: 42,
|
||||
RepoID: 1,
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
TriggerEvent: actions_module.GithubEventPullRequestTarget,
|
||||
EventPayload: string(payload),
|
||||
WorkflowCommitSHA: "head-sha",
|
||||
EventPayload: `{"pull_request":{"base":{"sha":"base-sha"},"head":{"sha":"head-sha"}}}`,
|
||||
CommitSHA: "head-sha",
|
||||
WorkflowCommitSHA: workflowSHA,
|
||||
}
|
||||
}
|
||||
pushRun := &actions_model.ActionRun{
|
||||
RepoID: 1,
|
||||
TriggerEvent: "push",
|
||||
WorkflowCommitSHA: "head-sha",
|
||||
scopedRun, payloadlessRun, defaultRun := prtRun("head-sha"), prtRun("default-sha"), prtRun("default-sha")
|
||||
scopedRun.IsScopedRun, payloadlessRun.EventPayload, defaultRun.WorkflowRef = true, "{}", "refs/heads/main"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
run *actions_model.ActionRun
|
||||
sourceRepoID int64
|
||||
sourceCommit, want string
|
||||
}{
|
||||
{"legacy pull_request_target recording the head resolves at the base", prtRun("head-sha"), 1, "head-sha", "base-sha"},
|
||||
{"pull_request_target resolves at its default branch commit", defaultRun, 1, "default-sha", "default-sha"},
|
||||
{"pull_request_target without a pull request payload resolves nowhere", payloadlessRun, 1, "default-sha", ""},
|
||||
{"non pull_request_target keeps stored SHA", &actions_model.ActionRun{RepoID: 1, TriggerEvent: "push", WorkflowCommitSHA: "head-sha"}, 1, "head-sha", "head-sha"},
|
||||
{"scoped run keeps stored SHA", scopedRun, 1, "head-sha", "head-sha"},
|
||||
{"cross-repo caller keeps stored SHA", prtRun("head-sha"), 2, "head-sha", "head-sha"},
|
||||
{"caller resolved from a uses: ref keeps its own SHA", prtRun("head-sha"), 1, "tag-v1-sha", "tag-v1-sha"},
|
||||
} {
|
||||
caller := &actions_model.ActionRunJob{WorkflowSourceRepoID: tc.sourceRepoID, WorkflowSourceCommitSHA: tc.sourceCommit}
|
||||
assert.Equal(t, tc.want, resolveSameRepoWorkflowSourceCommit(tc.run, caller), tc.name)
|
||||
}
|
||||
caller := func(sourceRepoID int64, sourceCommitSHA string) *actions_model.ActionRunJob {
|
||||
return &actions_model.ActionRunJob{WorkflowSourceRepoID: sourceRepoID, WorkflowSourceCommitSHA: sourceCommitSHA}
|
||||
}
|
||||
|
||||
t.Run("pull_request_target pins to base commit", func(t *testing.T) {
|
||||
got := resolveSameRepoWorkflowSourceCommit(prtRun("base-sha"), caller(1, "head-sha"))
|
||||
assert.Equal(t, "base-sha", got)
|
||||
})
|
||||
|
||||
t.Run("legacy nested caller (with head-sha) pins to base commit", func(t *testing.T) {
|
||||
nested := caller(1, "head-sha")
|
||||
nested.ParentJobID = 99
|
||||
got := resolveSameRepoWorkflowSourceCommit(prtRun("base-sha"), nested)
|
||||
assert.Equal(t, "base-sha", got)
|
||||
})
|
||||
|
||||
t.Run("pull_request_target keeps stored SHA when already base", func(t *testing.T) {
|
||||
run := prtRun("base-sha")
|
||||
run.WorkflowCommitSHA = "base-sha"
|
||||
got := resolveSameRepoWorkflowSourceCommit(run, caller(1, "base-sha"))
|
||||
assert.Equal(t, "base-sha", got)
|
||||
})
|
||||
|
||||
t.Run("non pull_request_target keeps stored SHA", func(t *testing.T) {
|
||||
got := resolveSameRepoWorkflowSourceCommit(pushRun, caller(1, "head-sha"))
|
||||
assert.Equal(t, "head-sha", got)
|
||||
})
|
||||
|
||||
t.Run("scoped run keeps stored SHA", func(t *testing.T) {
|
||||
run := prtRun("base-sha")
|
||||
run.IsScopedRun = true
|
||||
got := resolveSameRepoWorkflowSourceCommit(run, caller(1, "head-sha"))
|
||||
assert.Equal(t, "head-sha", got)
|
||||
})
|
||||
|
||||
t.Run("cross-repo caller keeps stored SHA", func(t *testing.T) {
|
||||
got := resolveSameRepoWorkflowSourceCommit(prtRun("base-sha"), caller(2, "head-sha"))
|
||||
assert.Equal(t, "head-sha", got)
|
||||
})
|
||||
|
||||
t.Run("caller resolved from a uses: ref keeps its own SHA", func(t *testing.T) {
|
||||
nested := caller(1, "tag-v1-sha")
|
||||
nested.ParentJobID = 99
|
||||
got := resolveSameRepoWorkflowSourceCommit(prtRun("base-sha"), nested)
|
||||
assert.Equal(t, "tag-v1-sha", got)
|
||||
})
|
||||
}
|
||||
|
||||
func TestQualifyRef(t *testing.T) {
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/models/unittest"
|
||||
user_model "gitea.dev/models/user"
|
||||
actions_module "gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/json"
|
||||
@@ -787,98 +786,40 @@ jobs:
|
||||
runner.execTask(t, task, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS})
|
||||
})
|
||||
|
||||
t.Run("pull_request_target resolves a local reusable workflow at the base commit", func(t *testing.T) {
|
||||
t.Run("pull_request_target into another branch runs the default branch workflow and its local reusable one", func(t *testing.T) {
|
||||
apiBaseRepo := createActionsTestRepo(t, user2Token, "prt-reusable-test", false)
|
||||
baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiBaseRepo.ID})
|
||||
|
||||
runner := newMockRunner()
|
||||
runner.registerAsRepoRunner(t, baseRepo.OwnerName, baseRepo.Name, "mock-prt-runner", []string{"ubuntu-latest"}, false)
|
||||
|
||||
reusablePath := ".gitea/workflows/reusable.yaml"
|
||||
// A pull_request_target run's workflow should always come from the base branch.
|
||||
createRepoWorkflowFile(t, user2, user2Token, baseRepo, reusablePath, `name: Reusable
|
||||
on:
|
||||
workflow_call:
|
||||
jobs:
|
||||
trusted:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo trusted
|
||||
`)
|
||||
baseFile := createWorkflowFile(t, user2Token, baseRepo.OwnerName, baseRepo.Name, ".gitea/workflows/prt.yaml",
|
||||
getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, "create prt.yaml", `name: PRT
|
||||
on: pull_request_target
|
||||
jobs:
|
||||
call_reusable:
|
||||
uses: ./.gitea/workflows/reusable.yaml
|
||||
secrets: inherit
|
||||
`))
|
||||
baseSHA := baseFile.Commit.SHA
|
||||
|
||||
// user4 forks
|
||||
req := NewRequestWithJSON(t, "POST",
|
||||
fmt.Sprintf("/api/v1/repos/%s/%s/forks", baseRepo.OwnerName, baseRepo.Name),
|
||||
testCreateFileInBranch(t, user2, baseRepo, createFileInBranchOptions{NewBranch: "release"}, map[string]string{
|
||||
".gitea/workflows/release-only.yaml": "on: pull_request_target\njobs:\n release-only:\n runs-on: ubuntu-latest\n steps:\n - run: echo release-only\n",
|
||||
})
|
||||
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks", baseRepo.OwnerName, baseRepo.Name),
|
||||
&api.CreateForkOption{Name: new("prt-reusable-test-fork")}).AddTokenAuth(user4Token)
|
||||
resp := MakeRequest(t, req, http.StatusAccepted)
|
||||
apiForkRepo := DecodeJSON(t, resp, &api.Repository{})
|
||||
forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiForkRepo.ID})
|
||||
user4APICtx := NewAPITestContext(t, user4.Name, forkRepo.Name, auth_model.AccessTokenScopeWriteRepository)
|
||||
forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: DecodeJSON(t, MakeRequest(t, req, http.StatusAccepted), &api.Repository{}).ID})
|
||||
reusablePath := ".gitea/workflows/reusable.yaml"
|
||||
forkHeadSHA := testCreateFileInBranch(t, user4, forkRepo, createFileInBranchOptions{NewBranch: "fork-branch"}, map[string]string{
|
||||
reusablePath: "on: workflow_call\njobs:\n from-fork:\n runs-on: ubuntu-latest\n steps:\n - run: echo from-fork\n",
|
||||
}).Commit.SHA
|
||||
defaultSHA := testCreateFileInBranch(t, user2, baseRepo, createFileInBranchOptions{}, map[string]string{
|
||||
reusablePath: "on: workflow_call\njobs:\n trusted:\n runs-on: ubuntu-latest\n steps:\n - run: echo trusted\n",
|
||||
".gitea/workflows/prt.yaml": "on: pull_request_target\njobs:\n call_reusable:\n uses: ./.gitea/workflows/reusable.yaml\n",
|
||||
}).Commit.SHA
|
||||
|
||||
// user4 rewrites the reusable workflow the base branch calls into, and opens a PR
|
||||
req = NewRequest(t, "GET",
|
||||
fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", forkRepo.OwnerName, forkRepo.Name, reusablePath)).AddTokenAuth(user4Token)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
forkReusable := DecodeJSON(t, resp, &api.ContentsResponse{})
|
||||
|
||||
req = NewRequestWithJSON(t, "PUT",
|
||||
fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", forkRepo.OwnerName, forkRepo.Name, reusablePath), &api.UpdateFileOptions{
|
||||
FileOptions: api.FileOptions{
|
||||
NewBranchName: "fork-branch",
|
||||
Message: "rewrite the reusable workflow",
|
||||
Author: api.Identity{Name: user4.Name, Email: user4.Email},
|
||||
Committer: api.Identity{Name: user4.Name, Email: user4.Email},
|
||||
Dates: api.CommitDateOptions{Author: time.Now(), Committer: time.Now()},
|
||||
},
|
||||
SHA: forkReusable.SHA,
|
||||
ContentBase64: base64.StdEncoding.EncodeToString([]byte(`name: Reusable
|
||||
on:
|
||||
workflow_call:
|
||||
jobs:
|
||||
from-fork:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo from-fork
|
||||
`)),
|
||||
}).AddTokenAuth(user4Token)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
forkHeadSHA := DecodeJSON(t, resp, &api.FileResponse{}).Commit.SHA
|
||||
require.NotEqual(t, baseSHA, forkHeadSHA)
|
||||
|
||||
doAPICreatePullRequest(user4APICtx, baseRepo.OwnerName, baseRepo.Name, baseRepo.DefaultBranch, user4.Name+":fork-branch")(t)
|
||||
doAPICreatePullRequest(APITestContext{Session: user4Session, Token: user4Token}, baseRepo.OwnerName, baseRepo.Name, "release", user4.Name+":fork-branch")(t)
|
||||
|
||||
assert.Equal(t, 1, unittest.GetCount(t, &actions_model.ActionRun{RepoID: baseRepo.ID}))
|
||||
prtRun := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: baseRepo.ID})
|
||||
assert.Equal(t, actions_module.GithubEventPullRequestTarget, prtRun.TriggerEvent)
|
||||
assert.True(t, prtRun.IsForkPullRequest)
|
||||
assert.False(t, prtRun.NeedApproval)
|
||||
// The run still points at the PR head, but its workflow source must be the base commit.
|
||||
prtRun := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: baseRepo.ID, WorkflowID: "prt.yaml"})
|
||||
assert.Equal(t, forkHeadSHA, prtRun.CommitSHA)
|
||||
assert.Equal(t, baseSHA, prtRun.WorkflowCommitSHA)
|
||||
|
||||
caller := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: prtRun.ID, JobID: "call_reusable"})
|
||||
assert.Equal(t, baseSHA, caller.WorkflowSourceCommitSHA)
|
||||
assert.NotContains(t, string(caller.ReusableWorkflowContent), "from-fork")
|
||||
|
||||
// The caller has no needs, so it is expanded inline at insert time: the child comes from the base branch.
|
||||
unittest.AssertNotExistsBean(t, &actions_model.ActionRunJob{RunID: prtRun.ID, JobID: "from-fork"})
|
||||
assert.Equal(t, defaultSHA, prtRun.WorkflowCommitSHA)
|
||||
child := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: prtRun.ID, JobID: "trusted"})
|
||||
assert.Equal(t, caller.ID, child.ParentJobID)
|
||||
assert.Equal(t, baseSHA, child.WorkflowSourceCommitSHA)
|
||||
assert.Equal(t, defaultSHA, child.WorkflowSourceCommitSHA)
|
||||
|
||||
task := runner.fetchTask(t)
|
||||
_, taskJob, _ := getTaskAndJobAndRunByTaskID(t, task.Id)
|
||||
require.Equal(t, "trusted", taskJob.JobID)
|
||||
runner.execTask(t, task, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS})
|
||||
taskContext := runner.fetchTask(t).Context.GetFields()
|
||||
assert.Equal(t, "refs/heads/main", taskContext["ref"].GetStringValue())
|
||||
assert.Equal(t, defaultSHA, taskContext["sha"].GetStringValue())
|
||||
assert.Equal(t, "release", taskContext["base_ref"].GetStringValue())
|
||||
})
|
||||
|
||||
t.Run("Caller alternates expanding across attempts", func(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user