Skip to content
Closed
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
28 changes: 28 additions & 0 deletions pkg/devcontainer/sshtunnel/command_error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package sshtunnel

import "github.com/devsy-org/devsy/pkg/log"

var _ log.LogSummaryProvider = (*agentCommandFailure)(nil)

const agentCommandFailedPrefix = "run agent command failed: "

// agentCommandFailure pairs a command failure with the redacted stderr tail
// the streamer already logged. Error includes the tail for CLI consumers;
// LogSummary omits it so log sites do not replay it.
type agentCommandFailure struct {
cause error
diagnostics string
}

func (e *agentCommandFailure) Error() string {
if e.diagnostics == "" {
return e.LogSummary()
}
return e.LogSummary() + "\n" + e.diagnostics
}

func (e *agentCommandFailure) Unwrap() error { return e.cause }

func (e *agentCommandFailure) LogSummary() string {
return agentCommandFailedPrefix + e.cause.Error()
}
78 changes: 78 additions & 0 deletions pkg/devcontainer/sshtunnel/command_error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package sshtunnel

import (
"context"
"errors"
"fmt"
"testing"

"github.com/devsy-org/devsy/pkg/log"
devssh "github.com/devsy-org/devsy/pkg/ssh"
"github.com/stretchr/testify/suite"
)

const failureDiagnostics = `{"level":"debug","ts":"2026-10-13T22:41:48.610Z","msg":"credentials server started"}
{"kind":"error","outcome":"error","code":"UNKNOWN","message":"command failed with exit code 1"}`

var errSentinelCause = errors.New("sentinel cause")

type AgentCommandFailureTestSuite struct {
suite.Suite
}

func TestAgentCommandFailureTestSuite(t *testing.T) {
suite.Run(t, new(AgentCommandFailureTestSuite))
}

func (s *AgentCommandFailureTestSuite) TestErrorKeepsDiagnosticsAndLogSummaryOmitsThem() {
cause := errors.New("exit status 1")

withDiagnostics := &agentCommandFailure{cause: cause, diagnostics: failureDiagnostics}
s.Equal(
fmt.Errorf("run agent command failed: %w\n%s", cause, failureDiagnostics).Error(),
withDiagnostics.Error(),
)
s.Same(cause, withDiagnostics.Unwrap())
s.Equal("run agent command failed: exit status 1", withDiagnostics.LogSummary())

empty := &agentCommandFailure{cause: cause}
s.Equal("run agent command failed: exit status 1", empty.Error())
s.Equal(empty.Error(), empty.LogSummary())
}

func (s *AgentCommandFailureTestSuite) TestWrappedFailureMatchesCauseAndType() {
exitErr := &devssh.ExitError{ExitCode: 1}
for _, tc := range []struct {
name string
cause error
target error
}{
{"context canceled", context.Canceled, context.Canceled},
{"sentinel", errSentinelCause, errSentinelCause},
{"ssh exit error", exitErr, exitErr},
} {
s.Run(tc.name, func() {
failure := &agentCommandFailure{cause: tc.cause, diagnostics: failureDiagnostics}
wrapped := fmt.Errorf("outer: %w", fmt.Errorf("middle: %w", failure))

s.ErrorIs(wrapped, tc.target)
s.ErrorIs(failure, tc.target)

var asFailure *agentCommandFailure
s.Require().ErrorAs(wrapped, &asFailure)
s.Same(failure, asFailure)

s.Equal(failure.LogSummary(), log.ErrorForLog(wrapped))
})
}

var exit *devssh.ExitError
failure := &agentCommandFailure{cause: fmt.Errorf("wrap: %w", exitErr)}
s.Require().ErrorAs(fmt.Errorf("outer: %w", failure), &exit)
s.Equal(1, exit.ExitCode)
}

func (s *AgentCommandFailureTestSuite) TestErrorForLogOmitsDiagnostics() {
failure := &agentCommandFailure{cause: errSentinelCause, diagnostics: failureDiagnostics}
s.Equal("run agent command failed: sentinel cause", log.ErrorForLog(failure))
}
8 changes: 4 additions & 4 deletions pkg/devcontainer/sshtunnel/sshtunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,11 @@ func runCommandInSSHTunnel(ctx context.Context, p sshCommandParams, stdin, stdou
Stderr: streamer,
})
if err != nil {
_ = streamer.Close()
if out := streamer.ErrorOutput(); out != "" {
return fmt.Errorf("run agent command failed: %w\n%s", err, out)
_ = streamer.Close() // drain before reading ErrorOutput
return &agentCommandFailure{
cause: err,
diagnostics: streamer.ErrorOutput(),
}
return fmt.Errorf("run agent command failed: %w", err)
}
return nil
}
Expand Down
48 changes: 48 additions & 0 deletions pkg/log/error_value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package log

import (
"errors"
"strings"
"unicode/utf8"
)

