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>
179 lines
5.5 KiB
Go
179 lines
5.5 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/json"
|
|
"encoding/pem"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestSigningFileAPIRestart(t *testing.T) {
|
|
dsn := os.Getenv("SIGNING_RESTART_TEST_DSN")
|
|
if dsn == "" {
|
|
t.Skip("isolated clean008 MySQL required")
|
|
}
|
|
// os.MkdirTemp default is outside the repository; never persist test private material in session data.
|
|
dir, err := os.MkdirTemp("", "license-protected-restart-")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
if runtime.GOOS == "windows" {
|
|
user := os.Getenv("USERNAME")
|
|
if user == "" {
|
|
t.Fatal("user ACL required")
|
|
}
|
|
if err := exec.Command("icacls", dir, "/inheritance:r", "/grant:r", user+":(OI)(CI)F").Run(); err != nil {
|
|
t.Fatal("cannot protect key directory")
|
|
}
|
|
} else {
|
|
if err := os.Chmod(dir, 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
der, _ := x509.MarshalECPrivateKey(key)
|
|
keyPath := filepath.Join(dir, "signing.pem")
|
|
if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
bin := filepath.Join(dir, "api")
|
|
if runtime.GOOS == "windows" {
|
|
bin += ".exe"
|
|
}
|
|
build := exec.Command("go", "build", "-o", bin, "../../cmd/server")
|
|
if err := build.Run(); err != nil {
|
|
t.Fatal("server build failed")
|
|
}
|
|
now := time.Now().UTC().Truncate(time.Second)
|
|
payloads := []string{canonicalCertificatePayload("license-v1", "00000000-0000-4000-8000-000000000001", 1, 2, 3, now, now.Add(time.Hour)), canonicalLease(leasePayload{Version: "lease-v1", InstanceID: "00000000-0000-4000-8000-000000000001", State: "active", ServerTime: now.Format(time.RFC3339), EntitlementExpiresAt: now.Add(time.Hour).Format(time.RFC3339), LeaseExpiresAt: now.Add(time.Hour).Format(time.RFC3339)})}
|
|
signatures := make([][]byte, 2)
|
|
for i, p := range payloads {
|
|
sum := sha256.Sum256([]byte(p))
|
|
signatures[i], err = ecdsa.SignASN1(rand.Reader, key, sum[:])
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
var prior string
|
|
for iteration := 0; iteration < 2; iteration++ {
|
|
listener, _ := net.Listen("tcp", "127.0.0.1:0")
|
|
addr := listener.Addr().String()
|
|
listener.Close()
|
|
monitor, _ := net.Listen("tcp", "127.0.0.1:0")
|
|
monitorAddr := monitor.Addr().String()
|
|
monitor.Close()
|
|
cmd := exec.Command(bin)
|
|
cmd.Env = append(os.Environ(), "HTTP_ADDR="+addr, "MYSQL_DSN="+dsn, "LICENSE_SIGNING_PRIVATE_KEY_PEM=", "LICENSE_SIGNING_PRIVATE_KEY_FILE="+keyPath, "METRICS_ADDR="+monitorAddr, "ENTRY_LIMIT_MODE=redis", "ENTRY_REDIS_ADDR="+os.Getenv("ENTRY_REDIS_TEST_ADDR"))
|
|
// Discard child output: neither private material nor connection errors become artifacts.
|
|
cmd.Stdout = io.Discard
|
|
cmd.Stderr = io.Discard
|
|
if err := cmd.Start(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
func() {
|
|
defer func() { cmd.Process.Kill(); cmd.Wait() }()
|
|
client := &http.Client{Timeout: time.Second}
|
|
var res *http.Response
|
|
for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); {
|
|
res, err = client.Get("http://" + addr + "/api/v1/activation/public-key")
|
|
if err == nil {
|
|
break
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
}
|
|
if err != nil {
|
|
t.Fatal("isolated API unavailable")
|
|
}
|
|
defer res.Body.Close()
|
|
var out struct {
|
|
Data struct {
|
|
PublicKey string `json:"public_key_pem"`
|
|
}
|
|
}
|
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if iteration > 0 && out.Data.PublicKey != prior {
|
|
t.Fatal("public key changed across restart")
|
|
}
|
|
prior = out.Data.PublicKey
|
|
block, _ := pem.Decode([]byte(prior))
|
|
if block == nil {
|
|
t.Fatal("no public key")
|
|
}
|
|
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pub := parsed.(*ecdsa.PublicKey)
|
|
for i, p := range payloads {
|
|
sum := sha256.Sum256([]byte(p))
|
|
if !ecdsa.VerifyASN1(pub, sum[:], signatures[i]) {
|
|
t.Fatal("old certificate/lease signature invalid after restart")
|
|
}
|
|
}
|
|
for _, p := range []string{"/api/v1/health/ready", "/metrics"} {
|
|
r, e := client.Get("http://" + addr + p)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
r.Body.Close()
|
|
if r.StatusCode != 404 {
|
|
t.Fatal("internal route publicly exposed")
|
|
}
|
|
}
|
|
r, e := client.Get("http://" + monitorAddr + "/api/v1/health/ready")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 {
|
|
t.Fatal("internal readiness", r.StatusCode)
|
|
}
|
|
r, e = client.Get("http://" + monitorAddr + "/metrics")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 {
|
|
t.Fatal("internal metrics", r.StatusCode)
|
|
}
|
|
for _, tc := range []struct {
|
|
path, body, origin string
|
|
status int
|
|
}{
|
|
{"/api/v1/products", "", "", 401},
|
|
{"/api/v1/auth/login", "{}", "https://evil.example", 403},
|
|
{"/api/v1/auth/login", strings.Repeat("x", 65537), "", 413},
|
|
} {
|
|
q, _ := http.NewRequest("POST", "http://"+addr+tc.path, strings.NewReader(tc.body))
|
|
q.Header.Set("Origin", tc.origin)
|
|
q.Header.Set("Content-Type", "application/json")
|
|
response, e := client.Do(q)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
response.Body.Close()
|
|
if response.StatusCode != tc.status || response.Header.Get("X-Request-ID") == "" {
|
|
t.Fatal("new API security smoke", response.StatusCode)
|
|
}
|
|
}
|
|
t.Logf("isolated API start %d: public key stable, old canonical signatures valid, ready/metrics internal only", iteration+1)
|
|
}()
|
|
}
|
|
}
|