-
Notifications
You must be signed in to change notification settings - Fork 5
fix: make strict replay sandbox survive docker-compose service starts #228
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package runner | ||
|
|
||
| // Platform-split sandbox adapter. Real implementation lives in sandbox_unix.go | ||
| // (fence-backed); Windows gets a no-op stub in sandbox_windows.go because | ||
| // fence doesn't cross-compile there. | ||
|
|
||
| // sandboxManager wraps whatever sandbox backs replay isolation on the current | ||
| // platform. Nil means no sandbox configured. | ||
| type sandboxManager interface { | ||
| WrapCommand(command string) (string, error) | ||
| Cleanup() | ||
| } | ||
|
|
||
| type replaySandboxOptions struct { | ||
| UserConfigPath string // optional fence config override (e.g. .tusk/replay.fence.json) | ||
| Debug bool | ||
| ExposedPort int | ||
| // BindsOnHost signals that an external daemon (docker, podman) binds | ||
| // ExposedPort outside the sandbox netns; skips the reverse bridge. | ||
| BindsOnHost bool | ||
| ExposedHostPaths []exposedHostPath | ||
| } | ||
|
|
||
| type exposedHostPath struct { | ||
| Path string | ||
| Writable bool | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| //go:build darwin || linux || freebsd | ||
|
|
||
| package runner | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/Use-Tusk/fence/pkg/fence" | ||
| "github.com/Use-Tusk/tusk-cli/internal/utils" | ||
| ) | ||
|
|
||
| // isSandboxSupported reports whether the current platform can actually | ||
| // isolate replay service startup (i.e. fence is available). | ||
| func isSandboxSupported() bool { | ||
| return fence.IsSupported() | ||
| } | ||
|
|
||
| // fenceSandbox is the Unix-platform implementation of sandboxManager, | ||
| // backed by github.com/Use-Tusk/fence. | ||
| type fenceSandbox struct { | ||
| mgr *fence.Manager | ||
| } | ||
|
|
||
| // WrapCommand delegates to the underlying fence.Manager. | ||
| func (s *fenceSandbox) WrapCommand(command string) (string, error) { | ||
| return s.mgr.WrapCommand(command) | ||
| } | ||
|
|
||
| // Cleanup releases fence's socat bridges, proxies, and temp sockets. | ||
| func (s *fenceSandbox) Cleanup() { | ||
| if s.mgr != nil { | ||
| s.mgr.Cleanup() | ||
| } | ||
| } | ||
|
|
||
| // newReplaySandboxManager builds the effective fence config for replay | ||
| // mode, creates the fence.Manager, applies the requested service | ||
| // execution model + exposed host paths, and initializes the manager. | ||
| // On error, any partial state is cleaned up before returning. | ||
| func newReplaySandboxManager(opts replaySandboxOptions) (sandboxManager, error) { | ||
| fenceCfg, err := createReplayFenceConfig(opts.UserConfigPath) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("prepare replay sandbox config: %w", err) | ||
| } | ||
|
|
||
| mgr := fence.NewManager(fenceCfg, opts.Debug, false) | ||
|
|
||
| executionModel := fence.ServiceBindsInSandbox | ||
| if opts.BindsOnHost { | ||
| executionModel = fence.ServiceBindsOnHost | ||
| } | ||
| mgr.SetService(fence.ServiceOptions{ | ||
| ExposedPorts: []int{opts.ExposedPort}, | ||
| ExecutionModel: executionModel, | ||
| }) | ||
|
|
||
| for _, ehp := range opts.ExposedHostPaths { | ||
| if err := mgr.ExposeHostPath(ehp.Path, ehp.Writable); err != nil { | ||
| return nil, fmt.Errorf("expose host path %q to sandbox: %w", ehp.Path, err) | ||
| } | ||
| } | ||
|
|
||
| if err := mgr.Initialize(); err != nil { | ||
| return nil, fmt.Errorf("initialize replay sandbox: %w", err) | ||
| } | ||
|
|
||
| return &fenceSandbox{mgr: mgr}, nil | ||
| } | ||
|
|
||
| // createReplayFenceConfig creates the effective fence config for replay mode. | ||
| // This blocks localhost outbound connections to force the service to use SDK | ||
| // mocks. | ||
| // | ||
| // Exposed (lowercase) for the Unix-only service_test.go tests that verify | ||
| // user-config merging behavior. Not part of the package's cross-platform | ||
| // surface. | ||
| func createReplayFenceConfig(userConfigPath string) (*fence.Config, error) { | ||
| cfg := baseReplayFenceConfig() | ||
| if userConfigPath == "" { | ||
| return cfg, nil | ||
| } | ||
|
|
||
| resolvedPath := utils.ResolveTuskPath(userConfigPath) | ||
| userCfg, err := fence.LoadConfigResolved(resolvedPath) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("load custom fence config %q: %w", resolvedPath, err) | ||
| } | ||
| if userCfg == nil { | ||
| return nil, fmt.Errorf("custom fence config not found: %s", resolvedPath) | ||
| } | ||
| if err := validateReplayFenceConfig(userCfg); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| merged := fence.MergeConfigs(cfg, userCfg) | ||
| applyReplayFenceInvariants(merged) | ||
| return merged, nil | ||
| } | ||
|
|
||
| func baseReplayFenceConfig() *fence.Config { | ||
| f := false | ||
| return &fence.Config{ | ||
| Network: fence.NetworkConfig{ | ||
| AllowedDomains: []string{ | ||
| // Allow localhost for the service's own health checks | ||
| "localhost", | ||
| "127.0.0.1", | ||
| }, | ||
| AllowLocalBinding: true, // Allow service to bind to its port | ||
| AllowLocalOutbound: &f, // Block outbound to localhost (Postgres, Redis, etc.) | ||
| AllowAllUnixSockets: true, // Allow SDK to connect to mock server via Unix socket | ||
| }, | ||
| Filesystem: fence.FilesystemConfig{ | ||
| AllowWrite: getAllowedWriteDirs(), | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| func validateReplayFenceConfig(cfg *fence.Config) error { | ||
| if cfg == nil { | ||
| return nil | ||
| } | ||
|
|
||
| requiredDomains := []string{"localhost", "127.0.0.1"} | ||
| for _, deniedDomain := range cfg.Network.DeniedDomains { | ||
| for _, requiredDomain := range requiredDomains { | ||
| if strings.EqualFold(deniedDomain, requiredDomain) { | ||
| return fmt.Errorf("custom replay fence config cannot deny %q because replay health checks require it", requiredDomain) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func applyReplayFenceInvariants(cfg *fence.Config) { | ||
| if cfg == nil { | ||
| return | ||
| } | ||
|
|
||
| f := false | ||
| cfg.Network.AllowedDomains = mergeUniqueStrings( | ||
| cfg.Network.AllowedDomains, | ||
| []string{"localhost", "127.0.0.1"}, | ||
| ) | ||
| cfg.Network.AllowLocalBinding = true | ||
| cfg.Network.AllowLocalOutbound = &f | ||
| cfg.Network.AllowAllUnixSockets = true | ||
| cfg.Filesystem.AllowWrite = mergeUniqueStrings(cfg.Filesystem.AllowWrite, getAllowedWriteDirs()) | ||
| } | ||
|
|
||
| func mergeUniqueStrings(existing, required []string) []string { | ||
| if len(required) == 0 { | ||
| return existing | ||
| } | ||
|
|
||
| seen := make(map[string]struct{}, len(existing)+len(required)) | ||
| merged := make([]string, 0, len(existing)+len(required)) | ||
| for _, value := range existing { | ||
| if _, ok := seen[value]; ok { | ||
| continue | ||
| } | ||
| seen[value] = struct{}{} | ||
| merged = append(merged, value) | ||
| } | ||
| for _, value := range required { | ||
| if _, ok := seen[value]; ok { | ||
| continue | ||
| } | ||
| seen[value] = struct{}{} | ||
| merged = append(merged, value) | ||
| } | ||
| return merged | ||
| } | ||
|
|
||
| // getAllowedWriteDirs returns the default writable paths for replay mode. | ||
| // We allow broad local writes by default. Note that Fence still enforces | ||
| // mandatory dangerous-path protections (see | ||
| // https://github.com/Use-Tusk/fence/blob/main/internal/sandbox/dangerous.go). | ||
| func getAllowedWriteDirs() []string { | ||
| return []string{ | ||
| "/", | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| //go:build darwin || linux || freebsd | ||
|
|
||
| package runner | ||
|
|
||
| import ( | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestCreateReplayFenceConfigMergesCustomConfig(t *testing.T) { | ||
| customConfigPath := filepath.Join(t.TempDir(), "replay.fence.json") | ||
| err := os.WriteFile(customConfigPath, []byte(`{ | ||
| "network": { | ||
| "allowedDomains": ["api.example.com"] | ||
| }, | ||
| "filesystem": { | ||
| "allowWrite": ["custom-cache"] | ||
| } | ||
| }`), 0o600) | ||
| require.NoError(t, err) | ||
|
|
||
| cfg, err := createReplayFenceConfig(customConfigPath) | ||
| require.NoError(t, err) | ||
| require.NotNil(t, cfg) | ||
| require.NotNil(t, cfg.Network.AllowLocalOutbound) | ||
|
|
||
| assert.Contains(t, cfg.Network.AllowedDomains, "localhost") | ||
| assert.Contains(t, cfg.Network.AllowedDomains, "127.0.0.1") | ||
| assert.Contains(t, cfg.Network.AllowedDomains, "api.example.com") | ||
| assert.True(t, cfg.Network.AllowLocalBinding) | ||
| assert.False(t, *cfg.Network.AllowLocalOutbound) | ||
| assert.True(t, cfg.Network.AllowAllUnixSockets) | ||
| assert.Contains(t, cfg.Filesystem.AllowWrite, "custom-cache") | ||
| assert.Contains(t, cfg.Filesystem.AllowWrite, "/") | ||
| } | ||
|
|
||
| func TestCreateReplayFenceConfigRejectsDeniedLocalhost(t *testing.T) { | ||
| customConfigPath := filepath.Join(t.TempDir(), "replay.fence.json") | ||
| err := os.WriteFile(customConfigPath, []byte(`{ | ||
| "network": { | ||
| "deniedDomains": ["localhost"] | ||
| } | ||
| }`), 0o600) | ||
| require.NoError(t, err) | ||
|
|
||
| _, err = createReplayFenceConfig(customConfigPath) | ||
| require.ErrorContains(t, err, `cannot deny "localhost"`) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| //go:build windows | ||
|
|
||
| package runner | ||
|
|
||
| import "errors" | ||
|
|
||
| // Fence only supports Linux and macOS; on Windows the replay sandbox is a | ||
| // no-op. Callers treat the error the same as "sandbox not available on this | ||
| // platform" on an unsupported Unix. | ||
| var errSandboxUnsupportedOnWindows = errors.New("replay sandbox not supported on Windows") | ||
|
|
||
| func isSandboxSupported() bool { | ||
| return false | ||
| } | ||
|
|
||
| func newReplaySandboxManager(_ replaySandboxOptions) (sandboxManager, error) { | ||
| return nil, errSandboxUnsupportedOnWindows | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.