Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
83ee5c2
feat: multi-write of a secret will still scrub it
dolanor Apr 7, 2023
b1c0e94
add linebreak writer
dolanor Apr 11, 2023
2a91fb5
remove debug log
dolanor Apr 13, 2023
823da3f
document the max size of secret possible
dolanor Apr 13, 2023
b4e1b44
shim: secret: sort secret lines by biggest size first
dolanor Apr 13, 2023
e7b2c77
regenerate SDKs
dolanor Apr 13, 2023
1aed29a
fix lint false positive
dolanor Apr 13, 2023
2b35204
fix test to use the new implementation correctly
dolanor Apr 13, 2023
4b26559
add containsPartialSecret()
dolanor Apr 20, 2023
1be5225
flush only when no part of a secret is at the end of the data
dolanor Apr 20, 2023
9c1bab9
Refactor secret scrub multi write implementation and reorganize tests.
matiasinsaurralde May 17, 2023
cae9082
Actually add multi write test
matiasinsaurralde May 17, 2023
44476c8
Ensure multiline secrets are scrubbed with a single ***
matiasinsaurralde May 23, 2023
213a3f7
Remove previous test code
matiasinsaurralde May 23, 2023
71c88ed
Simplify SecretScrubWriter.Write
matiasinsaurralde May 28, 2023
a04fc64
Refactor tests and remove secret scrub writer implementation
matiasinsaurralde May 31, 2023
533d8d1
Add secret scrub logic for stderr
matiasinsaurralde May 31, 2023
33a1f9a
Update integration tests
matiasinsaurralde May 31, 2023
249d30b
Remove other writers
matiasinsaurralde May 31, 2023
0567025
Remove wrapping type from secret scrub writer implementation
matiasinsaurralde Jun 6, 2023
213218f
Improve multiline secret test on TestScrubSecretWrite, removed dup code
matiasinsaurralde Jun 6, 2023
46bf7bc
Update tests
matiasinsaurralde Jun 12, 2023
190a826
Fix stdout/stderr pipe when using secret scrub feature
matiasinsaurralde Jun 12, 2023
6e879d2
shim: use cmd pipes and a WaitGroup to ensure stdout and stderr are p…
matiasinsaurralde Jun 13, 2023
39f7258
shim: extend cmd.Start usage for the rest of the code
matiasinsaurralde Jun 13, 2023
a7932e9
shim: add missing pipeWg.Wait to new cmd logic
matiasinsaurralde Jun 13, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 46 additions & 8 deletions cmd/shim/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"

