Files
Crussell/backend/startup_checks_test.go
T
popertotsandSisyphus e9b34d0ad6 fix: dev-mock/prod parity + fail-closed config gates — 402 verification, cnon:sca binding validation, refund reconcile parity, SNAPSHOT_ENC_KEY fail-closed, webhook config gates, access-token startup validation, ClientIP validation
- mock: 400->402 for CARD_DECLINED_VERIFICATION_REQUIRED, cnon:sca- tokenize-result binding validated (prefix/amount/deny), RefundPayment exact-amount reconcile parity, ReplayPaymentByKey snapshot sanity, verify_mock_ legacy widening removed, listRefunds zero-time omits begin_time
- main.go: SNAPSHOT_ENC_KEY log.Fatalf in non-mock, webhook key-set-URL-unset log.Fatalf, SQUARE_ACCESS_TOKEN/LOCATION startup validation, empty-env base URL matches 2FA production interpretation
- mw: ClientIP rejects garbage/comma/port XFF values, documented trusted-proxy requirement

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)
2026-08-22 00:34:51 +01:00

180 lines
7.6 KiB
Go

//go:build test
package main
import (
"bytes"
"encoding/base64"
"log"
"os"
"os/exec"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// captureLog redirects the process-wide logger into a buffer for the duration
// of fn and returns what was logged. These startup checks log through the
// global logger, so the tests that use this helper must stay sequential (no
// t.Parallel).
func captureLog(t *testing.T, fn func()) string {
t.Helper()
var buf bytes.Buffer
orig := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(orig)
fn()
return buf.String()
}
// TestCheckSnapshotEncKey_NonFatalBranches pins the surviving non-fatal
// branches of the startup check for SNAPSHOT_ENC_KEY: a valid base64 32-byte
// key logs nothing, and a dev/mock SQUARE_ENVIRONMENT skips the check
// entirely (the warn+plaintext-fallback posture survives ONLY there). The
// fail-closed branches (missing / invalid-base64 / wrong-length key in a
// non-mock env) log.Fatalf and are covered by the subprocess test below.
func TestCheckSnapshotEncKey_NonFatalBranches(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "production")
t.Run("valid_key_logs_nothing", func(t *testing.T) {
t.Setenv("SNAPSHOT_ENC_KEY", base64.StdEncoding.EncodeToString([]byte("12345678901234567890123456789012"))) // 32 bytes
got := captureLog(t, checkSnapshotEncKey)
require.Empty(t, got, "a valid key must not log: %s", got)
})
t.Run("mock_env_skips_check", func(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "mock")
t.Setenv("SNAPSHOT_ENC_KEY", "")
got := captureLog(t, checkSnapshotEncKey)
require.Empty(t, got, "a dev/mock env must skip the check: %s", got)
})
}
// TestCheckSnapshotEncKey_FatalBranch_Exits covers the fail-closed branches:
// in a non-mock environment an unset / invalid-base64 / wrong-length
// SNAPSHOT_ENC_KEY must refuse to start (log.Fatalf → os.Exit) instead of
// logging a CRITICAL warning and storing square_request_snapshot rows (buyer
// PII: email + ccof card tokens) PLAINTEXT at rest. log.Fatalf cannot run
// in-process, so the test re-executes the test binary with a marker env var
// and asserts the subprocess exits non-zero with a FATAL message naming the
// key.
func TestCheckSnapshotEncKey_FatalBranch_Exits(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
t.Setenv("SQUARE_ENVIRONMENT", "production")
switch os.Getenv("SNAPSHOT_ENC_KEY_BRANCH") {
case "MISSING":
t.Setenv("SNAPSHOT_ENC_KEY", "")
case "INVALID_BASE64":
t.Setenv("SNAPSHOT_ENC_KEY", "!!!not-base64!!!")
case "WRONG_LENGTH":
// 16 bytes base64 → not 32 bytes → not AES-256. Built at runtime
// so no secret-shaped literal exists in source.
t.Setenv("SNAPSHOT_ENC_KEY", base64.StdEncoding.EncodeToString([]byte("1234567890123456")))
}
checkSnapshotEncKey()
return
}
for _, tc := range []struct {
name string
branch string
}{
{name: "unset_key_exits", branch: "MISSING"},
{name: "invalid_base64_exits", branch: "INVALID_BASE64"},
{name: "wrong_length_exits", branch: "WRONG_LENGTH"},
} {
t.Run(tc.name, func(t *testing.T) {
cmd := exec.Command(os.Args[0], "-test.run=TestCheckSnapshotEncKey_FatalBranch_Exits")
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1", "SNAPSHOT_ENC_KEY_BRANCH="+tc.branch)
out, err := cmd.CombinedOutput()
require.Error(t, err, "expected the non-mock invalid-key branch to exit (log.Fatalf); output: %s", out)
require.Contains(t, string(out), "SNAPSHOT_ENC_KEY", "the fatal log must name SNAPSHOT_ENC_KEY: %s", out)
require.False(t, strings.Contains(string(out), "unexpected argument"), "the helper must not fail on argument parsing: %s", out)
})
}
}
// TestCheckProxyRateLimitConfig_WarnsWithoutTrustedProxy pins the fail-loud
// warning: a non-mock deployment without TRUST_PROXY_HEADERS collapses every
// per-IP limiter onto the proxy's address, so startup must warn. A dev/mock env
// skips the check.
func TestCheckProxyRateLimitConfig_WarnsWithoutTrustedProxy(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "production")
got := captureLog(t, checkProxyRateLimitConfig)
require.Contains(t, got, "TRUST_PROXY_HEADERS", "a non-mock deployment without TRUST_PROXY_HEADERS must warn: %s", got)
t.Setenv("SQUARE_ENVIRONMENT", "mock")
got = captureLog(t, checkProxyRateLimitConfig)
require.Empty(t, got, "a dev/mock env must skip the check: %s", got)
}
// TestCheckWebhookSignatureKey_NonFatalBranches pins the non-fatal branches of
// the webhook signing-key startup check: both configured → silent; neither →
// CRITICAL. The fatal branches — key-less-with-URL and key-without-URL — are
// covered by the subprocess tests below (log.Fatalf exits the process).
func TestCheckWebhookSignatureKey_NonFatalBranches(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "production")
t.Run("both_configured_silent", func(t *testing.T) {
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "k")
t.Setenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "https://example.com/webhooks")
got := captureLog(t, checkWebhookSignatureKey)
require.Empty(t, got, "both configured must be silent: %s", got)
})
t.Run("neither_configured_critical", func(t *testing.T) {
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "")
t.Setenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "")
got := captureLog(t, checkWebhookSignatureKey)
require.Contains(t, got, "SQUARE_WEBHOOK_SIGNATURE_KEY is not set", "neither configured must log CRITICAL: %s", got)
})
t.Run("mock_env_skips_check", func(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "mock")
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "")
t.Setenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "https://example.com/webhooks")
got := captureLog(t, checkWebhookSignatureKey)
require.Empty(t, got, "a dev/mock env must skip the check: %s", got)
})
}
// TestCheckWebhookSignatureKey_FatalBranch_Exits covers the fail-fast branches
// — a signing key is REQUIRED when a notification URL is configured, and a
// configured key with NO URL is equally fatal (the handler would verify HMACs
// against the public default URL, breaking every genuine event) — both call
// log.Fatalf (os.Exit). That cannot run in-process, so the test re-executes
// the test binary with a marker env var and asserts the subprocess exits
// non-zero with a FATAL message naming the misconfigured variable.
func TestCheckWebhookSignatureKey_FatalBranch_Exits(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
t.Setenv("SQUARE_ENVIRONMENT", "production")
switch os.Getenv("WEBHOOK_BRANCH") {
case "KEY_WITHOUT_URL":
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "k")
t.Setenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "")
default: // URL_WITHOUT_KEY
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "")
t.Setenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "https://example.com/webhooks")
}
checkWebhookSignatureKey()
return
}
for _, tc := range []struct {
name string
branch string
wantIn string
}{
{name: "key_without_url_exits", branch: "KEY_WITHOUT_URL", wantIn: "SQUARE_WEBHOOK_NOTIFICATION_URL"},
{name: "url_without_key_exits", branch: "URL_WITHOUT_KEY", wantIn: "SQUARE_WEBHOOK_SIGNATURE_KEY"},
} {
t.Run(tc.name, func(t *testing.T) {
cmd := exec.Command(os.Args[0], "-test.run=TestCheckWebhookSignatureKey_FatalBranch_Exits")
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1", "WEBHOOK_BRANCH="+tc.branch)
out, err := cmd.CombinedOutput()
require.Error(t, err, "expected the branch to exit (log.Fatalf); output: %s", out)
require.Contains(t, string(out), tc.wantIn, "the fatal log must name the misconfigured variable: %s", out)
require.False(t, strings.Contains(string(out), "unexpected argument"), "the helper must not fail on argument parsing: %s", out)
})
}
}