const (
errorSummaryMaxRunes = 2048
truncatedErrorSummarySuffix = "...[truncated]"
)

// LogSummaryProvider is implemented by errors whose Error text carries data
// that must not be replayed into a log record, such as a diagnostic tail that
// was already emitted separately.
type LogSummaryProvider interface {
LogSummary() string
}

// ErrorForLog returns a log-safe description of err, capped at 2048 runes
// including the truncation suffix. The first LogSummaryProvider found while
// unwrapping err supplies the summary; otherwise err.Error() is used.
func ErrorForLog(err error) string {
if err == nil {
return "<nil>"
}
summary := err.Error()
var provider LogSummaryProvider
if errors.As(err, &provider) {
summary = provider.LogSummary()
}
return truncateErrorSummary(summary)
}

func truncateErrorSummary(summary string) string {
summary = strings.ToValidUTF8(summary, "\uFFFD")
if utf8.RuneCountInString(summary) <= errorSummaryMaxRunes {
return summary
}
keep := errorSummaryMaxRunes - utf8.RuneCountInString(truncatedErrorSummarySuffix)
cutoff := 0
for range keep {
_, width := utf8.DecodeRuneInString(summary[cutoff:])
cutoff += width
}
return summary[:cutoff] + truncatedErrorSummarySuffix
}
103 changes: 103 additions & 0 deletions pkg/log/error_value_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package log

