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,193 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
)
func TestPortalKeyringMySQL(t *testing.T) {
dsn := os.Getenv("PORTAL_TEST_DSN")
if dsn == "" {
t.Skip("PORTAL_TEST_DSN isolated schema008 required")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal("database configuration invalid")
}
defer db.Close()
// Never run the fixture against a named business database.
var database string
if err = db.QueryRow("SELECT DATABASE()").Scan(&database); err != nil || !strings.HasPrefix(database, "license_portal_test_") {
t.Fatal("dedicated portal test database required")
}
insert := func(q string, args ...any) int64 {
t.Helper()
r, e := db.Exec(q, args...)
if e != nil {
t.Fatal("fixture SQL failed")
}
id, _ := r.LastInsertId()
return id
}
suffix := fmt.Sprint(time.Now().UnixNano())
admin := insert("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@portal.test", "unused")
owner := insert("INSERT INTO customers(name,contact_email) VALUES(?,'portal@test.invalid')", suffix)
other := insert("INSERT INTO customers(name,contact_email) VALUES(?,'other@test.invalid')", suffix+"other")
product := insert("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, "PortalProduct")
otherProduct := insert("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", "HiddenProduct")
old, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
next, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
pub := func(k *ecdsa.PrivateKey) string {
d, _ := x509.MarshalPKIXPublicKey(&k.PublicKey)
return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: d}))
}
router := func(k *ecdsa.PrivateKey, id string) *gin.Engine {
d, _ := x509.MarshalECPrivateKey(k)
private := string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: d}))
ring := &Keyring{Current: id, Keys: []VerificationKey{{KeyID: "old", PublicKeyPEM: pub(old)}, {KeyID: "new", PublicKeyPEM: pub(next)}}}
if e := ring.Validate(private); e != nil {
t.Fatal(e)
}
r := NewRouter()
RegisterBusinessWithKeyring(r, db, private, ring)
return r
}
r := router(old, "old")
request := func(path string, body any, idem string) *httptest.ResponseRecorder {
b, _ := json.Marshal(body)
q := httptest.NewRequest("POST", path, strings.NewReader(string(b)))
q.Header.Set("Content-Type", "application/json")
q.Header.Set("Idempotency-Key", idem)
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
return w
}
type fixture struct {
instance, secret, key string
license int64
}
create := func(customer, prod int64, label string) fixture {
raw := make([]byte, 32)
rand.Read(raw)
key := hex.EncodeToString(raw[:16])
license := insert("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", key, customer, prod, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix+label, admin)
secret := make([]byte, 32)
rand.Read(secret)
sum := sha256.Sum256(secret)
id, _ := newInstanceID()
insert("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", id, license, customer, prod, sum[:], admin)
return fixture{id, base64.RawURLEncoding.EncodeToString(secret), key, license}
}
first := create(owner, product, "first")
hidden := create(other, otherProduct, "hidden")
activate := func(f fixture) *httptest.ResponseRecorder {
return request("/api/v1/activation/instances/"+f.instance, map[string]string{"secret": f.secret, "license_key": f.key}, "activate")
}
envelopes := []json.RawMessage{}
collect := func(w *httptest.ResponseRecorder, key string) {
t.Helper()
if w.Code != 200 && w.Code != 201 {
t.Fatalf("issuance status %d", w.Code)
}
var out struct {
Data struct {
Certificate json.RawMessage `json:"certificate"`
Payload json.RawMessage `json:"payload"`
Signature string `json:"signature"`
} `json:"data"`
}
if json.Unmarshal(w.Body.Bytes(), &out) != nil {
t.Fatal("invalid response")
}
envelope := out.Data.Certificate
if len(envelope) == 0 {
var err error
envelope, err = json.Marshal(map[string]any{"payload": json.RawMessage(out.Data.Payload), "signature": out.Data.Signature})
if err != nil {
t.Fatal("invalid heartbeat envelope")
}
}
if !strings.Contains(string(envelope), `"key_id":"`+key+`"`) {
t.Fatal("wrong signing key")
}
envelopes = append(envelopes, envelope)
}
initial := activate(first)
collect(initial, "old")
beat := func(f fixture, idem string) *httptest.ResponseRecorder {
return request("/api/v1/instances/"+f.instance+"/heartbeat", map[string]string{"secret": f.secret, "client_time": time.Now().UTC().Format(time.RFC3339Nano)}, idem)
}
collect(beat(first, "old-beat"), "old")
r = router(next, "new")
replay := activate(first)
collect(replay, "old")
var a, b any
json.Unmarshal(initial.Body.Bytes(), &a)
json.Unmarshal(replay.Body.Bytes(), &b)
aa, _ := json.Marshal(a)
bb, _ := json.Marshal(b)
if string(aa) != string(bb) {
t.Fatal("rotation changed historical replay")
}
second := create(owner, product, "second")
collect(activate(second), "new")
collect(beat(second, "new-beat"), "new")
// Recreate router after rotation with same private material: application re-registration, not OS process restart.
r = router(next, "new")
collect(activate(second), "new")
insert("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,'v1',?,?,1,?)", product, strings.Repeat("a", 64)+".bin", strings.Repeat("a", 64), admin)
insert("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,'hidden-version',?,?,1,?)", otherProduct, strings.Repeat("b", 64)+".bin", strings.Repeat("b", 64), admin)
snapshot := func(f fixture, path string) *httptest.ResponseRecorder {
return request(path, map[string]string{"instance_id": f.instance, "secret": f.secret}, "")
}
w := snapshot(first, "/api/v1/portal/snapshot?page_size=1")
if w.Code != 200 || strings.Contains(w.Body.String(), "HiddenProduct") || strings.Contains(w.Body.String(), "hidden-version") || strings.Contains(w.Body.String(), first.secret) || strings.Contains(w.Body.String(), "secret_hash") {
t.Fatal("portal isolation failed")
}
if len(w.Result().Cookies()) != 0 || w.Header().Get("Cache-Control") != "private, no-store" {
t.Fatal("portal cookie/cache boundary")
}
if w = snapshot(first, "/api/v1/portal/snapshot?customer_id="+fmt.Sprint(other)); w.Code != 400 {
t.Fatal("customer override accepted")
}
bad := first
bad.instance = hidden.instance
if w = snapshot(bad, "/api/v1/portal/snapshot"); w.Code != 403 {
t.Fatal("cross-instance credentials accepted")
}
if w = snapshot(first, "/api/v1/portal/snapshot?page=10001"); w.Code != 400 {
t.Fatal("unbounded pagination")
}
var n int
if db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='portal.viewed'").Scan(&n) != nil || n < 1 {
t.Fatal("portal audit missing")
}
path := filepath.Join(t.TempDir(), "public-vectors.json")
vectors, _ := json.Marshal(map[string]any{"keys": []VerificationKey{{KeyID: "old", PublicKeyPEM: pub(old)}, {KeyID: "new", PublicKeyPEM: pub(next)}}, "envelopes": envelopes})
if os.WriteFile(path, vectors, 0600) != nil {
t.Fatal("vectors unavailable")
}
output, e := exec.Command("node", "--input-type=module", "-e", `import fs from 'node:fs';import {verifyEnvelope} from '../../../client/verify.mjs';const v=JSON.parse(fs.readFileSync(process.argv[1]));for(const e of v.envelopes)verifyEnvelope(e,v.keys);console.log('MySQL-issued v2 old/new/replay envelopes verified');`, path).CombinedOutput()
if e != nil {
t.Fatalf("Node validation failed: %s", output)
}
t.Log(string(output))
}