feat: implement license platform business flows and delivery tooling
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation.

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-09 15:33:22 +08:00
parent 3ab651d3a8
commit 54c318c615
142 changed files with 11105 additions and 178 deletions

View File

@@ -0,0 +1,293 @@
package httpapi
import (
"crypto/tls"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
func TestBusinessMySQLIntegration(t *testing.T) {
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN is not set")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = db.Ping(); err != nil {
t.Fatal(err)
}
for _, table := range []string{"instance_state_operations", "heartbeat_operations", "activation_operations", "license_instances", "order_operations", "offline_orders"} {
if _, err = db.Exec("DELETE FROM " + table); err != nil {
t.Fatal(err)
}
}
if _, err = db.Exec("DELETE FROM audit_events"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM license_operations"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM licenses"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM sessions"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM products"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM customers"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM admins"); err != nil {
t.Fatal(err)
}
hash, err := bcrypt.GenerateFromPassword([]byte("Integration-Test-Password-2026!"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", "integration", "integration@example.test", string(hash)); err != nil {
t.Fatal(err)
}
r := NewRouter()
RegisterBusiness(r, db)
request := func(method, path, body, cookie string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if strings.HasPrefix(path, "/api/v1/auth/login") {
req.TLS = &tls.ConnectionState{}
}
if cookie != "" {
req.Header.Set("Cookie", cookie)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
if w := request("GET", "/api/v1/customers", "", ""); w.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated code=%d body=%s", w.Code, w.Body)
}
w := request("POST", "/api/v1/auth/login", `{"username":"integration","password":"Integration-Test-Password-2026!"}`, "")
if w.Code != 200 {
t.Fatalf("login code=%d body=%s", w.Code, w.Body)
}
cookie := w.Result().Cookies()[0]
if cookie.Name != "lp_session" || !cookie.HttpOnly || !cookie.Secure {
t.Fatalf("insecure session cookie: %+v", cookie)
}
w = request("POST", "/api/v1/customers", `{"name":"Integration customer","contact_email":"customer@example.test"}`, cookie.Name+"="+cookie.Value)
if w.Code != 201 {
t.Fatalf("create customer code=%d body=%s", w.Code, w.Body)
}
var customerID, productID uint64
if err = db.QueryRow("SELECT id FROM customers ORDER BY id DESC LIMIT 1").Scan(&customerID); err != nil {
t.Fatal(err)
}
w = request("GET", "/api/v1/customers?page=1&page_size=20", "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Integration customer") {
t.Fatalf("list customers code=%d body=%s", w.Code, w.Body)
}
w = request("POST", "/api/v1/products", `{"code":"integration-product","name":"Integration Product","description":"probe"}`, cookie.Name+"="+cookie.Value)
if w.Code != 201 {
t.Fatalf("create product code=%d body=%s", w.Code, w.Body)
}
if err = db.QueryRow("SELECT id FROM products ORDER BY id DESC LIMIT 1").Scan(&productID); err != nil {
t.Fatal(err)
}
w = request("GET", "/api/v1/products", "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), "integration-product") {
t.Fatalf("list products code=%d body=%s", w.Code, w.Body)
}
issueBody := fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"starts_at":"2026-09-30T00:00:00Z","expires_at":"2027-09-30T00:00:00Z"}`, customerID, productID)
w = request("POST", "/api/v1/licenses", issueBody, "")
if w.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated issue code=%d", w.Code)
}
requestWithKey := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/v1/licenses", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "integration-issue-1")
req.AddCookie(cookie)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
w = requestWithKey(issueBody)
if w.Code != http.StatusCreated {
t.Fatalf("issue code=%d body=%s", w.Code, w.Body)
}
var first struct {
Data licenseRecord `json:"data"`
}
if err = json.Unmarshal(w.Body.Bytes(), &first); err != nil {
t.Fatal(err)
}
w = requestWithKey(issueBody)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) || !strings.Contains(w.Body.String(), first.Data.LicenseKey) {
t.Fatalf("idempotent replay code=%d body=%s", w.Code, w.Body)
}
var licenseCount, auditCount int
if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil {
t.Fatal(err)
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='license.issued'").Scan(&auditCount); err != nil {
t.Fatal(err)
}
if licenseCount != 1 || auditCount != 1 {
t.Fatalf("expected single license/audit; got %d/%d", licenseCount, auditCount)
}
w = request("GET", "/api/v1/licenses?page=1&page_size=20", "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"active"`) {
t.Fatalf("list licenses code=%d body=%s", w.Code, w.Body)
}
w = request("GET", fmt.Sprintf("/api/v1/licenses/%d", first.Data.ID), "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), first.Data.LicenseKey) {
t.Fatalf("license detail code=%d body=%s", w.Code, w.Body)
}
operation := func(method, path, body, key string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
req.AddCookie(cookie)
out := httptest.NewRecorder()
r.ServeHTTP(out, req)
return out
}
licensePath := func(suffix string) string { return fmt.Sprintf("/api/v1/licenses/%d/%s", first.Data.ID, suffix) }
w = operation("POST", licensePath("renew"), `{"expires_at":"2028-01-01T00:00:00Z"}`, "renew-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"expires_at":"2028-01-01T00:00:00Z"`) {
t.Fatalf("renew code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("renew"), `{"expires_at":"2028-01-01T00:00:00Z"}`, "renew-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) {
t.Fatalf("renew replay code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("renew"), `{"expires_at":"2029-01-01T00:00:00Z"}`, "renew-1")
if w.Code != 409 {
t.Fatalf("renew conflict code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("revoke"), "{}", "revoke-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"revoked"`) {
t.Fatalf("revoke code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("revoke"), "{}", "revoke-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) {
t.Fatalf("revoke replay code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("renew"), `{"expires_at":"2029-01-01T00:00:00Z"}`, "renew-after-revoke")
if w.Code != 400 {
t.Fatalf("renew revoked code=%d body=%s", w.Code, w.Body)
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events").Scan(&auditCount); err != nil {
t.Fatal(err)
}
if auditCount != 3 {
t.Fatalf("audit count after operations=%d", auditCount)
}
w = requestWithKey(fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"starts_at":"bad","expires_at":"2027-01-01T00:00:00Z"}`, customerID, productID))
if w.Code != 400 {
t.Fatalf("invalid dates code=%d body=%s", w.Code, w.Body)
}
w = requestWithKey(strings.Replace(issueBody, "2027-09-30", "2027-10-30", 1))
if w.Code != 409 {
t.Fatalf("changed payload code=%d body=%s", w.Code, w.Body)
}
if _, err = db.Exec("UPDATE admins SET role='viewer' WHERE email='integration@example.test'"); err != nil {
t.Fatal(err)
}
w = requestWithKey(issueBody)
if w.Code != 403 {
t.Fatalf("viewer issue code=%d body=%s", w.Code, w.Body)
}
if _, err = db.Exec("UPDATE admins SET role='admin' WHERE email='integration@example.test'"); err != nil {
t.Fatal(err)
}
// A new key must still validate current master-data state.
if _, err = db.Exec("UPDATE products SET active=0 WHERE id=?", productID); err != nil {
t.Fatal(err)
}
newKeyRequest := func(key string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/v1/licenses", strings.NewReader(issueBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
req.AddCookie(cookie)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
w = newKeyRequest("inactive-product")
if w.Code != 400 {
t.Fatalf("inactive product code=%d body=%s", w.Code, w.Body)
}
if _, err = db.Exec("UPDATE products SET active=1 WHERE id=?", productID); err != nil {
t.Fatal(err)
}
// Inject a test-only audit failure to prove issuance rolls back atomically.
if _, err = db.Exec("CREATE TRIGGER integration_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='integration audit failure'"); err != nil {
t.Fatal(err)
}
w = newKeyRequest("audit-failure")
_, dropErr := db.Exec("DROP TRIGGER integration_audit_failure")
if dropErr != nil {
t.Fatal(dropErr)
}
if w.Code != 500 {
t.Fatalf("audit failure code=%d body=%s", w.Code, w.Body)
}
if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil {
t.Fatal(err)
}
if licenseCount != 1 {
t.Fatalf("audit failure left %d licenses", licenseCount)
}
results := make(chan *httptest.ResponseRecorder, 2)
for i := 0; i < 2; i++ {
go func() { results <- newKeyRequest("concurrent-issue") }()
}
created, replayed := 0, 0
for i := 0; i < 2; i++ {
response := <-results
switch response.Code {
case 201:
created++
case 200:
replayed++
default:
t.Fatalf("concurrent issue code=%d body=%s", response.Code, response.Body)
}
}
if created != 1 || replayed != 1 {
t.Fatalf("concurrent created/replayed=%d/%d", created, replayed)
}
if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil {
t.Fatal(err)
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events").Scan(&auditCount); err != nil {
t.Fatal(err)
}
if licenseCount != 2 || auditCount != 4 {
t.Fatalf("concurrent license/audit=%d/%d", licenseCount, auditCount)
}
t.Run("orders", func(t *testing.T) { testOrdersMySQL(t, db, r, cookie, customerID, productID) })
t.Run("activation", func(t *testing.T) { testActivationMySQL(t, db, cookie) })
w = request("POST", "/api/v1/auth/logout", "", cookie.Name+"="+cookie.Value)
if w.Code != http.StatusNoContent {
t.Fatalf("logout code=%d", w.Code)
}
w = request("GET", "/api/v1/me", "", cookie.Name+"="+cookie.Value)
if w.Code != http.StatusUnauthorized {
t.Fatalf("revoked session code=%d", w.Code)
}
}