mirror of
https://gitea.com/gitea/act_runner.git
synced 2026-11-28 06:42:21 +08:00
fix: composite action masks, systempaths option and locked action clones (#1424)
- A composite action started in its pre stage shares masks with its job in every stage, so values masked by earlier steps stay masked inside it and neither side loses a mask - `systempaths=unconfined` in container options takes effect instead of being dropped when options are merged - A cached action or reusable workflow clone left locked by a killed git is cloned fresh instead of failing every later job - actionslib v1.7.1 validates the contexts a reusable workflow caller's `with:` may use, from https://gitea.com/gitea/actionslib/pulls/36 _Written by Claude (Opus 5.5)._ Reviewed-on: https://gitea.com/gitea/runner/pulls/1424 Reviewed-by: bircni <bircni@icloud.com> Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
This commit is contained in:
@@ -12,6 +12,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -192,7 +193,11 @@ type NewGitCloneExecutorInput struct {
|
||||
// CloneIfRequired reports whether an existing local clone was reused.
|
||||
func CloneIfRequired(ctx context.Context, input NewGitCloneExecutorInput, logger *logging.Logger) (bool, error) {
|
||||
var origin string
|
||||
_, err := os.Stat(filepath.Join(input.Dir, ".git")) // without it git would discover a repository around Dir
|
||||
gitDir := filepath.Join(input.Dir, ".git")
|
||||
_, err := os.Stat(gitDir) // without it git would discover a repository around Dir
|
||||
if err == nil && !input.OfflineMode {
|
||||
err = findStaleLock(gitDir)
|
||||
}
|
||||
if err == nil {
|
||||
origin, err = findGitRemoteURL(ctx, input.Dir)
|
||||
}
|
||||
@@ -205,7 +210,7 @@ func CloneIfRequired(ctx context.Context, input NewGitCloneExecutorInput, logger
|
||||
if err == nil {
|
||||
logger.Debugf("Removing cached clone at %s because origin URL changed from %s to %s", input.Dir, origin, input.URL)
|
||||
} else if _, statErr := os.Stat(input.Dir); statErr == nil {
|
||||
logger.Debugf("Removing cached clone at %s because origin cannot be read: %v", input.Dir, err)
|
||||
logger.Debugf("Removing cached clone at %s because it cannot be reused: %v", input.Dir, err)
|
||||
}
|
||||
if err := os.RemoveAll(input.Dir); err != nil {
|
||||
return false, fmt.Errorf("remove cached clone %s: %w", input.Dir, err)
|
||||
@@ -219,6 +224,21 @@ func CloneIfRequired(ctx context.Context, input NewGitCloneExecutorInput, logger
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// findStaleLock fails on a lock file a killed git left behind, which would fail every later fetch or checkout.
|
||||
func findStaleLock(gitDir string) error {
|
||||
for _, name := range []string{"HEAD.lock", "config.lock", "index.lock", "packed-refs.lock", "shallow.lock"} {
|
||||
if _, err := os.Lstat(filepath.Join(gitDir, name)); err == nil {
|
||||
return fmt.Errorf("stale lock %s", name)
|
||||
}
|
||||
}
|
||||
return filepath.WalkDir(filepath.Join(gitDir, "refs"), func(path string, _entry fs.DirEntry, err error) error {
|
||||
if err == nil && strings.HasSuffix(path, ".lock") {
|
||||
return fmt.Errorf("stale lock %s", path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// NewGitCloneExecutor creates an executor to clone git repos
|
||||
func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
||||
return func(ctx context.Context) error {
|
||||
|
||||
@@ -275,7 +275,7 @@ func TestGitCloneExecutor(t *testing.T) {
|
||||
clones.Wait()
|
||||
}
|
||||
|
||||
func TestGitCloneExecutorReclonesWhenOriginURLChanges(t *testing.T) {
|
||||
func TestGitCloneExecutorReclonesWhenOriginURLChangesOrLockIsStale(t *testing.T) {
|
||||
t.Parallel()
|
||||
createRemote := func(message string) string {
|
||||
dir := t.TempDir()
|
||||
@@ -324,6 +324,13 @@ func TestGitCloneExecutorReclonesWhenOriginURLChanges(t *testing.T) {
|
||||
|
||||
_, err = os.Stat(markerPath)
|
||||
require.True(t, os.IsNotExist(err), "stale cached directory should be removed before recloning")
|
||||
|
||||
lockPath := filepath.Join(cacheDir, ".git", "index.lock")
|
||||
require.NoError(t, os.WriteFile(lockPath, nil, 0o644))
|
||||
require.NoError(t, os.WriteFile(markerPath, nil, 0o644))
|
||||
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{URL: newRemoteDir, Ref: "main", Dir: cacheDir})(t.Context()))
|
||||
assert.NoFileExists(t, lockPath)
|
||||
assert.NoFileExists(t, markerPath)
|
||||
}
|
||||
|
||||
func TestGitCloneExecutorFollowsRemoteRefChanges(t *testing.T) {
|
||||
|
||||
@@ -661,6 +661,12 @@ func (cr *containerReference) mergeContainerConfigs(ctx context.Context, config
|
||||
overlay(reflect.ValueOf(hostConfig).Elem(), reflect.ValueOf(containerConfig.HostConfig).Elem(), false)
|
||||
hostConfig.Binds = binds
|
||||
hostConfig.Mounts = mounts
|
||||
if containerConfig.HostConfig.MaskedPaths != nil {
|
||||
hostConfig.MaskedPaths = containerConfig.HostConfig.MaskedPaths
|
||||
}
|
||||
if containerConfig.HostConfig.ReadonlyPaths != nil {
|
||||
hostConfig.ReadonlyPaths = containerConfig.HostConfig.ReadonlyPaths
|
||||
}
|
||||
if cf.name != "" {
|
||||
logger.Warn("--name in the options will be ignored.")
|
||||
}
|
||||
|
||||
@@ -805,7 +805,8 @@ func TestMergeContainerConfigsStripsDangerousOptionsWhenUnprivileged(t *testing.
|
||||
// OS-independent options only, --device and --gpus need a linux/windows server OS
|
||||
const dangerousOptions = "--pid=host --ipc=host --uts=host --cgroupns=host " +
|
||||
"--userns=host --cap-add=ALL --security-opt seccomp=unconfined " +
|
||||
"--security-opt apparmor=unconfined --volumes-from other --isolation process " +
|
||||
"--security-opt apparmor=unconfined --security-opt systempaths=unconfined " +
|
||||
"--volumes-from other --isolation process " +
|
||||
"--runtime runc --cgroup-parent /custom --sysctl net.ipv4.ip_forward=1 " +
|
||||
"--log-driver=syslog --log-opt syslog-address=tcp://169.254.169.254:514 " +
|
||||
"--oom-score-adj=-1000 --oom-kill-disable"
|
||||
@@ -825,6 +826,8 @@ func TestMergeContainerConfigsStripsDangerousOptionsWhenUnprivileged(t *testing.
|
||||
assert.Equal(t, []string{"ALL"}, kept.CapAdd)
|
||||
assert.Equal(t, "runc", kept.Runtime)
|
||||
assert.Equal(t, "host", string(kept.UsernsMode))
|
||||
assert.Equal(t, []string{}, kept.MaskedPaths)
|
||||
assert.Equal(t, []string{}, kept.ReadonlyPaths)
|
||||
assert.False(t, kept.Privileged)
|
||||
|
||||
// privileged is the administrator opting in, so the workflow's options are honored
|
||||
|
||||
@@ -53,7 +53,7 @@ func newCompositeRunContext(ctx context.Context, parent *RunContext, step action
|
||||
JobContainer: parent.JobContainer,
|
||||
ActionPath: actionPath,
|
||||
GlobalEnv: parent.GlobalEnv,
|
||||
Masks: parent.Masks,
|
||||
Masks: slices.Clip(parent.Masks),
|
||||
ExtraPath: parent.ExtraPath,
|
||||
Parent: parent,
|
||||
EventJSON: parent.EventJSON,
|
||||
@@ -99,11 +99,6 @@ func execAsComposite(ctx context.Context, step actionStep, inputs map[string]str
|
||||
rc.setOutput(ctx, map[string]string{"name": outputName}, value)
|
||||
}
|
||||
|
||||
// compositeRC.Masks is seeded with rc.Masks (see newCompositeRunContext)
|
||||
// and may have additional masks appended while the composite action runs.
|
||||
// Only append masks that are not already present, otherwise nested or
|
||||
// repeated composite actions grow rc.Masks exponentially.
|
||||
rc.Masks = appendUniqueMasks(rc.Masks, compositeRC.Masks)
|
||||
rc.ExtraPath = compositeRC.ExtraPath
|
||||
// Propagate GlobalEnv only, so composite inputs and step-local values do not escape.
|
||||
mergeIntoMap := mergeIntoMapCaseSensitive
|
||||
@@ -178,6 +173,10 @@ func (rc *RunContext) compositeExecutor(action *model.Action) *compositeSteps {
|
||||
|
||||
func (rc *RunContext) newCompositeCommandExecutor(executor common.Executor) common.Executor {
|
||||
return func(ctx context.Context) error {
|
||||
if parent := rc.Parent; parent != nil { // a composite context outlives the stage it was made in, so sync masks around every step
|
||||
rc.Masks = appendUniqueMasks(rc.Masks, parent.Masks)
|
||||
defer func() { parent.Masks = appendUniqueMasks(parent.Masks, rc.Masks) }()
|
||||
}
|
||||
return rc.withCommandLogWriter(WithCompositeLogger(ctx, &rc.Masks), executor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,25 @@ func TestCompositeActionParity(t *testing.T) {
|
||||
require.ErrorIs(t, rc.compositeExecutor(&model.Action{Runs: model.ActionRuns{Using: "composite", Steps: []model.Step{{ID: "nested", Uses: "org/action@v1"}}}}).pre(t.Context()), assert.AnError)
|
||||
})
|
||||
|
||||
t.Run("composite steps of every stage share masks with the job", func(t *testing.T) {
|
||||
parent := makeTestRC(t, "runs-on: ubuntu-latest")
|
||||
parent.JobContainer, parent.Masks = &jobContainerMock{}, make([]string, 0, 2)
|
||||
step := &stepActionRemote{Step: &model.Step{Uses: "own/action@v1"}, RunContext: parent, action: &model.Action{Runs: model.ActionRuns{Using: "composite"}}, remoteAction: mustNewRemoteAction(t, "own/action@v1")}
|
||||
composite := step.getCompositeRunContext(t.Context(), nil)
|
||||
require.NoError(t, composite.newCompositeCommandExecutor(func(ctx context.Context) error {
|
||||
composite.AddMask(ctx, "composite-pre")
|
||||
return nil
|
||||
})(t.Context()))
|
||||
parent.AddMask(t.Context(), "job-first")
|
||||
parent.AddMask(t.Context(), "job-later")
|
||||
require.NoError(t, composite.newCompositeCommandExecutor(func(ctx context.Context) error {
|
||||
assert.Contains(t, composite.Masks, "job-later")
|
||||
composite.AddMask(ctx, "composite-post")
|
||||
return nil
|
||||
})(t.Context()))
|
||||
assert.ElementsMatch(t, []string{"composite-pre", "job-first", "job-later", "composite-post"}, parent.Masks)
|
||||
})
|
||||
|
||||
t.Run("post steps log under their own step ids", func(t *testing.T) {
|
||||
hook := logtest.NewWithLevel(logging.LevelDebug)
|
||||
rc := &RunContext{Config: &Config{}, JobContainer: &jobContainerMock{}}
|
||||
|
||||
2
go.mod
2
go.mod
@@ -6,7 +6,7 @@ toolchain go1.27.4
|
||||
|
||||
require (
|
||||
connectrpc.com/connect/v2 v2.0.2
|
||||
gitea.dev/actionslib v1.7.0
|
||||
gitea.dev/actionslib v1.7.1
|
||||
github.com/bmatcuk/doublestar/v4 v4.10.4
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/containerd/errdefs v1.0.0
|
||||
|
||||
4
go.sum
4
go.sum
@@ -1,7 +1,7 @@
|
||||
connectrpc.com/connect/v2 v2.0.2 h1:PoPDmOlhc46elsuCdKCKTxjNBb3HJlKF+s/sP2oucPw=
|
||||
connectrpc.com/connect/v2 v2.0.2/go.mod h1:N32OLrstcPUzkykFynnefFro3+xzSdOrZlK2jHmS/xo=
|
||||
gitea.dev/actionslib v1.7.0 h1:J2KWyKyb2XvhizjGmLu3b1I94lZzTShZ3eMmSRMGm/Q=
|
||||
gitea.dev/actionslib v1.7.0/go.mod h1:i8wUQMnvGwT13f2re2ZTMCFL/TyauQLeOb1L4ngjtPk=
|
||||
gitea.dev/actionslib v1.7.1 h1:vOSV4K99kK5RBdMnTVRuwJCisL3egpNbvGpA7XhPXdA=
|
||||
gitea.dev/actionslib v1.7.1/go.mod h1:i8wUQMnvGwT13f2re2ZTMCFL/TyauQLeOb1L4ngjtPk=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
|
||||
Reference in New Issue
Block a user