Skip to content
Merged
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
26 changes: 14 additions & 12 deletions internal/checker/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@ func checkEndpoint(cfg *configure.Endpoint, timeout int, maxRetryTimes int, serv
remainingDays, expired, err := checkSSLCertificates(cfg.ParsedURL)
if err != nil {
urlIsHTTPS = false
log.Printf("SSL certificate check failed for %s: %v", cfg.ParsedURL, err)
// Only log success details during tests to avoid exposing secrets
logIfTest("SSL certificate check failed for %s: %v", cfg.ParsedURL, err)
failureDetails = append(failureDetails, fmt.Sprintf("SSL Certificate Error: %s", err.Error()))
} else {
certRemainingDays = remainingDays
isCertExpired = expired
log.Printf("SSL Certificate Info for %s: %d days remaining, expired: %v", cfg.ParsedURL, remainingDays, expired)
// Only log success details during tests to avoid exposing secrets
logIfTest("SSL Certificate Info for %s: %d days remaining, expired: %v", cfg.ParsedURL, remainingDays, expired)
}
}

Expand All @@ -62,8 +64,8 @@ func checkEndpoint(cfg *configure.Endpoint, timeout int, maxRetryTimes int, serv
client := &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
// TODO: Hide secrets in logs
log.Printf("[%s] %s %s (attempt %d/%d)\n",
// Only log request details during tests to avoid exposing secrets
logIfTest("[%s] %s %s (attempt %d/%d)\n",
serviceName, httpMethod, cfg.ParsedURL, currentAttemptNum+1, maxRetryTimes)

// build the request
Expand Down Expand Up @@ -94,8 +96,8 @@ func checkEndpoint(cfg *configure.Endpoint, timeout int, maxRetryTimes int, serv
failureDetails = append(failureDetails, fmt.Sprintf("StatusCode: %d, Error: %s", resp.StatusCode, err.Error()))
log.Printf("FAILED - StatusCode: %d, Error: %s", resp.StatusCode, err.Error())
if err := resp.Body.Close(); err != nil {
// TODO: Hide secrets in logs
log.Printf("Error closing response body for %s: %v", cfg.ParsedURL, err)
// Only log response body errors during tests to avoid exposing secrets
logIfTest("Error closing response body for %s: %v", cfg.ParsedURL, err)
}
continue
}
Expand All @@ -111,19 +113,19 @@ func checkEndpoint(cfg *configure.Endpoint, timeout int, maxRetryTimes int, serv
}
responseBody = ""
if err := resp.Body.Close(); err != nil {
// TODO: Hide secrets in logs
log.Printf("Error closing response body for %s: %v", cfg.ParsedURL, err)
// Only log response body errors during tests to avoid exposing secrets
logIfTest("Error closing response body for %s: %v", cfg.ParsedURL, err)
}
// TODO: Hide secrets in logs
log.Printf("SUCCESS - %s %s (attempt %d/%d) - Response Time: %d ms, Status Code: %d",
// Only log success details during tests to avoid exposing secrets
logIfTest("SUCCESS - %s %s (attempt %d/%d) - Response Time: %d ms, Status Code: %d",
httpMethod, cfg.ParsedURL, currentAttemptNum+1, maxRetryTimes, responseTime.Milliseconds(), resp.StatusCode)
break
}
failureDetails = append(failureDetails, fmt.Sprintf("StatusCode or ResponseRegex mismatch: %d", resp.StatusCode))
log.Printf("FAILED - StatusCode or ResponseRegex mismatch: %d", resp.StatusCode)
if err := resp.Body.Close(); err != nil {
// TODO: Hide secrets in logs
log.Printf("Error closing response body for %s: %v", cfg.ParsedURL, err)
// Only log response body errors during tests to avoid exposing secrets
logIfTest("Error closing response body for %s: %v", cfg.ParsedURL, err)
}
}
endTime := time.Now()
Expand Down
24 changes: 24 additions & 0 deletions internal/checker/utils.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,33 @@
package checker

import (
"log"
"os"
"strings"

"github.com/wcy-dt/ponghub/internal/types/types/chk_result"
)

// isTestMode checks if the current execution is in test mode
func isTestMode() bool {
// Check if any command line arguments contain "test"
for _, arg := range os.Args {
// Check for Go test flags (e.g., -test.v, -test.run, etc.)
if strings.HasPrefix(arg, "-test.") {
return true
}
}

return false
}

// logIfTest logs the message only if we're in test mode
func logIfTest(format string, args ...interface{}) {
if isTestMode() {
log.Printf(format, args...)
}
}

// getTestResult determines the test result based on the success count and actual attempts
func getTestResult(successNum, attemptNum int) chk_result.CheckResult {
switch successNum {
Expand Down
20 changes: 0 additions & 20 deletions internal/common/params/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,26 +39,6 @@ var HTTPMethods = []string{
"OPTIONS",
}

// SensitivePatterns Sensitive environment variable patterns for masking
var SensitivePatterns = []string{
"key",
"secret",
"token",
"password",
"pass",
"pwd",
"auth",
"credential",
"private",
"api_key",
"access",
"jwt",
"bearer",
"signature",
"hash",
"salt",
}

// UserAgents User agent strings for random user agent generation
var UserAgents = LoadUserAgents()

Expand Down
43 changes: 10 additions & 33 deletions internal/common/params/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,15 @@ func (pr *ParameterResolver) resolveSpecialParameter(param string) string {
}
}

// resolveSpecialParameterForDisplay resolves parameters for display with sensitive data masking
func (pr *ParameterResolver) resolveSpecialParameterForDisplay(param string) string {
// resolveSpecialParameterWithSecret resolves parameters for display with sensitive data masking
func (pr *ParameterResolver) resolveSpecialParameterWithSecret(param string) string {
// Handle different types of special parameters
switch {
// Environment variables - mask sensitive values
// Environment variables
case strings.HasPrefix(param, "env(") && strings.HasSuffix(param, ")"):
envVar := param[4 : len(param)-1]
if value := os.Getenv(envVar); value != "" {
return pr.maskSensitiveValue(value, envVar)
return pr.maskSensitiveValue(value)
}
return ""

Expand All @@ -198,41 +198,18 @@ func (pr *ParameterResolver) resolveSpecialParameterForDisplay(param string) str
}
}

// maskSensitiveValue masks sensitive environment variable values
func (pr *ParameterResolver) maskSensitiveValue(value, envVar string) string {
envVarLower := strings.ToLower(envVar)

// Check if this environment variable name suggests it contains sensitive data
for _, pattern := range SensitivePatterns {
if strings.Contains(envVarLower, pattern) {
return pr.maskValue(value)
}
}

// If value looks like a token/key (long alphanumeric string), mask it
if len(value) > 20 && regexp.MustCompile(`^[a-zA-Z0-9+/=-]+$`).MatchString(value) {
return pr.maskValue(value)
}

// Return original value if not considered sensitive
return value
}

// maskValue creates a masked version of a sensitive value
func (pr *ParameterResolver) maskValue(value string) string {
// maskSensitiveValue creates a masked version of a sensitive value
func (pr *ParameterResolver) maskSensitiveValue(value string) string {
if len(value) == 0 {
return value
}

if len(value) <= 4 {
if len(value) <= 6 {
return strings.Repeat("*", len(value))
}

// Show first 2 and last 2 characters, mask the middle
visible := 2
if len(value) < 8 {
visible = 1
}
// Show first 1 and last 1 character, mask the middle
visible := 1

prefix := value[:visible]
suffix := value[len(value)-visible:]
Expand Down Expand Up @@ -359,7 +336,7 @@ func (pr *ParameterResolver) HighlightChanges(originalURL string) (string, []hig
resolved = pr.formatTimeWithPattern(param)
} else {
// Use display version with masking for environment variables
resolved = pr.resolveSpecialParameterForDisplay(param)
resolved = pr.resolveSpecialParameterWithSecret(param)
}

result += resolved
Expand Down
16 changes: 5 additions & 11 deletions internal/common/params/params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,21 +389,15 @@ func TestMaskSensitiveValue(t *testing.T) {
pr := NewParameterResolver()

// Test short value masking
result := pr.maskSensitiveValue("abc", "api_key")
result := pr.maskSensitiveValue("abc")
if result != "***" {
t.Errorf("Short value should be fully masked, got %s", result)
}

// Test longer value masking
result = pr.maskSensitiveValue("secret123456", "password")
if !strings.HasPrefix(result, "se") || !strings.HasSuffix(result, "56") {
t.Errorf("Long value should show first 2 and last 2 chars, got %s", result)
}

// Test non-sensitive value
result = pr.maskSensitiveValue("normal_value", "normal_var")
if result != "normal_value" {
t.Errorf("Non-sensitive value should remain unchanged, got %s", result)
result = pr.maskSensitiveValue("secret123456")
if !strings.HasPrefix(result, "s") || !strings.HasSuffix(result, "6") {
t.Errorf("Long value should show first 1 and last 1 char, got %s", result)
}
}

Expand Down Expand Up @@ -472,7 +466,7 @@ func TestResolveSpecialParameterForDisplay(t *testing.T) {
}(testKey)

// Test that sensitive env vars are masked for display
result := pr.resolveSpecialParameterForDisplay("env(" + testKey + ")")
result := pr.resolveSpecialParameterWithSecret("env(" + testKey + ")")
if result == testValue {
t.Error("Sensitive environment variable should be masked for display")
}
Expand Down
Loading