fix(actions): use base branch ref for pull_request_target context (#38636) (#38657)

Backport #38636 by @SudhanshuMatrix

Fixes a bug in Actions context generation for `pull_request_target`
workflows where `github.ref` / `gitea.ref` was incorrectly populated
with `refs/heads/owner:branch` instead of `refs/heads/branch`.

### Problem Statement
In `services/actions/context.go`, when constructing the `ref` string for
`pull_request_target` events:
```go
ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name

Signed-off-by: Sudhanshu Singh <sudhanshuwriterblc@gmail.com>
Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Shudhanshu Singh <sudhanshuwriterblc@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Giteabot
2026-07-27 00:35:03 -07:00
committed by GitHub
parent 9c685dedbb
commit 2695b47887
2 changed files with 35 additions and 1 deletions

View File

@@ -49,7 +49,7 @@ func GenerateGiteaContext(ctx context.Context, run *actions_model.ActionRun, att
// In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target,
// the ref will be the base branch.
if run.TriggerEvent == actions_module.GithubEventPullRequestTarget {
ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name
ref = git.BranchPrefix + pullPayload.PullRequest.Base.Ref
sha = pullPayload.PullRequest.Base.Sha
}
}

View File

@@ -12,8 +12,10 @@ import (
repo_model "gitea.dev/models/repo"
"gitea.dev/models/unittest"
user_model "gitea.dev/models/user"
actions_module "gitea.dev/modules/actions"
"gitea.dev/modules/json"
api "gitea.dev/modules/structs"
webhook_module "gitea.dev/modules/webhook"
act_model "gitea.com/gitea/runner/act/model"
"github.com/stretchr/testify/assert"
@@ -321,6 +323,38 @@ func TestFindTaskNeeds(t *testing.T) {
assert.Equal(t, "bbb", ret["job1"].Outputs["output_b"])
}
func TestGenerateGiteaContextPullRequestTarget(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",
},
},
}
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"},
}
giteaCtx := GenerateGiteaContext(t.Context(), run, nil, nil)
assert.Equal(t, "refs/heads/main", giteaCtx["ref"])
assert.Equal(t, "main", giteaCtx["ref_name"])
}
// TestGenerateGiteaContext_NilAttempt verifies that, with no explicit attempt,
// use GetLatestAttempt to load the latest attempt and resolve attempt-related context variables.
func TestGenerateGiteaContext_NilAttempt(t *testing.T) {