Skip to content

Commit 00d24a3

Browse files
committed
Merge remote-tracking branch 'giteaofficial/main'
* giteaofficial/main: Only allow admins to rename default/protected branches (go-gitea#33276) Enable Typescript `noImplicitThis` (go-gitea#33250) Prepare for support performance trace (go-gitea#33286) Fix closed dependency title (go-gitea#33285) Move some Actions related functions from `routers` to `services` (go-gitea#33280) Fix incorrect TagName/BranchName usages (go-gitea#33279)
2 parents cc0a520 + 2483a93 commit 00d24a3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+621
-402
lines changed

models/fixtures/access.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,9 @@
171171
user_id: 40
172172
repo_id: 61
173173
mode: 4
174+
175+
-
176+
id: 30
177+
user_id: 40
178+
repo_id: 1
179+
mode: 2

modules/web/handler.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ func wrapHandlerProvider[T http.Handler](hp func(next http.Handler) T, funcInfo
121121
return func(next http.Handler) http.Handler {
122122
h := hp(next) // this handle could be dynamically generated, so we can't use it for debug info
123123
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
124-
routing.UpdateFuncInfo(req.Context(), funcInfo)
124+
defer routing.RecordFuncInfo(req.Context(), funcInfo)()
125125
h.ServeHTTP(resp, req)
126126
})
127127
}
@@ -157,7 +157,7 @@ func toHandlerProvider(handler any) func(next http.Handler) http.Handler {
157157
return // it's doing pre-check, just return
158158
}
159159

160-
routing.UpdateFuncInfo(req.Context(), funcInfo)
160+
defer routing.RecordFuncInfo(req.Context(), funcInfo)()
161161
ret := fn.Call(argsIn)
162162

163163
// handle the return value (no-op at the moment)

modules/web/routing/context.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,18 @@ type contextKeyType struct{}
1212

1313
var contextKey contextKeyType
1414

