feat(actions): support owner-level and global scoped workflows (#38154)

## Summary

This PR adds **scoped workflows** to Gitea Actions. Workflows defined
centrally in a "source" repository that automatically run on every
repository in scope: an organization's repositories, or (for instance
admins) every repository on the instance. Each scoped run executes in
the consuming repository's own context (its runners, secrets, and
branch) while its content is read from the source repository, so an org
or instance can mandate shared CI across many repositories without
copying workflow files into each one.

An owner or instance admin registers source repositories on a settings
page and can mark individual workflows as **required**. A required
scoped workflow cannot be opted out by a consuming repository and gates
its pull-request merges; an optional one can be disabled per repository.
Scoped workflows live under a dedicated `SCOPED_WORKFLOW_DIRS` (default
`.gitea/scoped_workflows`), kept separate from regular `WORKFLOW_DIRS`.

## Main changes

### Configuration 
New `SCOPED_WORKFLOW_DIRS` setting, validated to not overlap with
`WORKFLOW_DIRS`. Default: `.gitea/scoped_workflows`

### Data model & migration
- New `action_scoped_workflow_source` table mapping a registering owner
(`owner_id`, where `0` = instance-level) to a source repository, with a
per-workflow `WorkflowConfigs` map.
- `ActionRun` gains `WorkflowRepoID` / `WorkflowCommitSHA` (the pinned
content source) and an `IsScopedRun` flag.