import (
"errors"
"fmt"
"strings"
"testing"
"unicode/utf8"

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

type summaryError struct {
full string
summary string
}

func (e *summaryError) Error() string { return e.full }
func (e *summaryError) LogSummary() string { return e.summary }

type ErrorForLogTestSuite struct {
suite.Suite
}

func TestErrorForLogTestSuite(t *testing.T) {
suite.Run(t, new(ErrorForLogTestSuite))
}

func (s *ErrorForLogTestSuite) TestNilAndEmpty() {
s.Equal("<nil>", ErrorForLog(nil))
s.Empty(ErrorForLog(errors.New("")))
}

func (s *ErrorForLogTestSuite) TestWrappedTypedFallbackAndMultiline() {
typed := &summaryError{
full: "cause\n{\"level\":\"debug\",\"msg\":\"a\"}\n{\"level\":\"debug\",\"msg\":\"b\"}",
summary: "cause",
}
wrapped := fmt.Errorf("outer: %w", fmt.Errorf("middle: %w", typed))
s.Equal("cause", ErrorForLog(typed))
s.Equal("cause", ErrorForLog(wrapped), "provider summary wins over wrapper text")

multiline := errors.New("first\nsecond\r\nthird ")
s.Equal("first\nsecond\r\nthird ", ErrorForLog(multiline), "no trimming or first-line cut")
}

func (s *ErrorForLogTestSuite) TestTypedSummaryIsBounded() {
typed := &summaryError{full: "x", summary: strings.Repeat("a", 5000)}
got := ErrorForLog(fmt.Errorf("wrap: %w", typed))
s.Equal(errorSummaryMaxRunes, utf8.RuneCountInString(got))
s.True(strings.HasSuffix(got, truncatedErrorSummarySuffix))
}

func (s *ErrorForLogTestSuite) TestTruncationBoundaries() {
suffixRunes := utf8.RuneCountInString(truncatedErrorSummarySuffix)
for _, tc := range []struct {
name string
runes int
truncated bool
}{
{"2047", errorSummaryMaxRunes - 1, false},
{"2048", errorSummaryMaxRunes, false},
{"2049", errorSummaryMaxRunes + 1, true},
} {
s.Run(tc.name, func() {
input := strings.Repeat("a", tc.runes)
got := truncateErrorSummary(input)
if !tc.truncated {
s.Equal(input, got)
return
}
s.Equal(errorSummaryMaxRunes, utf8.RuneCountInString(got))
s.Equal(
strings.Repeat("a", errorSummaryMaxRunes-suffixRunes)+truncatedErrorSummarySuffix,
got,
)
})
}
}

func (s *ErrorForLogTestSuite) TestTruncationIsRuneSafe() {
input := strings.Repeat("é世🙂", 1000) // mixed 2/3/4-byte runes
got := truncateErrorSummary(input)
s.True(utf8.ValidString(got))
s.Equal(errorSummaryMaxRunes, utf8.RuneCountInString(got))
prefix := strings.TrimSuffix(got, truncatedErrorSummarySuffix)
s.Equal(errorSummaryMaxRunes-utf8.RuneCountInString(truncatedErrorSummarySuffix),
utf8.RuneCountInString(prefix))
s.True(strings.HasPrefix(input, prefix))
}

func (s *ErrorForLogTestSuite) TestInvalidUTF8IsNormalizedOnlyInSummary() {
raw := "bad\xff\xfebytes"
err := errors.New(raw)
got := ErrorForLog(err)
s.Equal("bad\uFFFDbytes", got)
s.Equal(raw, err.Error(), "original error text is not mutated")

// Each invalid run becomes one replacement rune before counting.
long := truncateErrorSummary(strings.Repeat("a\xff", 3000))
s.True(utf8.ValidString(long))
s.Equal(errorSummaryMaxRunes, utf8.RuneCountInString(long))
}
7 changes: 6 additions & 1 deletion pkg/log/logfmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"sort"
"strings"
"time"
"unicode"

"go.uber.org/zap"
"go.uber.org/zap/buffer"
Expand Down Expand Up @@ -79,12 +80,16 @@ func (e *logfmtEncoder) EncodeEntry(
}

func quoteLogfmt(s string) string {
if s == "" || strings.ContainsAny(s, " \t\n\"=") {
if s == "" || strings.IndexFunc(s, needsLogfmtQuote) >= 0 {
return fmt.Sprintf("%q", s)
}
return s
}

func needsLogfmtQuote(r rune) bool {
return unicode.IsSpace(r) || unicode.IsControl(r) || r == '"' || r == '=' || r == '\\'
}

// Required interface methods - delegate to buffer for simple types.
func (e *logfmtEncoder) AddArray(key string, arr zapcore.ArrayMarshaler) error { return nil }
func (e *logfmtEncoder) AddObject(key string, obj zapcore.ObjectMarshaler) error { return nil }
Expand Down
62 changes: 62 additions & 0 deletions pkg/log/logfmt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package log

import (
"strconv"
"strings"
"testing"

"github.com/stretchr/testify/suite"
"go.uber.org/zap"
)

type LogfmtQuotingSuite struct{ suite.Suite }

func TestLogfmtQuotingSuite(t *testing.T) { suite.Run(t, new(LogfmtQuotingSuite)) }

func (s *LogfmtQuotingSuite) TestSafeTokenStaysBare() {
s.Equal("plain-token_1.2/x:y", quoteLogfmt("plain-token_1.2/x:y"))
}

func (s *LogfmtQuotingSuite) TestControlQuoting() {
for name, value := range map[string]string{
"empty": "",
"CR only": "a\rb",
"LF": "a\nb",
"space": "a b",
"tab": "a\tb",
"vertical tab": "a\vb",
"form feed": "a\fb",
"NUL": "a\x00b",
"DEL": "a\x7fb",
"C1 NEL": "a\u0085b",
"line separator": "a\u2028b",
"para separator": "a\u2029b",
"no-break space": "a\u00a0b",
"backslash": `a\b`,
"quote": `a"b`,
"equals": "a=b",
"ANSI escape": "a\x1b[31mb",
} {
s.Run(name, func() {
quoted := quoteLogfmt(value)
s.True(strings.HasPrefix(quoted, `"`) && strings.HasSuffix(quoted, `"`), quoted)
s.NotContains(quoted, "\n")
s.NotContains(quoted, "\r")
unquoted, err := strconv.Unquote(quoted)
s.Require().NoError(err)
s.Equal(value, unquoted)
})
}
}

func (s *LogfmtQuotingSuite) TestEncodedRecordKeepsLayoutAndOneLine() {
enc := newLogfmtEncoder()
buf, err := enc.EncodeEntry(testEntry("cr\ronly"), []zap.Field{zap.String("b", "x\ry"), zap.String("a", "ok")})
s.Require().NoError(err)
out := buf.String()
buf.Free()

s.Equal(1, strings.Count(out, "\n"))
s.NotContains(out, "\r")
s.Equal(`level=debug ts=2026-10-13T22:41:50Z msg="cr\ronly" a=ok b="x\ry"`+"\n", out)
}
8 changes: 5 additions & 3 deletions pkg/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ type Config struct {

// Init configures the global logger. Called once in root command PersistentPreRunE.
func Init(cfg Config) {
cfg.Redactor = secrets.Combine(cfg.Redactor, secrets.NewEnvironmentRedactor(os.Environ()))
combined := secrets.Combine(cfg.Redactor, secrets.NewEnvironmentRedactor(os.Environ()))
// Writers redact serialized records, so secrets must match in escaped form too.
cfg.Redactor = secrets.WithLogEscapes(combined)
level := resolveLevel(cfg)
encoder := resolveEncoder(cfg.Format)
stderrWriter := zapcore.Lock(&redactingWriter{next: os.Stderr, redactor: cfg.Redactor})
Expand Down Expand Up @@ -191,9 +193,9 @@ func resolveEncoder(format string) zapcore.Encoder {
default:
// "text" - use console encoder, with color if stderr is a terminal
if colorEnabled() {
return zapcore.NewConsoleEncoder(colorEncoderConfig())
return newOneLineTextEncoder(zapcore.NewConsoleEncoder(colorEncoderConfig()))
}
return zapcore.NewConsoleEncoder(plainEncoderConfig())
return newOneLineTextEncoder(zapcore.NewConsoleEncoder(plainEncoderConfig()))
}
}

Expand Down
Loading
Loading