forked from gitea/gitea
1
0
Fork 0

Support `pull_request_target` event (#25229)

Fix #25088

This PR adds the support for
[`pull_request_target`](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target)
workflow trigger. `pull_request_target` is similar to `pull_request`,
but the workflow triggered by the `pull_request_target` event runs in
the context of the base branch of the pull request rather than the head
branch. Since the workflow from the base is considered trusted, it can
access the secrets and doesn't need approvals to run.
This commit is contained in:
Zettat123 2023-06-26 14:33:18 +08:00 committed by GitHub
parent e409e14bdf
commit 48e5a74f21
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 286 additions and 63 deletions

View File

@ -39,8 +39,9 @@ type ActionRun struct {
IsForkPullRequest bool // If this is triggered by a PR from a forked repository or an untrusted user, we need to check if it is approved and limit permissions when running the workflow. IsForkPullRequest bool // If this is triggered by a PR from a forked repository or an untrusted user, we need to check if it is approved and limit permissions when running the workflow.
NeedApproval bool // may need approval if it's a fork pull request NeedApproval bool // may need approval if it's a fork pull request
ApprovedBy int64 `xorm:"index"` // who approved ApprovedBy int64 `xorm:"index"` // who approved
Event webhook_module.HookEventType Event webhook_module.HookEventType // the webhook event that causes the workflow to run
EventPayload string `xorm:"LONGTEXT"` EventPayload string `xorm:"LONGTEXT"`
TriggerEvent string // the trigger event defined in the `on` configuration of the triggered workflow
Status Status `xorm:"index"` Status Status `xorm:"index"`
Started timeutil.TimeStamp Started timeutil.TimeStamp
Stopped timeutil.TimeStamp Stopped timeutil.TimeStamp

View File

@ -503,9 +503,10 @@ var migrations = []Migration{
// v260 -> v261 // v260 -> v261
NewMigration("Drop custom_labels column of action_runner table", v1_21.DropCustomLabelsColumnOfActionRunner), NewMigration("Drop custom_labels column of action_runner table", v1_21.DropCustomLabelsColumnOfActionRunner),
// v261 -> v262 // v261 -> v262
NewMigration("Add variable table", v1_21.CreateVariableTable), NewMigration("Add variable table", v1_21.CreateVariableTable),
// v262 -> v263
NewMigration("Add TriggerEvent to action_run table", v1_21.AddTriggerEventToActionRun),
} }
// GetCurrentDBVersion returns the current db version // GetCurrentDBVersion returns the current db version

View File

@ -0,0 +1,16 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package v1_21 //nolint
import (
"xorm.io/xorm"
)
func AddTriggerEventToActionRun(x *xorm.Engine) error {
type ActionRun struct {
TriggerEvent string
}
return x.Sync(new(ActionRun))
}

View File

@ -8,33 +8,33 @@ import (
) )
const ( const (
githubEventPullRequest = "pull_request" GithubEventPullRequest = "pull_request"
githubEventPullRequestTarget = "pull_request_target" GithubEventPullRequestTarget = "pull_request_target"
githubEventPullRequestReviewComment = "pull_request_review_comment" GithubEventPullRequestReviewComment = "pull_request_review_comment"
githubEventPullRequestReview = "pull_request_review" GithubEventPullRequestReview = "pull_request_review"
githubEventRegistryPackage = "registry_package" GithubEventRegistryPackage = "registry_package"
githubEventCreate = "create" GithubEventCreate = "create"
githubEventDelete = "delete" GithubEventDelete = "delete"
githubEventFork = "fork" GithubEventFork = "fork"
githubEventPush = "push" GithubEventPush = "push"
githubEventIssues = "issues" GithubEventIssues = "issues"
githubEventIssueComment = "issue_comment" GithubEventIssueComment = "issue_comment"
githubEventRelease = "release" GithubEventRelease = "release"
githubEventPullRequestComment = "pull_request_comment" GithubEventPullRequestComment = "pull_request_comment"
githubEventGollum = "gollum" GithubEventGollum = "gollum"
) )
// canGithubEventMatch check if the input Github event can match any Gitea event. // canGithubEventMatch check if the input Github event can match any Gitea event.
func canGithubEventMatch(eventName string, triggedEvent webhook_module.HookEventType) bool { func canGithubEventMatch(eventName string, triggedEvent webhook_module.HookEventType) bool {
switch eventName { switch eventName {
case githubEventRegistryPackage: case GithubEventRegistryPackage:
return triggedEvent == webhook_module.HookEventPackage return triggedEvent == webhook_module.HookEventPackage
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#gollum // See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#gollum
case githubEventGollum: case GithubEventGollum:
return triggedEvent == webhook_module.HookEventWiki return triggedEvent == webhook_module.HookEventWiki
case githubEventIssues: case GithubEventIssues:
switch triggedEvent { switch triggedEvent {
case webhook_module.HookEventIssues, case webhook_module.HookEventIssues,
webhook_module.HookEventIssueAssign, webhook_module.HookEventIssueAssign,
@ -46,7 +46,7 @@ func canGithubEventMatch(eventName string, triggedEvent webhook_module.HookEvent
return false return false
} }
case githubEventPullRequest, githubEventPullRequestTarget: case GithubEventPullRequest, GithubEventPullRequestTarget:
switch triggedEvent { switch triggedEvent {
case webhook_module.HookEventPullRequest, case webhook_module.HookEventPullRequest,
webhook_module.HookEventPullRequestSync, webhook_module.HookEventPullRequestSync,
@ -58,7 +58,7 @@ func canGithubEventMatch(eventName string, triggedEvent webhook_module.HookEvent
return false return false
} }
case githubEventPullRequestReview: case GithubEventPullRequestReview:
switch triggedEvent { switch triggedEvent {
case webhook_module.HookEventPullRequestReviewApproved, case webhook_module.HookEventPullRequestReviewApproved,
webhook_module.HookEventPullRequestReviewComment, webhook_module.HookEventPullRequestReviewComment,

View File

@ -21,85 +21,85 @@ func TestCanGithubEventMatch(t *testing.T) {
// registry_package event // registry_package event
{ {
"registry_package matches", "registry_package matches",
githubEventRegistryPackage, GithubEventRegistryPackage,
webhook_module.HookEventPackage, webhook_module.HookEventPackage,
true, true,
}, },
{ {
"registry_package cannot match", "registry_package cannot match",
githubEventRegistryPackage, GithubEventRegistryPackage,
webhook_module.HookEventPush, webhook_module.HookEventPush,
false, false,
}, },
// issues event // issues event
{ {
"issue matches", "issue matches",
githubEventIssues, GithubEventIssues,
webhook_module.HookEventIssueLabel, webhook_module.HookEventIssueLabel,
true, true,
}, },
{ {
"issue cannot match", "issue cannot match",
githubEventIssues, GithubEventIssues,
webhook_module.HookEventIssueComment, webhook_module.HookEventIssueComment,
false, false,
}, },
// issue_comment event // issue_comment event
{ {
"issue_comment matches", "issue_comment matches",
githubEventIssueComment, GithubEventIssueComment,
webhook_module.HookEventIssueComment, webhook_module.HookEventIssueComment,
true, true,
}, },
{ {
"issue_comment cannot match", "issue_comment cannot match",
githubEventIssueComment, GithubEventIssueComment,
webhook_module.HookEventIssues, webhook_module.HookEventIssues,
false, false,
}, },
// pull_request event // pull_request event
{ {
"pull_request matches", "pull_request matches",
githubEventPullRequest, GithubEventPullRequest,
webhook_module.HookEventPullRequestSync, webhook_module.HookEventPullRequestSync,
true, true,
}, },
{ {
"pull_request cannot match", "pull_request cannot match",
githubEventPullRequest, GithubEventPullRequest,
webhook_module.HookEventPullRequestComment, webhook_module.HookEventPullRequestComment,
false, false,
}, },
// pull_request_target event // pull_request_target event
{ {
"pull_request_target matches", "pull_request_target matches",
githubEventPullRequest, GithubEventPullRequest,
webhook_module.HookEventPullRequest, webhook_module.HookEventPullRequest,
true, true,
}, },
{ {
"pull_request_target cannot match", "pull_request_target cannot match",
githubEventPullRequest, GithubEventPullRequest,
webhook_module.HookEventPullRequestComment, webhook_module.HookEventPullRequestComment,
false, false,
}, },
// pull_request_review event // pull_request_review event
{ {
"pull_request_review matches", "pull_request_review matches",
githubEventPullRequestReview, GithubEventPullRequestReview,
webhook_module.HookEventPullRequestReviewComment, webhook_module.HookEventPullRequestReviewComment,
true, true,
}, },
{ {
"pull_request_review cannot match", "pull_request_review cannot match",
githubEventPullRequestReview, GithubEventPullRequestReview,
webhook_module.HookEventPullRequestComment, webhook_module.HookEventPullRequestComment,
false, false,
}, },
// other events // other events
{ {
"create event", "create event",
githubEventCreate, GithubEventCreate,
webhook_module.HookEventCreate, webhook_module.HookEventCreate,
true, true,
}, },

View File

@ -20,6 +20,14 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
type DetectedWorkflow struct {
EntryName string
TriggerEvent string
Commit *git.Commit
Ref string
Content []byte
}
func init() { func init() {
model.OnDecodeNodeError = func(node yaml.Node, out interface{}, err error) { model.OnDecodeNodeError = func(node yaml.Node, out interface{}, err error) {
// Log the error instead of panic or fatal. // Log the error instead of panic or fatal.
@ -89,13 +97,13 @@ func GetEventsFromContent(content []byte) ([]*jobparser.Event, error) {
return events, nil return events, nil
} }
func DetectWorkflows(commit *git.Commit, triggedEvent webhook_module.HookEventType, payload api.Payloader) (map[string][]byte, error) { func DetectWorkflows(commit *git.Commit, triggedEvent webhook_module.HookEventType, payload api.Payloader) ([]*DetectedWorkflow, error) {
entries, err := ListWorkflows(commit) entries, err := ListWorkflows(commit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
workflows := make(map[string][]byte, len(entries)) workflows := make([]*DetectedWorkflow, 0, len(entries))
for _, entry := range entries { for _, entry := range entries {
content, err := GetContentFromEntry(entry) content, err := GetContentFromEntry(entry)
if err != nil { if err != nil {
@ -109,7 +117,13 @@ func DetectWorkflows(commit *git.Commit, triggedEvent webhook_module.HookEventTy
for _, evt := range events { for _, evt := range events {
log.Trace("detect workflow %q for event %#v matching %q", entry.Name(), evt, triggedEvent) log.Trace("detect workflow %q for event %#v matching %q", entry.Name(), evt, triggedEvent)
if detectMatched(commit, triggedEvent, payload, evt) { if detectMatched(commit, triggedEvent, payload, evt) {
workflows[entry.Name()] = content dwf := &DetectedWorkflow{
EntryName: entry.Name(),
TriggerEvent: evt.Name,
Commit: commit,
Content: content,
}
workflows = append(workflows, dwf)
} }
} }
} }

View File

@ -23,77 +23,77 @@ func TestDetectMatched(t *testing.T) {
expected bool expected bool
}{ }{
{ {
desc: "HookEventCreate(create) matches githubEventCreate(create)", desc: "HookEventCreate(create) matches GithubEventCreate(create)",
triggedEvent: webhook_module.HookEventCreate, triggedEvent: webhook_module.HookEventCreate,
payload: nil, payload: nil,
yamlOn: "on: create", yamlOn: "on: create",
expected: true, expected: true,
}, },
{ {
desc: "HookEventIssues(issues) `opened` action matches githubEventIssues(issues)", desc: "HookEventIssues(issues) `opened` action matches GithubEventIssues(issues)",
triggedEvent: webhook_module.HookEventIssues, triggedEvent: webhook_module.HookEventIssues,
payload: &api.IssuePayload{Action: api.HookIssueOpened}, payload: &api.IssuePayload{Action: api.HookIssueOpened},
yamlOn: "on: issues", yamlOn: "on: issues",
expected: true, expected: true,
}, },
{ {
desc: "HookEventIssues(issues) `milestoned` action matches githubEventIssues(issues)", desc: "HookEventIssues(issues) `milestoned` action matches GithubEventIssues(issues)",
triggedEvent: webhook_module.HookEventIssues, triggedEvent: webhook_module.HookEventIssues,
payload: &api.IssuePayload{Action: api.HookIssueMilestoned}, payload: &api.IssuePayload{Action: api.HookIssueMilestoned},
yamlOn: "on: issues", yamlOn: "on: issues",
expected: true, expected: true,
}, },
{ {
desc: "HookEventPullRequestSync(pull_request_sync) matches githubEventPullRequest(pull_request)", desc: "HookEventPullRequestSync(pull_request_sync) matches GithubEventPullRequest(pull_request)",
triggedEvent: webhook_module.HookEventPullRequestSync, triggedEvent: webhook_module.HookEventPullRequestSync,
payload: &api.PullRequestPayload{Action: api.HookIssueSynchronized}, payload: &api.PullRequestPayload{Action: api.HookIssueSynchronized},
yamlOn: "on: pull_request", yamlOn: "on: pull_request",
expected: true, expected: true,
}, },
{ {
desc: "HookEventPullRequest(pull_request) `label_updated` action doesn't match githubEventPullRequest(pull_request) with no activity type", desc: "HookEventPullRequest(pull_request) `label_updated` action doesn't match GithubEventPullRequest(pull_request) with no activity type",
triggedEvent: webhook_module.HookEventPullRequest, triggedEvent: webhook_module.HookEventPullRequest,
payload: &api.PullRequestPayload{Action: api.HookIssueLabelUpdated}, payload: &api.PullRequestPayload{Action: api.HookIssueLabelUpdated},
yamlOn: "on: pull_request", yamlOn: "on: pull_request",
expected: false, expected: false,
}, },
{ {
desc: "HookEventPullRequest(pull_request) `label_updated` action matches githubEventPullRequest(pull_request) with `label` activity type", desc: "HookEventPullRequest(pull_request) `label_updated` action matches GithubEventPullRequest(pull_request) with `label` activity type",
triggedEvent: webhook_module.HookEventPullRequest, triggedEvent: webhook_module.HookEventPullRequest,
payload: &api.PullRequestPayload{Action: api.HookIssueLabelUpdated}, payload: &api.PullRequestPayload{Action: api.HookIssueLabelUpdated},
yamlOn: "on:\n pull_request:\n types: [labeled]", yamlOn: "on:\n pull_request:\n types: [labeled]",
expected: true, expected: true,
}, },
{ {
desc: "HookEventPullRequestReviewComment(pull_request_review_comment) matches githubEventPullRequestReviewComment(pull_request_review_comment)", desc: "HookEventPullRequestReviewComment(pull_request_review_comment) matches GithubEventPullRequestReviewComment(pull_request_review_comment)",
triggedEvent: webhook_module.HookEventPullRequestReviewComment, triggedEvent: webhook_module.HookEventPullRequestReviewComment,
payload: &api.PullRequestPayload{Action: api.HookIssueReviewed}, payload: &api.PullRequestPayload{Action: api.HookIssueReviewed},
yamlOn: "on:\n pull_request_review_comment:\n types: [created]", yamlOn: "on:\n pull_request_review_comment:\n types: [created]",
expected: true, expected: true,
}, },
{ {
desc: "HookEventPullRequestReviewRejected(pull_request_review_rejected) doesn't match githubEventPullRequestReview(pull_request_review) with `dismissed` activity type (we don't support `dismissed` at present)", desc: "HookEventPullRequestReviewRejected(pull_request_review_rejected) doesn't match GithubEventPullRequestReview(pull_request_review) with `dismissed` activity type (we don't support `dismissed` at present)",
triggedEvent: webhook_module.HookEventPullRequestReviewRejected, triggedEvent: webhook_module.HookEventPullRequestReviewRejected,
payload: &api.PullRequestPayload{Action: api.HookIssueReviewed}, payload: &api.PullRequestPayload{Action: api.HookIssueReviewed},
yamlOn: "on:\n pull_request_review:\n types: [dismissed]", yamlOn: "on:\n pull_request_review:\n types: [dismissed]",
expected: false, expected: false,
}, },
{ {
desc: "HookEventRelease(release) `published` action matches githubEventRelease(release) with `published` activity type", desc: "HookEventRelease(release) `published` action matches GithubEventRelease(release) with `published` activity type",
triggedEvent: webhook_module.HookEventRelease, triggedEvent: webhook_module.HookEventRelease,
payload: &api.ReleasePayload{Action: api.HookReleasePublished}, payload: &api.ReleasePayload{Action: api.HookReleasePublished},
yamlOn: "on:\n release:\n types: [published]", yamlOn: "on:\n release:\n types: [published]",
expected: true, expected: true,
}, },
{ {
desc: "HookEventPackage(package) `created` action doesn't match githubEventRegistryPackage(registry_package) with `updated` activity type", desc: "HookEventPackage(package) `created` action doesn't match GithubEventRegistryPackage(registry_package) with `updated` activity type",
triggedEvent: webhook_module.HookEventPackage, triggedEvent: webhook_module.HookEventPackage,
payload: &api.PackagePayload{Action: api.HookPackageCreated}, payload: &api.PackagePayload{Action: api.HookPackageCreated},
yamlOn: "on:\n registry_package:\n types: [updated]", yamlOn: "on:\n registry_package:\n types: [updated]",
expected: false, expected: false,
}, },
{ {
desc: "HookEventWiki(wiki) matches githubEventGollum(gollum)", desc: "HookEventWiki(wiki) matches GithubEventGollum(gollum)",
triggedEvent: webhook_module.HookEventWiki, triggedEvent: webhook_module.HookEventWiki,
payload: nil, payload: nil,
yamlOn: "on: gollum", yamlOn: "on: gollum",

View File

@ -9,6 +9,7 @@ import (
actions_model "code.gitea.io/gitea/models/actions" actions_model "code.gitea.io/gitea/models/actions"
secret_model "code.gitea.io/gitea/models/secret" secret_model "code.gitea.io/gitea/models/secret"
actions_module "code.gitea.io/gitea/modules/actions"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -54,8 +55,10 @@ func pickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv
func getSecretsOfTask(ctx context.Context, task *actions_model.ActionTask) map[string]string { func getSecretsOfTask(ctx context.Context, task *actions_model.ActionTask) map[string]string {
secrets := map[string]string{} secrets := map[string]string{}
if task.Job.Run.IsForkPullRequest { if task.Job.Run.IsForkPullRequest && task.Job.Run.TriggerEvent != actions_module.GithubEventPullRequestTarget {
// ignore secrets for fork pull request // ignore secrets for fork pull request
// 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
// see the documentation: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target
return secrets return secrets
} }
@ -116,6 +119,14 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
event := map[string]interface{}{} event := map[string]interface{}{}
_ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event) _ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event)
// TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229
// This fallback is for the old ActionRun that doesn't have the TriggerEvent field
// and should be removed in 1.22
eventName := t.Job.Run.TriggerEvent
if eventName == "" {
eventName = t.Job.Run.Event.Event()
}
baseRef := "" baseRef := ""
headRef := "" headRef := ""
if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil {
@ -137,7 +148,7 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
"base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. "base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
"env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." "env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
"event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload. "event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload.
"event_name": t.Job.Run.Event.Event(), // string, The name of the event that triggered the workflow run. "event_name": eventName, // string, The name of the event that triggered the workflow run.
"event_path": "", // string, The path to the file on the runner that contains the full event webhook payload. "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload.
"graphql_url": "", // string, The URL of the GitHub GraphQL API. "graphql_url": "", // string, The URL of the GitHub GraphQL API.
"head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. "head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.

View File

@ -142,13 +142,46 @@ func notify(ctx context.Context, input *notifyInput) error {
return fmt.Errorf("gitRepo.GetCommit: %w", err) return fmt.Errorf("gitRepo.GetCommit: %w", err)
} }
var detectedWorkflows []*actions_module.DetectedWorkflow
workflows, err := actions_module.DetectWorkflows(commit, input.Event, input.Payload) workflows, err := actions_module.DetectWorkflows(commit, input.Event, input.Payload)
if err != nil { if err != nil {
return fmt.Errorf("DetectWorkflows: %w", err) return fmt.Errorf("DetectWorkflows: %w", err)
} }
if len(workflows) == 0 { if len(workflows) == 0 {
log.Trace("repo %s with commit %s couldn't find workflows", input.Repo.RepoPath(), commit.ID) log.Trace("repo %s with commit %s couldn't find workflows", input.Repo.RepoPath(), commit.ID)
} else {
for _, wf := range workflows {
if wf.TriggerEvent != actions_module.GithubEventPullRequestTarget {
wf.Ref = ref
detectedWorkflows = append(detectedWorkflows, wf)
}
}
}
if input.PullRequest != nil {
// detect pull_request_target workflows
baseRef := git.BranchPrefix + input.PullRequest.BaseBranch
baseCommit, err := gitRepo.GetCommit(baseRef)
if err != nil {
return fmt.Errorf("gitRepo.GetCommit: %w", err)
}
baseWorkflows, err := actions_module.DetectWorkflows(baseCommit, input.Event, input.Payload)
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.RepoPath(), baseCommit.ID)
} else {
for _, wf := range baseWorkflows {
if wf.TriggerEvent == actions_module.GithubEventPullRequestTarget {
wf.Ref = baseRef
detectedWorkflows = append(detectedWorkflows, wf)
}
}
}
}
if len(detectedWorkflows) == 0 {
return nil return nil
} }
@ -172,18 +205,19 @@ func notify(ctx context.Context, input *notifyInput) error {
} }
} }
for id, content := range workflows { for _, dwf := range detectedWorkflows {
run := &actions_model.ActionRun{ run := &actions_model.ActionRun{
Title: strings.SplitN(commit.CommitMessage, "\n", 2)[0], Title: strings.SplitN(commit.CommitMessage, "\n", 2)[0],
RepoID: input.Repo.ID, RepoID: input.Repo.ID,
OwnerID: input.Repo.OwnerID, OwnerID: input.Repo.OwnerID,
WorkflowID: id, WorkflowID: dwf.EntryName,
TriggerUserID: input.Doer.ID, TriggerUserID: input.Doer.ID,
Ref: ref, Ref: dwf.Ref,
CommitSHA: commit.ID.String(), CommitSHA: dwf.Commit.ID.String(),
IsForkPullRequest: isForkPullRequest, IsForkPullRequest: isForkPullRequest,
Event: input.Event, Event: input.Event,
EventPayload: string(p), EventPayload: string(p),
TriggerEvent: dwf.TriggerEvent,
Status: actions_model.StatusWaiting, Status: actions_model.StatusWaiting,
} }
if need, err := ifNeedApproval(ctx, run, input.Repo, input.Doer); err != nil { if need, err := ifNeedApproval(ctx, run, input.Repo, input.Doer); err != nil {
@ -193,7 +227,7 @@ func notify(ctx context.Context, input *notifyInput) error {
run.NeedApproval = need run.NeedApproval = need
} }
jobs, err := jobparser.Parse(content) jobs, err := jobparser.Parse(dwf.Content)
if err != nil { if err != nil {
log.Error("jobparser.Parse: %v", err) log.Error("jobparser.Parse: %v", err)
continue continue
@ -259,8 +293,10 @@ func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_mo
} }
func ifNeedApproval(ctx context.Context, run *actions_model.ActionRun, repo *repo_model.Repository, user *user_model.User) (bool, error) { func ifNeedApproval(ctx context.Context, run *actions_model.ActionRun, repo *repo_model.Repository, user *user_model.User) (bool, error) {
// don't need approval if it's not a fork PR // 1. don't need approval if it's not a fork PR
if !run.IsForkPullRequest { // 2. don't need approval if the event is `pull_request_target` since the workflow will run in the context of base 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 return false, nil
} }

View File

@ -0,0 +1,144 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package integration
import (
"net/url"
"testing"
"time"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo"
unit_model "code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
actions_module "code.gitea.io/gitea/modules/actions"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
pull_service "code.gitea.io/gitea/services/pull"
repo_service "code.gitea.io/gitea/services/repository"
files_service "code.gitea.io/gitea/services/repository/files"
"github.com/stretchr/testify/assert"
)
func TestPullRequestTargetEvent(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the base repo
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // owner of the forked repo
// create the base repo
baseRepo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_module.CreateRepoOptions{
Name: "repo-pull-request-target",
Description: "test pull-request-target event",
AutoInit: true,
Gitignores: "Go",
License: "MIT",
Readme: "Default",
DefaultBranch: "main",
IsPrivate: false,
})
assert.NoError(t, err)
assert.NotEmpty(t, baseRepo)
// enable actions
err = repo_model.UpdateRepositoryUnits(baseRepo, []repo_model.RepoUnit{{
RepoID: baseRepo.ID,
Type: unit_model.TypeActions,
}}, nil)
assert.NoError(t, err)
// create the forked repo
forkedRepo, err := repo_service.ForkRepository(git.DefaultContext, user2, user3, repo_service.ForkRepoOptions{
BaseRepo: baseRepo,
Name: "forked-repo-pull-request-target",
Description: "test pull-request-target event",
})
assert.NoError(t, err)
assert.NotEmpty(t, forkedRepo)
// add workflow file to the base repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
TreePath: ".gitea/workflows/pr.yml",
Content: "name: test\non: pull_request_target\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: echo helloworld\n",
},
},
Message: "add workflow",
OldBranch: "main",
NewBranch: "main",
Author: &files_service.IdentityOptions{
Name: user2.Name,
Email: user2.Email,
},
Committer: &files_service.IdentityOptions{
Name: user2.Name,
Email: user2.Email,
},
Dates: &files_service.CommitDateOptions{
Author: time.Now(),
Committer: time.Now(),
},
})
assert.NoError(t, err)
assert.NotEmpty(t, addWorkflowToBaseResp)
// add a new file to the forked repo
addFileToForkedResp, err := files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, user3, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
TreePath: "file_1.txt",
Content: "file1",
},
},
Message: "add file1",
OldBranch: "main",
NewBranch: "fork-branch-1",
Author: &files_service.IdentityOptions{
Name: user3.Name,
Email: user3.Email,
},
Committer: &files_service.IdentityOptions{
Name: user3.Name,
Email: user3.Email,
},
Dates: &files_service.CommitDateOptions{
Author: time.Now(),
Committer: time.Now(),
},
})
assert.NoError(t, err)
assert.NotEmpty(t, addFileToForkedResp)
// create Pull
pullIssue := &issues_model.Issue{
RepoID: baseRepo.ID,
Title: "Test pull-request-target-event",
PosterID: user3.ID,
Poster: user3,
IsPull: true,
}
pullRequest := &issues_model.PullRequest{
HeadRepoID: forkedRepo.ID,
BaseRepoID: baseRepo.ID,
HeadBranch: "fork-branch-1",
BaseBranch: "main",
HeadRepo: forkedRepo,
BaseRepo: baseRepo,
Type: issues_model.PullRequestGitea,
}
err = pull_service.NewPullRequest(git.DefaultContext, baseRepo, pullIssue, nil, nil, pullRequest, nil)
assert.NoError(t, err)
// load and compare ActionRun
actionRun := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: baseRepo.ID})
assert.Equal(t, addWorkflowToBaseResp.Commit.SHA, actionRun.CommitSHA)
assert.Equal(t, actions_module.GithubEventPullRequestTarget, actionRun.TriggerEvent)
})
}