cli/pkg/log/log_test.go

179 lines
4.5 KiB
Go
Raw Normal View History

package log
import (
"bytes"
"strings"
"testing"
Implement log retention policy (#306) * Implement log retention policy - Added Append method to io.Medium interface and implementations. - Defined RotationOptions and updated log.Options to support log rotation. - Implemented RotatingWriter in pkg/log/rotation.go with size and age-based retention. - Updated Logger to use RotatingWriter when configured. - Added comprehensive tests for log rotation and retention. - Documented the log retention policy in docs/pkg/log.md and docs/configuration.md. - Fixed MockMedium to return current time for Stat to avoid premature cleanup in tests. * Fix formatting issues in pkg/io/local/client.go The CI failed due to formatting issues. This commit fixes them and ensures all modified files are properly formatted. * Fix auto-merge workflow CI failure Inlined the auto-merge logic and added actions/checkout and --repo flag to gh command to provide the necessary git context. This resolves the 'fatal: not a git repository' error in CI. * Address feedback on log retention policy - Made cleanup synchronous in RotatingWriter for better reliability. - Improved rotation error handling with recovery logic. - Fixed size tracking to only increment on successful writes. - Updated MockMedium to support and preserve ModTimes for age-based testing. - Added TestRotatingWriter_AgeRetention and TestLogger_RotationIntegration. - Implemented negative MaxAge to disable age-based retention. - Updated documentation for clarity on Output priority and MaxAge behavior. - Fixed typo in test comments. - Fixed CI failure in auto-merge workflow. --------- Co-authored-by: Claude <developers@lethean.io>
2026-02-05 10:26:32 +00:00
"github.com/host-uk/core/pkg/io"
)
func TestLogger_Levels(t *testing.T) {
tests := []struct {
name string
level Level
logFunc func(*Logger, string, ...any)
expected bool
}{
{"debug at debug", LevelDebug, (*Logger).Debug, true},
{"info at debug", LevelDebug, (*Logger).Info, true},
{"warn at debug", LevelDebug, (*Logger).Warn, true},
{"error at debug", LevelDebug, (*Logger).Error, true},
{"debug at info", LevelInfo, (*Logger).Debug, false},
{"info at info", LevelInfo, (*Logger).Info, true},
{"warn at info", LevelInfo, (*Logger).Warn, true},
{"error at info", LevelInfo, (*Logger).Error, true},
{"debug at warn", LevelWarn, (*Logger).Debug, false},
{"info at warn", LevelWarn, (*Logger).Info, false},
{"warn at warn", LevelWarn, (*Logger).Warn, true},
{"error at warn", LevelWarn, (*Logger).Error, true},
{"debug at error", LevelError, (*Logger).Debug, false},
{"info at error", LevelError, (*Logger).Info, false},
{"warn at error", LevelError, (*Logger).Warn, false},
{"error at error", LevelError, (*Logger).Error, true},
{"debug at quiet", LevelQuiet, (*Logger).Debug, false},
{"info at quiet", LevelQuiet, (*Logger).Info, false},
{"warn at quiet", LevelQuiet, (*Logger).Warn, false},
{"error at quiet", LevelQuiet, (*Logger).Error, false},
Add logging for security events (authentication, access) (#320) * feat(log): add security events logging for authentication and access control - Added `Security` method to `log.Logger` with `[SEC]` prefix at `LevelWarn`. - Added `SecurityStyle` (purple) to `pkg/cli` and `LogSecurity` helper. - Added security logging for GitHub CLI authentication checks. - Added security logging for Agentic configuration loading and token validation. - Added security logging for sandbox escape detection in `local.Medium`. - Updated MCP service to support logger injection and log tool executions and connections. - Ensured all security logs include `user` context for better auditability. * feat(log): add security events logging for authentication and access control - Added `Security` method to `log.Logger` with `[SEC]` prefix at `LevelWarn`. - Added `SecurityStyle` (purple) to `pkg/cli` and `LogSecurity` helper. - Added security logging for GitHub CLI authentication checks. - Added security logging for Agentic configuration loading and token validation. - Added security logging for sandbox escape detection in `local.Medium`. - Updated MCP service to support logger injection and log tool executions and connections. - Ensured all security logs include `user` context for better auditability. - Fixed code formatting issues identified by CI. * feat(log): refine security logging and fix auto-merge CI - Moved `Security` log level to `LevelError` for better visibility. - Added robust `log.Username()` helper using `os/user`. - Differentiated high-risk (Security) and low-risk (Info) MCP tool executions. - Ensured consistent `user` context in all security-related logs. - Fixed merge conflict and missing repository context in `auto-merge` CI. - Fixed comment positioning in `pkg/mcp/mcp.go`. - Downgraded MCP TCP accept errors to standard `Error` log level. - Fixed code formatting in `internal/cmd/setup/cmd_github.go`. * feat(log): finalize security logging and address CI/CodeQL alerts - Refined `Security` logging: moved to `LevelError` and consistently include `user` context using `os/user`. - Differentiated MCP tool executions: write/delete are `Security` level, others are `Info`. - Fixed CodeQL alert: made UniFi TLS verification configurable (defaults to verify). - Updated UniFi CLI with `--verify-tls` flag and config support. - Fixed `auto-merge` CI failure by setting `GH_REPO` env var. - Fixed formatting and unused imports. - Added tests for UniFi config resolution. * fix: handle MustServiceFor return values correctly MustServiceFor returns (T, error), not just T. This was causing build failures after the rebase. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <developers@lethean.io> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 10:26:48 +00:00
{"security at info", LevelInfo, (*Logger).Security, true},
{"security at error", LevelError, (*Logger).Security, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
l := New(Options{Level: tt.level, Output: &buf})
tt.logFunc(l, "test message")
hasOutput := buf.Len() > 0
if hasOutput != tt.expected {
t.Errorf("expected output=%v, got output=%v", tt.expected, hasOutput)
}
})
}
}
func TestLogger_KeyValues(t *testing.T) {
var buf bytes.Buffer
l := New(Options{Level: LevelDebug, Output: &buf})
l.Info("test message", "key1", "value1", "key2", 42)
output := buf.String()
if !strings.Contains(output, "test message") {
t.Error("expected message in output")
}
if !strings.Contains(output, "key1=value1") {
t.Error("expected key1=value1 in output")
}
if !strings.Contains(output, "key2=42") {
t.Error("expected key2=42 in output")
}
}
func TestLogger_SetLevel(t *testing.T) {
l := New(Options{Level: LevelInfo})
if l.Level() != LevelInfo {
t.Error("expected initial level to be Info")
}
l.SetLevel(LevelDebug)
if l.Level() != LevelDebug {
t.Error("expected level to be Debug after SetLevel")
}
}
func TestLevel_String(t *testing.T) {
tests := []struct {
level Level
expected string
}{
{LevelQuiet, "quiet"},
{LevelError, "error"},
{LevelWarn, "warn"},
{LevelInfo, "info"},
{LevelDebug, "debug"},
{Level(99), "unknown"},
}
for _, tt := range tests {
t.Run(tt.expected, func(t *testing.T) {
if got := tt.level.String(); got != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, got)
}
})
}
}
Add logging for security events (authentication, access) (#320) * feat(log): add security events logging for authentication and access control - Added `Security` method to `log.Logger` with `[SEC]` prefix at `LevelWarn`. - Added `SecurityStyle` (purple) to `pkg/cli` and `LogSecurity` helper. - Added security logging for GitHub CLI authentication checks. - Added security logging for Agentic configuration loading and token validation. - Added security logging for sandbox escape detection in `local.Medium`. - Updated MCP service to support logger injection and log tool executions and connections. - Ensured all security logs include `user` context for better auditability. * feat(log): add security events logging for authentication and access control - Added `Security` method to `log.Logger` with `[SEC]` prefix at `LevelWarn`. - Added `SecurityStyle` (purple) to `pkg/cli` and `LogSecurity` helper. - Added security logging for GitHub CLI authentication checks. - Added security logging for Agentic configuration loading and token validation. - Added security logging for sandbox escape detection in `local.Medium`. - Updated MCP service to support logger injection and log tool executions and connections. - Ensured all security logs include `user` context for better auditability. - Fixed code formatting issues identified by CI. * feat(log): refine security logging and fix auto-merge CI - Moved `Security` log level to `LevelError` for better visibility. - Added robust `log.Username()` helper using `os/user`. - Differentiated high-risk (Security) and low-risk (Info) MCP tool executions. - Ensured consistent `user` context in all security-related logs. - Fixed merge conflict and missing repository context in `auto-merge` CI. - Fixed comment positioning in `pkg/mcp/mcp.go`. - Downgraded MCP TCP accept errors to standard `Error` log level. - Fixed code formatting in `internal/cmd/setup/cmd_github.go`. * feat(log): finalize security logging and address CI/CodeQL alerts - Refined `Security` logging: moved to `LevelError` and consistently include `user` context using `os/user`. - Differentiated MCP tool executions: write/delete are `Security` level, others are `Info`. - Fixed CodeQL alert: made UniFi TLS verification configurable (defaults to verify). - Updated UniFi CLI with `--verify-tls` flag and config support. - Fixed `auto-merge` CI failure by setting `GH_REPO` env var. - Fixed formatting and unused imports. - Added tests for UniFi config resolution. * fix: handle MustServiceFor return values correctly MustServiceFor returns (T, error), not just T. This was causing build failures after the rebase. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <developers@lethean.io> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 10:26:48 +00:00
func TestLogger_Security(t *testing.T) {
var buf bytes.Buffer
l := New(Options{Level: LevelError, Output: &buf})
l.Security("unauthorized access", "user", "admin")
output := buf.String()
if !strings.Contains(output, "[SEC]") {
t.Error("expected [SEC] prefix in security log")
}
if !strings.Contains(output, "unauthorized access") {
t.Error("expected message in security log")
}
if !strings.Contains(output, "user=admin") {
t.Error("expected context in security log")
}
}
func TestDefault(t *testing.T) {
// Default logger should exist
if Default() == nil {
t.Error("expected default logger to exist")
}
// Package-level functions should work
var buf bytes.Buffer
l := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(l)
Info("test")
if buf.Len() == 0 {
t.Error("expected package-level Info to produce output")
}
}
Implement log retention policy (#306) * Implement log retention policy - Added Append method to io.Medium interface and implementations. - Defined RotationOptions and updated log.Options to support log rotation. - Implemented RotatingWriter in pkg/log/rotation.go with size and age-based retention. - Updated Logger to use RotatingWriter when configured. - Added comprehensive tests for log rotation and retention. - Documented the log retention policy in docs/pkg/log.md and docs/configuration.md. - Fixed MockMedium to return current time for Stat to avoid premature cleanup in tests. * Fix formatting issues in pkg/io/local/client.go The CI failed due to formatting issues. This commit fixes them and ensures all modified files are properly formatted. * Fix auto-merge workflow CI failure Inlined the auto-merge logic and added actions/checkout and --repo flag to gh command to provide the necessary git context. This resolves the 'fatal: not a git repository' error in CI. * Address feedback on log retention policy - Made cleanup synchronous in RotatingWriter for better reliability. - Improved rotation error handling with recovery logic. - Fixed size tracking to only increment on successful writes. - Updated MockMedium to support and preserve ModTimes for age-based testing. - Added TestRotatingWriter_AgeRetention and TestLogger_RotationIntegration. - Implemented negative MaxAge to disable age-based retention. - Updated documentation for clarity on Output priority and MaxAge behavior. - Fixed typo in test comments. - Fixed CI failure in auto-merge workflow. --------- Co-authored-by: Claude <developers@lethean.io>
2026-02-05 10:26:32 +00:00
func TestLogger_RotationIntegration(t *testing.T) {
m := io.NewMockMedium()
// Hack: override io.Local for testing
oldLocal := io.Local
io.Local = m
defer func() { io.Local = oldLocal }()
l := New(Options{
Level: LevelInfo,
Rotation: &RotationOptions{
Filename: "integration.log",
MaxSize: 1,
},
})
l.Info("integration test")
// RotatingWriter needs to be closed to ensure data is written to MockMedium
if rw, ok := l.output.(*RotatingWriter); ok {
rw.Close()
}
content, err := m.Read("integration.log")
if err != nil {
t.Fatalf("failed to read log: %v", err)
}
if !strings.Contains(content, "integration test") {
t.Errorf("expected content to contain log message, got %q", content)
}
}