Expand All @@ -38,6 +39,7 @@ const (
var (
stdoutPath = metaMountPath + "/stdout"
stderrPath = metaMountPath + "/stderr"
pipeWg sync.WaitGroup
)

/*
Expand Down Expand Up @@ -286,22 +288,40 @@ func shim() int {
outWriter := io.MultiWriter(stdoutFile, os.Stdout)
errWriter := io.MultiWriter(stderrFile, os.Stderr)

// Only initialize scrubbing logic if secrets are set:
if len(secretsToScrub.Envs) == 0 && len(secretsToScrub.Files) == 0 {
cmd.Stdout = outWriter
cmd.Stderr = errWriter
} else {
// Get pipes for command's stdout and stderr and process output
// through secret scrub reader in multiple goroutines:
envToScrub := os.Environ()
scrubOutWriter, err := NewSecretScrubWriter(outWriter, currentDirPath, shimFS, envToScrub, secretsToScrub)
stdoutPipe, err := cmd.StdoutPipe()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just noticed the test failure, looks like it may be significant: https://github.com/dagger/dagger/actions/runs/5189016555/jobs/9353423519?pr=5149#step:5:14608

Don't know, but I'm wondering if we are just ending up not always flushing all the output sometimes?

@matiasinsaurralde matiasinsaurralde Jun 9, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed the same changes and didn't see the issue again however I'm facing the following scenarios when testing latest main:

  • On M1 with Docker Desktop all TestContainerWithMountedSecretOwner tests work fine.
  • On my Linux box, if I use a regular user I see this issue:
=== RUN   TestContainerWithMountedSecretOwner/userid
#1 resolve image config for docker.io/library/alpine:3.16.2
    container_test.go:3671: 
        	Error Trace:	/home/matias/go/src/github.com/dagger/dagger/core/integration/container_test.go:3671
        	Error:      	Not equal: 
        	            	expected: "auser auser"
        	            	actual  : "auser "
        	            	
        	            	Diff:
        	            	--- Expected
        	            	+++ Actual
        	            	@@ -1 +1 @@
        	            	-auser auser
        	            	+auser 
        	Test:       	TestContainerWithMountedSecretOwner/userid
  • If I ran everything as root (sudo ./hack/dev, etc.) tests pass.

I tried the same with this branch, when running with sudo test pass, regular usar fails.

So I'm wandering the following:

  • I see there's some logic around inheriting permissions in 48fb31d. Could this break depending on which user is being used in the host?
  • Based on the above, do we run tests in some privileged mode? And/or did we change anything related to it since the last failing test report you did?

Could be good to involve @vito here too, thanks! Besides that I don't see that the previously failing test is related to my changes but would be good to understand why the issue happened.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am running as a normal user on:

Server:
 Server Version: 20.10.21
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Native Overlay Diff: true
 Cgroup Driver: systemd
 Cgroup Version: 2
 Plugins:
  Volume: local
 containerd version: v1.6.18
 Kernel Version: 5.15.81
 Operating System: NixOS 22.11 (Raccoon)
 Architecture: x86_64

First 5 local runs of _EXPERIMENTAL_DAGGER_INTERACTIVE_TUI=1 dagger run ./hack/make engine:test passed:
image

Next 5 local runs of _EXPERIMENTAL_DAGGER_INTERACTIVE_TUI=1 dagger run ./hack/make engine:testrace also passed. I have delete the Engine container as well as the volume after every run. If this is a race condition - which I suspect it is - it's not an easy one to trigger. I will keep running it until I do.

FTR, this is the last run in CI which hit it: https://github.com/dagger/dagger/actions/runs/5189016555/jobs/9353423519?pr=5149#step:5:14607

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gerhard Interesting, for me it works properly on Mac using a regular user.
The issue seems to occur on Linux only.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also guess this is some kind of race condition or issue with the secret scrubbing. These tests should have no relation to what user runs them on the host. 🤔 I can't think of a way to convince stat -c '%U %G' to print an empty %G, so it seems more like the last chunk of output is bring dropped. Happy to be wrong, but that's my guess.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vito makes sense however I also see it in latest main -without my changes-. Will debug a bit more on Monday.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've verified this again, tried the following:

  • Ran TestContainerWithMountedSecretOwner multiple times in both branches (main and this one), with and without race. Didn't see any issues so far.
  • Added a panic() to the block where secret scrub logic is initialized here so that the execution breaks If this part of the code is reached: regular secret scrub integration tests like TestBigSecretScrubbed got the panic but TestContainerWithMountedSecretOwner didn't, this indicates that the logic that's part of this PR isn't involved in TestContainerWithMountedSecretOwner at all.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also the reason why test TestContainerWithMountedSecretOwner/userid has been failing to me seems to be a caching issue. Even with rebuilds it would still print the wrong output (a user ).
I renamed the test to TestContainerWithMountedSecretOwner/userid-111, ran go test -v -count=1 -timeout 30s -run ^TestContainerWithMountedSecretOwner/userid-111$ github.com/dagger/dagger/core/integration and the results are just fine!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you saying that if TestContainerWithMountedSecretOwner/userid test changes, the previous run remains cached? That would be surprising behaviour which we should address.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I continued running this as mentioned, and even though I have hit other issues - still to create them - I was not able to reproduce the original failure. I have seen it fail once locally, before I started looking for it, but not since.

if err != nil {
panic(err)
}
cmd.Stdout = scrubOutWriter
scrubErrWriter, err := NewSecretScrubWriter(errWriter, currentDirPath, shimFS, envToScrub, secretsToScrub)
scrubOutReader, err := NewSecretScrubReader(stdoutPipe, currentDirPath, shimFS, envToScrub, secretsToScrub)
if err != nil {
panic(err)
}
cmd.Stderr = scrubErrWriter
pipeWg.Add(1)
go func() {
defer pipeWg.Done()
io.Copy(outWriter, scrubOutReader)
}()

stderrPipe, err := cmd.StderrPipe()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@matiasinsaurralde I think the test failures are due to use of cmd.StdoutPipe and cmd.StderrPipe. The docs for those say:

It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe. See the StdoutPipe example for idiomatic usage.

I was able to repro the failures consistently when pulling this PR locally, I was no longer able to repro w/ this (very rough patch):

diff --git a/cmd/shim/main.go b/cmd/shim/main.go
index ecdc8567..09972d94 100644
--- a/cmd/shim/main.go
+++ b/cmd/shim/main.go
@@ -291,21 +291,17 @@ func shim() int {
                cmd.Stderr = errWriter
        } else {
                envToScrub := os.Environ()
-               stdoutPipe, err := cmd.StdoutPipe()
-               if err != nil {
-                       panic(err)
-               }
-               scrubOutReader, err := NewSecretScrubReader(stdoutPipe, currentDirPath, shimFS, envToScrub, secretsToScrub)
+               outR, outW := io.Pipe()
+               cmd.Stdout = outW
+               scrubOutReader, err := NewSecretScrubReader(outR, currentDirPath, shimFS, envToScrub, secretsToScrub)
                if err != nil {
                        panic(err)
                }
                go io.Copy(outWriter, scrubOutReader)
 
-               stderrPipe, err := cmd.StderrPipe()
-               if err != nil {
-                       panic(err)
-               }
-               scrubErrReader, err := NewSecretScrubReader(stderrPipe, currentDirPath, shimFS, envToScrub, secretsToScrub)
+               errR, errW := io.Pipe()
+               cmd.Stderr = errW
+               scrubErrReader, err := NewSecretScrubReader(errR, currentDirPath, shimFS, envToScrub, secretsToScrub)
                if err != nil {
                        panic(err)
                }

if err != nil {
panic(err)
}
scrubErrReader, err := NewSecretScrubReader(stderrPipe, currentDirPath, shimFS, envToScrub, secretsToScrub)
if err != nil {
panic(err)
}
pipeWg.Add(1)
go func() {
defer pipeWg.Done()
io.Copy(errWriter, scrubErrReader)
}()
}

exitCode := 0
Expand Down Expand Up @@ -540,7 +560,17 @@ func internalEnv(name string) (string, bool) {
func runWithNesting(ctx context.Context, cmd *exec.Cmd) error {
if _, found := internalEnv("_DAGGER_ENABLE_NESTING"); !found {
// no nesting; run as normal
return cmd.Run()
if err := cmd.Start(); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This approach looks good, we just also need to update the use of cmd.Run on line 611 with the same thing

return err
}

// Wait for stdout and stderr copy goroutines to finish:
pipeWg.Wait()

if err := cmd.Wait(); err != nil {
return err
}
return nil
}

// setup a session and associated env vars for the container
Expand Down Expand Up @@ -578,8 +608,16 @@ func runWithNesting(ctx context.Context, cmd *exec.Cmd) error {
var cmdErr error
engineErr = engine.Start(ctx, engineConf, func(ctx context.Context, r *router.Router) error {
go http.Serve(l, r) //nolint:gosec
cmdErr = cmd.Run()
return cmdErr
cmdErr = cmd.Start()
if cmdErr != nil {
return cmdErr
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we need a pipeWg.Wait call before the cmd.Wait here too?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sipsma My bad, just added it!

pipeWg.Wait()
cmdErr = cmd.Wait()
if cmdErr != nil {
return cmdErr
}
return nil
})
if cmdErr != nil {
// propagate inner error with higher priority
Expand Down
84 changes: 24 additions & 60 deletions cmd/shim/secret_scrub.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,80 +6,44 @@ import (
"io/fs"
"path/filepath"
"strings"
"sync"

"github.com/dagger/dagger/core"
"github.com/icholy/replace"
"golang.org/x/text/transform"
)

// SecretScrubWriter is a writer that will scrub secretValues before writing to the underlying writer.
// It is safe to write to it concurrently.
type SecretScrubWriter struct {
mu sync.Mutex
w io.Writer

secretValues []string
}

// Write scrubs secret values from b and replace them with `***`.
func (w *SecretScrubWriter) Write(b []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
var (
// scrubString will be used as replacement for found secrets:
scrubString = []byte("***")
)

scrubbedBytes := scrubSecretBytes(w.secretValues, b)
func NewSecretScrubReader(r io.Reader, currentDirPath string, fsys fs.FS, env []string, secretsToScrub core.SecretToScrubInfo) (io.Reader, error) {
secrets := loadSecretsToScrubFromEnv(env, secretsToScrub.Envs)

_, err := w.w.Write(scrubbedBytes)
fileSecrets, err := loadSecretsToScrubFromFiles(currentDirPath, fsys, secretsToScrub.Files)
if err != nil {
return -1, err
return nil, fmt.Errorf("could not load secrets from file: %w", err)
}
secrets = append(secrets, fileSecrets...)

return len(b), err
}

func scrubSecretBytes(secretValues []string, b []byte) []byte {
s := string(b)
ss := strings.Split(s, "\n")

out := make([]string, 0, len(ss))

for _, line := range ss {
for _, secretValue := range secretValues {
var secretLines []string

lines := strings.Split(secretValue, "\n")
secretLines = append(secretLines, lines...)
for _, secretLine := range secretLines {
secretLine := strings.TrimSpace(secretLine)
if secretLine == "" {
continue
}
// FIXME: I think we can do better
line = strings.ReplaceAll(line, secretLine, "***")
}
secretAsBytes := make([][]byte, 0)
for _, v := range secrets {
// Skip empty env:
if len(v) == 0 {
continue
}
out = append(out, line)
secretAsBytes = append(secretAsBytes, []byte(v))
}

s = strings.Join(out, "\n")

return []byte(s)
}

// NewSecretScrubWriter replaces known secrets by "***".
// The value of the secrets referenced in secretsToScrub are loaded either
// from env or from the fs accessed at currentDirPath.
func NewSecretScrubWriter(w io.Writer, currentDirPath string, fsys fs.FS, env []string, secretsToScrub core.SecretToScrubInfo) (io.Writer, error) {
secrets := loadSecretsToScrubFromEnv(env, secretsToScrub.Envs)

fileSecrets, err := loadSecretsToScrubFromFiles(currentDirPath, fsys, secretsToScrub.Files)
if err != nil {
return nil, fmt.Errorf("could not load secrets from file: %w", err)
replaceChain := make([]transform.Transformer, 0)
for _, s := range secretAsBytes {
replaceChain = append(
replaceChain,
replace.Bytes(s, scrubString),
)
}
secrets = append(secrets, fileSecrets...)

return &SecretScrubWriter{
w: w,
secretValues: secrets,
}, nil
return replace.Chain(r, replaceChain...), nil
}

// loadSecretsToScrubFromEnv loads secrets value from env if they are in secretsToScrub.
Expand Down
Loading