From 1d6b45bb65bb1faf6e75e33f8fe229e8679b8973 Mon Sep 17 00:00:00 2001 From: silverwind <2021+silverwind@noreply.gitea.com> Date: Sun, 22 Nov 2026 10:18:04 +0000 Subject: [PATCH] feat: add `runner.action_replacements` to rewrite step `uses` (#1417) Adds `runner.action_replacements`, regex rules that rewrite the `uses` of steps before they run. This keeps commits with `uses: builtin:checkout` buildable after the builtin actions were removed, and also allows redirecting actions to a mirror. Each regex must match the whole `uses`, `${1}` refers to a group, and rules apply in order. Refs: https://gitea.com/gitea/runner/pulls/1407#issuecomment-1869470 _Written by Claude (Opus 5.5)._ Reviewed-on: https://gitea.com/gitea/runner/pulls/1417 Reviewed-by: bircni Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com> --- README.md | 15 +++++ act/runner/runner.go | 1 + act/runner/step_factory.go | 3 + act/runner/step_factory_test.go | 13 ++-- internal/app/run/runner.go | 1 + internal/pkg/config/config.example.yaml | 11 +++ internal/pkg/config/config.go | 90 ++++++++++++++++--------- internal/pkg/config/config_test.go | 22 ++++++ 8 files changed, 119 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index c9ce1343..5d0f9fc4 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,21 @@ Hook scripts run where the job's steps run, before the first step and after the Use them for per-job setup no workflow should carry, like registry logins or masking runner-wide secrets. They block the job, and a non-zero exit fails it. See [docs/job-hooks.md](docs/job-hooks.md). +### Action replacements (`runner.action_replacements`) + +Rewrite the `uses` of steps before they run, for example to keep old commits using `builtin:checkout` buildable, or to fetch actions from a mirror: + +```yaml +runner: + action_replacements: + - regex: 'builtin:checkout' + replacement: actions/checkout@v6 + - regex: '(?:https://github\.com/)?actions/(.+)' + replacement: https://git.example.com/mirror/${1} +``` + +A regex must match the whole `uses`, and the replacement can insert its capture groups as `${1}`, `${2}` and so on. Entries apply in order, each to the result of the previous one. Steps inside composite actions are rewritten too. + ### Secret masking Secrets and `::add-mask::` values are hidden in job logs, [local job logs](#local-job-logs-logjobdir), job summaries and container names. As on GitHub, a job output containing one is dropped with a warning. diff --git a/act/runner/runner.go b/act/runner/runner.go index f552a132..9b03c946 100644 --- a/act/runner/runner.go +++ b/act/runner/runner.go @@ -79,6 +79,7 @@ type Config struct { // AppURL. It is never set for github.com or a GithubMirror, so the token stays on-instance. DefaultActionInstanceIsSelfHosted bool PlatformPicker func(labels []string) string + ReplaceUses func(uses string) string // rewrites each step's uses before it is resolved KubernetesPicker func(labels []string) container.KubernetesOptions InstanceTransport http.RoundTripper JobLoggerLevel *logging.Level // the level of job logger diff --git a/act/runner/step_factory.go b/act/runner/step_factory.go index 5439df94..f66819d8 100644 --- a/act/runner/step_factory.go +++ b/act/runner/step_factory.go @@ -17,6 +17,9 @@ type stepFactory interface { type stepFactoryImpl struct{} func (sf *stepFactoryImpl) newStep(stepModel *model.Step, rc *RunContext) (step, error) { + if stepModel.Uses != "" && stepModel.Run == "" && rc.Config.ReplaceUses != nil { + stepModel.Uses = rc.Config.ReplaceUses(stepModel.Uses) + } switch stepModel.Type() { case model.StepTypeInvalid: return nil, fmt.Errorf("invalid run/uses syntax for job:%s step:%+v", rc.Name, stepModel) diff --git a/act/runner/step_factory_test.go b/act/runner/step_factory_test.go index 72aa1f5c..0a097223 100644 --- a/act/runner/step_factory_test.go +++ b/act/runner/step_factory_test.go @@ -5,6 +5,7 @@ package runner import ( + "cmp" "testing" "gitea.dev/actionslib/pkg/model" @@ -12,7 +13,9 @@ import ( "github.com/stretchr/testify/require" ) -func TestStepFactoryNewStep(t *testing.T) { +func TestStepFactoryNewStepAppliesReplaceUsesToUsesOnly(t *testing.T) { + replacements := map[string]string{"": "docker://image:tag", "remote/replaced@v1": "docker://image:tag"} + rc := &RunContext{Config: &Config{ReplaceUses: func(uses string) string { return cmp.Or(replacements[uses], uses) }}} for _, test := range []struct { name string model *model.Step @@ -21,21 +24,23 @@ func TestStepFactoryNewStep(t *testing.T) { {"StepRemoteAction", &model.Step{Uses: "remote/action@v1"}, &stepActionRemote{}}, {"StepLocalAction", &model.Step{Uses: "./action@v1"}, &stepActionLocal{}}, {"StepDocker", &model.Step{Uses: "docker://image:tag"}, &stepDocker{}}, + {"StepReplaced", &model.Step{Uses: "remote/replaced@v1"}, &stepDocker{}}, {"StepRun", &model.Step{Run: "cmd"}, &stepRun{}}, } { t.Run(test.name, func(t *testing.T) { - step, err := (&stepFactoryImpl{}).newStep(test.model, &RunContext{}) + step, err := (&stepFactoryImpl{}).newStep(test.model, rc) require.NoError(t, err) assert.IsType(t, test.want, step) }) } } -func TestStepFactoryInvalidStep(t *testing.T) { +func TestStepFactoryInvalidStepStaysInvalidWhenReplaceUsesEmptiesUses(t *testing.T) { + rc := &RunContext{Name: "build", Config: &Config{ReplaceUses: func(string) string { return "" }}} for _, stepModel := range []*model.Step{ {Uses: "remote/action@v1", Run: "cmd"}, } { - _, err := (&stepFactoryImpl{}).newStep(stepModel, &RunContext{Name: "build"}) + _, err := (&stepFactoryImpl{}).newStep(stepModel, rc) assert.ErrorContains(t, err, "job:build ", stepModel.Uses) } } diff --git a/internal/app/run/runner.go b/internal/app/run/runner.go index 94a594b7..117154d9 100644 --- a/internal/app/run/runner.go +++ b/internal/app/run/runner.go @@ -630,6 +630,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report. DefaultActionInstance: r.getDefaultActionsURL(task), DefaultActionInstanceIsSelfHosted: r.isSelfHostedActionsURL(task), PlatformPicker: platformPicker, + ReplaceUses: r.cfg.Runner.ReplaceUses, JobStartedHook: r.cfg.Runner.Hooks.JobStarted, JobCompletedHook: r.cfg.Runner.Hooks.JobCompleted, Vars: task.Vars, diff --git a/internal/pkg/config/config.example.yaml b/internal/pkg/config/config.example.yaml index c2bcd54a..8ea34a58 100644 --- a/internal/pkg/config/config.example.yaml +++ b/internal/pkg/config/config.example.yaml @@ -96,6 +96,17 @@ runner: # and github_mirror is not empty. In this case, # it replaces https://github.com with the value here, which is useful for some special network environments. #github_mirror: '' + # Replaces the `uses` of steps whose regex matches it in full, with capture groups as ${1}, ${2} and so on. + # Entries apply in order, each to the result of the previous one. + #action_replacements: + # - regex: 'builtin:checkout' + # replacement: actions/checkout@v6 + # - regex: 'actions/checkout@.*' + # replacement: actions/checkout@v6 + # - regex: 'actions/setup-node@(.+)' + # replacement: self:actions/setup-node@${1} + # - regex: '(?:https://github\.com/)?actions/(.+)' + # replacement: https://git.example.com/mirror/${1} # Extra HTTP headers for runner API requests to Gitea, e.g. reverse proxy authentication. # Not used for action downloads, artifacts, job summaries or jobs. Runner headers take precedence. # Dropped on redirects to another hostname, or to HTTP if the instance URL uses HTTPS. diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index f8e2119f..01b103d6 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -61,39 +61,40 @@ type LogJob struct { // Runner represents the configuration for the runner. type Runner struct { - File string `yaml:"file"` // File specifies the file path for the runner. - Capacity int `yaml:"capacity"` // Capacity specifies the capacity of the runner. - Envs map[string]string `yaml:"envs"` // Envs stores environment variables for the runner. - EnvFile string `yaml:"env_file"` // EnvFile specifies the path to the file containing environment variables for the runner. - Timeout time.Duration `yaml:"timeout"` // Timeout specifies the duration for runner timeout. - ShutdownTimeout time.Duration `yaml:"shutdown_timeout"` // ShutdownTimeout specifies the duration to wait for running jobs to complete during a shutdown of the runner. - Insecure bool `yaml:"insecure"` // Insecure indicates whether the runner operates in an insecure mode. - ClientCertFile string `yaml:"client_cert_file"` // ClientCertFile is the PEM certificate presented to a Gitea instance that requires mutual TLS. - ClientKeyFile string `yaml:"client_key_file"` // ClientKeyFile is the PEM private key paired with ClientCertFile. - CAFile string `yaml:"ca_file"` // CAFile holds PEM CA certificates trusted for the Gitea instance besides the system's. - ExtraHeaders map[string]string `yaml:"extra_headers"` // ExtraHeaders adds HTTP headers to runner API requests to Gitea. - FetchTimeout time.Duration `yaml:"fetch_timeout"` // FetchTimeout specifies the timeout duration for fetching resources. - FetchInterval time.Duration `yaml:"fetch_interval"` // FetchInterval specifies the interval duration for fetching resources. - FetchIntervalMax time.Duration `yaml:"fetch_interval_max"` // FetchIntervalMax specifies the maximum backoff interval when idle. - WorkdirCleanupAge time.Duration `yaml:"workdir_cleanup_age"` // WorkdirCleanupAge removes stale bind-workdir task directories, orphaned host-mode scratch dirs and orphaned Kubernetes job resources older than this duration during idle cleanup. - IdleCleanupInterval time.Duration `yaml:"idle_cleanup_interval"` // IdleCleanupInterval runs the idle cleanup (stale directories, orphaned docker networks and volumes, orphaned job pods) periodically while the runner is idle. Set to 0 to disable cleanup cadence. - LogReportInterval time.Duration `yaml:"log_report_interval"` // LogReportInterval specifies the base interval for periodic log flush. - LogReportMaxLatency time.Duration `yaml:"log_report_max_latency"` // LogReportMaxLatency specifies the max time a log row can wait before being sent. - LogReportBatchSize int `yaml:"log_report_batch_size"` // LogReportBatchSize triggers immediate log flush when buffer reaches this size. - LogReportLevel string `yaml:"log_report_level"` // LogReportLevel is the lowest level of the runner's own messages sent to the job log between steps. Empty, the default, follows log.level. - StateReportInterval time.Duration `yaml:"state_report_interval"` // StateReportInterval specifies the interval for state reporting. - ReportCloseTimeout time.Duration `yaml:"report_close_timeout"` // ReportCloseTimeout caps each RPC attempt when flushing the final logs and task state at job completion, on a detached context so a server cancel can't block the acknowledgement. - Labels []string `yaml:"labels"` // Labels specify the labels of the runner. Labels are declared on each startup - GithubMirror string `yaml:"github_mirror"` // GithubMirror defines what mirrors should be used when using github - ActionShallowClone *bool `yaml:"action_shallow_clone"` // ActionShallowClone clones only the requested ref at depth 1 instead of every branch's full history, for reusable workflows and actions without an archive. It is a pointer to distinguish between false and not set; if not set, it defaults to true. - SetActEnv *bool `yaml:"set_act_env"` // SetActEnv controls whether the ACT=true environment variable is injected into jobs. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false so workflows gated on `if: ${{ !env.ACT }}` behave like on GitHub. - PatchActions *bool `yaml:"patch_actions"` // PatchActions applies compatibility patches to the actions a job runs, so actions written for GitHub work against Gitea, see act/runner/patch_actions.go. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false to run every action exactly as published, at the price of the artifact actions refusing. - AllocatePTY bool `yaml:"allocate_pty"` // AllocatePTY allocates a pseudo-TTY for each step's process. Default is false, matching GitHub's actions/runner. Enable only for jobs that need an interactive terminal; tools like docker build emit redrawing progress frames into the captured log when a TTY is present. Applies to both host and docker backends. - DefaultImage string `yaml:"default_image"` // DefaultImage is the image a job runs in when its runs-on matches none of the runner's labels. A runner without docker runs such a job on the host instead. - ToolCacheMode string `yaml:"tool_cache_mode"` // ToolCacheMode is what the runner mounts at RUNNER_TOOL_CACHE on both backends: ToolCacheModeNone or ToolCacheModeShared. - PostTaskScript string `yaml:"post_task_script"` // PostTaskScript is the path to an executable script run on the host after each task's cleanup completes. Empty disables the hook. On Windows use .exe/.bat/.cmd; PowerShell (.ps1) is not supported yet as the configured path. - PostTaskScriptTimeout time.Duration `yaml:"post_task_script_timeout"` // PostTaskScriptTimeout caps how long the post-task script may run. Default is 5m when post_task_script is set. - Hooks RunnerHooks `yaml:"hooks"` // Hooks are scripts run inside the job environment around the job's steps. + File string `yaml:"file"` // File specifies the file path for the runner. + Capacity int `yaml:"capacity"` // Capacity specifies the capacity of the runner. + Envs map[string]string `yaml:"envs"` // Envs stores environment variables for the runner. + EnvFile string `yaml:"env_file"` // EnvFile specifies the path to the file containing environment variables for the runner. + Timeout time.Duration `yaml:"timeout"` // Timeout specifies the duration for runner timeout. + ShutdownTimeout time.Duration `yaml:"shutdown_timeout"` // ShutdownTimeout specifies the duration to wait for running jobs to complete during a shutdown of the runner. + Insecure bool `yaml:"insecure"` // Insecure indicates whether the runner operates in an insecure mode. + ClientCertFile string `yaml:"client_cert_file"` // ClientCertFile is the PEM certificate presented to a Gitea instance that requires mutual TLS. + ClientKeyFile string `yaml:"client_key_file"` // ClientKeyFile is the PEM private key paired with ClientCertFile. + CAFile string `yaml:"ca_file"` // CAFile holds PEM CA certificates trusted for the Gitea instance besides the system's. + ExtraHeaders map[string]string `yaml:"extra_headers"` // ExtraHeaders adds HTTP headers to runner API requests to Gitea. + FetchTimeout time.Duration `yaml:"fetch_timeout"` // FetchTimeout specifies the timeout duration for fetching resources. + FetchInterval time.Duration `yaml:"fetch_interval"` // FetchInterval specifies the interval duration for fetching resources. + FetchIntervalMax time.Duration `yaml:"fetch_interval_max"` // FetchIntervalMax specifies the maximum backoff interval when idle. + WorkdirCleanupAge time.Duration `yaml:"workdir_cleanup_age"` // WorkdirCleanupAge removes stale bind-workdir task directories, orphaned host-mode scratch dirs and orphaned Kubernetes job resources older than this duration during idle cleanup. + IdleCleanupInterval time.Duration `yaml:"idle_cleanup_interval"` // IdleCleanupInterval runs the idle cleanup (stale directories, orphaned docker networks and volumes, orphaned job pods) periodically while the runner is idle. Set to 0 to disable cleanup cadence. + LogReportInterval time.Duration `yaml:"log_report_interval"` // LogReportInterval specifies the base interval for periodic log flush. + LogReportMaxLatency time.Duration `yaml:"log_report_max_latency"` // LogReportMaxLatency specifies the max time a log row can wait before being sent. + LogReportBatchSize int `yaml:"log_report_batch_size"` // LogReportBatchSize triggers immediate log flush when buffer reaches this size. + LogReportLevel string `yaml:"log_report_level"` // LogReportLevel is the lowest level of the runner's own messages sent to the job log between steps. Empty, the default, follows log.level. + StateReportInterval time.Duration `yaml:"state_report_interval"` // StateReportInterval specifies the interval for state reporting. + ReportCloseTimeout time.Duration `yaml:"report_close_timeout"` // ReportCloseTimeout caps each RPC attempt when flushing the final logs and task state at job completion, on a detached context so a server cancel can't block the acknowledgement. + Labels []string `yaml:"labels"` // Labels specify the labels of the runner. Labels are declared on each startup + GithubMirror string `yaml:"github_mirror"` // GithubMirror defines what mirrors should be used when using github + ActionReplacements []ActionReplacement `yaml:"action_replacements"` // ActionReplacements rewrite the `uses` of steps, see ReplaceUses. + ActionShallowClone *bool `yaml:"action_shallow_clone"` // ActionShallowClone clones only the requested ref at depth 1 instead of every branch's full history, for reusable workflows and actions without an archive. It is a pointer to distinguish between false and not set; if not set, it defaults to true. + SetActEnv *bool `yaml:"set_act_env"` // SetActEnv controls whether the ACT=true environment variable is injected into jobs. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false so workflows gated on `if: ${{ !env.ACT }}` behave like on GitHub. + PatchActions *bool `yaml:"patch_actions"` // PatchActions applies compatibility patches to the actions a job runs, so actions written for GitHub work against Gitea, see act/runner/patch_actions.go. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false to run every action exactly as published, at the price of the artifact actions refusing. + AllocatePTY bool `yaml:"allocate_pty"` // AllocatePTY allocates a pseudo-TTY for each step's process. Default is false, matching GitHub's actions/runner. Enable only for jobs that need an interactive terminal; tools like docker build emit redrawing progress frames into the captured log when a TTY is present. Applies to both host and docker backends. + DefaultImage string `yaml:"default_image"` // DefaultImage is the image a job runs in when its runs-on matches none of the runner's labels. A runner without docker runs such a job on the host instead. + ToolCacheMode string `yaml:"tool_cache_mode"` // ToolCacheMode is what the runner mounts at RUNNER_TOOL_CACHE on both backends: ToolCacheModeNone or ToolCacheModeShared. + PostTaskScript string `yaml:"post_task_script"` // PostTaskScript is the path to an executable script run on the host after each task's cleanup completes. Empty disables the hook. On Windows use .exe/.bat/.cmd; PowerShell (.ps1) is not supported yet as the configured path. + PostTaskScriptTimeout time.Duration `yaml:"post_task_script_timeout"` // PostTaskScriptTimeout caps how long the post-task script may run. Default is 5m when post_task_script is set. + Hooks RunnerHooks `yaml:"hooks"` // Hooks are scripts run inside the job environment around the job's steps. rootCAs *x509.CertPool // the system's and CAFile's, nil for the system's alone } @@ -173,6 +174,22 @@ func parseSize(value string) (Size, error) { return Size(bytes), nil } +// ActionReplacement replaces a step `uses` that Regex matches in full with Replacement. +type ActionReplacement struct { + Regex string `yaml:"regex"` + Replacement string `yaml:"replacement"` + + regex *regexp.Regexp +} + +// ReplaceUses applies ActionReplacements to a step `uses` in order, each to the result of the previous. +func (r *Runner) ReplaceUses(uses string) string { + for _, replacement := range r.ActionReplacements { + uses = replacement.regex.ReplaceAllString(uses, replacement.Replacement) + } + return uses +} + // Container represents the configuration for the container. type Container struct { Network string `yaml:"network"` // Network specifies the network for the container. @@ -327,6 +344,13 @@ func LoadDefault(file string) (*Config, error) { return nil, err } } + for index := range cfg.Runner.ActionReplacements { + replacement := &cfg.Runner.ActionReplacements[index] + if _, err := regexp.Compile(replacement.Regex); err != nil { + return nil, fmt.Errorf("runner.action_replacements[%d].regex: %w", index, err) + } + replacement.regex = regexp.MustCompile(`^(?:` + replacement.Regex + `)$`) + } for _, spec := range cfg.Container.Volumes { if parsed, err := container.ParseVolume(spec); err != nil || parsed.Source == "" { return nil, fmt.Errorf("container.volumes entry %q is not source:target[:options]", spec) diff --git a/internal/pkg/config/config_test.go b/internal/pkg/config/config_test.go index 8a03b07f..f88229f9 100644 --- a/internal/pkg/config/config_test.go +++ b/internal/pkg/config/config_test.go @@ -202,6 +202,28 @@ func TestLoadDefault_RejectsInvalidLogReportLevel(t *testing.T) { require.ErrorContains(t, err, "runner.log_report_level") } +func TestLoadDefault_ActionReplacementsMatchWholeUsesAndChainInOrder(t *testing.T) { + cfg, err := LoadDefault(write(t, ` +runner: + action_replacements: + - regex: 'actions/checkout@v4' + replacement: actions/checkout@v6 + - regex: 'actions/(.+)' + replacement: https://mirror.example/actions/${1} +`)) + require.NoError(t, err) + for uses, want := range map[string]string{ + "actions/checkout@v4": "https://mirror.example/actions/checkout@v6", + "actions/checkout@v4.1.0": "https://mirror.example/actions/checkout@v4.1.0", + "my/actions/checkout@v4": "my/actions/checkout@v4", + } { + assert.Equal(t, want, cfg.Runner.ReplaceUses(uses), uses) + } + + _, err = LoadDefault(write(t, "runner:\n action_replacements:\n - regex: 'checkout)|(?:x'\n")) + require.ErrorContains(t, err, "runner.action_replacements[0].regex") +} + func TestLoadDefault_LoadsExtraHeaders(t *testing.T) { path := write(t, "runner:\n extra_headers:\n X-Proxy-Token: proxy-token\n") cfg, err := LoadDefault(path)