mirror of
https://github.com/go-gitea/gitea.git
synced 2026-04-05 03:31:51 +02:00
## Overview This PR introduces granular permission controls for Gitea Actions tokens (`GITEA_TOKEN`), aligning Gitea's security model with GitHub Actions standards while maintaining compatibility with Gitea's unique repository unit system. It addresses the need for finer access control by allowing administrators and repository owners to define default token permissions, set maximum permission ceilings, and control cross-repository access within organizations. ## Key Features ### 1. Granular Token Permissions - **Standard Keyword Support**: Implements support for the `permissions:` keyword in workflow and job YAML files (e.g., `contents: read`, `issues: write`). - **Permission Modes**: - **Permissive**: Default write access for most units (backwards compatible). - **Restricted**: Default read-only access for `contents` and `packages`, with no access to other units. - ~~**Custom**: Allows defining specific default levels for each unit type (Code, Issues, PRs, Packages, etc.).~~**EDIT removed UI was confusing** - **Clamping Logic**: Workflow-defined permissions are automatically "clamped" by repository or organization-level maximum settings. Workflows cannot escalate their own permissions beyond these limits. ### 2. Organization & Repository Settings - **Settings UI**: Added new settings pages at both Organization and Repository levels to manage Actions token defaults and maximums. - **Inheritance**: Repositories can be configured to "Follow organization-level configuration," simplifying management across large organizations. - **Cross-Repository Access**: Added a policy to control whether Actions workflows can access other repositories or packages within the same organization. This can be set to "None," "All," or restricted to a "Selected" list of repositories. ### 3. Security Hardening - **Fork Pull Request Protection**: Tokens for workflows triggered by pull requests from forks are strictly enforced as read-only, regardless of repository settings. - ~~**Package Access**: Actions tokens can now only access packages explicitly linked to a repository, with cross-repo access governed by the organization's security policy.~~ **EDIT removed https://github.com/go-gitea/gitea/pull/36173#issuecomment-3873675346** - **Git Hook Integration**: Propagates Actions Task IDs to git hooks to ensure that pushes performed by Actions tokens respect the specific permissions granted at runtime. ### 4. Technical Implementation - **Permission Persistence**: Parsed permissions are calculated at job creation and stored in the `action_run_job` table. This ensures the token's authority is deterministic throughout the job's lifecycle. - **Parsing Priority**: Implemented a priority system in the YAML parser where the broad `contents` scope is applied first, allowing granular scopes like `code` or `releases` to override it for precise control. - **Re-runs**: Permissions are re-evaluated during a job re-run to incorporate any changes made to repository settings in the interim. ### How to Test 1. **Unit Tests**: Run `go test ./services/actions/...` and `go test ./models/repo/...` to verify parsing logic and permission clamping. 2. **Integration Tests**: Comprehensive tests have been added to `tests/integration/actions_job_token_test.go` covering: - Permissive vs. Restricted mode behavior. - YAML `permissions:` keyword evaluation. - Organization cross-repo access policies. - Resource access (Git, API, and Packages) under various permission configs. 3. **Manual Verification**: - Navigate to **Site/Org/Repo Settings -> Actions -> General**. - Change "Default Token Permissions" and verify that newly triggered workflows reflect these changes in their `GITEA_TOKEN` capabilities. - Attempt a cross-repo API call from an Action and verify the Org policy is enforced. ## Documentation Added a PR in gitea's docs for this : https://gitea.com/gitea/docs/pulls/318 ## UI: <img width="1366" height="619" alt="Screenshot 2026-01-24 174112" src="https://github.com/user-attachments/assets/bfa29c9a-4ea5-4346-9410-16d491ef3d44" /> <img width="1360" height="621" alt="Screenshot 2026-01-24 174048" src="https://github.com/user-attachments/assets/d5ec46c8-9a13-4874-a6a4-fb379936cef5" /> /fixes #24635 /claim #24635 --------- Signed-off-by: Excellencedev <ademiluyisuccessandexcellence@gmail.com> Signed-off-by: ChristopherHX <christopher.homberger@web.de> Signed-off-by: silverwind <me@silverwind.io> Signed-off-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: ChristopherHX <christopher.homberger@web.de> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: Zettat123 <zettat123@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
402 lines
11 KiB
Go
402 lines
11 KiB
Go
// Copyright 2022 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package actions
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
|
|
actions_model "code.gitea.io/gitea/models/actions"
|
|
"code.gitea.io/gitea/models/db"
|
|
"code.gitea.io/gitea/modules/log"
|
|
"code.gitea.io/gitea/modules/setting"
|
|
"code.gitea.io/gitea/modules/templates"
|
|
"code.gitea.io/gitea/modules/util"
|
|
"code.gitea.io/gitea/modules/web"
|
|
shared_user "code.gitea.io/gitea/routers/web/shared/user"
|
|
"code.gitea.io/gitea/services/context"
|
|
"code.gitea.io/gitea/services/forms"
|
|
)
|
|
|
|
const (
|
|
// TODO: Separate secrets from runners when layout is ready
|
|
tplRepoRunners templates.TplName = "repo/settings/actions"
|
|
tplOrgRunners templates.TplName = "org/settings/actions"
|
|
tplAdminRunners templates.TplName = "admin/actions"
|
|
tplUserRunners templates.TplName = "user/settings/actions"
|
|
tplRepoRunnerEdit templates.TplName = "repo/settings/runner_edit"
|
|
tplOrgRunnerEdit templates.TplName = "org/settings/runners_edit"
|
|
tplAdminRunnerEdit templates.TplName = "admin/runners/edit"
|
|
tplUserRunnerEdit templates.TplName = "user/settings/runner_edit"
|
|
)
|
|
|
|
type runnersCtx struct {
|
|
OwnerID int64
|
|
RepoID int64
|
|
IsRepo bool
|
|
IsOrg bool
|
|
IsAdmin bool
|
|
IsUser bool
|
|
RunnersTemplate templates.TplName
|
|
RunnerEditTemplate templates.TplName
|
|
RedirectLink string
|
|
}
|
|
|
|
func getRunnersCtx(ctx *context.Context) (*runnersCtx, error) {
|
|
if ctx.Data["PageIsRepoSettings"] == true {
|
|
return &runnersCtx{
|
|
RepoID: ctx.Repo.Repository.ID,
|
|
OwnerID: 0,
|
|
IsRepo: true,
|
|
RunnersTemplate: tplRepoRunners,
|
|
RunnerEditTemplate: tplRepoRunnerEdit,
|
|
RedirectLink: ctx.Repo.RepoLink + "/settings/actions/runners/",
|
|
}, nil
|
|
}
|
|
|
|
if ctx.Data["PageIsOrgSettings"] == true {
|
|
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
|
return nil, fmt.Errorf("RenderUserOrgHeader: %w", err)
|
|
}
|
|
return &runnersCtx{
|
|
RepoID: 0,
|
|
OwnerID: ctx.Org.Organization.ID,
|
|
IsOrg: true,
|
|
RunnersTemplate: tplOrgRunners,
|
|
RunnerEditTemplate: tplOrgRunnerEdit,
|
|
RedirectLink: ctx.Org.OrgLink + "/settings/actions/runners/",
|
|
}, nil
|
|
}
|
|
|
|
if ctx.Data["PageIsAdmin"] == true {
|
|
return &runnersCtx{
|
|
RepoID: 0,
|
|
OwnerID: 0,
|
|
IsAdmin: true,
|
|
RunnersTemplate: tplAdminRunners,
|
|
RunnerEditTemplate: tplAdminRunnerEdit,
|
|
RedirectLink: setting.AppSubURL + "/-/admin/actions/runners/",
|
|
}, nil
|
|
}
|
|
|
|
if ctx.Data["PageIsUserSettings"] == true {
|
|
return &runnersCtx{
|
|
OwnerID: ctx.Doer.ID,
|
|
RepoID: 0,
|
|
IsUser: true,
|
|
RunnersTemplate: tplUserRunners,
|
|
RunnerEditTemplate: tplUserRunnerEdit,
|
|
RedirectLink: setting.AppSubURL + "/user/settings/actions/runners/",
|
|
}, nil
|
|
}
|
|
|
|
return nil, errors.New("unable to set Runners context")
|
|
}
|
|
|
|
// Runners render settings/actions/runners page for repo level
|
|
func Runners(ctx *context.Context) {
|
|
ctx.Data["PageIsSharedSettingsRunners"] = true
|
|
ctx.Data["Title"] = ctx.Tr("actions.actions")
|
|
ctx.Data["PageType"] = "runners"
|
|
|
|
rCtx, err := getRunnersCtx(ctx)
|
|
if err != nil {
|
|
ctx.ServerError("getRunnersCtx", err)
|
|
return
|
|
}
|
|
|
|
page := max(ctx.FormInt("page"), 1)
|
|
|
|
opts := actions_model.FindRunnerOptions{
|
|
ListOptions: db.ListOptions{
|
|
Page: page,
|
|
PageSize: 100,
|
|
},
|
|
Sort: ctx.Req.URL.Query().Get("sort"),
|
|
Filter: ctx.Req.URL.Query().Get("q"),
|
|
}
|
|
if rCtx.IsRepo {
|
|
opts.RepoID = rCtx.RepoID
|
|
opts.WithAvailable = true
|
|
} else if rCtx.IsOrg || rCtx.IsUser {
|
|
opts.OwnerID = rCtx.OwnerID
|
|
opts.WithAvailable = true
|
|
}
|
|
|
|
runners, count, err := db.FindAndCount[actions_model.ActionRunner](ctx, opts)
|
|
if err != nil {
|
|
ctx.ServerError("CountRunners", err)
|
|
return
|
|
}
|
|
|
|
if err := actions_model.RunnerList(runners).LoadAttributes(ctx); err != nil {
|
|
ctx.ServerError("LoadAttributes", err)
|
|
return
|
|
}
|
|
|
|
// ownid=0,repo_id=0,means this token is used for global
|
|
var token *actions_model.ActionRunnerToken
|
|
token, err = actions_model.GetLatestRunnerToken(ctx, opts.OwnerID, opts.RepoID)
|
|
if errors.Is(err, util.ErrNotExist) || (token != nil && !token.IsActive) {
|
|
token, err = actions_model.NewRunnerToken(ctx, opts.OwnerID, opts.RepoID)
|
|
if err != nil {
|
|
ctx.ServerError("CreateRunnerToken", err)
|
|
return
|
|
}
|
|
} else if err != nil {
|
|
ctx.ServerError("GetLatestRunnerToken", err)
|
|
return
|
|
}
|
|
|
|
ctx.Data["Keyword"] = opts.Filter
|
|
ctx.Data["Runners"] = runners
|
|
ctx.Data["Total"] = count
|
|
ctx.Data["RegistrationToken"] = token.Token
|
|
ctx.Data["RunnerOwnerID"] = opts.OwnerID
|
|
ctx.Data["RunnerRepoID"] = opts.RepoID
|
|
ctx.Data["SortType"] = opts.Sort
|
|
|
|
pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
|
|
|
|
ctx.Data["Page"] = pager
|
|
|
|
ctx.HTML(http.StatusOK, rCtx.RunnersTemplate)
|
|
}
|
|
|
|
// RunnersEdit renders runner edit page for repository level
|
|
func RunnersEdit(ctx *context.Context) {
|
|
ctx.Data["PageIsSharedSettingsRunners"] = true
|
|
ctx.Data["Title"] = ctx.Tr("actions.runners.edit_runner")
|
|
rCtx, err := getRunnersCtx(ctx)
|
|
if err != nil {
|
|
ctx.ServerError("getRunnersCtx", err)
|
|
return
|
|
}
|
|
|
|
page := max(ctx.FormInt("page"), 1)
|
|
|
|
runnerID := ctx.PathParamInt64("runnerid")
|
|
ownerID := rCtx.OwnerID
|
|
repoID := rCtx.RepoID
|
|
|
|
runner, err := actions_model.GetRunnerByID(ctx, runnerID)
|
|
if err != nil {
|
|
ctx.ServerError("GetRunnerByID", err)
|
|
return
|
|
}
|
|
if err := runner.LoadAttributes(ctx); err != nil {
|
|
ctx.ServerError("LoadAttributes", err)
|
|
return
|
|
}
|
|
if !runner.EditableInContext(ownerID, repoID) {
|
|
err = errors.New("no permission to edit this runner")
|
|
ctx.NotFound(err)
|
|
return
|
|
}
|
|
|
|
ctx.Data["Runner"] = runner
|
|
|
|
opts := actions_model.FindTaskOptions{
|
|
ListOptions: db.ListOptions{
|
|
Page: page,
|
|
PageSize: 30,
|
|
},
|
|
Status: actions_model.StatusUnknown, // Unknown means all
|
|
RunnerID: runner.ID,
|
|
}
|
|
|
|
tasks, count, err := db.FindAndCount[actions_model.ActionTask](ctx, opts)
|
|
if err != nil {
|
|
ctx.ServerError("CountTasks", err)
|
|
return
|
|
}
|
|
|
|
if err = actions_model.TaskList(tasks).LoadAttributes(ctx); err != nil {
|
|
ctx.ServerError("TasksLoadAttributes", err)
|
|
return
|
|
}
|
|
|
|
ctx.Data["Tasks"] = tasks
|
|
pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
|
|
ctx.Data["Page"] = pager
|
|
|
|
ctx.HTML(http.StatusOK, rCtx.RunnerEditTemplate)
|
|
}
|
|
|
|
func RunnersEditPost(ctx *context.Context) {
|
|
rCtx, err := getRunnersCtx(ctx)
|
|
if err != nil {
|
|
ctx.ServerError("getRunnersCtx", err)
|
|
return
|
|
}
|
|
|
|
runnerID := ctx.PathParamInt64("runnerid")
|
|
ownerID := rCtx.OwnerID
|
|
repoID := rCtx.RepoID
|
|
redirectTo := rCtx.RedirectLink
|
|
|
|
runner, err := actions_model.GetRunnerByID(ctx, runnerID)
|
|
if err != nil {
|
|
log.Warn("RunnerDetailsEditPost.GetRunnerByID failed: %v, url: %s", err, ctx.Req.URL)
|
|
ctx.ServerError("RunnerDetailsEditPost.GetRunnerByID", err)
|
|
return
|
|
}
|
|
if !runner.EditableInContext(ownerID, repoID) {
|
|
ctx.NotFound(util.NewPermissionDeniedErrorf("no permission to edit this runner"))
|
|
return
|
|
}
|
|
|
|
form := web.GetForm(ctx).(*forms.EditRunnerForm)
|
|
runner.Description = form.Description
|
|
|
|
err = actions_model.UpdateRunner(ctx, runner, "description")
|
|
if err != nil {
|
|
log.Warn("RunnerDetailsEditPost.UpdateRunner failed: %v, url: %s", err, ctx.Req.URL)
|
|
ctx.Flash.Warning(ctx.Tr("actions.runners.update_runner_failed"))
|
|
ctx.Redirect(redirectTo)
|
|
return
|
|
}
|
|
|
|
log.Debug("RunnerDetailsEditPost success: %s", ctx.Req.URL)
|
|
|
|
ctx.Flash.Success(ctx.Tr("actions.runners.update_runner_success"))
|
|
ctx.Redirect(redirectTo)
|
|
}
|
|
|
|
func ResetRunnerRegistrationToken(ctx *context.Context) {
|
|
rCtx, err := getRunnersCtx(ctx)
|
|
if err != nil {
|
|
ctx.ServerError("getRunnersCtx", err)
|
|
return
|
|
}
|
|
|
|
ownerID := rCtx.OwnerID
|
|
repoID := rCtx.RepoID
|
|
redirectTo := rCtx.RedirectLink
|
|
|
|
if _, err := actions_model.NewRunnerToken(ctx, ownerID, repoID); err != nil {
|
|
ctx.ServerError("ResetRunnerRegistrationToken", err)
|
|
return
|
|
}
|
|
ctx.Flash.Success(ctx.Tr("actions.runners.reset_registration_token_success"))
|
|
ctx.JSONRedirect(redirectTo)
|
|
}
|
|
|
|
// RunnerDeletePost response for deleting runner
|
|
func RunnerDeletePost(ctx *context.Context) {
|
|
rCtx, err := getRunnersCtx(ctx)
|
|
if err != nil {
|
|
ctx.ServerError("getRunnersCtx", err)
|
|
return
|
|
}
|
|
|
|
runner := findActionsRunner(ctx, rCtx)
|
|
if ctx.Written() {
|
|
return
|
|
}
|
|
|
|
if !runner.EditableInContext(rCtx.OwnerID, rCtx.RepoID) {
|
|
ctx.NotFound(util.NewPermissionDeniedErrorf("no permission to delete this runner"))
|
|
return
|
|
}
|
|
|
|
successRedirectTo := rCtx.RedirectLink
|
|
failedRedirectTo := rCtx.RedirectLink + url.PathEscape(ctx.PathParam("runnerid"))
|
|
|
|
if err := actions_model.DeleteRunner(ctx, runner.ID); err != nil {
|
|
log.Warn("DeleteRunnerPost.UpdateRunner failed: %v, url: %s", err, ctx.Req.URL)
|
|
ctx.Flash.Warning(ctx.Tr("actions.runners.delete_runner_failed"))
|
|
|
|
ctx.JSONRedirect(failedRedirectTo)
|
|
return
|
|
}
|
|
|
|
log.Info("DeleteRunnerPost success: %s", ctx.Req.URL)
|
|
|
|
ctx.Flash.Success(ctx.Tr("actions.runners.delete_runner_success"))
|
|
|
|
ctx.JSONRedirect(successRedirectTo)
|
|
}
|
|
|
|
func RunnerUpdatePost(ctx *context.Context) {
|
|
rCtx, err := getRunnersCtx(ctx)
|
|
if err != nil {
|
|
ctx.ServerError("getRunnersCtx", err)
|
|
return
|
|
}
|
|
|
|
runner := findActionsRunner(ctx, rCtx)
|
|
if ctx.Written() {
|
|
return
|
|
}
|
|
|
|
if !runner.EditableInContext(rCtx.OwnerID, rCtx.RepoID) {
|
|
ctx.NotFound(util.NewPermissionDeniedErrorf("no permission to edit this runner"))
|
|
return
|
|
}
|
|
|
|
isDisabled := ctx.FormOptionalBool("disabled")
|
|
if !isDisabled.Has() {
|
|
ctx.HTTPError(http.StatusBadRequest, "missing 'disabled' parameter")
|
|
return
|
|
}
|
|
|
|
successKey := "actions.runners.enable_runner_success"
|
|
failedKey := "actions.runners.enable_runner_failed"
|
|
if isDisabled.Value() {
|
|
successKey = "actions.runners.disable_runner_success"
|
|
failedKey = "actions.runners.disable_runner_failed"
|
|
}
|
|
|
|
if err := actions_model.SetRunnerDisabled(ctx, runner, isDisabled.Value()); err != nil {
|
|
log.Warn("RunnerUpdatePost.SetRunnerDisabled failed: %v, url: %s", err, ctx.Req.URL)
|
|
ctx.Flash.Error(ctx.Tr(failedKey))
|
|
ctx.JSONRedirect("")
|
|
return
|
|
}
|
|
|
|
ctx.Flash.Success(ctx.Tr(successKey))
|
|
ctx.JSONRedirect("")
|
|
}
|
|
|
|
func RedirectToDefaultSetting(ctx *context.Context) {
|
|
ctx.Redirect(ctx.Repo.RepoLink + "/settings/actions/runners")
|
|
}
|
|
|
|
func findActionsRunner(ctx *context.Context, rCtx *runnersCtx) *actions_model.ActionRunner {
|
|
runnerID := ctx.PathParamInt64("runnerid")
|
|
opts := &actions_model.FindRunnerOptions{
|
|
IDs: []int64{runnerID},
|
|
}
|
|
switch {
|
|
case rCtx.IsRepo:
|
|
opts.RepoID = rCtx.RepoID
|
|
if opts.RepoID == 0 {
|
|
panic("repoID is 0")
|
|
}
|
|
case rCtx.IsOrg, rCtx.IsUser:
|
|
opts.OwnerID = rCtx.OwnerID
|
|
if opts.OwnerID == 0 {
|
|
panic("ownerID is 0")
|
|
}
|
|
case rCtx.IsAdmin:
|
|
// do nothing
|
|
default:
|
|
panic("invalid actions runner context")
|
|
}
|
|
|
|
got, err := db.Find[actions_model.ActionRunner](ctx, opts)
|
|
if err != nil {
|
|
ctx.ServerError("FindRunner", err)
|
|
return nil
|
|
} else if len(got) == 0 {
|
|
ctx.NotFound(errors.New("runner not found"))
|
|
return nil
|
|
}
|
|
|
|
return got[0]
|
|
}
|