Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 4 additions & 7 deletions agent/log/line_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (

"github.com/rs/zerolog/log"

"go.woodpecker-ci.org/woodpecker/v3/pipeline/shared"
"go.woodpecker-ci.org/woodpecker/v3/rpc"
)

Expand All @@ -35,25 +34,23 @@ type LineWriter struct {
stepUUID string
num int
startTime time.Time
replacer *strings.Replacer
}

// NewLineWriter returns a new line reader.
func NewLineWriter(peer rpc.Peer, stepUUID string, secret ...string) io.Writer {
//
// Sanitizing (e.g. secret masking) is not handled here; wrap the writer
// with shared.NewSecretsWriter or shared.NewSanitizeWriter.
func NewLineWriter(peer rpc.Peer, stepUUID string) io.Writer {
lw := &LineWriter{
peer: peer,
stepUUID: stepUUID,
startTime: time.Now().UTC(),
replacer: shared.NewSecretsReplacer(secret),
}
return lw
}

func (w *LineWriter) Write(p []byte) (n int, err error) {
data := string(p)
if w.replacer != nil {
data = w.replacer.Replace(data)
}
log.Trace().Str("step-uuid", w.stepUUID).Msgf("grpc write line: %s", data)

line := &rpc.LogEntry{
Expand Down
32 changes: 29 additions & 3 deletions agent/log/line_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/stretchr/testify/mock"

"go.woodpecker-ci.org/woodpecker/v3/agent/log"
"go.woodpecker-ci.org/woodpecker/v3/pipeline/shared"
"go.woodpecker-ci.org/woodpecker/v3/rpc"
"go.woodpecker-ci.org/woodpecker/v3/rpc/mocks"
)
Expand All @@ -29,8 +30,7 @@ func TestLineWriter(t *testing.T) {
peer := mocks.NewMockPeer(t)
peer.On("EnqueueLog", mock.Anything)

secrets := []string{"world"}
lw := log.NewLineWriter(peer, "e9ea76a5-44a1-4059-9c4a-6956c478b26d", secrets...)
lw := log.NewLineWriter(peer, "e9ea76a5-44a1-4059-9c4a-6956c478b26d")

_, err := lw.Write([]byte("hello world\n"))
assert.NoError(t, err)
Expand All @@ -42,7 +42,7 @@ func TestLineWriter(t *testing.T) {
Time: 0,
Type: rpc.LogEntryStdout,
Line: 0,
Data: []byte("hello ********"),
Data: []byte("hello world"),
})

peer.AssertCalled(t, "EnqueueLog", &rpc.LogEntry{
Expand All @@ -55,3 +55,29 @@ func TestLineWriter(t *testing.T) {

peer.AssertExpectations(t)
}

// TestLineWriterWithSecretsWriter guards the agent contract: wrapping the
// line writer in shared.NewSecretsWriter masks secret values before they
// are enqueued, matching the previous built-in masking behavior.
func TestLineWriterWithSecretsWriter(t *testing.T) {
peer := mocks.NewMockPeer(t)
peer.On("EnqueueLog", mock.Anything)

lw := shared.NewSecretsWriter(
log.NewLineWriter(peer, "e9ea76a5-44a1-4059-9c4a-6956c478b26d"),
[]string{"world"},
)

_, err := lw.Write([]byte("hello world\n"))
assert.NoError(t, err)

peer.AssertCalled(t, "EnqueueLog", &rpc.LogEntry{
StepUUID: "e9ea76a5-44a1-4059-9c4a-6956c478b26d",
Time: 0,
Type: rpc.LogEntryStdout,
Line: 0,
Data: []byte("hello ********"),
})

peer.AssertExpectations(t)
}
3 changes: 2 additions & 1 deletion agent/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"go.woodpecker-ci.org/woodpecker/v3/pipeline"
backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types"
"go.woodpecker-ci.org/woodpecker/v3/pipeline/logging"
"go.woodpecker-ci.org/woodpecker/v3/pipeline/shared"
pipeline_utils "go.woodpecker-ci.org/woodpecker/v3/pipeline/utils"
"go.woodpecker-ci.org/woodpecker/v3/rpc"
)
Expand All @@ -42,7 +43,7 @@ func (r *Runner) createLogger(_logger zerolog.Logger, workflow *rpc.Workflow) lo

logger.Debug().Msg("log stream opened")

logStream := log.NewLineWriter(r.client, step.UUID, secrets...)
logStream := shared.NewSecretsWriter(log.NewLineWriter(r.client, step.UUID), secrets)
if err := pipeline_utils.CopyLineByLine(logStream, rc, pipeline.MaxLogLineLength); err != nil {
logger.Error().Err(err).Msg("copy limited logStream part")
}
Expand Down
20 changes: 15 additions & 5 deletions cli/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
"go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/yaml/compiler"
"go.woodpecker-ci.org/woodpecker/v3/pipeline/logging"
pipeline_runtime "go.woodpecker-ci.org/woodpecker/v3/pipeline/runtime"
"go.woodpecker-ci.org/woodpecker/v3/pipeline/shared"
pipeline_utils "go.woodpecker-ci.org/woodpecker/v3/pipeline/utils"
"go.woodpecker-ci.org/woodpecker/v3/shared/constant"
"go.woodpecker-ci.org/woodpecker/v3/shared/utils"
Expand Down Expand Up @@ -285,7 +286,7 @@ func runExec(ctx context.Context, c *cli.Command, yamls []*builder.YamlFile, rep
runtime := pipeline_runtime.New(
item.Config, backendEngine,
pipeline_runtime.WithContext(pipelineCtx), //nolint:contextcheck
pipeline_runtime.WithLogger(defaultLogger),
pipeline_runtime.WithLogger(newLogger(item.Config)),
pipeline_runtime.WithDescription(map[string]string{
"CLI": "exec",
}),
Expand Down Expand Up @@ -325,7 +326,16 @@ func convertPathForWindows(path string) string {
return filepath.ToSlash(path)
}

var defaultLogger = logging.Logger(func(step *backend_types.Step, rc io.ReadCloser) error {
logWriter := NewLineWriter(step.Name, step.UUID)
return pipeline_utils.CopyLineByLine(logWriter, rc, pipeline.MaxLogLineLength)
})
// newLogger builds a logger that masks the pipeline's secret values in the
// streamed step output by wrapping the line writer in a shared secrets writer.
func newLogger(config *backend_types.Config) logging.Logger {
var secrets []string
for _, s := range config.Secrets {
secrets = append(secrets, s.Value)
}
return func(step *backend_types.Step, rc io.ReadCloser) error {
logWriter := NewLineWriter(step.Name, step.UUID)
masked := shared.NewSecretsWriter(logWriter, secrets)
return pipeline_utils.CopyLineByLine(masked, rc, pipeline.MaxLogLineLength)
}
}
6 changes: 5 additions & 1 deletion cli/exec/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ steps:
image: alpine
commands:
- echo hello
- echo supersecret
`), 0o600))

// LineWriter writes to os.Stderr directly, so redirect the fd
Expand All @@ -60,6 +61,7 @@ steps:
"woodpecker-cli",
"--backend-engine", "dummy",
"--repo-path", repoDir,
"--secrets", "password=supersecret",
workflowPath,
})
require.NoError(t, err)
Expand All @@ -83,8 +85,10 @@ steps:
`[build:L3:0s] StepCommands:
[build:L4:0s] ------------------
[build:L5:0s] echo hello
[build:L6:0s] ------------------`,
[build:L6:0s] echo ********
[build:L7:0s] ------------------`,
)
assert.NotContains(t, stdout, "supersecret")

require.NoError(t, err)
}
Expand Down
6 changes: 5 additions & 1 deletion cli/exec/line.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type LineWriter struct {
stepUUID string
num int
startTime time.Time
out io.Writer
}

// NewLineWriter returns a new line reader.
Expand All @@ -35,11 +36,14 @@ func NewLineWriter(stepName, stepUUID string) io.WriteCloser {
stepName: stepName,
stepUUID: stepUUID,
startTime: time.Now().UTC(),
out: os.Stderr,
}
}

func (w *LineWriter) Write(p []byte) (n int, err error) {
fmt.Fprintf(os.Stderr, "[%s:L%d:%ds] %s", w.stepName, w.num, int64(time.Since(w.startTime).Seconds()), p)
if _, err := fmt.Fprintf(w.out, "[%s:L%d:%ds] %s", w.stepName, w.num, int64(time.Since(w.startTime).Seconds()), p); err != nil {
return 0, err
}
w.num++
return len(p), nil
}
Expand Down
53 changes: 53 additions & 0 deletions cli/exec/line_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2026 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package exec

import (
"bytes"
"errors"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type failWriter struct{ err error }

func (f *failWriter) Write([]byte) (int, error) { return 0, f.err }

func TestLineWriterPropagatesError(t *testing.T) {
wantErr := errors.New("broken pipe")
w := NewLineWriter("step", "uuid")
lw, ok := w.(*LineWriter)
require.True(t, ok)
lw.out = &failWriter{err: wantErr}

n, err := w.Write([]byte("line\n"))
assert.ErrorIs(t, err, wantErr)
assert.Zero(t, n)
}

func TestLineWriterWrites(t *testing.T) {
var buf bytes.Buffer
w := NewLineWriter("step", "uuid")
lw, ok := w.(*LineWriter)
require.True(t, ok)
lw.out = &buf

n, err := w.Write([]byte("hello\n"))
assert.NoError(t, err)
assert.Equal(t, len("hello\n"), n)
assert.Contains(t, buf.String(), "[step:L0:0s] hello")
}
51 changes: 51 additions & 0 deletions pipeline/shared/sanitize_writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2026 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shared

import "io"

// SanitizeFunc transforms log data before it is written, e.g. to mask
// secrets. It receives and returns a full write chunk (typically one line).
type SanitizeFunc func(string) string

// sanitizeWriter is an io.Writer decorator that runs a SanitizeFunc on the
// data before forwarding it to the wrapped writer. It is meant to wrap a
// line-oriented writer so that per-line transformations behave correctly.
type sanitizeWriter struct {
dst io.Writer
sanitize SanitizeFunc
}

// NewSanitizeWriter wraps dst so that every write is passed through the given
// sanitize function first. A nil function passes data through unchanged. The
// returned writer reports the number of input bytes consumed, so it composes
// transparently with callers that check n against the input length.
func NewSanitizeWriter(dst io.Writer, sanitize SanitizeFunc) io.Writer {
return &sanitizeWriter{
dst: dst,
sanitize: sanitize,
}
}

func (w *sanitizeWriter) Write(p []byte) (n int, err error) {
data := p
if w.sanitize != nil {
data = []byte(w.sanitize(string(p)))
}
if _, err := w.dst.Write(data); err != nil {
return 0, err
}
return len(p), nil
}
56 changes: 56 additions & 0 deletions pipeline/shared/sanitize_writer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2026 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shared

import (
"bytes"
"errors"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestSanitizeWriterCustomFunc(t *testing.T) {
var buf bytes.Buffer
w := NewSanitizeWriter(&buf, strings.ToUpper)

n, err := w.Write([]byte("hello\n"))
assert.NoError(t, err)
assert.Equal(t, len("hello\n"), n)
assert.Equal(t, "HELLO\n", buf.String())
}

func TestSanitizeWriterNilFuncPassesThrough(t *testing.T) {
var buf bytes.Buffer
w := NewSanitizeWriter(&buf, nil)

_, err := w.Write([]byte("as is\n"))
assert.NoError(t, err)
assert.Equal(t, "as is\n", buf.String())
}

type errWriter struct{ err error }

func (e *errWriter) Write([]byte) (int, error) { return 0, e.err }

func TestSanitizeWriterPropagatesError(t *testing.T) {
wantErr := errors.New("sink closed")
w := NewSanitizeWriter(&errWriter{err: wantErr}, nil)

n, err := w.Write([]byte("x"))
assert.ErrorIs(t, err, wantErr)
assert.Zero(t, n)
}
25 changes: 25 additions & 0 deletions pipeline/shared/secrets_writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright 2026 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shared

import "io"

// NewSecretsWriter wraps dst so that any of the given secret values are
// replaced with asterisks before being written. It is a convenience for
// NewSanitizeWriter with the secrets replacer as the sanitize function;
// other sanitize algorithms can be plugged in via NewSanitizeWriter.
func NewSecretsWriter(dst io.Writer, secrets []string) io.Writer {
return NewSanitizeWriter(dst, NewSecretsReplacer(secrets).Replace)
}
Loading