code.gitea.io/gitea@v1.21.7/routers/api/actions/runner/utils.go (about)

     1  // Copyright 2022 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package runner
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  
    10  	actions_model "code.gitea.io/gitea/models/actions"
    11  	secret_model "code.gitea.io/gitea/models/secret"
    12  	actions_module "code.gitea.io/gitea/modules/actions"
    13  	"code.gitea.io/gitea/modules/container"
    14  	"code.gitea.io/gitea/modules/git"
    15  	"code.gitea.io/gitea/modules/json"
    16  	"code.gitea.io/gitea/modules/log"
    17  	secret_module "code.gitea.io/gitea/modules/secret"
    18  	"code.gitea.io/gitea/modules/setting"
    19  	"code.gitea.io/gitea/services/actions"
    20  
    21  	runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
    22  	"google.golang.org/protobuf/types/known/structpb"
    23  )
    24  
    25  func pickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv1.Task, bool, error) {
    26  	t, ok, err := actions_model.CreateTaskForRunner(ctx, runner)
    27  	if err != nil {
    28  		return nil, false, fmt.Errorf("CreateTaskForRunner: %w", err)
    29  	}
    30  	if !ok {
    31  		return nil, false, nil
    32  	}
    33  
    34  	actions.CreateCommitStatus(ctx, t.Job)
    35  
    36  	task := &runnerv1.Task{
    37  		Id:              t.ID,
    38  		WorkflowPayload: t.Job.WorkflowPayload,
    39  		Context:         generateTaskContext(t),
    40  		Secrets:         getSecretsOfTask(ctx, t),
    41  		Vars:            getVariablesOfTask(ctx, t),
    42  	}
    43  
    44  	if needs, err := findTaskNeeds(ctx, t); err != nil {
    45  		log.Error("Cannot find needs for task %v: %v", t.ID, err)
    46  		// Go on with empty needs.
    47  		// If return error, the task will be wild, which means the runner will never get it when it has been assigned to the runner.
    48  		// In contrast, missing needs is less serious.
    49  		// And the task will fail and the runner will report the error in the logs.
    50  	} else {
    51  		task.Needs = needs
    52  	}
    53  
    54  	return task, true, nil
    55  }
    56  
    57  func getSecretsOfTask(ctx context.Context, task *actions_model.ActionTask) map[string]string {
    58  	secrets := map[string]string{}
    59  
    60  	secrets["GITHUB_TOKEN"] = task.Token
    61  	secrets["GITEA_TOKEN"] = task.Token
    62  
    63  	if task.Job.Run.IsForkPullRequest && task.Job.Run.TriggerEvent != actions_module.GithubEventPullRequestTarget {
    64  		// ignore secrets for fork pull request, except GITHUB_TOKEN and GITEA_TOKEN which are automatically generated.
    65  		// 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
    66  		// see the documentation: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target
    67  		return secrets
    68  	}
    69  
    70  	ownerSecrets, err := secret_model.FindSecrets(ctx, secret_model.FindSecretsOptions{OwnerID: task.Job.Run.Repo.OwnerID})
    71  	if err != nil {
    72  		log.Error("find secrets of owner %v: %v", task.Job.Run.Repo.OwnerID, err)
    73  		// go on
    74  	}
    75  	repoSecrets, err := secret_model.FindSecrets(ctx, secret_model.FindSecretsOptions{RepoID: task.Job.Run.RepoID})
    76  	if err != nil {
    77  		log.Error("find secrets of repo %v: %v", task.Job.Run.RepoID, err)
    78  		// go on
    79  	}
    80  
    81  	for _, secret := range append(ownerSecrets, repoSecrets...) {
    82  		if v, err := secret_module.DecryptSecret(setting.SecretKey, secret.Data); err != nil {
    83  			log.Error("decrypt secret %v %q: %v", secret.ID, secret.Name, err)
    84  			// go on
    85  		} else {
    86  			secrets[secret.Name] = v
    87  		}
    88  	}
    89  
    90  	return secrets
    91  }
    92  
    93  func getVariablesOfTask(ctx context.Context, task *actions_model.ActionTask) map[string]string {
    94  	variables := map[string]string{}
    95  
    96  	// Org / User level
    97  	ownerVariables, err := actions_model.FindVariables(ctx, actions_model.FindVariablesOpts{OwnerID: task.Job.Run.Repo.OwnerID})
    98  	if err != nil {
    99  		log.Error("find variables of org: %d, error: %v", task.Job.Run.Repo.OwnerID, err)
   100  	}
   101  
   102  	// Repo level
   103  	repoVariables, err := actions_model.FindVariables(ctx, actions_model.FindVariablesOpts{RepoID: task.Job.Run.RepoID})
   104  	if err != nil {
   105  		log.Error("find variables of repo: %d, error: %v", task.Job.Run.RepoID, err)
   106  	}
   107  
   108  	// Level precedence: Repo > Org / User
   109  	for _, v := range append(ownerVariables, repoVariables...) {
   110  		variables[v.Name] = v.Data
   111  	}
   112  
   113  	return variables
   114  }
   115  
   116  func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
   117  	event := map[string]any{}
   118  	_ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event)
   119  
   120  	// TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229
   121  	// This fallback is for the old ActionRun that doesn't have the TriggerEvent field
   122  	// and should be removed in 1.22
   123  	eventName := t.Job.Run.TriggerEvent
   124  	if eventName == "" {
   125  		eventName = t.Job.Run.Event.Event()
   126  	}
   127  
   128  	baseRef := ""
   129  	headRef := ""
   130  	ref := t.Job.Run.Ref
   131  	sha := t.Job.Run.CommitSHA
   132  	if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil {
   133  		baseRef = pullPayload.PullRequest.Base.Ref
   134  		headRef = pullPayload.PullRequest.Head.Ref
   135  
   136  		// if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request
   137  		// In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target,
   138  		// the ref will be the base branch.
   139  		if t.Job.Run.TriggerEvent == actions_module.GithubEventPullRequestTarget {
   140  			ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name
   141  			sha = pullPayload.PullRequest.Base.Sha
   142  		}
   143  	}
   144  
   145  	refName := git.RefName(ref)
   146  
   147  	taskContext, err := structpb.NewStruct(map[string]any{
   148  		// standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
   149  		"action":            "",                                                   // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2.
   150  		"action_path":       "",                                                   // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action.
   151  		"action_ref":        "",                                                   // string, For a step executing an action, this is the ref of the action being executed. For example, v2.
   152  		"action_repository": "",                                                   // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
   153  		"action_status":     "",                                                   // string, For a composite action, the current result of the composite action.
   154  		"actor":             t.Job.Run.TriggerUser.Name,                           // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
   155  		"api_url":           setting.AppURL + "api/v1",                            // string, The URL of the GitHub REST API.
   156  		"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.
   157  		"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."
   158  		"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.
   159  		"event_name":        eventName,                                            // string, The name of the event that triggered the workflow run.
   160  		"event_path":        "",                                                   // string, The path to the file on the runner that contains the full event webhook payload.
   161  		"graphql_url":       "",                                                   // string, The URL of the GitHub GraphQL API.
   162  		"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.
   163  		"job":               fmt.Sprint(t.JobID),                                  // string, The job_id of the current job.
   164  		"ref":               ref,                                                  // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/<branch_name>, for pull requests it is refs/pull/<pr_number>/merge, and for tags it is refs/tags/<tag_name>. For example, refs/heads/feature-branch-1.
   165  		"ref_name":          refName.ShortName(),                                  // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1.
   166  		"ref_protected":     false,                                                // boolean, true if branch protections are configured for the ref that triggered the workflow run.
   167  		"ref_type":          refName.RefType(),                                    // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
   168  		"path":              "",                                                   // string, Path on the runner to the file that sets system PATH 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."
   169  		"repository":        t.Job.Run.Repo.OwnerName + "/" + t.Job.Run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
   170  		"repository_owner":  t.Job.Run.Repo.OwnerName,                             // string, The repository owner's name. For example, Codertocat.
   171  		"repositoryUrl":     t.Job.Run.Repo.HTMLURL(),                             // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
   172  		"retention_days":    "",                                                   // string, The number of days that workflow run logs and artifacts are kept.
   173  		"run_id":            fmt.Sprint(t.Job.RunID),                              // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run.
   174  		"run_number":        fmt.Sprint(t.Job.Run.Index),                          // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run.
   175  		"run_attempt":       fmt.Sprint(t.Job.Attempt),                            // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run.
   176  		"secret_source":     "Actions",                                            // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
   177  		"server_url":        setting.AppURL,                                       // string, The URL of the GitHub server. For example: https://github.com.
   178  		"sha":               sha,                                                  // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53.
   179  		"token":             t.Token,                                              // string, A token to authenticate on behalf of the GitHub App installed on your repository. This is functionally equivalent to the GITHUB_TOKEN secret. For more information, see "Automatic token authentication."
   180  		"triggering_actor":  "",                                                   // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
   181  		"workflow":          t.Job.Run.WorkflowID,                                 // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository.
   182  		"workspace":         "",                                                   // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action.
   183  
   184  		// additional contexts
   185  		"gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(),
   186  	})
   187  	if err != nil {
   188  		log.Error("structpb.NewStruct failed: %v", err)
   189  	}
   190  
   191  	return taskContext
   192  }
   193  
   194  func findTaskNeeds(ctx context.Context, task *actions_model.ActionTask) (map[string]*runnerv1.TaskNeed, error) {
   195  	if err := task.LoadAttributes(ctx); err != nil {
   196  		return nil, fmt.Errorf("LoadAttributes: %w", err)
   197  	}
   198  	if len(task.Job.Needs) == 0 {
   199  		return nil, nil
   200  	}
   201  	needs := container.SetOf(task.Job.Needs...)
   202  
   203  	jobs, _, err := actions_model.FindRunJobs(ctx, actions_model.FindRunJobOptions{RunID: task.Job.RunID})
   204  	if err != nil {
   205  		return nil, fmt.Errorf("FindRunJobs: %w", err)
   206  	}
   207  
   208  	ret := make(map[string]*runnerv1.TaskNeed, len(needs))
   209  	for _, job := range jobs {
   210  		if !needs.Contains(job.JobID) {
   211  			continue
   212  		}
   213  		if job.TaskID == 0 || !job.Status.IsDone() {
   214  			// it shouldn't happen, or the job has been rerun
   215  			continue
   216  		}
   217  		outputs := make(map[string]string)
   218  		got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID)
   219  		if err != nil {
   220  			return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err)
   221  		}
   222  		for _, v := range got {
   223  			outputs[v.OutputKey] = v.OutputValue
   224  		}
   225  		ret[job.JobID] = &runnerv1.TaskNeed{
   226  			Outputs: outputs,
   227  			Result:  runnerv1.Result(job.Status),
   228  		}
   229  	}
   230  
   231  	return ret, nil
   232  }