Compare commits
1 Commits
refactor/a
...
docs/packa
| Author | SHA1 | Date | |
|---|---|---|---|
| ebbf66e76e |
@@ -225,23 +225,6 @@ func ReconcileExpiredCards(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReconcilePayRedirects deletes pay_redirects rows whose ExpiresAt had passed.
|
|
||||||
// Lazy deletion on read (PayRedirect) is the primary path, this sweep only
|
|
||||||
// reclaims tokens nobody ever followed so the table stays bounded.
|
|
||||||
func ReconcilePayRedirects(ctx context.Context) {
|
|
||||||
db := database.GetDB().WithContext(ctx)
|
|
||||||
|
|
||||||
res := db.Where("expires_at < ?", time.Now()).Delete(&models.PayRedirect{})
|
|
||||||
if res.Error != nil {
|
|
||||||
reconcileLog().Error("pay_redirects sweep failed", "error", res.Error)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if res.RowsAffected == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
reconcileLog().Info("swept expired pay_redirects", "count", res.RowsAffected)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReconcileUnshipped finds paid orders older than 24h with no tracking
|
// ReconcileUnshipped finds paid orders older than 24h with no tracking
|
||||||
// number and posts a single Slack reminder. Pure read + notify.
|
// number and posts a single Slack reminder. Pure read + notify.
|
||||||
func ReconcileUnshipped(ctx context.Context) {
|
func ReconcileUnshipped(ctx context.Context) {
|
||||||
|
|||||||
@@ -518,81 +518,3 @@ func seedRequiresActionOrder(t *testing.T, userID uint, piID string, updatedAt t
|
|||||||
}
|
}
|
||||||
return order
|
return order
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestReconcilePayRedirects_DeleteExpiredKeepsLive verifies the predicate
|
|
||||||
// boundary: a row past ExpiresAt is hard-deleted while a row whose ExpiresAt
|
|
||||||
// is still in the future survives. Seeding both sides through GORM keeps the
|
|
||||||
// stored timestamp format identical to the one the sweep binds for time.Now(),
|
|
||||||
// so the comparison is exercised exactly as it runs in production.
|
|
||||||
func TestReconcilePayRedirects_DeleteExpiredKeepsLive(t *testing.T) {
|
|
||||||
testDB := setupTestDB(t)
|
|
||||||
defer func() { _ = os.Remove(testDB) }()
|
|
||||||
defer database.ResetForTesting()
|
|
||||||
|
|
||||||
db := database.GetDB()
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
expired := models.PayRedirect{
|
|
||||||
Token: "tok_expired",
|
|
||||||
URL: "https://example.test/expired",
|
|
||||||
Purpose: models.RedirectPurposeCheckout3DS,
|
|
||||||
CreatedAt: now.Add(-20 * time.Minute),
|
|
||||||
ExpiresAt: now.Add(-10 * time.Minute),
|
|
||||||
}
|
|
||||||
|
|
||||||
live := models.PayRedirect{
|
|
||||||
Token: "tok_live",
|
|
||||||
URL: "https://example.test/live",
|
|
||||||
Purpose: models.RedirectPurposeAddCard,
|
|
||||||
CreatedAt: now,
|
|
||||||
ExpiresAt: now.Add(10 * time.Minute),
|
|
||||||
}
|
|
||||||
if err := db.Create(&expired).Error; err != nil {
|
|
||||||
t.Fatalf("seed expired: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Create(&live).Error; err != nil {
|
|
||||||
t.Fatalf("seed live: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ReconcilePayRedirects(context.Background())
|
|
||||||
|
|
||||||
var remaining []models.PayRedirect
|
|
||||||
if err := db.Find(&remaining).Error; err != nil {
|
|
||||||
t.Fatalf("list remaining: %v", err)
|
|
||||||
}
|
|
||||||
if len(remaining) != 1 {
|
|
||||||
t.Fatalf("want 1 row remaining, got %d", len(remaining))
|
|
||||||
}
|
|
||||||
if remaining[0].Token != "tok_live" {
|
|
||||||
t.Fatalf("wrong row survived: want tok_live, got %q", remaining[0].Token)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReconcilePayRedirects_NoExpiredIsNoOp(t *testing.T) {
|
|
||||||
testDB := setupTestDB(t)
|
|
||||||
defer func() { _ = os.Remove(testDB) }()
|
|
||||||
defer database.ResetForTesting()
|
|
||||||
|
|
||||||
db := database.GetDB()
|
|
||||||
|
|
||||||
live := models.PayRedirect{
|
|
||||||
Token: "tok_live_only",
|
|
||||||
URL: "https://example.test/live",
|
|
||||||
Purpose: models.RedirectPurposeCheckout3DS,
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
|
||||||
}
|
|
||||||
if err := db.Create(&live).Error; err != nil {
|
|
||||||
t.Fatalf("seed live: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ReconcilePayRedirects(context.Background())
|
|
||||||
|
|
||||||
var count int64
|
|
||||||
if err := db.Model(&models.PayRedirect{}).Count(&count).Error; err != nil {
|
|
||||||
t.Fatalf("count: %v", err)
|
|
||||||
}
|
|
||||||
if count != 1 {
|
|
||||||
t.Fatalf("want 1 row preserved, got %d", count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -53,17 +52,8 @@ func (h *WebhookHandler) HandleStripe(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// Verify the Stripe signature. Reject anything that doesn't match.
|
// Verify the Stripe signature. Reject anything that doesn't match.
|
||||||
if h.webhookSecret == "" {
|
if h.webhookSecret == "" {
|
||||||
// Fail closed in production. config.validate() requires STRIPE_WEBHOOK_SECRET
|
// No secret configured — log a loud warning but still process in dev.
|
||||||
// in production, so the server should never boot into this state; this is
|
webhookLog().Warn("stripe webhook secret not set; skipping signature verification")
|
||||||
// defense in depth against a misconfigured deploy. Mirrors the Shippo and
|
|
||||||
// Slack handlers, which already refuse to run without their secret.
|
|
||||||
if os.Getenv("ENVIRONMENT") == "production" {
|
|
||||||
webhookLog().Error("stripe webhook secret not set in production; refusing to process event")
|
|
||||||
utils.RespondError(w, http.StatusServiceUnavailable, "WEBHOOK_NOT_CONFIGURED", "webhook verification not configured", nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Development only; warn loudly but still process so local testing works.
|
|
||||||
webhookLog().Warn("stripe webhook secret not set; skipping signature verification (development only)")
|
|
||||||
} else {
|
} else {
|
||||||
sig := r.Header.Get("Stripe-Signature")
|
sig := r.Header.Get("Stripe-Signature")
|
||||||
if _, err := webhook.ConstructEventWithOptions(body, sig, h.webhookSecret, webhook.ConstructEventOptions{
|
if _, err := webhook.ConstructEventWithOptions(body, sig, h.webhookSecret, webhook.ConstructEventOptions{
|
||||||
@@ -134,20 +124,6 @@ func (h *WebhookHandler) handlePaymentIntentSucceeded(ctx context.Context, event
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Defense in depth: even behind a valid signature, refuse to mark an order
|
|
||||||
// paid unless the PaymentIntent's amount and currency match what we charged.
|
|
||||||
// Under ConvertCart these always match (Amount == order.Total at creation), so
|
|
||||||
// a mismatch means a malformed or unexpected event we should not trust.
|
|
||||||
if pi.Amount != int64(order.Total) {
|
|
||||||
webhookLog().Error("payment intent amount mismatch; refusing to mark paid", "order_id", orderIDStr, "pi", pi.ID, "pi_amount", pi.Amount, "order_total", order.Total)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if pi.Currency != "" && pi.Currency != stripe.CurrencyUSD {
|
|
||||||
webhookLog().Error("payment intent currency mismatch; refusing to mark paid",
|
|
||||||
"order_id", orderIDStr, "pi", pi.ID, "currency", string(pi.Currency))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
txErr := db.Transaction(func(tx *gorm.DB) error {
|
txErr := db.Transaction(func(tx *gorm.DB) error {
|
||||||
if err := tx.Model(&order).Updates(map[string]any{
|
if err := tx.Model(&order).Updates(map[string]any{
|
||||||
"status": models.OrderStatusPaid,
|
"status": models.OrderStatusPaid,
|
||||||
|
|||||||
@@ -222,38 +222,3 @@ func TestHandlePaymentIntentSucceeded_RequiresActionFlipsToPaid(t *testing.T) {
|
|||||||
t.Fatalf("stripe_payment_id: want %q, got %q", order.StripePaymentID, reloaded.StripePaymentID)
|
t.Fatalf("stripe_payment_id: want %q, got %q", order.StripePaymentID, reloaded.StripePaymentID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHandlePaymentIntentSucceeded_AmountMismatchDoesNotPay(t *testing.T) {
|
|
||||||
testDB, user := setupCartTestDB(t)
|
|
||||||
defer func() { _ = os.Remove(testDB) }()
|
|
||||||
defer database.ResetForTesting()
|
|
||||||
|
|
||||||
order := seedOrderForWebhook(t, user.ID, models.OrderStatusRequiresAction, "pi_test_amount_mismatch")
|
|
||||||
|
|
||||||
// PI claims 1 cent; seed order.Total is 500.
|
|
||||||
pi := map[string]any{
|
|
||||||
"id": order.StripePaymentID,
|
|
||||||
"amount": 1,
|
|
||||||
"metadata": map[string]string{"order_id": fmt.Sprintf("%d", order.ID)},
|
|
||||||
}
|
|
||||||
raw, err := json.Marshal(pi)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("marshal pi: %v", err)
|
|
||||||
}
|
|
||||||
evt := stripe.Event{
|
|
||||||
Type: "payment_intent.succeeded",
|
|
||||||
Data: &stripe.EventData{Raw: raw},
|
|
||||||
}
|
|
||||||
|
|
||||||
h := NewWebhookHandler("", "")
|
|
||||||
h.handlePaymentIntentSucceeded(context.Background(), evt)
|
|
||||||
|
|
||||||
db := database.GetDB()
|
|
||||||
var reloaded models.Order
|
|
||||||
if err := db.First(&reloaded, order.ID).Error; err != nil {
|
|
||||||
t.Fatalf("reloaded order: %v", err)
|
|
||||||
}
|
|
||||||
if reloaded.Status == models.OrderStatusPaid {
|
|
||||||
t.Fatalf("order marked paid despite amount mismatch")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
72
api/main.go
72
api/main.go
@@ -25,25 +25,6 @@ import (
|
|||||||
|
|
||||||
const version = "v0.1.0"
|
const version = "v0.1.0"
|
||||||
|
|
||||||
// everyTick runs fn on its own goroutine every d until ctx is cancelled.
|
|
||||||
// Shared by the reconciler sweeps so the ticker + shutdown plumbing lives in
|
|
||||||
// one place. ReconcileUnshipped intentionally does not use it, it needs a
|
|
||||||
// staggered warm-up run before its first tick.
|
|
||||||
func everyTick(ctx context.Context, d time.Duration, fn func(context.Context)) {
|
|
||||||
go func() {
|
|
||||||
ticker := time.NewTicker(d)
|
|
||||||
defer ticker.Stop()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ticker.C:
|
|
||||||
fn(ctx)
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
observability.InitLogger()
|
observability.InitLogger()
|
||||||
middleware.SetBuildInfo(version)
|
middleware.SetBuildInfo(version)
|
||||||
@@ -125,8 +106,20 @@ func main() {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Catch orders charged but not recorded due to a crash. Every 5 minutes
|
// Start reconciliation job. runs every 5 minutes to catch any orders
|
||||||
everyTick(ctx, 5*time.Minute, handlers.ReconcileOrders)
|
// that were charged but not recorded due to a crash.
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(5 * time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
handlers.ReconcileOrders(ctx)
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
select {
|
select {
|
||||||
@@ -149,18 +142,33 @@ func main() {
|
|||||||
|
|
||||||
// Sweep saved cards whose retention deadline elapsed. Read paths filter
|
// Sweep saved cards whose retention deadline elapsed. Read paths filter
|
||||||
// expired rows from query results, so this sweeper only drives the Stripe
|
// expired rows from query results, so this sweeper only drives the Stripe
|
||||||
// detach + audit + physical row delete asynchronously. Hourly.
|
// detach + audit + physical row delete asynchronously.
|
||||||
everyTick(ctx, 1*time.Hour, handlers.ReconcileExpiredCards)
|
go func() {
|
||||||
|
ticker := time.NewTicker(1 * time.Hour)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
handlers.ReconcileExpiredCards(ctx)
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// Flip abandoned 3DS orders to failed. Every 15 minutes.
|
go func() {
|
||||||
threshold := time.Duration(cfg.Abandoned3DSThresholdMinutes) * time.Minute
|
ticker := time.NewTicker(15 * time.Minute)
|
||||||
everyTick(ctx, 15*time.Minute, func(ctx context.Context) {
|
defer ticker.Stop()
|
||||||
handlers.ReconcileStale3DSOrders(ctx, threshold)
|
threshold := time.Duration(cfg.Abandoned3DSThresholdMinutes) * time.Minute
|
||||||
})
|
for {
|
||||||
|
select {
|
||||||
// Sweep expired pay_redirects rows so the table stays bounded. Lazy delete
|
case <-ticker.C:
|
||||||
// on read is the primary path; this only reclaims tokens nobody follows.
|
handlers.ReconcileStale3DSOrders(ctx, threshold)
|
||||||
everyTick(ctx, 10*time.Minute, handlers.ReconcilePayRedirects)
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
log.Println("API server started. Press Ctrl+C to shutdown.")
|
log.Println("API server started. Press Ctrl+C to shutdown.")
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,6 @@ func (c *Config) validate() error {
|
|||||||
{"JWT_SECRET", c.JWTSecret},
|
{"JWT_SECRET", c.JWTSecret},
|
||||||
{"STRIPE_SECRET_KEY", c.StripeSecretKey},
|
{"STRIPE_SECRET_KEY", c.StripeSecretKey},
|
||||||
{"AUTH_FINGERPRINT_KEY", c.AuthFingerprintKey},
|
{"AUTH_FINGERPRINT_KEY", c.AuthFingerprintKey},
|
||||||
{"STRIPE_WEBHOOK_SECRET", c.StripeWebhookSecret},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var missing []string
|
var missing []string
|
||||||
|
|||||||
Reference in New Issue
Block a user