15-
// UpdateFuncInfo updates a context's func info
16-
func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) {
17-
record, ok := ctx.Value(contextKey).(*requestRecord)
18-
if !ok {
19-
return
15+
// RecordFuncInfo records a func info into context
16+
func RecordFuncInfo(ctx context.Context, funcInfo *FuncInfo) (end func()) {
17+
// TODO: reqCtx := reqctx.FromContext(ctx), add trace support
18+
end = func() {}
19+
20+
// save the func info into the context record
21+
if record, ok := ctx.Value(contextKey).(*requestRecord); ok {
22+
record.lock.Lock()
23+
record.funcInfo = funcInfo
24+
record.lock.Unlock()
2025
}
21-
22-
record.lock.Lock()
23-
record.funcInfo = funcInfo
24-
record.lock.Unlock()
26+
return end
2527
}
2628

2729
// MarkLongPolling marks the request is a long-polling request, and the logger may output different message for it

options/locale/locale_en-US.ini

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2714,6 +2714,8 @@ branch.create_branch_operation = Create branch
27142714
branch.new_branch = Create new branch
27152715
branch.new_branch_from = Create new branch from "%s"
27162716
branch.renamed = Branch %s was renamed to %s.
2717+
branch.rename_default_or_protected_branch_error = Only admins can rename default or protected branches.
2718+
branch.rename_protected_branch_failed = This branch is protected by glob-based protection rules.
27172719
27182720
tag.create_tag = Create tag %s
27192721
tag.create_tag_operation = Create tag

routers/api/actions/runner/main_test.go

Lines changed: 0 additions & 14 deletions
This file was deleted.

routers/api/actions/runner/utils.go

Lines changed: 12 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,8 @@ import (
88
"fmt"
99

1010
actions_model "code.gitea.io/gitea/models/actions"
11-
"code.gitea.io/gitea/models/db"
1211
secret_model "code.gitea.io/gitea/models/secret"
13-
actions_module "code.gitea.io/gitea/modules/actions"
14-
"code.gitea.io/gitea/modules/container"
15-
"code.gitea.io/gitea/modules/git"
16-
"code.gitea.io/gitea/modules/json"
1712
"code.gitea.io/gitea/modules/log"
18-
"code.gitea.io/gitea/modules/setting"
1913
"code.gitea.io/gitea/services/actions"
2014

2115
runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
@@ -65,82 +59,16 @@ func pickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv
6559
}
6660

6761
func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
68-
event := map[string]any{}
69-
_ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event)
70-
71-
// TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229
72-
// This fallback is for the old ActionRun that doesn't have the TriggerEvent field
73-
// and should be removed in 1.22
74-
eventName := t.Job.Run.TriggerEvent
75-
if eventName == "" {
76-
eventName = t.Job.Run.Event.Event()
77-
}
78-
79-
baseRef := ""
80-
headRef := ""
81-
ref := t.Job.Run.Ref
82-
sha := t.Job.Run.CommitSHA
83-
if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil {
84-
baseRef = pullPayload.PullRequest.Base.Ref
85-
headRef = pullPayload.PullRequest.Head.Ref
86-
87-
// if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request
88-
// In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target,
89-
// the ref will be the base branch.
90-
if t.Job.Run.TriggerEvent == actions_module.GithubEventPullRequestTarget {
91-
ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name
92-
sha = pullPayload.PullRequest.Base.Sha
93-
}
94-
}
95-
96-
refName := git.RefName(ref)
97-
9862
giteaRuntimeToken, err := actions.CreateAuthorizationToken(t.ID, t.Job.RunID, t.JobID)
9963
if err != nil {
10064
log.Error("actions.CreateAuthorizationToken failed: %v", err)
10165
}
10266

103-
taskContext, err := structpb.NewStruct(map[string]any{
104-
// standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
105-
"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.
106-
"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.
107-
"action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2.
108-
"action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
109-
"action_status": "", // string, For a composite action, the current result of the composite action.
110-
"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.
111-
"api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API.
112-
"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.
113-
"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."
114-
"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.
115-
"event_name": eventName, // string, The name of the event that triggered the workflow run.
116-
"event_path": "", // string, The path to the file on the runner that contains the full event webhook payload.
117-
"graphql_url": "", // string, The URL of the GitHub GraphQL API.
118-
"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.
119-
"job": fmt.Sprint(t.JobID), // string, The job_id of the current job.
120-
"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.
121-
"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.
122-
"ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run.
123-
"ref_type": string(refName.RefType()), // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
124-
"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."
125-
"repository": t.Job.Run.Repo.OwnerName + "/" + t.Job.Run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
126-
"repository_owner": t.Job.Run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat.
127-
"repositoryUrl": t.Job.Run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
128-
"retention_days": "", // string, The number of days that workflow run logs and artifacts are kept.
129-
"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.
130-
"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.
131-
"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.
132-
"secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
133-
"server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com.
134-
"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.
135-
"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."
136-
"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.
137-
"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.
138-
"workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action.
139-
140-
// additional contexts
141-
"gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(),
142-
"gitea_runtime_token": giteaRuntimeToken,
143-
})
67+
gitCtx := actions.GenerateGiteaContext(t.Job.Run, t.Job)
68+
gitCtx["token"] = t.Token
69+
gitCtx["gitea_runtime_token"] = giteaRuntimeToken
70+
71+
taskContext, err := structpb.NewStruct(gitCtx)
14472
if err != nil {
14573
log.Error("structpb.NewStruct failed: %v", err)
14674
}
@@ -150,68 +78,18 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
15078

15179
func findTaskNeeds(ctx context.Context, task *actions_model.ActionTask) (map[string]*runnerv1.TaskNeed, error) {
15280
if err := task.LoadAttributes(ctx); err != nil {
153-
return nil, fmt.Errorf("LoadAttributes: %w", err)
154-
}
155-
if len(task.Job.Needs) == 0 {
156-
return nil, nil
81+
return nil, fmt.Errorf("task LoadAttributes: %w", err)
15782
}
158-
needs := container.SetOf(task.Job.Needs...)
159-
160-
jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: task.Job.RunID})
83+
taskNeeds, err := actions.FindTaskNeeds(ctx, task.Job)
16184
if err != nil {
162-
return nil, fmt.Errorf("FindRunJobs: %w", err)
85+
return nil, err
16386
}
164-
165-
jobIDJobs := make(map[string][]*actions_model.ActionRunJob)
166-
for _, job := range jobs {
167-
jobIDJobs[job.JobID] = append(jobIDJobs[job.JobID], job)
168-
}
169-
170-
ret := make(map[string]*runnerv1.TaskNeed, len(needs))
171-
for jobID, jobsWithSameID := range jobIDJobs {
172-
if !needs.Contains(jobID) {
173-
continue
174-
}
175-
var jobOutputs map[string]string
176-
for _, job := range jobsWithSameID {
177-
if job.TaskID == 0 || !job.Status.IsDone() {
178-
// it shouldn't happen, or the job has been rerun
179-
continue
180-
}
181-
got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID)
182-
if err != nil {
183-
return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err)
184-
}
185-
outputs := make(map[string]string, len(got))
186-
for _, v := range got {
187-
outputs[v.OutputKey] = v.OutputValue
188-
}
189-
if len(jobOutputs) == 0 {
190-
jobOutputs = outputs
191-
} else {
192-
jobOutputs = mergeTwoOutputs(outputs, jobOutputs)
193-
}
194-
}
87+
ret := make(map[string]*runnerv1.TaskNeed, len(taskNeeds))
88+
for jobID, taskNeed := range taskNeeds {
19589
ret[jobID] = &runnerv1.TaskNeed{
196-
Outputs: jobOutputs,
197-
Result: runnerv1.Result(actions_model.AggregateJobStatus(jobsWithSameID)),
90+
Outputs: taskNeed.Outputs,
91+
Result: runnerv1.Result(taskNeed.Result),
19892
}
19993
}
200-
20194
return ret, nil
20295
}
203-
204-
// mergeTwoOutputs merges two outputs from two different ActionRunJobs
205-
// Values with the same output name may be overridden. The user should ensure the output names are unique.
206-
// See https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#using-job-outputs-in-a-matrix-job
207-
func mergeTwoOutputs(o1, o2 map[string]string) map[string]string {
208-
ret := make(map[string]string, len(o1))
209-
for k1, v1 := range o1 {
210-
if len(v1) > 0 {
211-
ret[k1] = v1
212-
} else {
213-
ret[k1] = o2[k1]
214-
}
215-
}
216-
return ret
217-
}

