Files
yhy-mager/backend/internal/httpapi/purchase_test.go
xiewenjun cfcc9b386b
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-15 17:33:52 +08:00

376 lines
15 KiB
Go

package httpapi
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"database/sql/driver"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"io"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
type purchaseStep struct {
sql string
rows [][]driver.Value
args func([]driver.NamedValue) bool
err error
}
type purchaseTestDB struct {
t *testing.T
steps []purchaseStep
commits int
}
type purchaseDriver struct{ db *purchaseTestDB }
func (d purchaseDriver) Open(string) (driver.Conn, error) { return d.db, nil }
func (d *purchaseTestDB) Prepare(string) (driver.Stmt, error) { return nil, errors.New("unsupported") }
func (d *purchaseTestDB) Close() error { return nil }
func (d *purchaseTestDB) Begin() (driver.Tx, error) { return d, nil }
func (d *purchaseTestDB) Commit() error { d.commits++; return nil }
func (d *purchaseTestDB) Rollback() error { return nil }
func (d *purchaseTestDB) next(q string, args []driver.NamedValue) purchaseStep {
d.t.Helper()
if len(d.steps) == 0 {
d.t.Fatalf("unexpected SQL: %s", q)
}
s := d.steps[0]
d.steps = d.steps[1:]
if !strings.Contains(q, s.sql) {
d.t.Fatalf("SQL %s missing %s", q, s.sql)
}
if s.args != nil && !s.args(args) {
d.t.Fatalf("SQL argument assertion failed for %s", s.sql)
}
return s
}
func (d *purchaseTestDB) QueryContext(_ context.Context, q string, a []driver.NamedValue) (driver.Rows, error) {
s := d.next(q, a)
if s.err != nil {
return nil, s.err
}
return &purchaseRows{rows: s.rows}, nil
}
func (d *purchaseTestDB) ExecContext(_ context.Context, q string, a []driver.NamedValue) (driver.Result, error) {
s := d.next(q, a)
return purchaseResult{}, s.err
}
type purchaseResult struct{}
func (purchaseResult) LastInsertId() (int64, error) { return 42, nil }
func (purchaseResult) RowsAffected() (int64, error) { return 1, nil }
type purchaseRows struct{ rows [][]driver.Value }
func (r *purchaseRows) Columns() []string {
n := 1
if len(r.rows) > 0 {
n = len(r.rows[0])
}
out := make([]string, n)
for i := range out {
out[i] = fmt.Sprint(i)
}
return out
}
func (r *purchaseRows) Close() error { return nil }
func (r *purchaseRows) Next(v []driver.Value) error {
if len(r.rows) == 0 {
return io.EOF
}
copy(v, r.rows[0])
r.rows = r.rows[1:]
return nil
}
var purchaseDriverSeq atomic.Uint64
func purchaseDB(t *testing.T, steps ...purchaseStep) (*sql.DB, *purchaseTestDB) {
t.Helper()
d := &purchaseTestDB{t: t, steps: steps}
name := fmt.Sprintf("purchase-%d", purchaseDriverSeq.Add(1))
sql.Register(name, purchaseDriver{d})
db, e := sql.Open(name, "")
if e != nil {
t.Fatal(e)
}
db.SetMaxOpenConns(1)
t.Cleanup(func() {
db.Close()
if len(d.steps) != 0 {
t.Errorf("unconsumed SQL steps: %d", len(d.steps))
}
})
return db, d
}
func one(v ...driver.Value) [][]driver.Value { return [][]driver.Value{v} }
func scopeStep() purchaseStep {
return purchaseStep{sql: "SELECT pc.id FROM purchase_credentials", rows: one(int64(1))}
}
func purchaseDirect(a *BusinessAPI, path, body string, handler gin.HandlerFunc) *httptest.ResponseRecorder {
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("purchase_scope", purchaseScope{1, 2, 3, 4})
c.Header("Cache-Control", "no-store")
})
r.POST(path, handler)
req := httptest.NewRequest("POST", path, strings.NewReader(body))
req.Header.Set("Idempotency-Key", "attempt-1")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestPurchaseBearerAndAdminBoundary(t *testing.T) {
r := paymentTestEngine(nil, nil)
for _, path := range []string{"/api/v1/client/plans", "/api/v1/client/purchases", "/api/v1/client/purchases/status", "/api/v1/client/purchases/claim"} {
for _, auth := range []string{"", "Bearer broken", "Basic admin", "Bearer " + strings.Repeat("ab", 31)} {
req := httptest.NewRequest("POST", path, strings.NewReader("{}"))
req.Header.Set("Authorization", auth)
req.Header.Set("Cookie", "lp_session=admin")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != 401 || w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("%s: status=%d", path, w.Code)
}
}
}
for _, tc := range []struct{ method, path string }{{"GET", "/api/v1/payment-plans"}, {"POST", "/api/v1/payment-plans"}, {"PUT", "/api/v1/payment-plans/1"}, {"GET", "/api/v1/purchase-credentials"}, {"POST", "/api/v1/purchase-credentials"}, {"PUT", "/api/v1/purchase-credentials/1"}} {
req := httptest.NewRequest(tc.method, tc.path, nil)
req.Header.Set("Origin", "https://foreign.invalid")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != 403 || w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("admin boundary %s status=%d", tc.path, w.Code)
}
req = httptest.NewRequest(tc.method, tc.path, nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != 401 {
t.Fatalf("admin auth %s status=%d", tc.path, w.Code)
}
}
}
func TestPurchaseBearerScopedHash(t *testing.T) {
raw := bytes.Repeat([]byte{7}, 32)
sum := sha256.Sum256(raw)
db, _ := purchaseDB(t, purchaseStep{sql: "pc.token_hash=? AND pc.enabled=1", rows: one(int64(1), int64(2), int64(3), int64(4)), args: func(args []driver.NamedValue) bool { return bytes.Equal(args[0].Value.([]byte), sum[:]) }})
a := &BusinessAPI{db: db}
r := gin.New()
r.POST("/", a.purchaseAuthenticated, func(c *gin.Context) {
s := scopeOf(c)
if s.Customer != 2 || s.Product != 3 || s.Actor != 4 {
t.Fatal("scope mismatch")
}
if _, ok := c.Get("admin_id"); ok {
t.Fatal("escalated admin context")
}
c.Status(204)
})
req := httptest.NewRequest("POST", "/", nil)
req.Header.Set("Authorization", "Bearer "+hex.EncodeToString(raw))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != 204 {
t.Fatal(w.Code)
}
}
func TestPurchaseInputAndEncryptionGate(t *testing.T) {
a := &BusinessAPI{}
for _, body := range []string{`{}`, `{"plan_id":1,"plan_version":1,"installation_id":"bad id","channel":"alipay"}`, `{"plan_id":1,"plan_version":1,"installation_id":"install","channel":"cash"}`} {
w := purchaseDirect(a, "/", body, a.clientCreatePurchase)
if w.Code != 400 {
t.Fatal(w.Code)
}
}
body := `{"plan_id":1,"plan_version":1,"installation_id":"install","channel":"alipay"}`
for _, n := range []int{0, 16, 24, 31, 33} {
a.credentialEncryptionKey = make([]byte, n)
w := purchaseDirect(a, "/", body, a.clientCreatePurchase)
if w.Code != 503 || !strings.Contains(w.Body.String(), "credentials_unavailable") {
t.Fatal(w.Code)
}
}
}
func TestPurchaseIdempotencyAndPlanVersion(t *testing.T) {
body := `{"plan_id":1,"plan_version":1,"installation_id":"install","channel":"alipay"}`
for _, mode := range []string{"idempotency", "version", "disabled", "scope"} {
t.Run(mode, func(t *testing.T) {
steps := []purchaseStep{scopeStep()}
if mode == "scope" {
steps[0].rows = nil
} else {
old := purchaseStep{sql: "SELECT order_id,request_fingerprint"}
if mode == "idempotency" {
old.rows = one(int64(8), []byte("different"))
}
steps = append(steps, old)
if mode != "idempotency" {
steps = append(steps, purchaseStep{sql: "FROM payment_plans WHERE id=? AND product_id=? FOR UPDATE", rows: one(int64(1), int64(3), "basic", "Basic", int64(100), "CNY", int64(30), mode != "disabled", int64(2)), args: func(a []driver.NamedValue) bool { return a[1].Value == int64(3) }})
}
}
db, _ := purchaseDB(t, steps...)
a := &BusinessAPI{db: db, credentialEncryptionKey: make([]byte, 32)}
w := purchaseDirect(a, "/", body, a.clientCreatePurchase)
want := "plan_version_conflict"
if mode == "idempotency" {
want = "idempotency_conflict"
}
if mode == "disabled" {
want = "plan_disabled"
}
if mode == "scope" {
want = "invalid_purchase_credential"
}
if !strings.Contains(w.Body.String(), want) {
t.Fatalf("status=%d expected code=%s", w.Code, want)
}
})
}
}
func TestPurchaseLookupInstallationIsolation(t *testing.T) {
for _, body := range []string{`{"order_no":"01234567890123456789012345678901","installation_id":"wrong-install"}`, `{"idempotency_key":"attempt-1","installation_id":"wrong-install"}`} {
db, _ := purchaseDB(t, purchaseStep{sql: "WHERE cp.credential_id=? AND cp.installation_id=?", args: func(a []driver.NamedValue) bool { return a[0].Value == int64(1) && a[1].Value == "wrong-install" }})
a := &BusinessAPI{db: db}
w := purchaseDirect(a, "/", body, a.clientPurchaseStatus)
if w.Code != 404 {
t.Fatal(w.Code)
}
}
}
func TestPurchaseClaimCreateAndRecover(t *testing.T) {
key := bytes.Repeat([]byte{9}, 32)
var savedID string
var savedCipher []byte
body := `{"order_no":"01234567890123456789012345678901","installation_id":"install"}`
lookup := func() purchaseStep {
return purchaseStep{sql: "WHERE cp.credential_id=? AND cp.installation_id=?", rows: one(int64(42))}
}
common := func() []purchaseStep {
return []purchaseStep{lookup(), scopeStep(), {sql: "FROM offline_orders", rows: one("issued", int64(6))}, {sql: "SELECT status FROM payment_orders", rows: one("paid")}, {sql: "FROM licenses", rows: one("license-test", "active", time.Now().Add(24*time.Hour))}}
}
steps := common()
steps = append(steps, purchaseStep{sql: "SELECT instance_id FROM client_purchases", rows: one(nil)}, purchaseStep{sql: "FROM license_instances"}, purchaseStep{sql: "INSERT INTO license_instances", args: func(a []driver.NamedValue) bool {
savedID = a[0].Value.(string)
savedCipher = append([]byte(nil), a[6].Value.([]byte)...)
return len(a[4].Value.([]byte)) == 32
}}, purchaseStep{sql: "UPDATE client_purchases"}, purchaseStep{sql: "purchase.claimed"})
db, d := purchaseDB(t, steps...)
a := &BusinessAPI{db: db, credentialEncryptionKey: key}
w := purchaseDirect(a, "/", body, a.clientPurchaseClaim)
if w.Code != 200 {
t.Fatalf("claim status=%d", w.Code)
}
var first struct {
Data struct {
Instance string `json:"instance_id"`
Secret string `json:"secret"`
License int `json:"license_id"`
}
}
if json.Unmarshal(w.Body.Bytes(), &first) != nil || first.Data.Instance != savedID || first.Data.License != 6 {
t.Fatal("claim response mismatch")
}
raw, e := base64.RawURLEncoding.DecodeString(first.Data.Secret)
if e != nil || len(raw) != 32 || bytes.Contains(savedCipher, []byte(first.Data.Secret)) {
t.Fatal("invalid retained credential")
}
steps = common()
steps = append(steps, purchaseStep{sql: "SELECT instance_id FROM client_purchases", rows: one(savedID)}, purchaseStep{sql: "FROM license_instances", rows: one(savedID, savedCipher, "activated", "none")}, purchaseStep{sql: "purchase.claimed"})
d.steps = steps
w = purchaseDirect(a, "/", body, a.clientPurchaseClaim)
if w.Code != 200 {
t.Fatalf("reclaim status=%d", w.Code)
}
var response struct{ Data map[string]any }
json.Unmarshal(w.Body.Bytes(), &response)
if response.Data["instance_id"] != first.Data.Instance || response.Data["secret"] != first.Data.Secret || d.commits != 2 {
t.Fatal("claim did not recover same instance and secret")
}
}
func TestPurchaseClaimUnpaid(t *testing.T) {
body := `{"order_no":"01234567890123456789012345678901","installation_id":"install"}`
db, d := purchaseDB(t, purchaseStep{sql: "WHERE cp.credential_id", rows: one(int64(42))}, scopeStep(), purchaseStep{sql: "FROM offline_orders", rows: one("pending_payment", nil)})
a := &BusinessAPI{db: db, credentialEncryptionKey: make([]byte, 32)}
w := purchaseDirect(a, "/", body, a.clientPurchaseClaim)
if w.Code != 409 || d.commits != 0 {
t.Fatal("unpaid claim accepted")
}
}
func TestPaymentPlanValidation(t *testing.T) {
p := paymentPlan{ProductID: 1, Code: "basic", Name: "基础套餐", AmountCents: 1, Currency: "CNY", LicenseDays: 30}
if !validPlan(p) {
t.Fatal("valid plan rejected")
}
for _, change := range []func(*paymentPlan){func(p *paymentPlan) { p.Currency = "USD" }, func(p *paymentPlan) { p.LicenseDays = 0 }, func(p *paymentPlan) { p.LicenseDays = 3651 }, func(p *paymentPlan) { p.AmountCents = 0 }, func(p *paymentPlan) { p.Code = "bad code" }} {
bad := p
change(&bad)
if validPlan(bad) {
t.Fatal("invalid plan accepted")
}
}
}
func TestPurchaseClaimRejectsInactiveInstance(t *testing.T) {
for _, state := range []struct{ status, freeze string }{{"activated", "frozen"}, {"revoked", "none"}, {"unknown", "none"}} {
t.Run(state.status+state.freeze, func(t *testing.T) {
db, d := purchaseDB(t, purchaseStep{sql: "WHERE cp.credential_id", rows: one(int64(42))}, scopeStep(), purchaseStep{sql: "FROM offline_orders", rows: one("issued", int64(6))}, purchaseStep{sql: "SELECT status FROM payment_orders", rows: one("paid")}, purchaseStep{sql: "FROM licenses", rows: one("license", "active", time.Now().Add(time.Hour))}, purchaseStep{sql: "SELECT instance_id FROM client_purchases", rows: one("instance")}, purchaseStep{sql: "FROM license_instances", rows: one("instance", []byte("cipher"), state.status, state.freeze)})
a := &BusinessAPI{db: db, credentialEncryptionKey: make([]byte, 32)}
w := purchaseDirect(a, "/", `{"order_no":"01234567890123456789012345678901","installation_id":"install"}`, a.clientPurchaseClaim)
if w.Code != 409 || !strings.Contains(w.Body.String(), "authorization_unavailable") || strings.Contains(w.Body.String(), "secret") || d.commits != 0 {
t.Fatal(w.Code, w.Body.String())
}
})
}
}
func TestPurchaseCredentialEnableAudit(t *testing.T) {
for _, auditFail := range []bool{false, true} {
for _, enabled := range []bool{false, true} {
t.Run(fmt.Sprint(auditFail, enabled), func(t *testing.T) {
var auditErr error
if auditFail {
auditErr = errors.New("audit unavailable")
}
db, d := purchaseDB(t, purchaseStep{sql: "SELECT id FROM admins", rows: one(int64(4))}, purchaseStep{sql: "FROM purchase_credentials WHERE id=? FOR UPDATE", rows: one(int64(2), int64(3), "label", !enabled)}, purchaseStep{sql: "UPDATE purchase_credentials SET enabled=?", args: func(a []driver.NamedValue) bool { return a[0].Value == enabled && a[1].Value == int64(1) }}, purchaseStep{sql: "purchase.credential.updated", err: auditErr, args: func(a []driver.NamedValue) bool {
var details map[string]bool
return json.Unmarshal(a[2].Value.([]byte), &details) == nil && details["enabled"] == enabled
}})
a := &BusinessAPI{db: db}
r := gin.New()
r.PUT("/:id", purchaseAdminBoundary, func(c *gin.Context) { c.Set("admin_id", uint64(4)) }, a.updatePurchaseCredential)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("PUT", "/1", strings.NewReader(fmt.Sprintf(`{"enabled":%t}`, enabled))))
want := 200
commits := 1
if auditFail {
want = 503
commits = 0
}
if w.Code != want || d.commits != commits || w.Header().Get("Cache-Control") != "no-store" || strings.Contains(w.Body.String(), "token") {
t.Fatal(w.Code, w.Body.String())
}
})
}
}
for _, body := range []string{`{}`, `{"enabled":null}`, `{"enabled":"false"}`} {
a := &BusinessAPI{}
r := gin.New()
r.PUT("/:id", a.updatePurchaseCredential)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("PUT", "/1", strings.NewReader(body)))
if w.Code != 400 {
t.Fatal(w.Code)
}
}
}