Files
yhy-mager/backend/internal/httpapi/keyring_test.go
xiewenjun 54c318c615
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: implement license platform business flows and delivery tooling
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>
2026-10-09 15:33:22 +08:00

88 lines
4.5 KiB
Go

package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
func TestKeyringCrossLanguageRotation(t *testing.T) {
old, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
current, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
public := func(k *ecdsa.PrivateKey) string {
der, _ := x509.MarshalPKIXPublicKey(&k.PublicKey)
return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))
}
der, _ := x509.MarshalECPrivateKey(current)
private := string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}))
ring := Keyring{Current: "new", Keys: []VerificationKey{{KeyID: "old", PublicKeyPEM: public(old)}, {KeyID: "new", PublicKeyPEM: public(current)}}}
if err := ring.Validate(private); err != nil {
t.Fatal(err)
}
bad := ring
bad.Keys = append([]VerificationKey(nil), ring.Keys...)
for i := range bad.Keys {
if bad.Keys[i].KeyID == "new" {
bad.Keys[i].Revoked = true
}
}
if bad.Validate(private) == nil {
t.Fatal("revoked current accepted")
}
if ring.Validate(string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: func() []byte { d, _ := x509.MarshalECPrivateKey(old); return d }()}))) == nil {
t.Fatal("mismatch accepted")
}
now := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
id := "00000000-0000-4000-8000-000000000001"
sign := func(k *ecdsa.PrivateKey, keyID, kind string) map[string]any {
var p map[string]any
var text string
if kind == "license" {
p = map[string]any{"version": "license-v2", "instance_id": id, "license_id": 1, "customer_id": 2, "product_id": 3, "starts_at": now.Format(time.RFC3339), "expires_at": now.Add(time.Hour).Format(time.RFC3339), "key_id": keyID}
text = canonicalCertificatePayload("license-v2", id, 1, 2, 3, now, now.Add(time.Hour)) + "\nkey_id=" + keyID
} else {
lease := leasePayload{"lease-v2", id, "active", now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)}
p = map[string]any{"version": lease.Version, "instance_id": lease.InstanceID, "state": lease.State, "server_time": lease.ServerTime, "entitlement_expires_at": lease.EntitlementExpiresAt, "lease_expires_at": lease.LeaseExpiresAt, "key_id": keyID}
text = canonicalLease(lease) + "\nkey_id=" + keyID
}
hash := sha256.Sum256([]byte(text))
sig, _ := ecdsa.SignASN1(rand.Reader, k, hash[:])
return map[string]any{"payload": p, "signature": base64.RawStdEncoding.EncodeToString(sig)}
}
vectors := map[string]any{"keys": ring.Keys, "old": sign(old, "old", "license"), "current": sign(current, "new", "license"), "lease": sign(current, "new", "lease"), "now": now.UnixMilli(), "instance": id}
data, _ := json.Marshal(vectors)
path := filepath.Join(t.TempDir(), "vectors.json")
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
// Only public keys/signatures leave Go; private keys stay in test process memory.
script := `import fs from 'node:fs'; import assert from 'node:assert/strict'; import {verifyEnvelope,acceptLease,canRunOffline} from '../../../client/verify.mjs';
const v=JSON.parse(fs.readFileSync(process.argv[1]));
assert.equal(verifyEnvelope(v.old,v.keys).key_id,'old');assert.equal(verifyEnvelope(v.current,v.keys).key_id,'new');
assert.throws(()=>verifyEnvelope(v.old,v.keys.map(k=>({...k,revoked:k.key_id==='old'}))),/revoked/);
assert.throws(()=>verifyEnvelope(v.current,[]),/unknown/);
assert.throws(()=>verifyEnvelope({...v.current,payload:{...v.current.payload,key_id:'old'}},v.keys),/signature/);
assert.throws(()=>verifyEnvelope({...v.current,payload:{...v.current.payload,product_id:99}},v.keys),/signature/);
const state=acceptLease(v.lease,v.keys,v.instance,null,v.now);assert.ok(state.enabled);assert.ok(canRunOffline(state,v.instance,v.now+1));assert.ok(!canRunOffline(state,v.instance,v.now-1));assert.ok(!canRunOffline(state,v.instance,state.lease_expires));
assert.throws(()=>acceptLease(v.lease,v.keys,'other',null,v.now),/instance/);
assert.throws(()=>acceptLease(v.lease,v.keys,v.instance,{...state,server_high_water:v.now+1},v.now),/rollback/);
assert.throws(()=>acceptLease(v.lease,v.keys,v.instance,state,v.now-1),/rollback/);
console.log('Go -> Node: old/current signatures, revoked/unknown/tampered rejection, lease high-water passed');`
cmd := exec.Command("node", "--input-type=module", "-e", script, path)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Node vectors failed: %s", out)
}
t.Log(string(out))
}