routers/api/v1/repo/branch.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"code.gitea.io/gitea/models/db"
1313
git_model "code.gitea.io/gitea/models/git"
1414
"code.gitea.io/gitea/models/organization"
15+
repo_model "code.gitea.io/gitea/models/repo"
1516
user_model "code.gitea.io/gitea/models/user"
1617
"code.gitea.io/gitea/modules/git"
1718
"code.gitea.io/gitea/modules/gitrepo"
@@ -443,7 +444,14 @@ func UpdateBranch(ctx *context.APIContext) {
443444

444445
msg, err := repo_service.RenameBranch(ctx, repo, ctx.Doer, ctx.Repo.GitRepo, oldName, opt.Name)
445446
if err != nil {
446-
ctx.Error(http.StatusInternalServerError, "RenameBranch", err)
447+
switch {
448+
case repo_model.IsErrUserDoesNotHaveAccessToRepo(err):
449+
ctx.Error(http.StatusForbidden, "", "User must be a repo or site admin to rename default or protected branches.")
450+
case errors.Is(err, git_model.ErrBranchIsProtected):
451+
ctx.Error(http.StatusForbidden, "", "Branch is protected by glob-based protection rules.")
452+
default:
453+
ctx.Error(http.StatusInternalServerError, "RenameBranch", err)
454+
}
447455
return
448456
}
449457
if msg == "target_exist" {

routers/init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ func NormalRoutes() *web.Router {
213213
}
214214

215215
r.NotFound(func(w http.ResponseWriter, req *http.Request) {
216-
routing.UpdateFuncInfo(req.Context(), routing.GetFuncInfo(http.NotFound, "GlobalNotFound"))
216+
defer routing.RecordFuncInfo(req.Context(), routing.GetFuncInfo(http.NotFound, "GlobalNotFound"))()
217217
http.NotFound(w, req)
218218
})
219219
return r

routers/web/base.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func storageHandler(storageSetting *setting.Storage, prefix string, objStore sto
3434
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
3535
return
3636
}
37-
routing.UpdateFuncInfo(req.Context(), funcInfo)
37+
defer routing.RecordFuncInfo(req.Context(), funcInfo)()
3838

3939
rPath := strings.TrimPrefix(req.URL.Path, "/"+prefix+"/")
4040
rPath = util.PathJoinRelX(rPath)
@@ -65,7 +65,7 @@ func storageHandler(storageSetting *setting.Storage, prefix string, objStore sto
6565
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
6666
return
6767
}
68-
routing.UpdateFuncInfo(req.Context(), funcInfo)
68+
defer routing.RecordFuncInfo(req.Context(), funcInfo)()
6969

7070
rPath := strings.TrimPrefix(req.URL.Path, "/"+prefix+"/")
7171
rPath = util.PathJoinRelX(rPath)

routers/web/repo/release.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,7 @@ func SingleRelease(ctx *context.Context) {
295295
}
296296

297297
ctx.Data["PageIsSingleTag"] = release.IsTag
298+
ctx.Data["SingleReleaseTagName"] = release.TagName
298299
if release.IsTag {
299300
ctx.Data["Title"] = release.TagName
300301
} else {

routers/web/repo/search.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func Search(ctx *context.Context) {
7070
res, err := git.GrepSearch(ctx, ctx.Repo.GitRepo, prepareSearch.Keyword, git.GrepOptions{
7171
ContextLineNumber: 1,
7272
IsFuzzy: prepareSearch.IsFuzzy,
73-
RefName: git.RefNameFromBranch(ctx.Repo.BranchName).String(), // BranchName should be default branch or the first existing branch
73+
RefName: git.RefNameFromBranch(ctx.Repo.Repository.DefaultBranch).String(), // BranchName should be default branch or the first existing branch
7474
PathspecList: indexSettingToGitGrepPathspecList(),
7575
})
7676
if err != nil {

0 commit comments

Comments
 (0)