###  Detection & run creation
On consumer events, scoped workflows from the effective sources (the
owner's own sources plus instance-level ones) are matched and turned
into runs that execute in the consumer's context, with content pinned to
the source repo's default-branch commit.

`on: workflow_run` and `on: schedule` are currently not supported.

###  Opt-out
A consuming repository can disable an optional scoped workflow (tracked
separately from regular `DisabledWorkflows`); required scoped workflows
can never be disabled, opted out, or bypassed.

###  Commit status 
A scoped run's status context format is `"<source repo full name>:
<workflow display name> / <job> (<event>)"`
(for example: `my-org/scoped-workflows: db-tests / test-sqlite
(pull_request)`),
keeping it distinct from a same-named repo-level workflow and from other
sources.

###  Required status checks
Admins mark workflows required and supply status-check patterns.
`EffectiveRequiredContexts` appends those patterns to the branch
protection's required contexts and they are matched
must-present-and-pass. If the status checks from scoped workflows fail,
the PR cannot be merged.

NOTE: scoped workflows' required status checks patterns can protect any
target branch that has a protection rule, even though the rule's "Status
Check" is disabled. A target branch with no protection rule cannot be
protected.

<details>
  <summary>Screenshots</summary>

<img width="1400" alt="image"
src="https://github.com/user-attachments/assets/a5d1db33-15ec-487e-93be-2bc04b4e6643"
/>

</details>


###  Reusable workflows (`uses:`)
A scoped workflow's local `uses: ./...` resolves against the source
repository. `uses:` directory validation honors the
instance-configurable `WORKFLOW_DIRS` and `SCOPED_WORKFLOW_DIRS`
(previously hardcoded to `.gitea`/`.github/workflows`).

###  Manual dispatch
`workflow_dispatch` is supported for scoped workflows (web and API),
resolving inputs/content from the source repo.

###  Performance
A process-local LRU cache keyed by source repo ID for the per-source
workflow parse, so instance-level and owner-level sources don't open the
source repo and parse workflow files on every event.

### UI
Org / user / admin pages to register and remove sources, search
repositories, and mark workflows required with their status-check
patterns. The repository Actions sidebar groups scoped workflows by
source with owner/instance labels and required/disabled badges.

<details>
  <summary>Screenshots</summary>

Scoped workflows setting page:

<img width="1600" alt="image"
src="https://github.com/user-attachments/assets/9d19f667-97a5-4935-92b2-e53f105e3642"
/>


Consumer repo's Actions runs list:

<img width="1600" alt="image"
src="https://github.com/user-attachments/assets/a77241f9-0aa9-41aa-ba73-12a9a688cb64"
/>

- `Owner`: this is a owner-level scoped workflows source repo
- `Global`: this is a global scoped workflows source repo
- `Required`: this scoped workflow is required, repo admin cannot
disable it

</details>

---

Docs: https://gitea.com/gitea/docs/pulls/447

---------

Co-authored-by: bircni <bircni@icloud.com>
This commit is contained in:
Zettat123
2026-06-28 03:31:35 -06:00
committed by GitHub
parent c9920b7bd0
commit f46c9a9769
71 changed files with 3399 additions and 249 deletions
+17 -2
View File
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
@@ -50,6 +51,13 @@ type ActionRun struct {
Version int `xorm:"version default 0"` // Status could be updated concomitantly, so an optimistic lock is needed
RawConcurrency string // raw concurrency
// WorkflowRepoID/WorkflowCommitSHA record the (repo, commit) the run's workflow file content came from.
// Always filled (repo-level run = the repo itself; scoped run = the source repo).
WorkflowRepoID int64 `xorm:"NOT NULL DEFAULT 0"`
WorkflowCommitSHA string `xorm:"VARCHAR(64) NOT NULL DEFAULT ''"`
IsScopedRun bool `xorm:"NOT NULL DEFAULT false"` // IsScopedRun explicitly classifies scoped runs.
// Started and Stopped are identical to the latest attempt after ActionRunAttempt was introduced.
// When a rerun creates a new latest attempt, they are reset until the new attempt starts and stops.
Started timeutil.TimeStamp
@@ -88,7 +96,11 @@ func (run *ActionRun) WorkflowLink() string {
if run.Repo == nil {
return ""
}
return fmt.Sprintf("%s/actions/?workflow=%s", run.Repo.Link(), run.WorkflowID)
// A scoped run's workflow is disambiguated by its source repo, so carry scoped_workflow_source_repo_id back to the run list
if run.IsScopedRun {
return fmt.Sprintf("%s/actions/?workflow=%s&scoped_workflow_source_repo_id=%d", run.Repo.Link(), url.QueryEscape(run.WorkflowID), run.WorkflowRepoID)
}
return fmt.Sprintf("%s/actions/?workflow=%s", run.Repo.Link(), url.QueryEscape(run.WorkflowID))
}
// RefLink return the url of run's ref
@@ -291,7 +303,10 @@ func GetWorkflowLatestRun(ctx context.Context, repoID int64, workflowFile, branc
var run ActionRun
q := db.GetEngine(ctx).Where("repo_id=?", repoID).
And("ref = ?", branch).
And("workflow_id = ?", workflowFile)
And("workflow_id = ?", workflowFile).
// TODO: the badge only reflects the repo's own (repo-level) runs; a same-named scoped run must not leak in.
// Support a scoped-workflow badge later by making this source-aware.
And("is_scoped_run = ?", false)
if event != "" {
q.And("event = ?", event)
}
+22 -2
View File
@@ -10,6 +10,7 @@ import (
repo_model "gitea.dev/models/repo"
user_model "gitea.dev/models/user"
"gitea.dev/modules/container"
"gitea.dev/modules/optional"
"gitea.dev/modules/translation"
webhook_module "gitea.dev/modules/webhook"
@@ -61,7 +62,9 @@ type FindRunOptions struct {
RepoID int64
OwnerID int64
WorkflowID string
Ref string // the commit/tag/… that caused this workflow
WorkflowRepoID int64 // source-aware filter: the repo a run's workflow content came from (0 = any)
IsScopedRun optional.Option[bool] // is the run from a scoped workflow
Ref string // the commit/tag/… that caused this workflow
TriggerUserID int64
TriggerEvent webhook_module.HookEventType
Status []Status
@@ -77,6 +80,12 @@ func (opts FindRunOptions) ToConds() builder.Cond {
if opts.WorkflowID != "" {
cond = cond.And(builder.Eq{"`action_run`.workflow_id": opts.WorkflowID})
}
if opts.WorkflowRepoID > 0 {
cond = cond.And(builder.Eq{"`action_run`.workflow_repo_id": opts.WorkflowRepoID})
}
if opts.IsScopedRun.Has() {
cond = cond.And(builder.Eq{"`action_run`.is_scoped_run": opts.IsScopedRun.Value()})
}
if opts.TriggerUserID > 0 {
cond = cond.And(builder.Eq{"`action_run`.trigger_user_id": opts.TriggerUserID})
}
@@ -156,9 +165,20 @@ func GetRunBranches(ctx context.Context, repoID int64) ([]string, error) {
// GetRunWorkflowIDs returns all distinct WorkflowIDs that have at least
// one ActionRun in the given repo.
func GetRunWorkflowIDs(ctx context.Context, repoID int64) ([]string, error) {
return getRunWorkflowIDs(ctx, repoID, builder.NewCond())
}
// GetRepoRunWorkflowIDs returns all distinct WorkflowIDs that have at least
// one repo-level ActionRun in the given repo.
func GetRepoRunWorkflowIDs(ctx context.Context, repoID int64) ([]string, error) {
return getRunWorkflowIDs(ctx, repoID, builder.Eq{"is_scoped_run": false})
}
func getRunWorkflowIDs(ctx context.Context, repoID int64, extraCond builder.Cond) ([]string, error) {
ids := make([]string, 0, 10)
cond := builder.Eq{"repo_id": repoID}
return ids, db.GetEngine(ctx).Table("action_run").
Where(builder.Eq{"repo_id": repoID}).
Where(cond.And(extraCond)).
Distinct("workflow_id").
Cols("workflow_id").
Asc("workflow_id").
+125
View File
@@ -6,10 +6,13 @@ package actions
import (
"testing"
"gitea.dev/models/db"
"gitea.dev/models/unittest"
"gitea.dev/modules/optional"
"gitea.dev/modules/translation"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetRunWorkflowIDs(t *testing.T) {
@@ -24,6 +27,46 @@ func TestGetRunWorkflowIDs(t *testing.T) {
assert.Empty(t, ids)
}
func TestGetRepoRunWorkflowIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
const (
repoID = int64(4)
repoWorkflowID = "repo-orphan.yaml"
scopedWorkflowID = "scoped-only.yaml"
sharedWorkflowID = "shared-name.yaml"
scopedWorkflowRepo = int64(111)
)
for _, spec := range []struct {
id int64
workflowID string
workflowRepoID int64
isScopedRun bool
}{
{99811, repoWorkflowID, repoID, false},
{99812, scopedWorkflowID, scopedWorkflowRepo, true},
{99813, sharedWorkflowID, repoID, false},
{99814, sharedWorkflowID, scopedWorkflowRepo, true},
} {
require.NoError(t, db.Insert(t.Context(), &ActionRun{
ID: spec.id,
Index: spec.id,
RepoID: repoID,
OwnerID: 1,
TriggerUserID: 1,
WorkflowID: spec.workflowID,
WorkflowRepoID: spec.workflowRepoID,
IsScopedRun: spec.isScopedRun,
}))
}
ids, err := GetRepoRunWorkflowIDs(t.Context(), repoID)
require.NoError(t, err)
assert.Contains(t, ids, repoWorkflowID)
assert.Contains(t, ids, sharedWorkflowID)
assert.NotContains(t, ids, scopedWorkflowID)
}
func TestGetStatusInfoList(t *testing.T) {
statusInfoList := GetStatusInfoList(t.Context(), translation.MockLocale{})
@@ -35,3 +78,85 @@ func TestGetStatusInfoList(t *testing.T) {
{Status: int(StatusCancelling), StatusName: StatusCancelling.String(), DisplayedStatus: "actions.status.cancelling"},
}, statusInfoList)
}
// TestFindRunOptions_WorkflowRepoID: two runs share the bare WorkflowID but come from different content-source repos;
// the source-aware WorkflowRepoID filter must separate them.
func TestFindRunOptions_WorkflowRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
const (
repoID = int64(4)
sourceA = int64(111)
sourceB = int64(222)
workflowID = "u3-shared.yaml"
)
for _, spec := range []struct{ id, workflowRepoID int64 }{
{99801, sourceA},
{99802, sourceB},
} {
require.NoError(t, db.Insert(t.Context(), &ActionRun{
ID: spec.id,
Index: spec.id,
RepoID: repoID,
OwnerID: 1,
TriggerUserID: 1,
WorkflowID: workflowID,
WorkflowRepoID: spec.workflowRepoID,
IsScopedRun: true,
}))
}
// no source filter -> both
all, err := db.Find[ActionRun](t.Context(), FindRunOptions{RepoID: repoID, WorkflowID: workflowID})
require.NoError(t, err)
assert.Len(t, all, 2)
// filter by source A -> only the run whose content came from A
onlyA, err := db.Find[ActionRun](t.Context(), FindRunOptions{RepoID: repoID, WorkflowID: workflowID, WorkflowRepoID: sourceA})
require.NoError(t, err)
require.Len(t, onlyA, 1)
assert.EqualValues(t, 99801, onlyA[0].ID)
// filter by source B -> only the run whose content came from B
onlyB, err := db.Find[ActionRun](t.Context(), FindRunOptions{RepoID: repoID, WorkflowID: workflowID, WorkflowRepoID: sourceB})
require.NoError(t, err)
require.Len(t, onlyB, 1)
assert.EqualValues(t, 99802, onlyB[0].ID)
}
func TestFindRunOptions_IsScopedRun(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
const (
repoID = int64(4)
workflowID = "scoped-flag.yaml"
)
for _, spec := range []struct {
id int64
scoped bool
}{
{99821, false},
{99822, true},
} {
require.NoError(t, db.Insert(t.Context(), &ActionRun{
ID: spec.id,
Index: spec.id,
RepoID: repoID,
OwnerID: 1,
TriggerUserID: 1,
WorkflowID: workflowID,
WorkflowRepoID: repoID,
IsScopedRun: spec.scoped,
}))
}
repoLevel, err := db.Find[ActionRun](t.Context(), FindRunOptions{RepoID: repoID, WorkflowID: workflowID, IsScopedRun: optional.Some(false)})
require.NoError(t, err)
require.Len(t, repoLevel, 1)
assert.EqualValues(t, 99821, repoLevel[0].ID)
scoped, err := db.Find[ActionRun](t.Context(), FindRunOptions{RepoID: repoID, WorkflowID: workflowID, IsScopedRun: optional.Some(true)})
require.NoError(t, err)
require.Len(t, scoped, 1)
assert.EqualValues(t, 99822, scoped[0].ID)
}
+55
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/modules/timeutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUpdateRepoRunsNumbers(t *testing.T) {
@@ -44,3 +45,57 @@ func TestActionRun_Duration_NonNegative(t *testing.T) {
}
assert.Equal(t, time.Duration(0), run.Duration())
}
func TestActionRun_WorkflowLink(t *testing.T) {
repo := &repo_model.Repository{OwnerName: "org", Name: "consumer"}
// a repo-level run links by file name only
repoLevel := &ActionRun{Repo: repo, WorkflowID: "ci.yaml", WorkflowRepoID: repo.ID}
assert.Equal(t, repo.Link()+"/actions/?workflow=ci.yaml", repoLevel.WorkflowLink())
// a scoped run carries its source repo id back, so the list stays filtered to that source
scoped := &ActionRun{Repo: repo, WorkflowID: "ci.yaml", WorkflowRepoID: 42, IsScopedRun: true}
assert.Equal(t, repo.Link()+"/actions/?workflow=ci.yaml&scoped_workflow_source_repo_id=42", scoped.WorkflowLink())
}
func TestGetWorkflowLatestRun_RepoLevelOnly(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
const (
repoID = int64(4)
workflowID = "badge-source-aware.yaml"
ref = "refs/heads/main"
)
require.NoError(t, db.Insert(t.Context(), &ActionRun{
ID: 99811,
Index: 99811,
RepoID: repoID,
OwnerID: 1,
TriggerUserID: 1,
WorkflowID: workflowID,
Ref: ref,
Event: "push",
Status: StatusSuccess,
WorkflowRepoID: repoID,
WorkflowCommitSHA: "repo-level-sha",
}))
require.NoError(t, db.Insert(t.Context(), &ActionRun{
ID: 99812,
Index: 99812,
RepoID: repoID,
OwnerID: 1,
TriggerUserID: 1,
WorkflowID: workflowID,
Ref: ref,
Event: "push",
Status: StatusFailure,
WorkflowRepoID: 111,
WorkflowCommitSHA: "scoped-sha",
IsScopedRun: true,
}))
run, err := GetWorkflowLatestRun(t.Context(), repoID, workflowID, ref, "push")
require.NoError(t, err)
assert.EqualValues(t, 99811, run.ID)
assert.False(t, run.IsScopedRun)
}
+179
View File
@@ -0,0 +1,179 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package actions
import (
"context"
"fmt"
"gitea.dev/models/db"
repo_model "gitea.dev/models/repo"
"gitea.dev/modules/timeutil"
"gitea.dev/modules/util"
"xorm.io/builder"
)
// ActionScopedWorkflowSource registers a repository as a source of scoped workflows, either for an owner (user/org) or for the whole instance.
type ActionScopedWorkflowSource struct {
ID int64 `xorm:"pk autoincr"`
// OwnerID is the scope the source applies to: a user/org ID (applies to that owner's repos), or 0 for instance-level (applies to every repo).
OwnerID int64 `xorm:"UNIQUE(owner_repo) NOT NULL DEFAULT 0"`
// SourceRepoID is the source repository providing the workflow files; always non-zero.
SourceRepoID int64 `xorm:"INDEX UNIQUE(owner_repo) NOT NULL DEFAULT 0"`
// WorkflowConfigs maps a workflow ID (entry name) to its merge-gate config.
WorkflowConfigs map[string]*ScopedWorkflowConfig `xorm:"JSON TEXT 'workflow_configs'"`
CreatedUnix timeutil.TimeStamp `xorm:"created"`
UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
}
// ScopedWorkflowConfig is one scoped workflow's config within a source registration.
type ScopedWorkflowConfig struct {
Required bool `json:"required"`
Patterns []string `json:"patterns"` // the status-check patterns that must be present and pass, only effective when Required is true
}
func init() {
db.RegisterModel(new(ActionScopedWorkflowSource))
}
// IsWorkflowRequired reports whether the given workflow ID (entry name) is marked required in this source.
func (s *ActionScopedWorkflowSource) IsWorkflowRequired(workflowID string) bool {
c, ok := s.WorkflowConfigs[workflowID]
return ok && c.Required
}
type FindScopedWorkflowSourceOpts struct {
db.ListOptions
OwnerIDs []int64
SourceRepoID int64
}
func (opts FindScopedWorkflowSourceOpts) ToConds() builder.Cond {
cond := builder.NewCond()
if len(opts.OwnerIDs) > 0 {
cond = cond.And(builder.In("owner_id", opts.OwnerIDs))
}
if opts.SourceRepoID != 0 {
cond = cond.And(builder.Eq{"source_repo_id": opts.SourceRepoID})
}
return cond
}
// GetEffectiveScopedWorkflowSources returns the scoped-workflow sources effective for a repo owned by repoOwnerID:
// the owner's own sources plus instance-level (owner_id=0) sources.
func GetEffectiveScopedWorkflowSources(ctx context.Context, repoOwnerID int64) ([]*ActionScopedWorkflowSource, error) {
owners := []int64{0}
if repoOwnerID != 0 {
owners = append(owners, repoOwnerID)
}
return db.Find[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: owners})
}
// IsScopedWorkflowSourceEffective reports whether sourceRepoID is a scoped-workflow source effective for a repo owned by repoOwnerID.
func IsScopedWorkflowSourceEffective(ctx context.Context, repoOwnerID, sourceRepoID int64) (bool, error) {
owners := []int64{0}
if repoOwnerID != 0 {
owners = append(owners, repoOwnerID)
}
return db.Exist[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: owners, SourceRepoID: sourceRepoID}.ToConds())
}
// IsWorkflowRequiredInSources reports whether workflowID from sourceRepoID is required by any of the given sources.
func IsWorkflowRequiredInSources(sources []*ActionScopedWorkflowSource, sourceRepoID int64, workflowID string) bool {
for _, s := range sources {
if s.SourceRepoID == sourceRepoID && s.IsWorkflowRequired(workflowID) {
return true
}
}
return false
}
// ScopedStatusContextPrefix returns the source-repo prefix that makes a scoped run's commit-status context distinct from same-named workflows.
func ScopedStatusContextPrefix(ctx context.Context, sourceRepoID int64) string {
if sourceRepo, err := repo_model.GetRepositoryByID(ctx, sourceRepoID); err == nil {
return sourceRepo.FullName()
}
return fmt.Sprintf("scoped:%d", sourceRepoID)
}
// IsScopedWorkflowRequired reports whether workflowID from sourceRepoID is required for a repo owned by consumerOwnerID.
func IsScopedWorkflowRequired(ctx context.Context, consumerOwnerID, sourceRepoID int64, workflowID string) (bool, error) {
sources, err := GetEffectiveScopedWorkflowSources(ctx, consumerOwnerID)
if err != nil {
return false, err
}
return IsWorkflowRequiredInSources(sources, sourceRepoID, workflowID), nil
}
// IsScopedWorkflowOptedOutloads the consumer's effective sources then calls ScopedWorkflowOptedOut
func IsScopedWorkflowOptedOut(ctx context.Context, cfg *repo_model.ActionsConfig, consumerOwnerID, sourceRepoID int64, workflowID string) (bool, error) {
if !cfg.IsScopedWorkflowDisabled(sourceRepoID, workflowID) {
return false, nil
}
sources, err := GetEffectiveScopedWorkflowSources(ctx, consumerOwnerID)
if err != nil {
return false, err
}
return ScopedWorkflowOptedOut(cfg, sources, sourceRepoID, workflowID), nil
}
// ScopedWorkflowOptedOut reports whether a consumer's opt-out of (sourceRepoID, workflowID) is in effect.
func ScopedWorkflowOptedOut(cfg *repo_model.ActionsConfig, sources []*ActionScopedWorkflowSource, sourceRepoID int64, workflowID string) bool {
return !IsWorkflowRequiredInSources(sources, sourceRepoID, workflowID) && cfg.IsScopedWorkflowDisabled(sourceRepoID, workflowID)
}
// GetScopedWorkflowSourcesByOwner returns the sources an owner (user/org, or 0 for instance) registered.
func GetScopedWorkflowSourcesByOwner(ctx context.Context, ownerID int64) ([]*ActionScopedWorkflowSource, error) {
return db.Find[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: []int64{ownerID}})
}
// GetScopedWorkflowSource returns the (owner, repo) source registration or a NotExist error.
func GetScopedWorkflowSource(ctx context.Context, ownerID, repoID int64) (*ActionScopedWorkflowSource, error) {
src := &ActionScopedWorkflowSource{}
has, err := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Get(src)
if err != nil {
return nil, err
}
if !has {
return nil, util.NewNotExistErrorf("scoped workflow source (owner %d, repo %d) does not exist", ownerID, repoID)
}
return src, nil
}
// AddScopedWorkflowSource registers repoID as a source for ownerID (no-op if already registered).
func AddScopedWorkflowSource(ctx context.Context, ownerID, repoID int64) error {
exists, err := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Exist(new(ActionScopedWorkflowSource))
if err != nil {
return err
}
if exists {
return nil
}
if err := db.Insert(ctx, &ActionScopedWorkflowSource{OwnerID: ownerID, SourceRepoID: repoID}); err != nil {
// Re-check and treat an already-present row as the intended no-op.
if exists, existErr := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Exist(new(ActionScopedWorkflowSource)); existErr == nil && exists {
return nil
}
return err
}
return nil
}
// SetScopedWorkflowSourceConfigs replaces the per-workflow merge-gate configs (workflow ID -> config).
func SetScopedWorkflowSourceConfigs(ctx context.Context, ownerID, repoID int64, configs map[string]*ScopedWorkflowConfig) error {
_, err := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).
Cols("workflow_configs").
Update(&ActionScopedWorkflowSource{WorkflowConfigs: configs})
return err
}
// RemoveScopedWorkflowSource removes the (owner, repo) source registration.
func RemoveScopedWorkflowSource(ctx context.Context, ownerID, repoID int64) error {
_, err := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Delete(new(ActionScopedWorkflowSource))
return err
}
+139
View File
@@ -0,0 +1,139 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package actions
import (
"testing"
"gitea.dev/models/db"
"gitea.dev/models/unittest"
"gitea.dev/modules/util"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestScopedWorkflowSource_IsWorkflowRequired(t *testing.T) {
src := &ActionScopedWorkflowSource{WorkflowConfigs: map[string]*ScopedWorkflowConfig{
"a.yml": {Required: true, Patterns: []string{"p"}},
"b.yml": {Required: true, Patterns: []string{"p"}},
"c.yml": {Required: false, Patterns: []string{"p"}}, // patterns kept as history, not required
}}
assert.True(t, src.IsWorkflowRequired("a.yml"))
assert.True(t, src.IsWorkflowRequired("b.yml"))
assert.False(t, src.IsWorkflowRequired("c.yml"), "config kept as history but not required")
assert.False(t, src.IsWorkflowRequired("d.yml"))
empty := &ActionScopedWorkflowSource{}
assert.False(t, empty.IsWorkflowRequired("a.yml"))
}
func TestIsWorkflowRequiredInSources(t *testing.T) {
// repo 100 registered twice (org optional + instance required).
sources := []*ActionScopedWorkflowSource{
{OwnerID: 2, SourceRepoID: 100, WorkflowConfigs: nil},
{OwnerID: 0, SourceRepoID: 100, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"a.yml": {Required: true, Patterns: []string{"p"}}}},
{OwnerID: 0, SourceRepoID: 200, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"b.yml": {Required: true, Patterns: []string{"p"}}}},
}
assert.True(t, IsWorkflowRequiredInSources(sources, 100, "a.yml"), "required at instance level wins over org optional")
assert.False(t, IsWorkflowRequiredInSources(sources, 100, "z.yml"))
assert.False(t, IsWorkflowRequiredInSources(sources, 200, "a.yml"), "a.yml is required for repo 100, not repo 200")
assert.True(t, IsWorkflowRequiredInSources(sources, 200, "b.yml"))
assert.False(t, IsWorkflowRequiredInSources(sources, 999, "a.yml"), "unknown source repo")
}
func TestGetEffectiveScopedWorkflowSources(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
ctx := t.Context()
rows := []*ActionScopedWorkflowSource{
{OwnerID: 2, SourceRepoID: 100, WorkflowConfigs: nil}, // org 2 registers repo 100 (optional)
{OwnerID: 0, SourceRepoID: 100, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"a.yml": {Required: true, Patterns: []string{"p"}}}}, // instance also registers repo 100 (required)
{OwnerID: 0, SourceRepoID: 200, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"b.yml": {Required: true, Patterns: []string{"p"}}}}, // instance source 200
{OwnerID: 3, SourceRepoID: 300, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"c.yml": {Required: true, Patterns: []string{"p"}}}}, // a different owner's source
}
for _, r := range rows {
require.NoError(t, db.Insert(ctx, r))
}
// owner 2 sees its own sources plus instance-level ones, but not owner 3's.
owner2, err := GetEffectiveScopedWorkflowSources(ctx, 2)
require.NoError(t, err)
assert.Len(t, owner2, 3)
required, err := IsScopedWorkflowRequired(ctx, 2, 100, "a.yml")
require.NoError(t, err)
assert.True(t, required, "instance marks a.yml required → required for owner 2 even though org left it optional")
required, err = IsScopedWorkflowRequired(ctx, 2, 100, "x.yml")
require.NoError(t, err)
assert.False(t, required)
required, err = IsScopedWorkflowRequired(ctx, 2, 200, "b.yml")
require.NoError(t, err)
assert.True(t, required)
// owner 3's source must not be effective for owner 2.
required, err = IsScopedWorkflowRequired(ctx, 2, 300, "c.yml")
require.NoError(t, err)
assert.False(t, required)
// IsScopedWorkflowSourceEffective: owner-level and instance-level sources are effective; another owner's is not.
effective, err := IsScopedWorkflowSourceEffective(ctx, 2, 100)
require.NoError(t, err)
assert.True(t, effective, "owner 2's own source")
effective, err = IsScopedWorkflowSourceEffective(ctx, 2, 200)
require.NoError(t, err)
assert.True(t, effective, "instance-level source is effective for any owner")
effective, err = IsScopedWorkflowSourceEffective(ctx, 2, 300)
require.NoError(t, err)
assert.False(t, effective, "owner 3's source is not effective for owner 2")
effective, err = IsScopedWorkflowSourceEffective(ctx, 2, 999)
require.NoError(t, err)
assert.False(t, effective, "unknown source repo")
effective, err = IsScopedWorkflowSourceEffective(ctx, 3, 300)
require.NoError(t, err)
assert.True(t, effective, "owner 3's own source is effective for owner 3")
}
func TestScopedWorkflowSourceCRUD(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
ctx := t.Context()
// add is idempotent
require.NoError(t, AddScopedWorkflowSource(ctx, 5, 10))
require.NoError(t, AddScopedWorkflowSource(ctx, 5, 10))
sources, err := GetScopedWorkflowSourcesByOwner(ctx, 5)
require.NoError(t, err)
assert.Len(t, sources, 1)
// set the per-workflow configs (entry name -> {required, patterns}); a.yml required, b.yml kept as history (not required)
configs := map[string]*ScopedWorkflowConfig{
"a.yml": {Required: true, Patterns: []string{"src: a.yml / *"}},
"b.yml": {Required: false, Patterns: []string{"src: b.yml / build (push)"}},
}
require.NoError(t, SetScopedWorkflowSourceConfigs(ctx, 5, 10, configs))
src, err := GetScopedWorkflowSource(ctx, 5, 10)
require.NoError(t, err)
assert.Equal(t, configs, src.WorkflowConfigs)
// clearing the configs works
require.NoError(t, SetScopedWorkflowSourceConfigs(ctx, 5, 10, nil))
src, err = GetScopedWorkflowSource(ctx, 5, 10)
require.NoError(t, err)
assert.Empty(t, src.WorkflowConfigs)
// remove
require.NoError(t, RemoveScopedWorkflowSource(ctx, 5, 10))
_, err = GetScopedWorkflowSource(ctx, 5, 10)
assert.ErrorIs(t, err, util.ErrNotExist)
sources, err = GetScopedWorkflowSourcesByOwner(ctx, 5)
require.NoError(t, err)
assert.Empty(t, sources)
}
+1
View File
@@ -419,6 +419,7 @@ func prepareMigrationTasks() []*migration {
newMigration(339, "Extend action c_u index to include created_unix for faster dashboard feed queries", v1_27.AddCreatedUnixToActionUserIsDeletedIndex),
newMigration(340, "Add ContinueOnError column to ActionRunJob", v1_27.AddContinueOnErrorToActionRunJob),
newMigration(341, "Convert legacy MSSQL DATETIME columns to DATETIME2", v1_27.FixLegacyMSSQLDateTimeColumns),
newMigration(342, "Add scoped workflows schema", v1_27.AddScopedWorkflowsSchema),
}
return preparedMigrations
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package v1_27
import (
"gitea.dev/models/db"
"gitea.dev/modules/timeutil"
"xorm.io/xorm"
)
func AddScopedWorkflowsSchema(x db.EngineMigration) error {
// Create the action_scoped_workflow_source table
type ScopedWorkflowConfig struct {
Required bool `json:"required"`
Patterns []string `json:"patterns"`
}
type ActionScopedWorkflowSource struct {
ID int64 `xorm:"pk autoincr"`
OwnerID int64 `xorm:"UNIQUE(owner_repo) NOT NULL DEFAULT 0"`
SourceRepoID int64 `xorm:"INDEX UNIQUE(owner_repo) NOT NULL DEFAULT 0"`
WorkflowConfigs map[string]*ScopedWorkflowConfig `xorm:"JSON TEXT 'workflow_configs'"`
CreatedUnix timeutil.TimeStamp `xorm:"created"`
UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
}
if err := x.Sync(new(ActionScopedWorkflowSource)); err != nil {
return err
}
// Add the columns that record where a run's workflow content came from
type ActionRun struct {
WorkflowRepoID int64 `xorm:"NOT NULL DEFAULT 0"`
WorkflowCommitSHA string `xorm:"VARCHAR(64) NOT NULL DEFAULT ''"`
IsScopedRun bool `xorm:"NOT NULL DEFAULT false"`
}
_, err := x.SyncWithOptions(xorm.SyncOptions{
IgnoreDropIndices: true,
IgnoreConstrains: true,
}, new(ActionRun))
return err
}
+25
View File
@@ -70,6 +70,8 @@ func MakeRestrictedPermissions() ActionsTokenPermissions {
type ActionsConfig struct {
DisabledWorkflows []string
// DisabledScopedWorkflows maps a scoped workflow's source repository ID to the entry names opted out of in this repository.
DisabledScopedWorkflows map[int64][]string
// CollaborativeOwnerIDs is a list of owner IDs used to share actions from private repos.
// Only workflows from the private repos whose owners are in CollaborativeOwnerIDs can access the current repo's actions.
CollaborativeOwnerIDs []int64
@@ -98,6 +100,29 @@ func (cfg *ActionsConfig) DisableWorkflow(file string) {
cfg.DisabledWorkflows = append(cfg.DisabledWorkflows, file)
}
func (cfg *ActionsConfig) IsScopedWorkflowDisabled(sourceRepoID int64, workflowID string) bool {
return slices.Contains(cfg.DisabledScopedWorkflows[sourceRepoID], workflowID)
}
func (cfg *ActionsConfig) DisableScopedWorkflow(sourceRepoID int64, workflowID string) {
if slices.Contains(cfg.DisabledScopedWorkflows[sourceRepoID], workflowID) {
return
}
if cfg.DisabledScopedWorkflows == nil {
cfg.DisabledScopedWorkflows = make(map[int64][]string)
}
cfg.DisabledScopedWorkflows[sourceRepoID] = append(cfg.DisabledScopedWorkflows[sourceRepoID], workflowID)
}
func (cfg *ActionsConfig) EnableScopedWorkflow(sourceRepoID int64, workflowID string) {
workflowIDs := util.SliceRemoveAll(cfg.DisabledScopedWorkflows[sourceRepoID], workflowID)
if len(workflowIDs) == 0 {
delete(cfg.DisabledScopedWorkflows, sourceRepoID)
return
}
cfg.DisabledScopedWorkflows[sourceRepoID] = workflowIDs
}
func (cfg *ActionsConfig) AddCollaborativeOwner(ownerID int64) {
if !slices.Contains(cfg.CollaborativeOwnerIDs, ownerID) {
cfg.CollaborativeOwnerIDs = append(cfg.CollaborativeOwnerIDs, ownerID)
+51
View File
@@ -0,0 +1,51 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package repo
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestActionsConfig_ScopedWorkflowOptOut(t *testing.T) {
cfg := &ActionsConfig{}
assert.False(t, cfg.IsScopedWorkflowDisabled(100, "ci.yml"))
cfg.DisableScopedWorkflow(100, "ci.yml")
assert.True(t, cfg.IsScopedWorkflowDisabled(100, "ci.yml"))
// idempotent
cfg.DisableScopedWorkflow(100, "ci.yml")
assert.Len(t, cfg.DisabledScopedWorkflows, 1)
// keyed by source repo: the same filename from a different source repo is independent
assert.False(t, cfg.IsScopedWorkflowDisabled(200, "ci.yml"))
// must not collide with the repo-level DisabledWorkflows list (bare filename)
assert.False(t, cfg.IsWorkflowDisabled("ci.yml"))
cfg.DisableWorkflow("ci.yml")
assert.True(t, cfg.IsWorkflowDisabled("ci.yml"))
assert.True(t, cfg.IsScopedWorkflowDisabled(100, "ci.yml"), "repo-level disable must not touch the scoped entry")
cfg.EnableScopedWorkflow(100, "ci.yml")
assert.False(t, cfg.IsScopedWorkflowDisabled(100, "ci.yml"))
assert.True(t, cfg.IsWorkflowDisabled("ci.yml"), "enabling the scoped entry must not touch the repo-level disable")
}
func TestActionsConfig_ScopedWorkflowSerialization(t *testing.T) {
cfg := &ActionsConfig{}
cfg.DisableScopedWorkflow(100, "ci.yml")
cfg.DisableWorkflow("repo.yml")
bs, err := cfg.ToDB()
require.NoError(t, err)
got := &ActionsConfig{}
require.NoError(t, got.FromDB(bs))
assert.True(t, got.IsScopedWorkflowDisabled(100, "ci.yml"))
assert.True(t, got.IsWorkflowDisabled("repo.yml"))
}