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>
This commit is contained in:
14
.dockerignore
Normal file
14
.dockerignore
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
.git
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
sessions
|
||||||
|
sources
|
||||||
|
skills
|
||||||
|
node_modules
|
||||||
|
frontend/node_modules
|
||||||
|
frontend/dist
|
||||||
|
backend/**/*.test
|
||||||
|
**/*.pem
|
||||||
|
**/*.key
|
||||||
|
**/secrets
|
||||||
35
.env.example
35
.env.example
@@ -1,2 +1,37 @@
|
|||||||
# API listen address (local development)
|
# API listen address (local development)
|
||||||
HTTP_ADDR=127.0.0.1:18080
|
HTTP_ADDR=127.0.0.1:18080
|
||||||
|
# Empty means no trusted proxies. Explicit proxy CIDRs only, never /0.
|
||||||
|
HTTP_TRUSTED_PROXY_CIDRS=
|
||||||
|
# Set true behind managed TLS termination; forwarded headers alone are insufficient.
|
||||||
|
SESSION_COOKIE_SECURE=false
|
||||||
|
HTTP_READ_HEADER_TIMEOUT=5s
|
||||||
|
HTTP_READ_TIMEOUT=30s
|
||||||
|
HTTP_WRITE_TIMEOUT=30s
|
||||||
|
HTTP_IDLE_TIMEOUT=60s
|
||||||
|
HTTP_SHUTDOWN_TIMEOUT=10s
|
||||||
|
# Optional separate metrics listener, numeric loopback only; never publish through Web.
|
||||||
|
METRICS_ADDR=
|
||||||
|
# Required default: redis. Only controlled development may explicitly use local-dev.
|
||||||
|
ENTRY_LIMIT_MODE=redis
|
||||||
|
ENTRY_REDIS_ADDR=127.0.0.1:16379
|
||||||
|
ENTRY_REDIS_NAMESPACE=license-platform:entry:
|
||||||
|
ENTRY_REDIS_USERNAME=
|
||||||
|
ENTRY_REDIS_PASSWORD_FILE=
|
||||||
|
# Redis errors fail closed with 503; no automatic local fallback.
|
||||||
|
# Migration CLI URL. Do not reuse as MYSQL_DSN.
|
||||||
|
MIGRATION_DSN=mysql://user:password@tcp(127.0.0.1:3306)/license_platform?multiStatements=true
|
||||||
|
# Go MySQL driver DSN for API and admin-init.
|
||||||
|
MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/license_platform?parseTime=true
|
||||||
|
# Optional PEM P-256 ECDSA private key, injected by secret manager; never commit a real key.
|
||||||
|
LICENSE_SIGNING_PRIVATE_KEY_PEM=
|
||||||
|
# Alternative absolute protected PEM file; never configure both key sources.
|
||||||
|
LICENSE_SIGNING_PRIVATE_KEY_FILE=
|
||||||
|
# Optional absolute public-key ring JSON; opt-in DEV license-v2/lease-v2.
|
||||||
|
# Lifecycle/rotation approval required; private key NEVER belongs in this JSON.
|
||||||
|
LICENSE_KEYRING_FILE=
|
||||||
|
# Absolute existing trusted non-public directory; hard links must be supported.
|
||||||
|
PACKAGE_STORAGE_ROOT=
|
||||||
|
# This example is documentation, not a production security profile.
|
||||||
|
# Compose external path variables (not secret values): MYSQL_APP_SECRET_FILE,
|
||||||
|
# MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST.
|
||||||
|
# See docs/deployment-delivery.md for outstanding TLS/cookie/restore blockers.
|
||||||
|
|||||||
28
.github/workflows/check.yml
vendored
28
.github/workflows/check.yml
vendored
@@ -1,12 +1,31 @@
|
|||||||
name: Check
|
name: Check
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
paths: ['backend/**', 'frontend/**', '.github/workflows/check.yml']
|
paths: ['backend/**', 'client/**', 'frontend/**', 'scripts/**', 'deploy/**', 'compose.yaml', '.github/workflows/check.yml']
|
||||||
pull_request:
|
pull_request:
|
||||||
paths: ['backend/**', 'frontend/**', '.github/workflows/check.yml']
|
paths: ['backend/**', 'client/**', 'frontend/**', 'scripts/**', 'deploy/**', 'compose.yaml', '.github/workflows/check.yml']
|
||||||
jobs:
|
jobs:
|
||||||
|
delivery-static:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- run: sh scripts/check-delivery.sh
|
||||||
|
- name: Compose configuration only (not runtime acceptance)
|
||||||
|
env:
|
||||||
|
MYSQL_APP_SECRET_FILE: /tmp/delivery-app.secret
|
||||||
|
MYSQL_ROOT_SECRET_FILE: /tmp/delivery-root.secret
|
||||||
|
LICENSE_SIGNING_KEY_HOST_FILE: /tmp/delivery-signing.pem
|
||||||
|
PACKAGE_STORAGE_HOST: /tmp/delivery-packages
|
||||||
|
run: docker compose config --quiet
|
||||||
api:
|
api:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
services:
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
ports: ['16379:6379']
|
||||||
|
options: --health-cmd 'redis-cli ping' --health-interval 5s --health-timeout 3s --health-retries 10
|
||||||
|
env:
|
||||||
|
ENTRY_REDIS_TEST_ADDR: 127.0.0.1:16379
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: backend
|
working-directory: backend
|
||||||
@@ -16,8 +35,12 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
go-version-file: backend/go.mod
|
go-version-file: backend/go.mod
|
||||||
cache-dependency-path: backend/go.sum
|
cache-dependency-path: backend/go.sum
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '24'
|
||||||
- run: go test ./...
|
- run: go test ./...
|
||||||
- run: go vet ./...
|
- run: go vet ./...
|
||||||
|
- run: go test -race ./internal/httpapi -run 'TestOperations|TestOrigin|TestLocalLimiter|TestSessionCookie|TestPublicEntry|TestChunkedBody|TestRedisEntry|TestEntryMode' -count=1
|
||||||
web:
|
web:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
defaults:
|
defaults:
|
||||||
@@ -31,4 +54,5 @@ jobs:
|
|||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
- run: npm test
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ First implementation slice: Gin API and Vue 3/Vite management shell. This is **n
|
|||||||
|
|
||||||
Prerequisites: Go 1.23+, Node 20+. From `backend`, run `go run ./cmd/server`. From `frontend`, run `npm ci` and `npm run dev`. Visit http://127.0.0.1:5173/ (Vite proxies `/api` to the Go server at 127.0.0.1:18080). Set `HTTP_ADDR` to override the Go listen address; update the Vite proxy when changing API port.
|
Prerequisites: Go 1.23+, Node 20+. From `backend`, run `go run ./cmd/server`. From `frontend`, run `npm ci` and `npm run dev`. Visit http://127.0.0.1:5173/ (Vite proxies `/api` to the Go server at 127.0.0.1:18080). Set `HTTP_ADDR` to override the Go listen address; update the Vite proxy when changing API port.
|
||||||
|
|
||||||
Checks: `go test ./...` from `backend`, `npm run build` from `frontend`. `/api/v1/health/live` reports only process liveness and does not prove database readiness. No secret is committed; `.env.example` is documentation only.
|
Checks: `go test ./...` from `backend`, `npm run build` from `frontend`. `/api/v1/health/live` reports only process liveness and does not prove database readiness. No secret is committed; `.env.example` is documentation only and is not loaded automatically. Export the variables in your shell or deployment environment. HTTP timeout values must be positive Go durations no greater than 5m; invalid configuration fails startup. The server handles SIGTERM/interrupt with a bounded graceful shutdown and does not trust forwarded client IP headers by default.
|
||||||
|
|
||||||
|
Migration conventions: `backend/migrations/README.md`. SQL and migration runner validation are not implemented yet. Task status and verification records: `docs/task-execution.md` and the detailed task plan. T03 remains in progress; no task has been accepted as release-ready.
|
||||||
|
|
||||||
Before implementing binding and issuance: decide the licensed Web product, instance identity across container recreation/replicas and its integration owner. Confirm the remaining ADRs in `软件授权与统一管理平台-架构决策与MVP验收规格.md`.
|
Before implementing binding and issuance: decide the licensed Web product, instance identity across container recreation/replicas and its integration owner. Confirm the remaining ADRs in `软件授权与统一管理平台-架构决策与MVP验收规格.md`.
|
||||||
|
|||||||
85
backend/cmd/admin-init/main.go
Normal file
85
backend/cmd/admin-init/main.go
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
_ "github.com/go-sql-driver/mysql"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := run(os.Args[1:]); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func run(args []string) error {
|
||||||
|
f := flag.NewFlagSet("admin-init", flag.ContinueOnError)
|
||||||
|
dsn := f.String("dsn", os.Getenv("MYSQL_DSN"), "MySQL driver DSN")
|
||||||
|
email := f.String("email", "", "admin email")
|
||||||
|
username := f.String("username", "admin", "admin username (3-32 lowercase letters, digits, _ or -)")
|
||||||
|
password := f.String("password", "", "admin password (non-empty, up to 72 bytes)")
|
||||||
|
if err := f.Parse(args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*username = strings.ToLower(strings.TrimSpace(*username))
|
||||||
|
if *dsn == "" || !strings.Contains(*email, "@") || !validUsername(*username) {
|
||||||
|
return errors.New("-dsn, valid -email and valid -username are required")
|
||||||
|
}
|
||||||
|
if *password == "" {
|
||||||
|
return errors.New("-password must not be empty")
|
||||||
|
}
|
||||||
|
if len(*password) > 72 {
|
||||||
|
return errors.New("-password must not exceed 72 bytes")
|
||||||
|
}
|
||||||
|
db, err := sql.Open("mysql", *dsn)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err = db.PingContext(context.Background()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx, err := db.BeginTx(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
emailValue := strings.ToLower(strings.TrimSpace(*email))
|
||||||
|
var id uint64
|
||||||
|
err = tx.QueryRow("SELECT id FROM admins WHERE email=? FOR UPDATE", emailValue).Scan(&id)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
_, err = tx.Exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", *username, emailValue, string(hash))
|
||||||
|
} else if err == nil {
|
||||||
|
_, err = tx.Exec("UPDATE admins SET username=?,password_hash=?,active=1 WHERE id=?", *username, string(hash), id)
|
||||||
|
if err == nil {
|
||||||
|
_, err = tx.Exec("UPDATE sessions SET revoked_at=UTC_TIMESTAMP(6) WHERE admin_id=? AND revoked_at IS NULL", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func validUsername(value string) bool {
|
||||||
|
if len(value) < 3 || len(value) > 32 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range value {
|
||||||
|
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
54
backend/cmd/migrate/main.go
Normal file
54
backend/cmd/migrate/main.go
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"license-platform/backend/internal/migrations"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := run(os.Args[1:]); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(args []string) error {
|
||||||
|
flags := flag.NewFlagSet("migrate", flag.ContinueOnError)
|
||||||
|
dsn := flags.String("dsn", os.Getenv("MIGRATION_DSN"), "MySQL migrate URL, e.g. mysql://user:pass@tcp(host:3306)/db?multiStatements=true (also MIGRATION_DSN)")
|
||||||
|
directory := flags.String("dir", "./migrations", "migration directory")
|
||||||
|
forceVersion := flags.Int("version", -2, "version for force; required only with force")
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if flags.NArg() != 1 {
|
||||||
|
return errors.New("usage: migrate [-dsn DSN] [-dir DIR] up|down|version|force")
|
||||||
|
}
|
||||||
|
runner, err := migrations.Open(*dsn, *directory)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer runner.Close()
|
||||||
|
switch flags.Arg(0) {
|
||||||
|
case "up":
|
||||||
|
return runner.Up()
|
||||||
|
case "down":
|
||||||
|
return runner.Down()
|
||||||
|
case "version":
|
||||||
|
version, dirty, err := runner.Version()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("version=%d dirty=%t\n", version, dirty)
|
||||||
|
return nil
|
||||||
|
case "force":
|
||||||
|
if *forceVersion < -1 {
|
||||||
|
return errors.New("-version is required for force")
|
||||||
|
}
|
||||||
|
return runner.Force(*forceVersion)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown action %q", flags.Arg(0))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,100 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"context"
|
||||||
"os"
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
_ "github.com/go-sql-driver/mysql"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"license-platform/backend/internal/config"
|
||||||
"license-platform/backend/internal/httpapi"
|
"license-platform/backend/internal/httpapi"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func run() error {
|
||||||
addr := os.Getenv("HTTP_ADDR")
|
cfg, err := config.Load(os.Getenv)
|
||||||
if addr == "" {
|
if err != nil {
|
||||||
addr = "127.0.0.1:18080"
|
return err
|
||||||
}
|
}
|
||||||
if err := httpapi.NewRouter().Run(addr); err != nil {
|
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||||
log.Fatal(err)
|
ops := httpapi.NewOperations(logger)
|
||||||
|
closeLimiter, err := httpapi.ConfigureEntryLimiter(ops, os.Getenv)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer closeLimiter()
|
||||||
|
router := httpapi.NewOperationalRouter(ops)
|
||||||
|
var readinessDB *sql.DB
|
||||||
|
if dsn := os.Getenv("MYSQL_DSN"); dsn != "" {
|
||||||
|
db, err := sql.Open("mysql", dsn)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := db.PingContext(context.Background()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := httpapi.CheckSchema(context.Background(), db); err != nil {
|
||||||
|
return fmt.Errorf("database schema is not ready; explicit clean migration to version %d required", httpapi.RequiredSchemaVersion)
|
||||||
|
}
|
||||||
|
readinessDB = db
|
||||||
|
ring, err := httpapi.LoadKeyring(os.Getenv("LICENSE_KEYRING_FILE"), cfg.SigningPrivateKeyPEM)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring)
|
||||||
|
}
|
||||||
|
// Readiness is registered only on the loopback operations listener.
|
||||||
|
if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: cfg.HTTPAddr, Handler: router,
|
||||||
|
ReadHeaderTimeout: cfg.ReadHeaderTimeout, ReadTimeout: cfg.ReadTimeout,
|
||||||
|
WriteTimeout: cfg.WriteTimeout, IdleTimeout: cfg.IdleTimeout,
|
||||||
|
}
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
if addr := os.Getenv("METRICS_ADDR"); addr != "" {
|
||||||
|
host, _, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() {
|
||||||
|
return fmt.Errorf("METRICS_ADDR must use a numeric loopback address")
|
||||||
|
}
|
||||||
|
listener, err := net.Listen("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("metrics listener unavailable")
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/metrics", ops.Metrics)
|
||||||
|
internal := httpapi.NewRouter()
|
||||||
|
httpapi.RegisterReadiness(internal, readinessDB)
|
||||||
|
mux.Handle("/api/v1/health/ready", internal)
|
||||||
|
metrics := &http.Server{Handler: mux, ReadHeaderTimeout: cfg.ReadHeaderTimeout, WriteTimeout: cfg.WriteTimeout}
|
||||||
|
defer metrics.Close()
|
||||||
|
go func() {
|
||||||
|
if err := metrics.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||||
|
logger.Error("metrics_listener_failed")
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
mode := os.Getenv("ENTRY_LIMIT_MODE")
|
||||||
|
if mode == "" {
|
||||||
|
mode = "redis"
|
||||||
|
}
|
||||||
|
logger.Info("api_starting", "address", cfg.HTTPAddr, "rate_limit_mode", mode)
|
||||||
|
return httpapi.Serve(ctx, server, cfg.ShutdownTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := run(); err != nil {
|
||||||
|
slog.New(slog.NewJSONHandler(os.Stderr, nil)).Error("startup_failed", "code", "startup_error")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,19 +2,29 @@ module license-platform/backend
|
|||||||
|
|
||||||
go 1.23.0
|
go 1.23.0
|
||||||
|
|
||||||
require github.com/gin-gonic/gin v1.10.0
|
require (
|
||||||
|
github.com/gin-gonic/gin v1.10.0
|
||||||
|
github.com/go-sql-driver/mysql v1.5.0
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.18.3
|
||||||
|
github.com/redis/go-redis/v9 v9.7.3
|
||||||
|
golang.org/x/crypto v0.36.0
|
||||||
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/bytedance/sonic v1.11.6 // indirect
|
github.com/bytedance/sonic v1.11.6 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.2 // indirect
|
github.com/goccy/go-json v0.10.2 // indirect
|
||||||
|
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
@@ -24,11 +34,11 @@ require (
|
|||||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
|
go.uber.org/atomic v1.7.0 // indirect
|
||||||
golang.org/x/arch v0.8.0 // indirect
|
golang.org/x/arch v0.8.0 // indirect
|
||||||
golang.org/x/crypto v0.23.0 // indirect
|
golang.org/x/net v0.38.0 // indirect
|
||||||
golang.org/x/net v0.25.0 // indirect
|
golang.org/x/sys v0.31.0 // indirect
|
||||||
golang.org/x/sys v0.20.0 // indirect
|
golang.org/x/text v0.23.0 // indirect
|
||||||
golang.org/x/text v0.15.0 // indirect
|
google.golang.org/protobuf v1.34.2 // indirect
|
||||||
google.golang.org/protobuf v1.34.1 // indirect
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
|
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||||
|
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||||
@@ -9,12 +19,30 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
|
github.com/dhui/dktest v0.4.5 h1:uUfYBIVREmj/Rw6MvgmqNAYzTiKOHJak+enB5Di73MM=
|
||||||
|
github.com/dhui/dktest v0.4.5/go.mod h1:tmcyeHDKagvlDrz7gDKq4UAJOLIfVZYkfD5OnHDwcCo=
|
||||||
|
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||||
|
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||||
|
github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4=
|
||||||
|
github.com/docker/docker v27.2.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||||
|
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||||
|
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||||
|
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||||
|
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||||
|
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||||
|
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||||
|
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||||
|
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
@@ -23,11 +51,22 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
|||||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||||
|
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
||||||
|
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||||
|
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||||
|
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=
|
||||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||||
|
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||||
|
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
@@ -36,17 +75,33 @@ github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZY
|
|||||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||||
|
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||||
|
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||||
|
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||||
|
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||||
|
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||||
|
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||||
|
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||||
|
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||||
|
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
@@ -63,23 +118,33 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
|
|||||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
||||||
|
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
||||||
|
go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8=
|
||||||
|
go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc=
|
||||||
|
go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8=
|
||||||
|
go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4=
|
||||||
|
go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ=
|
||||||
|
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||||
|
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
||||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
||||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
||||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
|
||||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
98
backend/internal/config/config.go
Normal file
98
backend/internal/config/config.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
HTTPAddr string
|
||||||
|
TrustedProxies []string
|
||||||
|
ReadHeaderTimeout time.Duration
|
||||||
|
ReadTimeout time.Duration
|
||||||
|
WriteTimeout time.Duration
|
||||||
|
IdleTimeout time.Duration
|
||||||
|
ShutdownTimeout time.Duration
|
||||||
|
SigningPrivateKeyPEM string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Load(getenv func(string) string) (Config, error) {
|
||||||
|
c := Config{HTTPAddr: "127.0.0.1:18080"}
|
||||||
|
if v := getenv("HTTP_ADDR"); v != "" {
|
||||||
|
c.HTTPAddr = v
|
||||||
|
}
|
||||||
|
_, port, err := net.SplitHostPort(c.HTTPAddr)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, fmt.Errorf("HTTP_ADDR must be host:port")
|
||||||
|
}
|
||||||
|
p, err := strconv.Atoi(port)
|
||||||
|
if err != nil || p < 1 || p > 65535 {
|
||||||
|
return Config{}, fmt.Errorf("HTTP_ADDR port must be between 1 and 65535")
|
||||||
|
}
|
||||||
|
for _, setting := range []struct {
|
||||||
|
name string
|
||||||
|
value *time.Duration
|
||||||
|
fallback time.Duration
|
||||||
|
}{
|
||||||
|
{"HTTP_READ_HEADER_TIMEOUT", &c.ReadHeaderTimeout, 5 * time.Second},
|
||||||
|
{"HTTP_READ_TIMEOUT", &c.ReadTimeout, 30 * time.Second},
|
||||||
|
{"HTTP_WRITE_TIMEOUT", &c.WriteTimeout, 30 * time.Second},
|
||||||
|
{"HTTP_IDLE_TIMEOUT", &c.IdleTimeout, 60 * time.Second},
|
||||||
|
{"HTTP_SHUTDOWN_TIMEOUT", &c.ShutdownTimeout, 10 * time.Second},
|
||||||
|
} {
|
||||||
|
*setting.value = setting.fallback
|
||||||
|
if v := getenv(setting.name); v != "" {
|
||||||
|
d, err := time.ParseDuration(v)
|
||||||
|
if err != nil || d <= 0 || d > 5*time.Minute {
|
||||||
|
return Config{}, fmt.Errorf("%s must be a duration greater than zero and at most 5m", setting.name)
|
||||||
|
}
|
||||||
|
*setting.value = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if value := getenv("HTTP_TRUSTED_PROXY_CIDRS"); value != "" {
|
||||||
|
for _, value := range strings.Split(value, ",") {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
_, network, err := net.ParseCIDR(value)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, fmt.Errorf("trusted proxies must be explicit CIDRs")
|
||||||
|
}
|
||||||
|
ones, _ := network.Mask.Size()
|
||||||
|
if ones == 0 {
|
||||||
|
return Config{}, fmt.Errorf("trust-all proxies are forbidden")
|
||||||
|
}
|
||||||
|
c.TrustedProxies = append(c.TrustedProxies, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if value := getenv("SESSION_COOKIE_SECURE"); value != "" && value != "true" && value != "false" {
|
||||||
|
return Config{}, fmt.Errorf("SESSION_COOKIE_SECURE must be true or false")
|
||||||
|
}
|
||||||
|
c.SigningPrivateKeyPEM = getenv("LICENSE_SIGNING_PRIVATE_KEY_PEM")
|
||||||
|
if path := getenv("LICENSE_SIGNING_PRIVATE_KEY_FILE"); path != "" {
|
||||||
|
if c.SigningPrivateKeyPEM != "" {
|
||||||
|
return Config{}, fmt.Errorf("only one signing key source may be configured")
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return Config{}, fmt.Errorf("LICENSE_SIGNING_PRIVATE_KEY_FILE must be absolute")
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil || len(data) == 0 || len(data) > 16384 {
|
||||||
|
return Config{}, fmt.Errorf("signing key file must be readable and between 1 and 16384 bytes")
|
||||||
|
}
|
||||||
|
c.SigningPrivateKeyPEM = string(data)
|
||||||
|
}
|
||||||
|
if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" {
|
||||||
|
if !filepath.IsAbs(root) {
|
||||||
|
return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute")
|
||||||
|
}
|
||||||
|
info, err := os.Stat(root)
|
||||||
|
if err != nil || !info.IsDir() {
|
||||||
|
return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be an existing directory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
64
backend/internal/config/config_test.go
Normal file
64
backend/internal/config/config_test.go
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoadDefaults(t *testing.T) {
|
||||||
|
c, err := Load(func(string) string { return "" })
|
||||||
|
if err != nil || c.HTTPAddr != "127.0.0.1:18080" || c.ReadHeaderTimeout != 5*time.Second || c.ShutdownTimeout != 10*time.Second {
|
||||||
|
t.Fatalf("config=%+v err=%v", c, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadOverrides(t *testing.T) {
|
||||||
|
values := map[string]string{"HTTP_ADDR": "[::1]:18081", "HTTP_WRITE_TIMEOUT": "2m"}
|
||||||
|
c, err := Load(func(key string) string { return values[key] })
|
||||||
|
if err != nil || c.HTTPAddr != values["HTTP_ADDR"] || c.WriteTimeout != 2*time.Minute {
|
||||||
|
t.Fatalf("config=%+v err=%v", c, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadKeyFileAndStorage(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
key := filepath.Join(root, "key.pem")
|
||||||
|
if err := os.WriteFile(key, []byte("test-only-content"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
values := map[string]string{"LICENSE_SIGNING_PRIVATE_KEY_FILE": key, "PACKAGE_STORAGE_ROOT": root}
|
||||||
|
cfg, err := Load(func(k string) string { return values[k] })
|
||||||
|
if err != nil || cfg.SigningPrivateKeyPEM != "test-only-content" {
|
||||||
|
t.Fatal("file injection failed")
|
||||||
|
}
|
||||||
|
values["LICENSE_SIGNING_PRIVATE_KEY_PEM"] = "conflicting-source"
|
||||||
|
if _, err := Load(func(k string) string { return values[k] }); err == nil {
|
||||||
|
t.Fatal("ambiguous key sources accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadRejectsInvalid(t *testing.T) {
|
||||||
|
for _, tc := range []struct{ key, value string }{
|
||||||
|
{"HTTP_TRUSTED_PROXY_CIDRS", "0.0.0.0/0"}, {"HTTP_TRUSTED_PROXY_CIDRS", "::/0"},
|
||||||
|
{"HTTP_TRUSTED_PROXY_CIDRS", "127.0.0.1"}, {"HTTP_TRUSTED_PROXY_CIDRS", "bad"},
|
||||||
|
{"SESSION_COOKIE_SECURE", "yes"},
|
||||||
|
{"PACKAGE_STORAGE_ROOT", "relative/packages"}, {"LICENSE_SIGNING_PRIVATE_KEY_FILE", "relative/key.pem"},
|
||||||
|
{"HTTP_ADDR", "localhost"}, {"HTTP_ADDR", ":0"}, {"HTTP_ADDR", ":65536"}, {"HTTP_ADDR", ":abc"},
|
||||||
|
{"HTTP_READ_HEADER_TIMEOUT", "bad"}, {"HTTP_READ_TIMEOUT", "0s"},
|
||||||
|
{"HTTP_WRITE_TIMEOUT", "-1s"}, {"HTTP_IDLE_TIMEOUT", "6m"}, {"HTTP_SHUTDOWN_TIMEOUT", "0s"},
|
||||||
|
} {
|
||||||
|
t.Run(tc.key+tc.value, func(t *testing.T) {
|
||||||
|
_, err := Load(func(key string) string {
|
||||||
|
if key == tc.key {
|
||||||
|
return tc.value
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected configuration error")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
348
backend/internal/httpapi/activation.go
Normal file
348
backend/internal/httpapi/activation.go
Normal file
@@ -0,0 +1,348 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type instanceRecord struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
InstanceID string `json:"instance_id"`
|
||||||
|
LicenseID uint64 `json:"license_id"`
|
||||||
|
CustomerID uint64 `json:"customer_id"`
|
||||||
|
ProductID uint64 `json:"product_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
ActivatedAt *time.Time `json:"activated_at,omitempty"`
|
||||||
|
CertificateVersion string `json:"certificate_version,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
LastSeenAt *time.Time `json:"last_seen_at,omitempty"`
|
||||||
|
LeaseExpiresAt *time.Time `json:"lease_expires_at,omitempty"`
|
||||||
|
FreezeState string `json:"freeze_state"`
|
||||||
|
ObservedState string `json:"observed_state"`
|
||||||
|
EntitlementState string `json:"entitlement_state"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func newInstanceID() (string, error) {
|
||||||
|
b := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
b[6] = (b[6] & 0x0f) | 0x40
|
||||||
|
b[8] = (b[8] & 0x3f) | 0x80
|
||||||
|
return fmt.Sprintf("%s-%s-%s-%s-%s", hex.EncodeToString(b[:4]), hex.EncodeToString(b[4:6]), hex.EncodeToString(b[6:8]), hex.EncodeToString(b[8:10]), hex.EncodeToString(b[10:])), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readSigningKey(pemText string) (*ecdsa.PrivateKey, error) {
|
||||||
|
block, _ := pem.Decode([]byte(pemText))
|
||||||
|
if block == nil {
|
||||||
|
return nil, errors.New("missing PEM")
|
||||||
|
}
|
||||||
|
if key, err := x509.ParseECPrivateKey(block.Bytes); err == nil && key.Curve == elliptic.P256() {
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
keyAny, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
key, ok := keyAny.(*ecdsa.PrivateKey)
|
||||||
|
if !ok || key.Curve != elliptic.P256() {
|
||||||
|
return nil, errors.New("signing key must be P-256 ECDSA")
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// canonicalCertificatePayload is newline-delimited key=value with fixed order and no whitespace.
|
||||||
|
func canonicalCertificatePayload(version, instanceID string, licenseID, customerID, productID uint64, startsAt, expiresAt time.Time) string {
|
||||||
|
return strings.Join([]string{
|
||||||
|
"version=" + version,
|
||||||
|
"instance_id=" + instanceID,
|
||||||
|
"license_id=" + strconv.FormatUint(licenseID, 10),
|
||||||
|
"customer_id=" + strconv.FormatUint(customerID, 10),
|
||||||
|
"product_id=" + strconv.FormatUint(productID, 10),
|
||||||
|
"starts_at=" + startsAt.UTC().Format(time.RFC3339Nano),
|
||||||
|
"expires_at=" + expiresAt.UTC().Format(time.RFC3339Nano),
|
||||||
|
}, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) provisionInstance(c *gin.Context) {
|
||||||
|
licenseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || licenseID == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "授权 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor := c.MustGet("admin_id")
|
||||||
|
instanceID, err := newInstanceID()
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
secretBytes := make([]byte, 32)
|
||||||
|
if _, err = rand.Read(secretBytes); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
secret := base64.RawURLEncoding.EncodeToString(secretBytes)
|
||||||
|
hash := sha256.Sum256(secretBytes)
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var customerID, productID uint64
|
||||||
|
var status string
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM licenses WHERE id=? FOR UPDATE", licenseID).Scan(&customerID, &productID, &status); errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "授权不存在")
|
||||||
|
return
|
||||||
|
} else if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if status == "revoked" {
|
||||||
|
apiError(c, 409, "invalid_state", "已撤销授权不能创建实例")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var existing string
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT instance_id FROM license_instances WHERE license_id=?", licenseID).Scan(&existing); err == nil {
|
||||||
|
apiError(c, 409, "instance_conflict", "授权已绑定实例")
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var id uint64
|
||||||
|
res, err := tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", instanceID, licenseID, customerID, productID, hash[:], actor)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 409, "instance_conflict", "实例创建失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id64, _ := res.LastInsertId()
|
||||||
|
id = uint64(id64)
|
||||||
|
details, _ := json.Marshal(gin.H{"license_id": licenseID, "instance_id": instanceID})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.provisioned','license_instance',?,?)", actor, id, details); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "secret_expires": "one-time"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) listInstances(c *gin.Context) {
|
||||||
|
licenseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || licenseID == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "授权 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := a.db.QueryContext(c, "SELECT id,instance_id,license_id,customer_id,product_id,status,activated_at,COALESCE(certificate_version,''),created_at,last_seen_at,lease_expires_at,freeze_state,observed_state,(SELECT status FROM licenses WHERE id=license_id) FROM license_instances WHERE license_id=? ORDER BY id", licenseID)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []instanceRecord{}
|
||||||
|
for rows.Next() {
|
||||||
|
var x instanceRecord
|
||||||
|
if err = rows.Scan(&x.ID, &x.InstanceID, &x.LicenseID, &x.CustomerID, &x.ProductID, &x.Status, &x.ActivatedAt, &x.CertificateVersion, &x.CreatedAt, &x.LastSeenAt, &x.LeaseExpiresAt, &x.FreezeState, &x.ObservedState, &x.EntitlementState); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, x)
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) activateInstance(c *gin.Context) {
|
||||||
|
if a.signingPrivateKeyPEM == "" {
|
||||||
|
apiError(c, 503, "signing_unavailable", "签名密钥未配置")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
instanceID := strings.TrimSpace(c.Param("instance_id"))
|
||||||
|
if len(instanceID) != 36 {
|
||||||
|
apiError(c, 400, "invalid_request", "instance_id 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key, ok := parseOperationKey(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
LicenseKey string `json:"license_key"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(in.Secret) < 20 || len(in.Secret) > 128 {
|
||||||
|
apiError(c, 400, "invalid_request", "secret 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
secretBytes, err := base64.RawURLEncoding.DecodeString(in.Secret)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "secret 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
secretHash := sha256.Sum256(secretBytes)
|
||||||
|
fingerprint := sha256.Sum256([]byte(instanceID + "\x00" + hex.EncodeToString(secretHash[:])))
|
||||||
|
var actor uint64
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var inst instanceRecord
|
||||||
|
var storedHash []byte
|
||||||
|
var startsAt, expiresAt time.Time
|
||||||
|
err = tx.QueryRowContext(c, `SELECT i.id,i.instance_id,i.license_id,i.customer_id,i.product_id,i.status,i.activated_at,COALESCE(i.certificate_version,''),i.created_at,i.secret_hash,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.instance_id=? FOR UPDATE`, instanceID).Scan(&inst.ID, &inst.InstanceID, &inst.LicenseID, &inst.CustomerID, &inst.ProductID, &inst.Status, &inst.ActivatedAt, &inst.CertificateVersion, &inst.CreatedAt, &storedHash, &startsAt, &expiresAt)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "实例不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT created_by FROM license_instances WHERE id=?", inst.ID).Scan(&actor); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var licenseKey string
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT license_key FROM licenses WHERE id=?", inst.LicenseID).Scan(&licenseKey); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !bytesEqual([]byte(in.LicenseKey), []byte(licenseKey)) || !bytesEqual(storedHash, secretHash[:]) {
|
||||||
|
apiError(c, 403, "forbidden", "激活凭据无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var opID uint64
|
||||||
|
var oldInstance uint64
|
||||||
|
var oldFingerprint []byte
|
||||||
|
var oldResponse []byte
|
||||||
|
err = tx.QueryRowContext(c, "SELECT id,instance_id,request_fingerprint,response FROM activation_operations WHERE instance_id=? AND idempotency_key=?", inst.ID, key).Scan(&opID, &oldInstance, &oldFingerprint, &oldResponse)
|
||||||
|
if err == nil {
|
||||||
|
if oldInstance != inst.ID || !bytesEqual(oldFingerprint, fingerprint[:]) {
|
||||||
|
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同激活请求")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var replay any
|
||||||
|
_ = json.Unmarshal(oldResponse, &replay)
|
||||||
|
c.JSON(200, replay)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !bytesEqual(storedHash, secretHash[:]) {
|
||||||
|
apiError(c, 403, "forbidden", "实例secret无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if inst.Status == "activated" {
|
||||||
|
apiError(c, 409, "invalid_state", "实例已经激活")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var licenseStatus, customerStatus string
|
||||||
|
var productActive bool
|
||||||
|
var licenseCustomer, licenseProduct uint64
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM licenses WHERE id=? FOR UPDATE", inst.LicenseID).Scan(&licenseCustomer, &licenseProduct, &licenseStatus); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if licenseCustomer != inst.CustomerID || licenseProduct != inst.ProductID || currentLicenseStatus(licenseStatus, startsAt, expiresAt, time.Now().UTC()) != "active" {
|
||||||
|
apiError(c, 409, "invalid_state", "授权归属或有效期无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT status FROM customers WHERE id=? FOR UPDATE", inst.CustomerID).Scan(&customerStatus); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", inst.ProductID).Scan(&productActive); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if customerStatus != "active" || !productActive {
|
||||||
|
apiError(c, 409, "invalid_state", "客户或产品未启用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var orderCustomer, orderProduct uint64
|
||||||
|
var orderStatus string
|
||||||
|
err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM offline_orders WHERE issued_license_id=? FOR UPDATE", inst.LicenseID).Scan(&orderCustomer, &orderProduct, &orderStatus)
|
||||||
|
if err == nil && (orderCustomer != inst.CustomerID || orderProduct != inst.ProductID || orderStatus != "issued") {
|
||||||
|
apiError(c, 409, "invalid_state", "订单归属无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
privateKey, err := readSigningKey(a.signingPrivateKeyPEM)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "signing_unavailable", "签名密钥无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
version := "license-v1"
|
||||||
|
canonical := canonicalCertificatePayload(version, instanceID, inst.LicenseID, inst.CustomerID, inst.ProductID, startsAt, expiresAt)
|
||||||
|
if a.keyring != nil {
|
||||||
|
version = "license-v2"
|
||||||
|
canonical = canonicalCertificatePayload(version, instanceID, inst.LicenseID, inst.CustomerID, inst.ProductID, startsAt, expiresAt) + "\nkey_id=" + a.keyring.Current
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256([]byte(canonical))
|
||||||
|
signature, err := ecdsa.SignASN1(rand.Reader, privateKey, digest[:])
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "签发失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload := gin.H{"version": version, "instance_id": instanceID, "license_id": inst.LicenseID, "customer_id": inst.CustomerID, "product_id": inst.ProductID, "starts_at": startsAt.UTC().Format(time.RFC3339Nano), "expires_at": expiresAt.UTC().Format(time.RFC3339Nano)}
|
||||||
|
if a.keyring != nil {
|
||||||
|
payload["key_id"] = a.keyring.Current
|
||||||
|
}
|
||||||
|
payloadJSON, _ := json.Marshal(payload)
|
||||||
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE license_instances SET status='activated',activated_at=?,certificate_version=?,certificate_payload=?,certificate_signature=? WHERE id=?", now, version, payloadJSON, base64.RawStdEncoding.EncodeToString(signature), inst.ID); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "激活失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response := gin.H{"data": gin.H{"instance_id": instanceID, "status": "activated", "certificate": gin.H{"version": version, "payload": payload, "signature": base64.RawStdEncoding.EncodeToString(signature), "canonical_sha256": hex.EncodeToString(digest[:])}}, "idempotent_replay": false}
|
||||||
|
responseJSON, _ := json.Marshal(response)
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO activation_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?)", inst.ID, actor, key, fingerprint[:], responseJSON); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "激活失败,请使用相同幂等键重试")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(gin.H{"instance_id": instanceID, "license_id": inst.LicenseID, "certificate_version": version})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.activated','license_instance',?,?)", actor, inst.ID, details); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(201, response)
|
||||||
|
}
|
||||||
|
|
||||||
|
func bytesEqual(a, b []byte) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var x byte
|
||||||
|
for i := range a {
|
||||||
|
x |= a[i] ^ b[i]
|
||||||
|
}
|
||||||
|
return x == 0
|
||||||
|
}
|
||||||
129
backend/internal/httpapi/activation_integration_test.go
Normal file
129
backend/internal/httpapi/activation_integration_test.go
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/x509"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) {
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
der, err := x509.MarshalECPrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := NewRouter()
|
||||||
|
RegisterBusiness(r, db, string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})))
|
||||||
|
var licenseID uint64
|
||||||
|
var licenseKey string
|
||||||
|
if err = db.QueryRow("SELECT l.id,l.license_key FROM licenses l JOIN offline_orders o ON o.issued_license_id=l.id WHERE o.status='issued' LIMIT 1").Scan(&licenseID, &licenseKey); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := func(method, path, body, idem string, auth bool) *httptest.ResponseRecorder {
|
||||||
|
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Idempotency-Key", idem)
|
||||||
|
if auth {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
provisionPath := fmt.Sprintf("/api/v1/licenses/%d/instances", licenseID)
|
||||||
|
if w := request("POST", provisionPath, "{}", "", false); w.Code != 401 {
|
||||||
|
t.Fatalf("unauthorized status=%d", w.Code)
|
||||||
|
}
|
||||||
|
w := request("POST", provisionPath, "{}", "", true)
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatalf("provision status=%d", w.Code)
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Data struct {
|
||||||
|
InstanceID string `json:"instance_id"`
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
instanceID, secret := response.Data.InstanceID, response.Data.Secret
|
||||||
|
if instanceID == "" || secret == "" {
|
||||||
|
t.Fatal("provision fields missing")
|
||||||
|
}
|
||||||
|
if w = request("POST", provisionPath, "{}", "", true); w.Code != 409 || strings.Contains(w.Body.String(), secret) {
|
||||||
|
t.Fatal("duplicate provision result invalid")
|
||||||
|
}
|
||||||
|
w = request("GET", provisionPath, "", "", true)
|
||||||
|
if w.Code != 200 || strings.Contains(w.Body.String(), secret) || strings.Contains(w.Body.String(), "secret_hash") {
|
||||||
|
t.Fatal("instance list leaked secret")
|
||||||
|
}
|
||||||
|
path := "/api/v1/activation/instances/" + instanceID
|
||||||
|
bodyBytes, _ := json.Marshal(gin.H{"license_key": licenseKey, "secret": secret})
|
||||||
|
body := string(bodyBytes)
|
||||||
|
badBytes, _ := json.Marshal(gin.H{"license_key": "wrong", "secret": secret})
|
||||||
|
if w = request("POST", path, string(badBytes), "activate", false); w.Code != 403 {
|
||||||
|
t.Fatalf("wrong credential=%d", w.Code)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec("CREATE TRIGGER activation_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS activation_audit_failure") })
|
||||||
|
if w = request("POST", path, body, "activate", false); w.Code != 500 {
|
||||||
|
t.Fatalf("rollback status=%d", w.Code)
|
||||||
|
}
|
||||||
|
var status string
|
||||||
|
db.QueryRow("SELECT status FROM license_instances WHERE instance_id=?", instanceID).Scan(&status)
|
||||||
|
if status != "provisioned" {
|
||||||
|
t.Fatal("audit failure committed activation")
|
||||||
|
}
|
||||||
|
db.Exec("DROP TRIGGER activation_audit_failure")
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
codes := make(chan int, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() { defer wg.Done(); codes <- request("POST", path, body, "activate", false).Code }()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(codes)
|
||||||
|
successes, replays := 0, 0
|
||||||
|
for code := range codes {
|
||||||
|
if code == 201 {
|
||||||
|
successes++
|
||||||
|
} else if code == 200 {
|
||||||
|
replays++
|
||||||
|
} else {
|
||||||
|
t.Fatalf("concurrent activation=%d", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if successes != 1 || replays != 1 {
|
||||||
|
t.Fatal("activation did not serialize")
|
||||||
|
}
|
||||||
|
if w = request("POST", path, body, "different", false); w.Code != 409 {
|
||||||
|
t.Fatalf("repeat activation=%d", w.Code)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err = db.QueryRow("SELECT COUNT(*) FROM activation_operations").Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("operation count mismatch")
|
||||||
|
}
|
||||||
|
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.activated'").Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("activation audit count mismatch")
|
||||||
|
}
|
||||||
|
t.Run("heartbeat", func(t *testing.T) {
|
||||||
|
testHeartbeatMySQL(t, db, r, cookie, instanceID, secret, licenseID, &key.PublicKey)
|
||||||
|
})
|
||||||
|
}
|
||||||
28
backend/internal/httpapi/activation_public.go
Normal file
28
backend/internal/httpapi/activation_public.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *BusinessAPI) activationPublicKey(c *gin.Context) {
|
||||||
|
key, err := readSigningKey(a.signingPrivateKeyPEM)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "signing_unavailable", "签名密钥未配置或无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
der, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
version := "license-v1"
|
||||||
|
data := gin.H{"algorithm": "ECDSA-P256-SHA256", "signature_encoding": "ASN.1-DER/base64-no-padding", "public_key_pem": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))}
|
||||||
|
if a.keyring != nil {
|
||||||
|
version = "license-v2"
|
||||||
|
data["key_id"] = a.keyring.Current
|
||||||
|
}
|
||||||
|
data["certificate_version"] = version
|
||||||
|
c.JSON(200, gin.H{"data": data})
|
||||||
|
}
|
||||||
49
backend/internal/httpapi/activation_test.go
Normal file
49
backend/internal/httpapi/activation_test.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestActivationCanonicalSignature(t *testing.T) {
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
der, err := x509.MarshalECPrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loaded, err := readSigningKey(string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
start := time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)
|
||||||
|
end := start.AddDate(1, 0, 0)
|
||||||
|
canonical := canonicalCertificatePayload("license-v1", "00000000-0000-4000-8000-000000000001", 1, 2, 3, start, end)
|
||||||
|
expected := "version=license-v1\ninstance_id=00000000-0000-4000-8000-000000000001\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-09-30T00:00:00Z\nexpires_at=2027-09-30T00:00:00Z"
|
||||||
|
if canonical != expected {
|
||||||
|
t.Fatal("canonical payload mismatch")
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256([]byte(canonical))
|
||||||
|
sig, err := ecdsa.SignASN1(rand.Reader, loaded, sum[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ecdsa.VerifyASN1(&loaded.PublicKey, sum[:], sig) {
|
||||||
|
t.Fatal("signature not valid")
|
||||||
|
}
|
||||||
|
modified := sha256.Sum256([]byte(canonical + "x"))
|
||||||
|
if ecdsa.VerifyASN1(&loaded.PublicKey, modified[:], sig) {
|
||||||
|
t.Fatal("modified payload accepted")
|
||||||
|
}
|
||||||
|
if _, err = readSigningKey(""); err == nil {
|
||||||
|
t.Fatal("missing key accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
246
backend/internal/httpapi/admin_accounts.go
Normal file
246
backend/internal/httpapi/admin_accounts.go
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/mail"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type adminAccount struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeAdminUsername(value string) string { return strings.ToLower(strings.TrimSpace(value)) }
|
||||||
|
func validAdminUsername(value string) bool {
|
||||||
|
if len(value) < 3 || len(value) > 32 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range value {
|
||||||
|
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func validAdminPassword(value string) bool { return value != "" && len(value) <= 72 }
|
||||||
|
|
||||||
|
func (a *BusinessAPI) listAdmins(c *gin.Context) {
|
||||||
|
rows, err := a.db.QueryContext(c, "SELECT id,username,email,active,created_at FROM admins ORDER BY id")
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员列表加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []adminAccount{}
|
||||||
|
for rows.Next() {
|
||||||
|
var item adminAccount
|
||||||
|
if err = rows.Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员列表加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员列表加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": items})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) createAdmin(c *gin.Context) {
|
||||||
|
var in struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "用户名、邮箱和密码不能为空")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
in.Username = normalizeAdminUsername(in.Username)
|
||||||
|
in.Email = strings.ToLower(strings.TrimSpace(in.Email))
|
||||||
|
address, emailErr := mail.ParseAddress(in.Email)
|
||||||
|
if !validAdminUsername(in.Username) || emailErr != nil || address.Address != in.Email || len(in.Email) > 190 || !validAdminPassword(in.Password) {
|
||||||
|
apiError(c, 400, "invalid_request", "用户名须为 3–32 位小写字母、数字、下划线或短横线;邮箱和密码必须有效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员创建失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员创建失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
result, err := tx.ExecContext(c, "INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", in.Username, in.Email, string(hash))
|
||||||
|
if err != nil {
|
||||||
|
var duplicate *mysql.MySQLError
|
||||||
|
if errors.As(err, &duplicate) && duplicate.Number == 1062 {
|
||||||
|
apiError(c, 409, "conflict", "用户名或邮箱已存在")
|
||||||
|
} else {
|
||||||
|
apiError(c, 500, "internal_error", "管理员创建失败")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, _ := result.LastInsertId()
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.created','admin',?,?)", c.GetUint64("admin_id"), id, `{"fields":["username","email"]}`); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员创建失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员创建结果未确认,请刷新检查")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var item adminAccount
|
||||||
|
if err = a.db.QueryRowContext(c, "SELECT id,username,email,active,created_at FROM admins WHERE id=?", id).Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员已创建,请刷新检查")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, gin.H{"data": item})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) setAdminActive(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "管理员 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
Active *bool `json:"active"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || in.Active == nil {
|
||||||
|
apiError(c, 400, "invalid_request", "必须指定 active")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if id == c.GetUint64("admin_id") && !*in.Active {
|
||||||
|
apiError(c, 400, "invalid_request", "不能停用当前登录的管理员")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
// Lock accounts in a stable order to serialize simultaneous disable operations.
|
||||||
|
rows, err := tx.QueryContext(c, "SELECT id,active FROM admins ORDER BY id FOR UPDATE")
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
found, current, actorActive := false, false, false
|
||||||
|
for rows.Next() {
|
||||||
|
var accountID uint64
|
||||||
|
var active bool
|
||||||
|
if err = rows.Scan(&accountID, &active); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if accountID == id {
|
||||||
|
found, current = true, active
|
||||||
|
}
|
||||||
|
if accountID == c.GetUint64("admin_id") {
|
||||||
|
actorActive = active
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = rows.Err()
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !actorActive {
|
||||||
|
apiError(c, 401, "unauthorized", "当前管理员已停用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
apiError(c, 404, "not_found", "管理员不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if current == *in.Active {
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE admins SET active=? WHERE id=?", *in.Active, id); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !*in.Active {
|
||||||
|
_, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.active_changed','admin',?,?)", c.GetUint64("admin_id"), id, `{"active":`+map[bool]string{true: "true", false: "false"}[*in.Active]+`}`)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员状态更新失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "管理员状态更新结果未确认,请刷新检查")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) resetAdminPassword(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "管理员 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || !validAdminPassword(in.Password) {
|
||||||
|
apiError(c, 400, "invalid_request", "新密码不能为空,且最多 72 字节")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码重置失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码重置失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
result, err := tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码重置失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
affected, _ := result.RowsAffected()
|
||||||
|
if affected == 0 {
|
||||||
|
apiError(c, 404, "not_found", "管理员不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id); err == nil {
|
||||||
|
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_reset','admin',?,?)", c.GetUint64("admin_id"), id, `{"sessions_revoked":true}`)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码重置失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码重置结果未确认,请刷新检查")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
}
|
||||||
47
backend/internal/httpapi/admin_accounts_test.go
Normal file
47
backend/internal/httpapi/admin_accounts_test.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAdminCredentialValidation(t *testing.T) {
|
||||||
|
for _, name := range []string{"admin", "admin-1", "ops_team", strings.Repeat("a", 32)} {
|
||||||
|
if !validAdminUsername(name) {
|
||||||
|
t.Fatalf("valid username rejected: %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range []string{"", "ab", "name with space", "root@example.test", "管理员", "ADMIN", strings.Repeat("a", 33)} {
|
||||||
|
if validAdminUsername(name) {
|
||||||
|
t.Fatalf("invalid username accepted: %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if normalizeAdminUsername(" TEAM_1 ") != "team_1" {
|
||||||
|
t.Fatal("normalization")
|
||||||
|
}
|
||||||
|
for _, password := range []string{"x", strings.Repeat("a", 72), strings.Repeat("中", 24)} {
|
||||||
|
if !validAdminPassword(password) {
|
||||||
|
t.Fatal("valid password rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, password := range []string{"", strings.Repeat("a", 73), strings.Repeat("中", 25)} {
|
||||||
|
if validAdminPassword(password) {
|
||||||
|
t.Fatal("invalid password accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestAdminCannotDisableSelf(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("POST", "/admins/1/active", strings.NewReader(`{"active":false}`))
|
||||||
|
c.Request.Header.Set("Content-Type", "application/json")
|
||||||
|
c.Params = gin.Params{{Key: "id", Value: "1"}}
|
||||||
|
c.Set("admin_id", uint64(1))
|
||||||
|
(&BusinessAPI{}).setAdminActive(c)
|
||||||
|
if w.Code != 400 || !strings.Contains(w.Body.String(), "不能停用当前登录的管理员") {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
255
backend/internal/httpapi/admin_settings.go
Normal file
255
backend/internal/httpapi/admin_settings.go
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"net/mail"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type platformSettings struct {
|
||||||
|
SiteName string `json:"site_name"`
|
||||||
|
SupportEmail string `json:"support_email"`
|
||||||
|
Announcement string `json:"announcement"`
|
||||||
|
UpdatedAt *time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateSettings(s *platformSettings) bool {
|
||||||
|
s.SiteName = strings.TrimSpace(s.SiteName)
|
||||||
|
s.SupportEmail = strings.TrimSpace(s.SupportEmail)
|
||||||
|
if s.SiteName == "" || utf8.RuneCountInString(s.SiteName) > 100 || len(s.SupportEmail) > 254 || utf8.RuneCountInString(s.Announcement) > 2000 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if s.SupportEmail != "" {
|
||||||
|
a, err := mail.ParseAddress(s.SupportEmail)
|
||||||
|
if err != nil || a.Address != s.SupportEmail {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) getSettings(c *gin.Context) {
|
||||||
|
var s platformSettings
|
||||||
|
if err := a.db.QueryRowContext(c, "SELECT site_name,support_email,announcement,updated_at FROM system_settings WHERE id=1").Scan(&s.SiteName, &s.SupportEmail, &s.Announcement, &s.UpdatedAt); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "设置加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": s})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) updateSettings(c *gin.Context) {
|
||||||
|
var s platformSettings
|
||||||
|
if c.ShouldBindJSON(&s) != nil || !validateSettings(&s) {
|
||||||
|
apiError(c, 400, "invalid_request", "平台名称为1至100字,联系邮箱必须有效,公告最多2000字")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
s.UpdatedAt = &now
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "设置保存失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
// Lock the singleton so concurrent saves are serialized with their audit record.
|
||||||
|
var id int
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT id FROM system_settings WHERE id=1 FOR UPDATE").Scan(&id); err == nil {
|
||||||
|
_, err = tx.ExecContext(c, "UPDATE system_settings SET site_name=?,support_email=?,announcement=?,updated_at=? WHERE id=1", s.SiteName, s.SupportEmail, s.Announcement, now)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'settings.updated','system_settings',1,?)", c.GetUint64("admin_id"), `{"fields":["site_name","support_email","announcement"]}`)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "设置保存失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tx.Commit() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "设置保存结果未确认,请刷新检查")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": s})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) changePassword(c *gin.Context) {
|
||||||
|
var in struct {
|
||||||
|
Current string `json:"current_password"`
|
||||||
|
New string `json:"new_password"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || in.Current == "" || in.New == "" || len(in.New) > 72 {
|
||||||
|
apiError(c, 400, "invalid_request", "当前密码和新密码不能为空,新密码最多72字节")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Hash before acquiring the row lock to keep the write transaction short.
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(in.New), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码修改失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码修改失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var old string
|
||||||
|
id := c.GetUint64("admin_id")
|
||||||
|
err = tx.QueryRowContext(c, "SELECT password_hash FROM admins WHERE id=? AND active=1 FOR UPDATE", id).Scan(&old)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
apiError(c, 401, "unauthorized", "账号已失效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码修改失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword([]byte(old), []byte(in.Current)) != nil {
|
||||||
|
apiError(c, 400, "invalid_credentials", "当前密码错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, _ := c.Cookie("lp_session")
|
||||||
|
decoded, _ := hex.DecodeString(raw)
|
||||||
|
sum := sha256.Sum256(decoded)
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id); err == nil {
|
||||||
|
_, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND token_hash<>? AND revoked_at IS NULL", time.Now().UTC(), id, sum[:])
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_changed','admin',?,?)", id, id, `{"other_sessions_revoked":true}`)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码修改失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tx.Commit() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "密码修改结果未确认,请重新登录检查")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(204)
|
||||||
|
}
|
||||||
|
|
||||||
|
type auditRecord struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
ActorID uint64 `json:"actor_admin_id"`
|
||||||
|
ActorEmail string `json:"actor_email"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
ResourceType string `json:"resource_type"`
|
||||||
|
ResourceID uint64 `json:"resource_id"`
|
||||||
|
Details map[string]any `json:"details"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expose known business fields only. Future events cannot accidentally expose credentials.
|
||||||
|
func publicAuditDetails(raw []byte) map[string]any {
|
||||||
|
var input map[string]any
|
||||||
|
_ = json.Unmarshal(raw, &input)
|
||||||
|
out := map[string]any{}
|
||||||
|
for _, key := range []string{"client_actor", "customer_id", "product_id", "license_id", "order_id", "instance_id", "release_id", "starts_at", "expires_at", "operation", "amount_cents", "currency", "certificate_version", "state", "previous_state", "freeze_state", "lease_expires_at", "version", "sha256", "size_bytes", "fields", "other_sessions_revoked"} {
|
||||||
|
if v, ok := input[key]; ok {
|
||||||
|
switch v.(type) {
|
||||||
|
case string, float64, bool, nil:
|
||||||
|
out[key] = v
|
||||||
|
case []any:
|
||||||
|
if key == "fields" {
|
||||||
|
out[key] = []string{"site_name", "support_email", "announcement"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func auditFilter(c *gin.Context) (string, []any, bool) {
|
||||||
|
clauses := []string{"1=1"}
|
||||||
|
args := []any{}
|
||||||
|
for _, item := range []struct{ key, column string }{{"action", "e.action"}, {"resource_type", "e.resource_type"}} {
|
||||||
|
if v := strings.TrimSpace(c.Query(item.key)); v != "" {
|
||||||
|
if len(v) > 64 {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
clauses = append(clauses, item.column+"=?")
|
||||||
|
args = append(args, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if q := strings.TrimSpace(c.Query("q")); q != "" {
|
||||||
|
if utf8.RuneCountInString(q) > 200 {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
clauses = append(clauses, "(a.email LIKE ? OR e.action LIKE ? OR e.resource_type LIKE ?)")
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
args = append(args, "%"+q+"%")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var from, to time.Time
|
||||||
|
for _, key := range []string{"from", "to"} {
|
||||||
|
if v := c.Query(key); v != "" {
|
||||||
|
t, err := time.Parse(time.RFC3339, v)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
op := ">="
|
||||||
|
if key == "to" {
|
||||||
|
op = "<="
|
||||||
|
to = t
|
||||||
|
} else {
|
||||||
|
from = t
|
||||||
|
}
|
||||||
|
clauses = append(clauses, "e.created_at"+op+"?")
|
||||||
|
args = append(args, t.UTC())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !from.IsZero() && !to.IsZero() && from.After(to) {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
return strings.Join(clauses, " AND "), args, true
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) listAuditEvents(c *gin.Context) {
|
||||||
|
where, args, ok := auditFilter(c)
|
||||||
|
if !ok {
|
||||||
|
apiError(c, 400, "invalid_request", "审计筛选参数无效,时间请使用ISO格式")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, size := page(c)
|
||||||
|
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "日志加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE " + where
|
||||||
|
var total int64
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT COUNT(*)"+base, args...).Scan(&total); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "日志加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pageArgs := append(append([]any{}, args...), size, (p-1)*size)
|
||||||
|
rows, err := tx.QueryContext(c, "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at"+base+" ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", pageArgs...)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "日志加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []auditRecord{}
|
||||||
|
for rows.Next() {
|
||||||
|
var v auditRecord
|
||||||
|
var raw []byte
|
||||||
|
if err = rows.Scan(&v.ID, &v.ActorID, &v.ActorEmail, &v.Action, &v.ResourceType, &v.ResourceID, &raw, &v.CreatedAt); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "日志加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v.Details = publicAuditDetails(raw)
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "日志加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if tx.Commit() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "日志加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||||||
|
}
|
||||||
99
backend/internal/httpapi/admin_settings_test.go
Normal file
99
backend/internal/httpapi/admin_settings_test.go
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAuditListSnapshot(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 9, 2, 0, 0, 0, time.UTC)
|
||||||
|
base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE 1=1 AND e.action=?"
|
||||||
|
db, stub := newDashboardTestDB(t, []dashboardQuery{
|
||||||
|
{sql: "SELECT COUNT(*)" + base, args: []any{"license.issued"}, rows: [][]driver.Value{{int64(21)}}},
|
||||||
|
{sql: "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at" + base + " ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", args: []any{"license.issued", 20, 20}, rows: [][]driver.Value{{int64(1), int64(2), "admin@example.test", "license.issued", "license", int64(3), []byte(`{"license_id":3,"password":"hidden"}`), now}}},
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/?action=license.issued&page=2", nil)
|
||||||
|
(&BusinessAPI{db: db}).listAuditEvents(c)
|
||||||
|
if w.Code != 200 || strings.Contains(w.Body.String(), "hidden") {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
Data []auditRecord `json:"data"`
|
||||||
|
Meta struct {
|
||||||
|
Total int `json:"total"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
} `json:"meta"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Meta.Total != 21 || result.Meta.Page != 2 || len(result.Data) != 1 || !stub.committed || !stub.txOptions.ReadOnly {
|
||||||
|
t.Fatalf("unexpected snapshot: %s", w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestPlatformSettingsValidation(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
s platformSettings
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{platformSettings{SiteName: " 管理台 "}, true},
|
||||||
|
{platformSettings{SiteName: ""}, false},
|
||||||
|
{platformSettings{SiteName: strings.Repeat("中", 101)}, false},
|
||||||
|
{platformSettings{SiteName: "平台", SupportEmail: "admin@example.test"}, true},
|
||||||
|
{platformSettings{SiteName: "平台", SupportEmail: "Name <admin@example.test>"}, false},
|
||||||
|
{platformSettings{SiteName: "平台", Announcement: strings.Repeat("中", 2001)}, false},
|
||||||
|
} {
|
||||||
|
if got := validateSettings(&tc.s); got != tc.ok {
|
||||||
|
t.Fatalf("validation=%v want %v", got, tc.ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestAuditDetailsAllowlist(t *testing.T) {
|
||||||
|
out := publicAuditDetails([]byte(`{"license_id":3,"password":"private","token":"private","instance_secret":"private","state":{"password":"private"},"fields":["private"]}`))
|
||||||
|
if len(out) != 2 || out["license_id"] != float64(3) {
|
||||||
|
t.Fatalf("unsafe details: %#v", out)
|
||||||
|
}
|
||||||
|
if len(publicAuditDetails([]byte(`invalid`))) != 0 {
|
||||||
|
t.Fatal("invalid JSON exposed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestAuditFilterValidation(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
query string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{"?action=license.issued&resource_type=license&q=admin", true},
|
||||||
|
{"?from=2026-10-09T00:00:00Z&to=2026-10-10T00:00:00Z", true},
|
||||||
|
{"?from=not-a-date", false},
|
||||||
|
{"?from=2026-10-10T00:00:00Z&to=2026-10-09T00:00:00Z", false},
|
||||||
|
{"?action=" + strings.Repeat("x", 65), false},
|
||||||
|
} {
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Request = httptest.NewRequest("GET", "/"+tc.query, nil)
|
||||||
|
where, _, ok := auditFilter(c)
|
||||||
|
if ok != tc.ok {
|
||||||
|
t.Fatalf("%s got %v", tc.query, ok)
|
||||||
|
}
|
||||||
|
if ok && where == "" {
|
||||||
|
t.Fatal("missing predicate")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestAdminModuleAuthentication(t *testing.T) {
|
||||||
|
r := gin.New()
|
||||||
|
registerBusinessRoutes(r, &BusinessAPI{})
|
||||||
|
for _, tc := range []struct{ method, path string }{{"GET", "/api/v1/audit-events"}, {"GET", "/api/v1/settings"}, {"PUT", "/api/v1/settings"}, {"POST", "/api/v1/settings/password"}} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
|
||||||
|
if w.Code != 401 {
|
||||||
|
t.Fatalf("%s %s: %d", tc.method, tc.path, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
372
backend/internal/httpapi/business.go
Normal file
372
backend/internal/httpapi/business.go
Normal file
@@ -0,0 +1,372 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BusinessAPI struct {
|
||||||
|
db *sql.DB
|
||||||
|
signingPrivateKeyPEM string
|
||||||
|
keyring *Keyring
|
||||||
|
}
|
||||||
|
|
||||||
|
func secureSessionCookie(c *gin.Context) bool {
|
||||||
|
return c.Request.TLS != nil || os.Getenv("SESSION_COOKIE_SECURE") == "true"
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterBusiness(r *gin.Engine, db *sql.DB, signingPrivateKeyPEM ...string) {
|
||||||
|
if db == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a := &BusinessAPI{db: db}
|
||||||
|
if len(signingPrivateKeyPEM) > 0 {
|
||||||
|
a.signingPrivateKeyPEM = signingPrivateKeyPEM[0]
|
||||||
|
}
|
||||||
|
registerBusinessRoutes(r, a)
|
||||||
|
}
|
||||||
|
func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring) {
|
||||||
|
if db == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
registerBusinessRoutes(r, &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring})
|
||||||
|
}
|
||||||
|
func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||||
|
api := r.Group("/api/v1")
|
||||||
|
api.POST("/auth/login", a.login)
|
||||||
|
api.POST("/portal/snapshot", a.portalSnapshot)
|
||||||
|
api.POST("/activation/instances/:instance_id", a.activateInstance)
|
||||||
|
api.GET("/activation/public-key", a.activationPublicKey)
|
||||||
|
api.GET("/activation/keyring", func(c *gin.Context) {
|
||||||
|
if a.keyring == nil {
|
||||||
|
apiError(c, 404, "not_found", "Keyring unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": a.keyring})
|
||||||
|
})
|
||||||
|
api.POST("/instances/:instance_id/heartbeat", a.heartbeat)
|
||||||
|
api.POST("/auth/logout", a.authenticated, a.logout)
|
||||||
|
secured := api.Group("", a.authenticated)
|
||||||
|
secured.GET("/me", a.me)
|
||||||
|
secured.GET("/admins", a.listAdmins)
|
||||||
|
secured.POST("/admins", a.createAdmin)
|
||||||
|
secured.POST("/admins/:id/active", a.setAdminActive)
|
||||||
|
secured.POST("/admins/:id/reset-password", a.resetAdminPassword)
|
||||||
|
secured.GET("/dashboard/summary", a.dashboardSummary)
|
||||||
|
secured.GET("/audit-events", a.listAuditEvents)
|
||||||
|
secured.GET("/settings", a.getSettings)
|
||||||
|
secured.PUT("/settings", a.updateSettings)
|
||||||
|
secured.POST("/settings/password", a.changePassword)
|
||||||
|
secured.GET("/integration-kit", a.integrationKit)
|
||||||
|
secured.GET("/integration-kit/download", a.downloadIntegrationKit)
|
||||||
|
secured.GET("/integration-kit/archive", a.downloadIntegrationArchive)
|
||||||
|
secured.GET("/customers", a.listCustomers)
|
||||||
|
secured.POST("/customers", a.createCustomer)
|
||||||
|
secured.PUT("/customers/:id", a.updateCustomer)
|
||||||
|
secured.DELETE("/customers/:id", a.deleteCustomer)
|
||||||
|
secured.GET("/products", a.listProducts)
|
||||||
|
secured.POST("/products", a.createProduct)
|
||||||
|
secured.PUT("/products/:id", a.updateProduct)
|
||||||
|
secured.DELETE("/products/:id", a.deleteProduct)
|
||||||
|
secured.GET("/orders", a.listOrders)
|
||||||
|
secured.GET("/orders/:id", a.getOrder)
|
||||||
|
secured.POST("/orders", func(c *gin.Context) { a.writeOrder(c, "create") })
|
||||||
|
secured.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") })
|
||||||
|
secured.POST("/orders/:id/issue", func(c *gin.Context) { a.writeOrder(c, "issue") })
|
||||||
|
secured.GET("/licenses", a.listLicenses)
|
||||||
|
secured.GET("/licenses/:id", a.getLicense)
|
||||||
|
secured.GET("/licenses/:id/instances", a.listInstances)
|
||||||
|
secured.POST("/licenses/:id/instances", a.provisionInstance)
|
||||||
|
secured.POST("/products/:id/releases", a.createRelease)
|
||||||
|
secured.GET("/products/:id/releases", a.listReleases)
|
||||||
|
api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease)
|
||||||
|
secured.POST("/instances/:instance_id/freeze", a.freezeInstance)
|
||||||
|
secured.POST("/licenses", a.issueLicense)
|
||||||
|
secured.POST("/licenses/:id/revoke", func(c *gin.Context) { a.operateLicense(c, "revoke") })
|
||||||
|
secured.POST("/licenses/:id/renew", func(c *gin.Context) { a.operateLicense(c, "renew") })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) login(c *gin.Context) {
|
||||||
|
var in struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil {
|
||||||
|
apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := strings.ToLower(strings.TrimSpace(in.Username))
|
||||||
|
if username == "" || in.Password == "" {
|
||||||
|
apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var id uint64
|
||||||
|
var hash string
|
||||||
|
var role string
|
||||||
|
var email string
|
||||||
|
err := a.db.QueryRowContext(c, "SELECT id,email,password_hash,role FROM admins WHERE username=? AND active=1", username).Scan(&id, &email, &hash, &role)
|
||||||
|
if err != nil || bcrypt.CompareHashAndPassword([]byte(hash), []byte(in.Password)) != nil {
|
||||||
|
apiError(c, http.StatusUnauthorized, "invalid_credentials", "用户名或密码错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw := make([]byte, 32)
|
||||||
|
if _, err = rand.Read(raw); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
expires := time.Now().UTC().Add(8 * time.Hour)
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
if _, err = a.db.ExecContext(c, "INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", id, sum[:], expires); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.SetSameSite(http.SameSiteStrictMode)
|
||||||
|
secure := secureSessionCookie(c)
|
||||||
|
c.SetCookie("lp_session", hex.EncodeToString(raw), 8*3600, "/", "", secure, true)
|
||||||
|
c.JSON(http.StatusOK, gin.H{"data": gin.H{"username": username, "email": email, "role": role, "expires_at": expires}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) authenticated(c *gin.Context) {
|
||||||
|
raw, err := c.Cookie("lp_session")
|
||||||
|
if err != nil || len(raw) != 64 {
|
||||||
|
apiError(c, 401, "unauthorized", "请先登录")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
decoded, err := hex.DecodeString(raw)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 401, "unauthorized", "请先登录")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(decoded)
|
||||||
|
var id uint64
|
||||||
|
var username, email, role string
|
||||||
|
err = a.db.QueryRowContext(c, "SELECT a.id,a.username,a.email,a.role FROM sessions s JOIN admins a ON a.id=s.admin_id WHERE s.token_hash=? AND s.revoked_at IS NULL AND s.expires_at>? AND a.active=1", sum[:], time.Now().UTC()).Scan(&id, &username, &email, &role)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 401, "unauthorized", "会话已失效")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if role != "admin" {
|
||||||
|
apiError(c, http.StatusForbidden, "forbidden", "无权访问管理接口")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Set("admin_id", id)
|
||||||
|
c.Set("admin_username", username)
|
||||||
|
c.Set("admin_email", email)
|
||||||
|
c.Set("admin_role", role)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) logout(c *gin.Context) {
|
||||||
|
if raw, err := c.Cookie("lp_session"); err == nil {
|
||||||
|
if b, e := hex.DecodeString(raw); e == nil {
|
||||||
|
sum := sha256.Sum256(b)
|
||||||
|
_, _ = a.db.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE token_hash=?", time.Now().UTC(), sum[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.SetSameSite(http.SameSiteStrictMode)
|
||||||
|
c.SetCookie("lp_session", "", -1, "/", "", secureSessionCookie(c), true)
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) me(c *gin.Context) {
|
||||||
|
c.JSON(200, gin.H{"data": gin.H{"username": c.GetString("admin_username"), "email": c.GetString("admin_email"), "role": c.GetString("admin_role")}})
|
||||||
|
}
|
||||||
|
|
||||||
|
type customer struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
ContactEmail string `json:"contact_email"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
type product struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func page(c *gin.Context) (int, int) {
|
||||||
|
p, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||||
|
if p < 1 {
|
||||||
|
p = 1
|
||||||
|
}
|
||||||
|
if size < 1 || size > 100 {
|
||||||
|
size = 20
|
||||||
|
}
|
||||||
|
return p, size
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) listCustomers(c *gin.Context) {
|
||||||
|
p, size := page(c)
|
||||||
|
q := strings.TrimSpace(c.Query("q"))
|
||||||
|
like := "%" + q + "%"
|
||||||
|
var total int
|
||||||
|
if err := a.db.QueryRowContext(c, "SELECT COUNT(*) FROM customers WHERE name LIKE ? OR contact_email LIKE ?", like, like).Scan(&total); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := a.db.QueryContext(c, "SELECT id,name,contact_email,status,created_at,updated_at FROM customers WHERE name LIKE ? OR contact_email LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?", like, like, size, (p-1)*size)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []customer{}
|
||||||
|
for rows.Next() {
|
||||||
|
var x customer
|
||||||
|
if err := rows.Scan(&x.ID, &x.Name, &x.ContactEmail, &x.Status, &x.CreatedAt, &x.UpdatedAt); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, x)
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) createCustomer(c *gin.Context) {
|
||||||
|
var in struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ContactEmail string `json:"contact_email"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") {
|
||||||
|
apiError(c, 400, "invalid_request", "客户名称和邮箱格式不正确")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res, err := a.db.ExecContext(c, "INSERT INTO customers(name,contact_email) VALUES(?,?)", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)))
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 409, "customer_conflict", "客户创建失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, _ := res.LastInsertId()
|
||||||
|
c.JSON(201, gin.H{"data": gin.H{"id": id}})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) updateCustomer(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
var in struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ContactEmail string `json:"contact_email"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") {
|
||||||
|
apiError(c, 400, "invalid_request", "客户字段不正确")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res, err := a.db.ExecContext(c, "UPDATE customers SET name=?,contact_email=?,status=? WHERE id=?", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)), in.Status, id)
|
||||||
|
if err != nil || func() bool { n, _ := res.RowsAffected(); return n == 0 }() {
|
||||||
|
apiError(c, 404, "not_found", "客户不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(204)
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) deleteCustomer(c *gin.Context) {
|
||||||
|
res, err := a.db.ExecContext(c, "DELETE FROM customers WHERE id=?", c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "删除失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n == 0 {
|
||||||
|
apiError(c, 404, "not_found", "客户不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(204)
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) listProducts(c *gin.Context) {
|
||||||
|
rows, err := a.db.QueryContext(c, "SELECT id,code,name,description,active,created_at,updated_at FROM products ORDER BY id DESC")
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []product{}
|
||||||
|
for rows.Next() {
|
||||||
|
var x product
|
||||||
|
if rows.Scan(&x.ID, &x.Code, &x.Name, &x.Description, &x.Active, &x.CreatedAt, &x.UpdatedAt) != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, x)
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) createProduct(c *gin.Context) {
|
||||||
|
var in struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 {
|
||||||
|
apiError(c, 400, "invalid_request", "产品编码和名称不能为空")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res, err := a.db.ExecContext(c, "INSERT INTO products(code,name,description) VALUES(?,?,?)", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 409, "product_conflict", "产品编码已存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, _ := res.LastInsertId()
|
||||||
|
c.JSON(201, gin.H{"data": gin.H{"id": id}})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) updateProduct(c *gin.Context) {
|
||||||
|
var in struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Active *bool `json:"active"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 {
|
||||||
|
apiError(c, 400, "invalid_request", "产品字段不正确")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
active := true
|
||||||
|
if in.Active != nil {
|
||||||
|
active = *in.Active
|
||||||
|
}
|
||||||
|
res, err := a.db.ExecContext(c, "UPDATE products SET code=?,name=?,description=?,active=? WHERE id=?", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description, active, c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 409, "product_conflict", "产品更新失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n == 0 {
|
||||||
|
apiError(c, 404, "not_found", "产品不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(204)
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) deleteProduct(c *gin.Context) {
|
||||||
|
res, err := a.db.ExecContext(c, "DELETE FROM products WHERE id=?", c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "删除失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n == 0 {
|
||||||
|
apiError(c, 404, "not_found", "产品不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(204)
|
||||||
|
}
|
||||||
|
func apiError(c *gin.Context, status int, code, message string) {
|
||||||
|
if status >= 500 {
|
||||||
|
message = "Service unavailable"
|
||||||
|
}
|
||||||
|
c.Set("error_code", code)
|
||||||
|
c.JSON(status, gin.H{"error": gin.H{"code": code, "message": message, "request_id": c.GetString("request_id")}})
|
||||||
|
}
|
||||||
293
backend/internal/httpapi/business_integration_test.go
Normal file
293
backend/internal/httpapi/business_integration_test.go
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
111
backend/internal/httpapi/dashboard.go
Normal file
111
backend/internal/httpapi/dashboard.go
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type licenseTrendPoint struct {
|
||||||
|
Month string `json:"month"`
|
||||||
|
Issued int64 `json:"issued"`
|
||||||
|
Expired int64 `json:"expired"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type dashboardSummaryRecord struct {
|
||||||
|
ActiveLicenses int64 `json:"active_licenses"`
|
||||||
|
NewCustomers int64 `json:"new_customers"`
|
||||||
|
PaidRevenueCents int64 `json:"paid_revenue_cents"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
ExpiringLicenses int64 `json:"expiring_licenses"`
|
||||||
|
LicenseTrend []licenseTrendPoint `json:"license_trend"`
|
||||||
|
UpcomingExpirations []licenseRecord `json:"upcoming_expirations"`
|
||||||
|
RecentLicenses []licenseRecord `json:"recent_licenses"`
|
||||||
|
GeneratedAt time.Time `json:"generated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func dashboardMonths(c *gin.Context) (int, bool) {
|
||||||
|
switch c.DefaultQuery("months", "6") {
|
||||||
|
case "6":
|
||||||
|
return 6, true
|
||||||
|
case "12":
|
||||||
|
return 12, true
|
||||||
|
default:
|
||||||
|
apiError(c, 400, "invalid_request", "months 必须为 6 或 12")
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) dashboardSummary(c *gin.Context) {
|
||||||
|
months, ok := dashboardMonths(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
out, err := a.loadDashboardSummary(c, now, months)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out})
|
||||||
|
}
|
||||||
|
|
||||||
|
// A read-only consistent snapshot prevents concurrent issuance/payment from making
|
||||||
|
// the summary counts and its lists disagree. No application rows are changed.
|
||||||
|
func (a *BusinessAPI) loadDashboardSummary(c *gin.Context, now time.Time, months int) (dashboardSummaryRecord, error) {
|
||||||
|
now = now.UTC()
|
||||||
|
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
nextMonth := monthStart.AddDate(0, 1, 0)
|
||||||
|
out := dashboardSummaryRecord{Currency: "CNY", GeneratedAt: now,
|
||||||
|
LicenseTrend: make([]licenseTrendPoint, months),
|
||||||
|
UpcomingExpirations: []licenseRecord{}, RecentLicenses: []licenseRecord{}}
|
||||||
|
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
err = tx.QueryRowContext(c, `SELECT
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?),
|
||||||
|
(SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at<?),
|
||||||
|
(SELECT COALESCE(SUM(amount_cents),0) FROM offline_orders WHERE status IN ('paid','issued') AND currency='CNY' AND paid_at>=? AND paid_at<?),
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)`,
|
||||||
|
now, now, monthStart, nextMonth, monthStart, nextMonth, now, now, now.Add(30*24*time.Hour)).Scan(
|
||||||
|
&out.ActiveLicenses, &out.NewCustomers, &out.PaidRevenueCents, &out.ExpiringLicenses)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
// Range aggregates use UTC boundaries rather than the database session's date
|
||||||
|
// formatting/timezone. Each bucket includes its start and excludes its end.
|
||||||
|
for i := range out.LicenseTrend {
|
||||||
|
start := monthStart.AddDate(0, i-months+1, 0)
|
||||||
|
end := start.AddDate(0, 1, 0)
|
||||||
|
point := &out.LicenseTrend[i]
|
||||||
|
point.Month = start.Format("2006-01")
|
||||||
|
err = tx.QueryRowContext(c, `SELECT
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at<?),
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND expires_at>=? AND expires_at<? AND expires_at<=?)`,
|
||||||
|
start, end, start, end, now).Scan(&point.Issued, &point.Expired)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
where, args, _ := licenseFilter("expiring", "", now)
|
||||||
|
rows, err := tx.QueryContext(c, licenseSelect+where+" ORDER BY l.expires_at ASC,l.id ASC LIMIT 10", args...)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.UpcomingExpirations, err = readLicenseRecords(rows, now)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
rows, err = tx.QueryContext(c, licenseSelect+" ORDER BY l.created_at DESC,l.id DESC LIMIT 10")
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.RecentLicenses, err = readLicenseRecords(rows, now)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, tx.Commit()
|
||||||
|
}
|
||||||
355
backend/internal/httpapi/dashboard_test.go
Normal file
355
backend/internal/httpapi/dashboard_test.go
Normal file
@@ -0,0 +1,355 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This driver has no network or filesystem access. Every query must consume an
|
||||||
|
// explicit expectation, so an accidental write or unfiltered query fails.
|
||||||
|
type dashboardQuery struct {
|
||||||
|
sql string
|
||||||
|
args []any
|
||||||
|
rows [][]driver.Value
|
||||||
|
err error
|
||||||
|
rowErr error
|
||||||
|
}
|
||||||
|
type dashboardDB struct {
|
||||||
|
t *testing.T
|
||||||
|
queries []dashboardQuery
|
||||||
|
txOptions driver.TxOptions
|
||||||
|
began, committed, rolledBack bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dashboardDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
|
||||||
|
func (d *dashboardDB) Driver() driver.Driver { return dashboardDriver{d} }
|
||||||
|
|
||||||
|
type dashboardDriver struct{ db *dashboardDB }
|
||||||
|
|
||||||
|
func (d dashboardDriver) Open(string) (driver.Conn, error) { return d.db, nil }
|
||||||
|
func (*dashboardDB) Prepare(string) (driver.Stmt, error) {
|
||||||
|
return nil, errors.New("unexpected prepare")
|
||||||
|
}
|
||||||
|
func (*dashboardDB) Close() error { return nil }
|
||||||
|
func (*dashboardDB) Begin() (driver.Tx, error) { return nil, errors.New("use BeginTx") }
|
||||||
|
func (d *dashboardDB) BeginTx(_ context.Context, options driver.TxOptions) (driver.Tx, error) {
|
||||||
|
d.began = true
|
||||||
|
d.txOptions = options
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
func (d *dashboardDB) Commit() error { d.committed = true; return nil }
|
||||||
|
func (d *dashboardDB) Rollback() error { d.rolledBack = true; return nil }
|
||||||
|
func (d *dashboardDB) QueryContext(_ context.Context, query string, values []driver.NamedValue) (driver.Rows, error) {
|
||||||
|
if len(d.queries) == 0 {
|
||||||
|
d.t.Errorf("unexpected SQL: %s", query)
|
||||||
|
return nil, errors.New("unexpected SQL")
|
||||||
|
}
|
||||||
|
q := d.queries[0]
|
||||||
|
d.queries = d.queries[1:]
|
||||||
|
if strings.Join(strings.Fields(query), " ") != strings.Join(strings.Fields(q.sql), " ") {
|
||||||
|
d.t.Errorf("SQL mismatch\ngot: %s\nwant: %s", query, q.sql)
|
||||||
|
}
|
||||||
|
got := make([]any, len(values))
|
||||||
|
for i, v := range values {
|
||||||
|
got[i] = v.Value
|
||||||
|
}
|
||||||
|
// database/sql converts integer bind arguments to int64.
|
||||||
|
want := make([]any, len(q.args))
|
||||||
|
for i, v := range q.args {
|
||||||
|
if n, ok := v.(int); ok {
|
||||||
|
want[i] = int64(n)
|
||||||
|
} else {
|
||||||
|
want[i] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
d.t.Errorf("arguments got %#v want %#v", got, want)
|
||||||
|
}
|
||||||
|
if q.err != nil {
|
||||||
|
return nil, q.err
|
||||||
|
}
|
||||||
|
width := 1
|
||||||
|
if len(q.rows) > 0 {
|
||||||
|
width = len(q.rows[0])
|
||||||
|
} else if strings.HasPrefix(query, "SELECT l.id") {
|
||||||
|
width = 11
|
||||||
|
}
|
||||||
|
return &dashboardRows{rows: q.rows, width: width, err: q.rowErr}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type dashboardRows struct {
|
||||||
|
rows [][]driver.Value
|
||||||
|
width int
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *dashboardRows) Columns() []string {
|
||||||
|
out := make([]string, r.width)
|
||||||
|
for i := range out {
|
||||||
|
out[i] = fmt.Sprint(i)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func (*dashboardRows) Close() error { return nil }
|
||||||
|
func (r *dashboardRows) Next(dst []driver.Value) error {
|
||||||
|
if len(r.rows) == 0 {
|
||||||
|
if r.err != nil {
|
||||||
|
return r.err
|
||||||
|
}
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
copy(dst, r.rows[0])
|
||||||
|
r.rows = r.rows[1:]
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func newDashboardTestDB(t *testing.T, queries []dashboardQuery) (*sql.DB, *dashboardDB) {
|
||||||
|
t.Helper()
|
||||||
|
stub := &dashboardDB{t: t, queries: queries}
|
||||||
|
db := sql.OpenDB(stub)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
db.Close()
|
||||||
|
if len(stub.queries) > 0 {
|
||||||
|
t.Errorf("%d unconsumed SQL expectations", len(stub.queries))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return db, stub
|
||||||
|
}
|
||||||
|
|
||||||
|
const dashboardTotalsSQL = `SELECT
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?),
|
||||||
|
(SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at<?),
|
||||||
|
(SELECT COALESCE(SUM(amount_cents),0) FROM offline_orders WHERE status IN ('paid','issued') AND currency='CNY' AND paid_at>=? AND paid_at<?),
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)`
|
||||||
|
const dashboardTrendSQL = `SELECT
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at<?),
|
||||||
|
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND expires_at>=? AND expires_at<? AND expires_at<=?)`
|
||||||
|
|
||||||
|
func dashboardExpectations(now time.Time, months int) []dashboardQuery {
|
||||||
|
start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
end := start.AddDate(0, 1, 0)
|
||||||
|
queries := []dashboardQuery{{sql: dashboardTotalsSQL, args: []any{now, now, start, end, start, end, now, now, now.Add(30 * 24 * time.Hour)}, rows: [][]driver.Value{{int64(123), int64(45), int64(987654321), int64(27)}}}}
|
||||||
|
for i := 0; i < months; i++ {
|
||||||
|
from := start.AddDate(0, i-months+1, 0)
|
||||||
|
to := from.AddDate(0, 1, 0)
|
||||||
|
queries = append(queries, dashboardQuery{sql: dashboardTrendSQL, args: []any{from, to, from, to, now}, rows: [][]driver.Value{{int64(i), int64(i % 2)}}})
|
||||||
|
}
|
||||||
|
queries = append(queries,
|
||||||
|
dashboardQuery{sql: licenseSelect + " WHERE 1=1 AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>? AND l.expires_at<=? ORDER BY l.expires_at ASC,l.id ASC LIMIT 10", args: []any{now, now, now.Add(30 * 24 * time.Hour)}, rows: [][]driver.Value{testLicenseRow(1, "active", now.Add(-time.Hour), now.Add(time.Hour), now)}},
|
||||||
|
dashboardQuery{sql: licenseSelect + " ORDER BY l.created_at DESC,l.id DESC LIMIT 10", rows: [][]driver.Value{testLicenseRow(2, "active", now.Add(time.Hour), now.Add(2*time.Hour), now)}})
|
||||||
|
return queries
|
||||||
|
}
|
||||||
|
func testLicenseRow(id int64, status string, start, end, created time.Time) []driver.Value {
|
||||||
|
return []driver.Value{id, "key", int64(7), "Customer", int64(8), "Product", "code", status, start, end, created}
|
||||||
|
}
|
||||||
|
func TestDashboardSummarySnapshot(t *testing.T) {
|
||||||
|
for _, months := range []int{6, 12} {
|
||||||
|
t.Run(fmt.Sprint(months), func(t *testing.T) {
|
||||||
|
// January in UTC+8 is still December in UTC; also tests crossing a year.
|
||||||
|
now := time.Date(2027, 1, 1, 1, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)).UTC()
|
||||||
|
db, stub := newDashboardTestDB(t, dashboardExpectations(now, months))
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Request = httptest.NewRequest("GET", "/", nil)
|
||||||
|
out, err := (&BusinessAPI{db: db}).loadDashboardSummary(c, now, months)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if out.ActiveLicenses != 123 || out.NewCustomers != 45 || out.PaidRevenueCents != 987654321 || out.ExpiringLicenses != 27 || out.Currency != "CNY" {
|
||||||
|
t.Fatalf("wrong totals: %+v", out)
|
||||||
|
}
|
||||||
|
if !stub.began || !stub.committed || stub.rolledBack || !stub.txOptions.ReadOnly || stub.txOptions.Isolation != driver.IsolationLevel(sql.LevelRepeatableRead) {
|
||||||
|
t.Fatalf("snapshot transaction: %+v", stub)
|
||||||
|
}
|
||||||
|
if len(out.LicenseTrend) != months || out.LicenseTrend[months-1].Month != "2026-12" || out.LicenseTrend[0].Issued != 0 {
|
||||||
|
t.Fatalf("trend: %+v", out.LicenseTrend)
|
||||||
|
}
|
||||||
|
if len(out.UpcomingExpirations) != 1 || len(out.RecentLicenses) != 1 || out.RecentLicenses[0].Status != "scheduled" || out.UpcomingExpirations[0].CustomerName != "Customer" {
|
||||||
|
t.Fatalf("records: %+v", out)
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(out)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var fields map[string]json.RawMessage
|
||||||
|
json.Unmarshal(data, &fields)
|
||||||
|
for _, field := range []string{"active_licenses", "new_customers", "paid_revenue_cents", "currency", "expiring_licenses", "license_trend", "upcoming_expirations", "recent_licenses", "generated_at"} {
|
||||||
|
if _, ok := fields[field]; !ok {
|
||||||
|
t.Errorf("missing %s", field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var generated string
|
||||||
|
json.Unmarshal(fields["generated_at"], &generated)
|
||||||
|
parsed, err := time.Parse(time.RFC3339, generated)
|
||||||
|
if err != nil || !parsed.Equal(now) {
|
||||||
|
t.Fatalf("generated_at %s", generated)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestDashboardEmptyAndFailure(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 8, 10, 0, 0, 0, time.UTC)
|
||||||
|
for _, mode := range []string{"empty", "aggregate error", "trend error", "list error", "row error", "scan error"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
qs := dashboardExpectations(now, 6)
|
||||||
|
switch mode {
|
||||||
|
case "empty":
|
||||||
|
for i := 0; i < 7; i++ {
|
||||||
|
for j := range qs[i].rows[0] {
|
||||||
|
qs[i].rows[0][j] = int64(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qs[7].rows = nil
|
||||||
|
qs[8].rows = nil
|
||||||
|
case "aggregate error":
|
||||||
|
qs = qs[:1]
|
||||||
|
qs[0].err = errors.New("private database detail")
|
||||||
|
case "trend error":
|
||||||
|
qs = qs[:2]
|
||||||
|
qs[1].err = errors.New("failure")
|
||||||
|
case "list error":
|
||||||
|
qs = qs[:8]
|
||||||
|
qs[7].err = errors.New("failure")
|
||||||
|
case "row error":
|
||||||
|
qs = qs[:8]
|
||||||
|
qs[7].rowErr = errors.New("failure")
|
||||||
|
case "scan error":
|
||||||
|
qs = qs[:8]
|
||||||
|
qs[7].rows[0][0] = "invalid id"
|
||||||
|
}
|
||||||
|
db, stub := newDashboardTestDB(t, qs)
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Request = httptest.NewRequest("GET", "/", nil)
|
||||||
|
out, err := (&BusinessAPI{db: db}).loadDashboardSummary(c, now, 6)
|
||||||
|
if mode == "empty" {
|
||||||
|
if err != nil || out.PaidRevenueCents != 0 || out.UpcomingExpirations == nil || out.RecentLicenses == nil || len(out.LicenseTrend) != 6 {
|
||||||
|
t.Fatalf("empty summary %+v %v", out, err)
|
||||||
|
}
|
||||||
|
} else if err == nil || !stub.rolledBack || stub.committed {
|
||||||
|
t.Fatalf("failure err=%v rollback=%v commit=%v", err, stub.rolledBack, stub.committed)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestDashboardMonthsValidation(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
query string
|
||||||
|
want int
|
||||||
|
ok bool
|
||||||
|
}{{"", 6, true}, {"?months=6", 6, true}, {"?months=12", 12, true}, {"?months=", 0, false}, {"?months=3", 0, false}, {"?months=abc", 0, false}, {"?months=06", 0, false}} {
|
||||||
|
t.Run(tc.query, func(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/"+tc.query, nil)
|
||||||
|
got, ok := dashboardMonths(c)
|
||||||
|
if got != tc.want || ok != tc.ok {
|
||||||
|
t.Fatalf("got %d/%v", got, ok)
|
||||||
|
}
|
||||||
|
if !ok && (w.Code != 400 || !strings.Contains(w.Body.String(), "invalid_request")) {
|
||||||
|
t.Fatal(w.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestDashboardAndLicenseAdminRoutes(t *testing.T) {
|
||||||
|
// Authentication is exercised through real route registration. An unauthorized
|
||||||
|
// request must never reach summary/list SQL, even with invalid query parameters.
|
||||||
|
for _, path := range []string{"/api/v1/dashboard/summary?months=invalid", "/api/v1/licenses?status=invalid"} {
|
||||||
|
for _, mode := range []string{"missing", "malformed", "viewer", "expired", "admin"} {
|
||||||
|
t.Run(path+mode, func(t *testing.T) {
|
||||||
|
db, stub := newDashboardTestDB(t, nil)
|
||||||
|
r := gin.New()
|
||||||
|
RegisterBusiness(r, db)
|
||||||
|
req := httptest.NewRequest("GET", path, nil)
|
||||||
|
if mode == "malformed" {
|
||||||
|
req.AddCookie(&http.Cookie{Name: "lp_session", Value: strings.Repeat("z", 64)})
|
||||||
|
}
|
||||||
|
if mode == "viewer" || mode == "expired" || mode == "admin" {
|
||||||
|
req.AddCookie(&http.Cookie{Name: "lp_session", Value: strings.Repeat("0", 64)})
|
||||||
|
// The expiry cutoff is generated by authentication; capture and check it in
|
||||||
|
// a dedicated connector rather than relying on a wall-clock exact match.
|
||||||
|
db.Close()
|
||||||
|
auth := &dashboardAuthDB{t: t, mode: mode}
|
||||||
|
db = sql.OpenDB(auth)
|
||||||
|
defer db.Close()
|
||||||
|
r = gin.New()
|
||||||
|
RegisterBusiness(r, db)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
want := 401
|
||||||
|
if mode == "viewer" {
|
||||||
|
want = 403
|
||||||
|
}
|
||||||
|
if mode == "admin" {
|
||||||
|
want = 400 // Valid administrator reaches the handler's validation.
|
||||||
|
}
|
||||||
|
if w.Code != want {
|
||||||
|
t.Fatalf("got %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
if stub.began {
|
||||||
|
t.Fatal("unauthorized aggregate")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authentication queries contain a live expiry cutoff, checked independently.
|
||||||
|
type dashboardAuthDB struct {
|
||||||
|
t *testing.T
|
||||||
|
mode string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dashboardAuthDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
|
||||||
|
func (d *dashboardAuthDB) Driver() driver.Driver { return dashboardAuthDriver{d} }
|
||||||
|
|
||||||
|
type dashboardAuthDriver struct{ db *dashboardAuthDB }
|
||||||
|
|
||||||
|
func (d dashboardAuthDriver) Open(string) (driver.Conn, error) { return d.db, nil }
|
||||||
|
func (*dashboardAuthDB) Close() error { return nil }
|
||||||
|
func (*dashboardAuthDB) Prepare(string) (driver.Stmt, error) {
|
||||||
|
return nil, errors.New("unexpected prepare")
|
||||||
|
}
|
||||||
|
func (*dashboardAuthDB) Begin() (driver.Tx, error) { return nil, errors.New("unexpected transaction") }
|
||||||
|
func (d *dashboardAuthDB) QueryContext(_ context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {
|
||||||
|
if !strings.Contains(q, "s.expires_at>?") || !strings.Contains(q, "a.active=1") || len(args) != 2 {
|
||||||
|
d.t.Errorf("unexpected auth SQL %s", q)
|
||||||
|
return nil, errors.New("unexpected auth SQL")
|
||||||
|
}
|
||||||
|
if cutoff, ok := args[1].Value.(time.Time); !ok || time.Since(cutoff) > time.Second {
|
||||||
|
d.t.Error("invalid session expiry cutoff")
|
||||||
|
}
|
||||||
|
if d.mode == "expired" {
|
||||||
|
return &dashboardRows{width: 4}, nil
|
||||||
|
}
|
||||||
|
role := "viewer"
|
||||||
|
if d.mode == "admin" {
|
||||||
|
role = "admin"
|
||||||
|
}
|
||||||
|
return &dashboardRows{width: 4, rows: [][]driver.Value{{int64(1), "admin-1", "admin@example.test", role}}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDashboardSummaryHTTPFailure(t *testing.T) {
|
||||||
|
db, _ := newDashboardTestDB(t, nil)
|
||||||
|
// A closed, network-free database exercises the handler's failure response.
|
||||||
|
db.Close()
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/api/v1/dashboard/summary", nil)
|
||||||
|
(&BusinessAPI{db: db}).dashboardSummary(c)
|
||||||
|
if w.Code != 500 || !strings.Contains(w.Body.String(), `"code":"internal_error"`) || !strings.Contains(w.Body.String(), `"message":"Service unavailable"`) || strings.Contains(w.Body.String(), "database is closed") {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
253
backend/internal/httpapi/downloads.go
Normal file
253
backend/internal/httpapi/downloads.go
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
var packageKeyPattern = regexp.MustCompile(`^[0-9a-f]{64}\.bin$`)
|
||||||
|
var releaseVersionPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
|
||||||
|
|
||||||
|
// Each package must be a regular file directly below a trusted, non-public root.
|
||||||
|
func localPackage(root, key string) (string, error) {
|
||||||
|
if root == "" || !filepath.IsAbs(root) || !packageKeyPattern.MatchString(key) {
|
||||||
|
return "", errors.New("invalid storage configuration")
|
||||||
|
}
|
||||||
|
realRoot, err := filepath.EvalSymlinks(root)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
path := filepath.Join(realRoot, key)
|
||||||
|
info, err := os.Lstat(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
return "", errors.New("not a regular package")
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) createRelease(c *gin.Context) {
|
||||||
|
productID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
version := c.Query("version")
|
||||||
|
root := os.Getenv("PACKAGE_STORAGE_ROOT")
|
||||||
|
if err != nil || productID == 0 || !releaseVersionPattern.MatchString(version) {
|
||||||
|
apiError(c, 400, "invalid_request", "产品或版本无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if root == "" || !filepath.IsAbs(root) {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储未配置")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
root, err = filepath.EvalSymlinks(root)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var active bool
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", productID).Scan(&active); err != nil || !active {
|
||||||
|
apiError(c, 409, "invalid_state", "产品不可发布")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
file, err := os.CreateTemp(root, ".upload-")
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer os.Remove(file.Name())
|
||||||
|
defer file.Close()
|
||||||
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<20)
|
||||||
|
hash := sha256.New()
|
||||||
|
n, err := io.Copy(io.MultiWriter(file, hash), c.Request.Body)
|
||||||
|
if err != nil || n == 0 {
|
||||||
|
apiError(c, 400, "invalid_package", "包为空或超过DEV 64MiB限制")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
digest := hex.EncodeToString(hash.Sum(nil))
|
||||||
|
key := digest + ".bin"
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO package_objects(sha256,size_bytes) VALUES(?,?) ON DUPLICATE KEY UPDATE sha256=sha256", digest, n); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "发布失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var storedSize int64
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT size_bytes FROM package_objects WHERE sha256=? FOR UPDATE", digest).Scan(&storedSize); err != nil || storedSize != n {
|
||||||
|
apiError(c, 409, "package_integrity", "包元数据不匹配")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = file.Sync(); err != nil {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
file.Close()
|
||||||
|
// Hard link publishes immutable bytes without overwriting an existing digest.
|
||||||
|
publishedPath := filepath.Join(root, key)
|
||||||
|
linked := false
|
||||||
|
if err = os.Link(file.Name(), publishedPath); err != nil && !os.IsExist(err) {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
linked = true
|
||||||
|
}
|
||||||
|
cleanupPublished := func() {
|
||||||
|
if linked {
|
||||||
|
_ = os.Remove(publishedPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
path, err := localPackage(root, key)
|
||||||
|
if err != nil {
|
||||||
|
cleanupPublished()
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
existing, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
cleanupPublished()
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
verify := sha256.New()
|
||||||
|
size, err := io.Copy(verify, existing)
|
||||||
|
existing.Close()
|
||||||
|
if err != nil || size != n || hex.EncodeToString(verify.Sum(nil)) != digest {
|
||||||
|
cleanupPublished()
|
||||||
|
apiError(c, 409, "package_integrity", "已存文件不匹配")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result, err := tx.ExecContext(c, "INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,?,?,?,?,?)", productID, version, key, digest, n, c.GetUint64("admin_id"))
|
||||||
|
if err != nil {
|
||||||
|
cleanupPublished()
|
||||||
|
apiError(c, 409, "release_conflict", "版本已存在或不可发布")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
cleanupPublished()
|
||||||
|
apiError(c, 500, "internal_error", "发布失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(gin.H{"product_id": productID, "version": version, "sha256": digest, "size_bytes": n})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'release.published','product_release',?,?)", c.GetUint64("admin_id"), id, details); err != nil {
|
||||||
|
cleanupPublished()
|
||||||
|
apiError(c, 500, "internal_error", "发布失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
// Commit can succeed remotely even when its acknowledgement is lost.
|
||||||
|
// Keep the private content object for reconciliation, never delete here.
|
||||||
|
apiError(c, 500, "internal_error", "发布失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(201, gin.H{"data": gin.H{"id": id, "product_id": productID, "version": version, "sha256": digest, "size_bytes": n}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) downloadRelease(c *gin.Context) {
|
||||||
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
|
||||||
|
var in struct {
|
||||||
|
InstanceID string `json:"instance_id"`
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(in.InstanceID) != 36 || len(in.Secret) > 128 {
|
||||||
|
apiError(c, 400, "invalid_request", "下载请求无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
|
||||||
|
if err != nil || len(raw) != 32 {
|
||||||
|
apiError(c, 403, "forbidden", "下载凭据无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
customerID, err := strconv.ParseUint(c.Param("customer_id"), 10, 64)
|
||||||
|
if err != nil || customerID == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "客户无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
releaseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || releaseID == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "版本无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var id, actor, owner, productID uint64
|
||||||
|
var stored []byte
|
||||||
|
var status, freeze, licenseStatus, customerStatus string
|
||||||
|
var active bool
|
||||||
|
var starts, expires, now time.Time
|
||||||
|
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.secret_hash,i.status,i.freeze_state,l.status,c.status,p.active,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id AND l.customer_id=i.customer_id AND l.product_id=i.product_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=? FOR UPDATE`, in.InstanceID).Scan(&id, &actor, &owner, &productID, &stored, &status, &freeze, &licenseStatus, &customerStatus, &active, &starts, &expires)
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
if err != nil || !bytesEqual(stored, sum[:]) {
|
||||||
|
apiError(c, 403, "forbidden", "下载凭据无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
allowed := owner == customerID && leaseState(status, freeze, licenseStatus, customerStatus, active, starts, expires, now) == "active"
|
||||||
|
var key, digest string
|
||||||
|
var n uint64
|
||||||
|
if allowed {
|
||||||
|
err = tx.QueryRowContext(c, "SELECT storage_key,sha256,size_bytes FROM product_releases WHERE id=? AND product_id=? AND published=1 FOR UPDATE", releaseID, productID).Scan(&key, &digest, &n)
|
||||||
|
allowed = err == nil
|
||||||
|
}
|
||||||
|
action := "release.download_denied"
|
||||||
|
if allowed {
|
||||||
|
action = "release.download_authorized"
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(gin.H{"instance_id": in.InstanceID, "customer_id": customerID, "release_id": releaseID, "client_actor": "instance"})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'license_instance',?,?)", actor, action, id, details); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "下载审计失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !allowed {
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "下载审计失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiError(c, 403, "forbidden", "无下载权限")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
path, err := localPackage(os.Getenv("PACKAGE_STORAGE_ROOT"), key)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil || uint64(info.Size()) != n {
|
||||||
|
apiError(c, 503, "storage_unavailable", "文件存储不匹配")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "下载审计失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Header("X-Accel-Redirect", "/_packages/"+key)
|
||||||
|
c.Header("Content-Type", "application/octet-stream")
|
||||||
|
c.Header("Content-Disposition", `attachment; filename="`+key+`"`)
|
||||||
|
c.Header("X-Package-SHA256", digest)
|
||||||
|
c.Header("Cache-Control", "private, no-store")
|
||||||
|
c.Status(200)
|
||||||
|
}
|
||||||
270
backend/internal/httpapi/downloads_integration_test.go
Normal file
270
backend/internal/httpapi/downloads_integration_test.go
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
osexec "os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDownloadsMySQLIntegration(t *testing.T) {
|
||||||
|
dsn := os.Getenv("DOWNLOAD_TEST_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("DOWNLOAD_TEST_DSN must name an isolated migrated database")
|
||||||
|
}
|
||||||
|
db, err := sql.Open("mysql", dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
root := t.TempDir()
|
||||||
|
t.Setenv("PACKAGE_STORAGE_ROOT", root)
|
||||||
|
exec := func(q string, args ...any) int64 {
|
||||||
|
t.Helper()
|
||||||
|
r, e := db.Exec(q, args...)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
id, _ := r.LastInsertId()
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
suffix := fmt.Sprint(time.Now().UnixNano())
|
||||||
|
admin := exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@download.test", "unused")
|
||||||
|
raw := make([]byte, 32)
|
||||||
|
rand.Read(raw)
|
||||||
|
sessionHash := sha256.Sum256(raw)
|
||||||
|
exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", admin, sessionHash[:], time.Now().Add(time.Hour))
|
||||||
|
cookie := &http.Cookie{Name: "lp_session", Value: hex.EncodeToString(raw)}
|
||||||
|
customer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'download@example.test')", suffix)
|
||||||
|
otherCustomer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'other@example.test')", suffix+"other")
|
||||||
|
product := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, suffix)
|
||||||
|
otherProduct := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", suffix)
|
||||||
|
license := exec("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", hex.EncodeToString(raw[:16]), customer, product, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix, admin)
|
||||||
|
secret := make([]byte, 32)
|
||||||
|
rand.Read(secret)
|
||||||
|
secretHash := sha256.Sum256(secret)
|
||||||
|
instanceID, _ := newInstanceID()
|
||||||
|
instanceRow := exec("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,status,created_by) VALUES(?,?,?,?,?,'activated',?)", instanceID, license, customer, product, secretHash[:], admin)
|
||||||
|
r := NewRouter()
|
||||||
|
RegisterBusiness(r, db)
|
||||||
|
req := func(path string, body io.Reader, auth bool) *httptest.ResponseRecorder {
|
||||||
|
q := httptest.NewRequest("POST", path, body)
|
||||||
|
if auth {
|
||||||
|
q.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
publish := func(p int64, v, body string, auth bool) *httptest.ResponseRecorder {
|
||||||
|
return req(fmt.Sprintf("/api/v1/products/%d/releases?version=%s", p, v), strings.NewReader(body), auth)
|
||||||
|
}
|
||||||
|
releaseID := func(w *httptest.ResponseRecorder) int64 {
|
||||||
|
t.Helper()
|
||||||
|
if w.Code != 201 {
|
||||||
|
t.Fatalf("publish %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var out struct{ Data struct{ ID int64 } }
|
||||||
|
if e := json.Unmarshal(w.Body.Bytes(), &out); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
return out.Data.ID
|
||||||
|
}
|
||||||
|
if w := publish(product, "unauth", "body", false); w.Code != 401 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
id := releaseID(publish(product, "v1", "package bytes", true))
|
||||||
|
otherID := releaseID(publish(otherProduct, "v1", "other bytes", true))
|
||||||
|
download := func(cust, id int64, sec string) *httptest.ResponseRecorder {
|
||||||
|
body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": sec})
|
||||||
|
return req(fmt.Sprintf("/api/v1/customers/%d/releases/%d/download", cust, id), strings.NewReader(string(body)), false)
|
||||||
|
}
|
||||||
|
encoded := base64.RawURLEncoding.EncodeToString(secret)
|
||||||
|
auditCount := func(action string) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action=? AND resource_type='license_instance' AND resource_id=?", action, instanceRow).Scan(&n); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
check := func(cust, id int64, sec string, code int) {
|
||||||
|
t.Helper()
|
||||||
|
w := download(cust, id, sec)
|
||||||
|
if w.Code != code {
|
||||||
|
t.Fatalf("download %d want %d: %s", w.Code, code, w.Body)
|
||||||
|
}
|
||||||
|
if code != 200 && w.Header().Get("X-Accel-Redirect") != "" {
|
||||||
|
t.Fatal("denied request exposes file redirect")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check(customer, id, encoded, 200)
|
||||||
|
deniedBefore := auditCount("release.download_denied")
|
||||||
|
exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(-time.Minute), license)
|
||||||
|
check(customer, id, encoded, 403)
|
||||||
|
if auditCount("release.download_denied") != deniedBefore+1 {
|
||||||
|
t.Fatal("expired download was not audited")
|
||||||
|
}
|
||||||
|
exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(time.Hour), license)
|
||||||
|
unpublished := exec("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,published,created_by) VALUES(?,?,?,?,?,0,?)", product, "unpublished", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin", strings.Repeat("a", 64), 1, admin)
|
||||||
|
deniedBefore = auditCount("release.download_denied")
|
||||||
|
check(customer, unpublished, encoded, 403)
|
||||||
|
if auditCount("release.download_denied") != deniedBefore+1 {
|
||||||
|
t.Fatal("unpublished download was not audited")
|
||||||
|
}
|
||||||
|
deniedBefore = auditCount("release.download_denied")
|
||||||
|
check(customer, id+999999, encoded, 403)
|
||||||
|
if auditCount("release.download_denied") != deniedBefore+1 {
|
||||||
|
t.Fatal("missing release was not audited")
|
||||||
|
}
|
||||||
|
check(otherCustomer, id, encoded, 403)
|
||||||
|
check(customer, otherID, encoded, 403)
|
||||||
|
check(customer, id, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), 403)
|
||||||
|
for _, state := range []struct{ deny, restore string }{
|
||||||
|
{"UPDATE license_instances SET freeze_state='frozen' WHERE license_id=?", "UPDATE license_instances SET freeze_state='none' WHERE license_id=?"},
|
||||||
|
{"UPDATE licenses SET status='revoked' WHERE id=?", "UPDATE licenses SET status='active' WHERE id=?"},
|
||||||
|
} {
|
||||||
|
exec(state.deny, license)
|
||||||
|
check(customer, id, encoded, 403)
|
||||||
|
exec(state.restore, license)
|
||||||
|
}
|
||||||
|
exec("UPDATE customers SET status='inactive' WHERE id=?", customer)
|
||||||
|
check(customer, id, encoded, 403)
|
||||||
|
exec("UPDATE customers SET status='active' WHERE id=?", customer)
|
||||||
|
exec("UPDATE products SET active=0 WHERE id=?", product)
|
||||||
|
check(customer, id, encoded, 403)
|
||||||
|
exec("UPDATE products SET active=1 WHERE id=?", product)
|
||||||
|
exec("CREATE TRIGGER download_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'")
|
||||||
|
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS download_audit_failure") })
|
||||||
|
check(customer, id, encoded, 500)
|
||||||
|
failedBody := "audit fails unique body"
|
||||||
|
digest := sha256.Sum256([]byte(failedBody))
|
||||||
|
if w := publish(product, "audit-fails", failedBody, true); w.Code != 500 {
|
||||||
|
t.Fatalf("audit upload %d", w.Code)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
db.QueryRow("SELECT COUNT(*) FROM product_releases WHERE version='audit-fails'").Scan(&count)
|
||||||
|
if count != 0 {
|
||||||
|
t.Fatal("failed release committed")
|
||||||
|
}
|
||||||
|
if _, e := os.Stat(filepath.Join(root, hex.EncodeToString(digest[:])+".bin")); !os.IsNotExist(e) {
|
||||||
|
t.Fatal("failed upload left new file")
|
||||||
|
}
|
||||||
|
exec("DROP TRIGGER download_audit_failure")
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
codes := make(chan int, 2)
|
||||||
|
for i, p := range []int64{product, otherProduct} {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(i int, p int64) {
|
||||||
|
defer wg.Done()
|
||||||
|
codes <- publish(p, fmt.Sprintf("concurrent-%d", i), "same digest bytes", true).Code
|
||||||
|
}(i, p)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(codes)
|
||||||
|
for code := range codes {
|
||||||
|
if code != 201 {
|
||||||
|
t.Fatalf("concurrent digest %d", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
digest = sha256.Sum256([]byte("same digest bytes"))
|
||||||
|
data, e := os.ReadFile(filepath.Join(root, hex.EncodeToString(digest[:])+".bin"))
|
||||||
|
if e != nil || string(data) != "same digest bytes" {
|
||||||
|
t.Fatal("shared digest damaged")
|
||||||
|
}
|
||||||
|
if w := publish(product, "v1", "conflicting version bytes", true); w.Code != 409 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
if w := publish(product, "empty", "", true); w.Code != 400 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
for _, n := range []int64{64 << 20, (64 << 20) + 1} {
|
||||||
|
w := req(fmt.Sprintf("/api/v1/products/%d/releases?version=limit-%d", product, n), io.LimitReader(zeroReader{}, n), true)
|
||||||
|
want := 201
|
||||||
|
if n > 64<<20 {
|
||||||
|
want = 400
|
||||||
|
}
|
||||||
|
if w.Code != want {
|
||||||
|
t.Fatalf("size %d code=%d want=%d %s", n, w.Code, want, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files, _ := filepath.Glob(filepath.Join(root, ".upload-*"))
|
||||||
|
if len(files) != 0 {
|
||||||
|
t.Fatal("temporary uploads leaked")
|
||||||
|
}
|
||||||
|
if os.Getenv("DOWNLOAD_NGINX_E2E") == "1" {
|
||||||
|
server := &http.Server{Addr: "0.0.0.0:18082", Handler: r}
|
||||||
|
go server.ListenAndServe()
|
||||||
|
defer server.Close()
|
||||||
|
conf, _ := filepath.Abs("../../../deploy/nginx/download-local.conf")
|
||||||
|
cmd := osexec.Command("docker", "run", "-d", "--name", "license-download-e2e", "-p", "127.0.0.1:18181:18181", "--mount", "type=bind,source="+root+",target=/srv/license-packages,readonly", "--mount", "type=bind,source="+conf+",target=/etc/nginx/conf.d/default.conf,readonly", "nginx:stable-alpine")
|
||||||
|
if out, e := cmd.CombinedOutput(); e != nil {
|
||||||
|
t.Fatalf("nginx start: %v %s", e, out)
|
||||||
|
}
|
||||||
|
defer osexec.Command("docker", "stop", "license-download-e2e").Run()
|
||||||
|
defer osexec.Command("docker", "rm", "-f", "license-download-e2e").Run()
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
client := &http.Client{Timeout: 10 * time.Second}
|
||||||
|
body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": encoded})
|
||||||
|
url := fmt.Sprintf("http://127.0.0.1:18181/api/v1/customers/%d/releases/%d/download", customer, id)
|
||||||
|
for _, partial := range []bool{false, true} {
|
||||||
|
q, _ := http.NewRequest("POST", url, strings.NewReader(string(body)))
|
||||||
|
q.Header.Set("Content-Type", "application/json")
|
||||||
|
if partial {
|
||||||
|
q.Header.Set("Range", "bytes=0-6")
|
||||||
|
}
|
||||||
|
resp, e := client.Do(q)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
b, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if partial {
|
||||||
|
if resp.StatusCode != 206 || string(b) != "package" {
|
||||||
|
t.Fatalf("range %d %q", resp.StatusCode, b)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sum := sha256.Sum256(b)
|
||||||
|
if resp.StatusCode != 200 || string(b) != "package bytes" || hex.EncodeToString(sum[:]) != resp.Header.Get("X-Package-SHA256") {
|
||||||
|
t.Fatalf("bytes/hash %d %q", resp.StatusCode, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
direct := download(customer, id, encoded).Header().Get("X-Accel-Redirect")
|
||||||
|
resp, e := client.Get("http://127.0.0.1:18181" + direct)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != 404 && resp.StatusCode != 403 {
|
||||||
|
t.Fatalf("public internal path %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
resp, e = client.Post(url, "application/json", strings.NewReader("{}"))
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode < 400 {
|
||||||
|
t.Fatal("unauthenticated download succeeded")
|
||||||
|
}
|
||||||
|
t.Log("Nginx 18181: actual bytes/SHA256, Range 206, external internal-path denial and unauthenticated denial verified; temporary E2E service stopped")
|
||||||
|
}
|
||||||
|
t.Log("customer/product/state isolation, wrong secret, audit rollback, file cleanup, duplicate digest concurrency and exact 64MiB boundary verified")
|
||||||
|
}
|
||||||
|
|
||||||
|
type zeroReader struct{}
|
||||||
|
|
||||||
|
func (zeroReader) Read(p []byte) (int, error) { clear(p); return len(p), nil }
|
||||||
34
backend/internal/httpapi/downloads_test.go
Normal file
34
backend/internal/httpapi/downloads_test.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLocalPackageRejectsTraversalAndSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
good := filepath.Join(root, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin")
|
||||||
|
if err := os.WriteFile(good, []byte("ok"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := localPackage(root, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, key := range []string{"../secret.bin", "short.bin", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.bin"} {
|
||||||
|
if _, err := localPackage(root, key); err == nil {
|
||||||
|
t.Fatalf("accepted unsafe key %q", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outside := filepath.Join(t.TempDir(), "outside.bin")
|
||||||
|
if err := os.WriteFile(outside, []byte("secret"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
link := filepath.Join(root, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.bin")
|
||||||
|
if err := os.Symlink(outside, link); err != nil {
|
||||||
|
t.Skipf("symlink unavailable: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := localPackage(root, filepath.Base(link)); err == nil {
|
||||||
|
t.Fatal("accepted symlink package")
|
||||||
|
}
|
||||||
|
}
|
||||||
213
backend/internal/httpapi/heartbeat.go
Normal file
213
backend/internal/httpapi/heartbeat.go
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxOfflineLease = 14 * 24 * time.Hour
|
||||||
|
const heartbeatInterval = time.Minute
|
||||||
|
const clockTolerance = 5 * time.Minute
|
||||||
|
|
||||||
|
type leasePayload struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
InstanceID string `json:"instance_id"`
|
||||||
|
State string `json:"state"`
|
||||||
|
ServerTime string `json:"server_time"`
|
||||||
|
EntitlementExpiresAt string `json:"entitlement_expires_at"`
|
||||||
|
LeaseExpiresAt string `json:"lease_expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalLease(p leasePayload) string {
|
||||||
|
return strings.Join([]string{"version=" + p.Version, "instance_id=" + p.InstanceID, "state=" + p.State, "server_time=" + p.ServerTime, "entitlement_expires_at=" + p.EntitlementExpiresAt, "lease_expires_at=" + p.LeaseExpiresAt}, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func leaseState(instanceStatus, freeze, licenseStatus, customerStatus string, productActive bool, starts, expires, now time.Time) string {
|
||||||
|
if licenseStatus == "revoked" {
|
||||||
|
return "revoked"
|
||||||
|
}
|
||||||
|
if freeze == "frozen" || customerStatus != "active" || !productActive {
|
||||||
|
return "frozen"
|
||||||
|
}
|
||||||
|
if instanceStatus != "activated" {
|
||||||
|
return "not_activated"
|
||||||
|
}
|
||||||
|
return currentLicenseStatus(licenseStatus, starts, expires, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
func boundedLease(now, entitlement time.Time) time.Time {
|
||||||
|
end := now.Add(maxOfflineLease)
|
||||||
|
if entitlement.Before(end) {
|
||||||
|
end = entitlement
|
||||||
|
}
|
||||||
|
return end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) heartbeat(c *gin.Context) {
|
||||||
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
|
||||||
|
key, ok := parseOperationKey(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
ClientTime string `json:"client_time"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || len(in.Secret) > 128 {
|
||||||
|
apiError(c, 400, "invalid_request", "心跳请求无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
|
||||||
|
if err != nil || len(raw) != 32 {
|
||||||
|
apiError(c, 403, "forbidden", "实例凭据无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientTime, err := time.Parse(time.RFC3339Nano, in.ClientTime)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "client_time 必须为 RFC3339")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientTime = clientTime.UTC().Truncate(time.Microsecond)
|
||||||
|
hash := sha256.Sum256(raw)
|
||||||
|
fingerprint := sha256.Sum256([]byte(clientTime.Format(time.RFC3339Nano)))
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
fail := func() { apiError(c, 500, "internal_error", "心跳失败,请使用相同幂等键重试") }
|
||||||
|
var id, actor uint64
|
||||||
|
var stored []byte
|
||||||
|
var instanceStatus, freeze, licenseStatus, customerStatus string
|
||||||
|
var productActive bool
|
||||||
|
var starts, expires time.Time
|
||||||
|
var last, previousClient sql.NullTime
|
||||||
|
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.secret_hash,i.status,i.freeze_state,i.last_seen_at,i.client_seen_at,l.status,l.starts_at,l.expires_at,c.status,p.active FROM license_instances i JOIN licenses l ON l.id=i.license_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=? FOR UPDATE`, c.Param("instance_id")).Scan(&id, &actor, &stored, &instanceStatus, &freeze, &last, &previousClient, &licenseStatus, &starts, &expires, &customerStatus, &productActive)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 403, "forbidden", "实例凭据无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !bytesEqual(stored, hash[:]) {
|
||||||
|
apiError(c, 403, "forbidden", "实例凭据无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var now time.Time
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now = now.UTC()
|
||||||
|
if last.Valid && now.Before(last.Time.Add(-clockTolerance)) {
|
||||||
|
apiError(c, 409, "server_clock_rollback", "服务时钟回拨,暂停签发租约")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if last.Valid && now.Before(last.Time) {
|
||||||
|
now = last.Time.UTC()
|
||||||
|
}
|
||||||
|
state := leaseState(instanceStatus, freeze, licenseStatus, customerStatus, productActive, starts, expires, now)
|
||||||
|
var oldFingerprint, oldResponse []byte
|
||||||
|
var oldState string
|
||||||
|
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response,state FROM heartbeat_operations WHERE instance_id=? AND idempotency_key=?", id, key).Scan(&oldFingerprint, &oldResponse, &oldState)
|
||||||
|
if err == nil {
|
||||||
|
if !bytesEqual(oldFingerprint, fingerprint[:]) {
|
||||||
|
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同心跳")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if oldState != state {
|
||||||
|
apiError(c, 409, "state_changed", "实例状态已变化,请使用新幂等键心跳")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var replay any
|
||||||
|
if json.Unmarshal(oldResponse, &replay) != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, replay)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if clientTime.Before(now.Add(-clockTolerance)) || clientTime.After(now.Add(clockTolerance)) || (previousClient.Valid && clientTime.Before(previousClient.Time.Add(-clockTolerance))) {
|
||||||
|
apiError(c, 409, "clock_skew", "客户端时钟偏差或回拨超过五分钟")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// State changes bypass the normal interval so revocation/freeze can propagate promptly.
|
||||||
|
var observed string
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT observed_state FROM license_instances WHERE id=?", id).Scan(&observed); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if last.Valid && now.Sub(last.Time) < heartbeatInterval && state == observed {
|
||||||
|
c.Header("Retry-After", "60")
|
||||||
|
apiError(c, 429, "rate_limited", "心跳间隔至少一分钟")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
privateKey, err := readSigningKey(a.signingPrivateKeyPEM)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "signing_unavailable", "签名服务不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
leaseEnd := now
|
||||||
|
if state == "active" {
|
||||||
|
leaseEnd = boundedLease(now, expires)
|
||||||
|
}
|
||||||
|
payload := leasePayload{"lease-v1", c.Param("instance_id"), state, now.Format(time.RFC3339Nano), expires.UTC().Format(time.RFC3339Nano), leaseEnd.Format(time.RFC3339Nano)}
|
||||||
|
canonical := canonicalLease(payload)
|
||||||
|
var responsePayload any = payload
|
||||||
|
if a.keyring != nil {
|
||||||
|
payload.Version = "lease-v2"
|
||||||
|
canonical = canonicalLease(payload) + "\nkey_id=" + a.keyring.Current
|
||||||
|
responsePayload = gin.H{"version": payload.Version, "instance_id": payload.InstanceID, "state": payload.State, "server_time": payload.ServerTime, "entitlement_expires_at": payload.EntitlementExpiresAt, "lease_expires_at": payload.LeaseExpiresAt, "key_id": a.keyring.Current}
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256([]byte(canonical))
|
||||||
|
sig, err := ecdsa.SignASN1(rand.Reader, privateKey, digest[:])
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response := gin.H{"data": gin.H{"payload": responsePayload, "signature": base64.RawStdEncoding.EncodeToString(sig), "canonical_sha256": hex.EncodeToString(digest[:]), "algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": 60}}
|
||||||
|
responseJSON, err := json.Marshal(response)
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if previousClient.Valid && clientTime.Before(previousClient.Time) {
|
||||||
|
clientTime = previousClient.Time.UTC()
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE license_instances SET last_seen_at=?,client_seen_at=?,lease_expires_at=?,observed_state=? WHERE id=?", now, clientTime, leaseEnd, state, id); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO heartbeat_operations(instance_id,idempotency_key,request_fingerprint,response,state) VALUES(?,?,?,?,?)", id, key, fingerprint[:], responseJSON, state); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(gin.H{"state": state, "previous_state": observed, "lease_expires_at": leaseEnd, "client_actor": "instance"})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.heartbeat','license_instance',?,?)", actor, id, details); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, response)
|
||||||
|
}
|
||||||
140
backend/internal/httpapi/heartbeat_integration_test.go
Normal file
140
backend/internal/httpapi/heartbeat_integration_test.go
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testHeartbeatMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Cookie, instanceID, secret string, licenseID uint64, publicKey *ecdsa.PublicKey) {
|
||||||
|
request := func(path, body, key string, auth bool) *httptest.ResponseRecorder {
|
||||||
|
req := httptest.NewRequest("POST", path, strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Idempotency-Key", key)
|
||||||
|
if auth {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
path := "/api/v1/instances/" + instanceID + "/heartbeat"
|
||||||
|
bodyFor := func(secret string, at time.Time) string {
|
||||||
|
b, _ := json.Marshal(gin.H{"secret": secret, "client_time": at.UTC().Format(time.RFC3339Nano)})
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
body := bodyFor(secret, now)
|
||||||
|
if w := request(path, bodyFor(base64.RawURLEncoding.EncodeToString(make([]byte, 32)), now), "wrong", false); w.Code != 403 {
|
||||||
|
t.Fatalf("wrong secret status=%d", w.Code)
|
||||||
|
}
|
||||||
|
if _, err := db.Exec("CREATE TRIGGER heartbeat_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS heartbeat_audit_failure") })
|
||||||
|
if w := request(path, body, "first", false); w.Code != 500 {
|
||||||
|
t.Fatalf("rollback status=%d", w.Code)
|
||||||
|
}
|
||||||
|
var last sql.NullTime
|
||||||
|
db.QueryRow("SELECT last_seen_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&last)
|
||||||
|
if last.Valid {
|
||||||
|
t.Fatal("audit failure committed last_seen")
|
||||||
|
}
|
||||||
|
db.Exec("DROP TRIGGER heartbeat_audit_failure")
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
results := make(chan *httptest.ResponseRecorder, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() { defer wg.Done(); results <- request(path, body, "first", false) }()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(results)
|
||||||
|
var response struct {
|
||||||
|
Data struct {
|
||||||
|
Payload leasePayload `json:"payload"`
|
||||||
|
Signature string `json:"signature"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for w := range results {
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatalf("concurrent status=%d", w.Code)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256([]byte(canonicalLease(response.Data.Payload)))
|
||||||
|
sig, err := base64.RawStdEncoding.DecodeString(response.Data.Signature)
|
||||||
|
if err != nil || !ecdsa.VerifyASN1(publicKey, digest[:], sig) {
|
||||||
|
t.Fatal("lease signature invalid")
|
||||||
|
}
|
||||||
|
p := response.Data.Payload
|
||||||
|
server, _ := time.Parse(time.RFC3339Nano, p.ServerTime)
|
||||||
|
end, _ := time.Parse(time.RFC3339Nano, p.LeaseExpiresAt)
|
||||||
|
entitlement, _ := time.Parse(time.RFC3339Nano, p.EntitlementExpiresAt)
|
||||||
|
if p.State != "active" || end.After(server.Add(maxOfflineLease)) || end.After(entitlement) {
|
||||||
|
t.Fatal("lease bound invalid")
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
db.QueryRow("SELECT COUNT(*) FROM heartbeat_operations").Scan(&count)
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatal("duplicate heartbeat operation")
|
||||||
|
}
|
||||||
|
if w := request(path, body, "new", false); w.Code != 429 {
|
||||||
|
t.Fatalf("limit status=%d", w.Code)
|
||||||
|
}
|
||||||
|
if w := request(path, bodyFor(secret, now.Add(time.Second)), "first", false); w.Code != 409 {
|
||||||
|
t.Fatalf("conflict=%d", w.Code)
|
||||||
|
}
|
||||||
|
if w := request(path, bodyFor(secret, now.Add(-time.Hour)), "clock", false); w.Code != 409 {
|
||||||
|
t.Fatalf("clock skew=%d", w.Code)
|
||||||
|
}
|
||||||
|
freezePath := "/api/v1/instances/" + instanceID + "/freeze"
|
||||||
|
if w := request(freezePath, `{"frozen":true}`, "freeze", false); w.Code != 401 {
|
||||||
|
t.Fatal("freeze unauthorized")
|
||||||
|
}
|
||||||
|
if w := request(freezePath, `{"frozen":true}`, "freeze", true); w.Code != 200 {
|
||||||
|
t.Fatalf("freeze=%d", w.Code)
|
||||||
|
}
|
||||||
|
if w := request(path, body, "first", false); w.Code != 409 {
|
||||||
|
t.Fatal("old allow replay masked freeze")
|
||||||
|
}
|
||||||
|
w := request(path, body, "frozen", false)
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatalf("frozen heartbeat=%d", w.Code)
|
||||||
|
}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &response)
|
||||||
|
if response.Data.Payload.State != "frozen" || response.Data.Payload.LeaseExpiresAt != response.Data.Payload.ServerTime {
|
||||||
|
t.Fatal("frozen lease allowed use")
|
||||||
|
}
|
||||||
|
if w = request(freezePath, `{"frozen":false}`, "unfreeze", true); w.Code != 200 {
|
||||||
|
t.Fatal("unfreeze failed")
|
||||||
|
}
|
||||||
|
w = request(path, body, "resume", false)
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal("resume heartbeat failed")
|
||||||
|
}
|
||||||
|
revokePath := "/api/v1/licenses/" + strconv.FormatUint(licenseID, 10) + "/revoke"
|
||||||
|
if w = request(revokePath, `{}`, "heartbeat-revoke", true); w.Code != 200 {
|
||||||
|
t.Fatalf("revoke=%d", w.Code)
|
||||||
|
}
|
||||||
|
w = request(path, body, "revoked", false)
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatalf("revoked heartbeat=%d", w.Code)
|
||||||
|
}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &response)
|
||||||
|
if response.Data.Payload.State != "revoked" {
|
||||||
|
t.Fatal("revocation not propagated")
|
||||||
|
}
|
||||||
|
}
|
||||||
67
backend/internal/httpapi/heartbeat_test.go
Normal file
67
backend/internal/httpapi/heartbeat_test.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLeaseBoundsAndCanonical(t *testing.T) {
|
||||||
|
now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
|
||||||
|
far := now.AddDate(10, 0, 0)
|
||||||
|
if got := boundedLease(now, far); !got.Equal(now.Add(14 * 24 * time.Hour)) {
|
||||||
|
t.Fatal("far-future entitlement gave permanent offline lease")
|
||||||
|
}
|
||||||
|
short := now.Add(time.Hour)
|
||||||
|
if !boundedLease(now, short).Equal(short) {
|
||||||
|
t.Fatal("lease exceeded entitlement")
|
||||||
|
}
|
||||||
|
p := leasePayload{"lease-v1", "00000000-0000-4000-8000-000000000001", "active", "2026-09-30T12:00:00Z", "2036-09-30T12:00:00Z", "2026-10-14T12:00:00Z"}
|
||||||
|
expected := "version=lease-v1\ninstance_id=00000000-0000-4000-8000-000000000001\nstate=active\nserver_time=2026-09-30T12:00:00Z\nentitlement_expires_at=2036-09-30T12:00:00Z\nlease_expires_at=2026-10-14T12:00:00Z"
|
||||||
|
if canonicalLease(p) != expected {
|
||||||
|
t.Fatal("canonical lease changed")
|
||||||
|
}
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256([]byte(expected))
|
||||||
|
signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
der, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ecdsa.VerifyASN1(&key.PublicKey, digest[:], signature) {
|
||||||
|
t.Fatal("signature failed")
|
||||||
|
}
|
||||||
|
_ = der
|
||||||
|
block, _ := pem.Decode([]byte("-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz39VZCPp0fPgbDhKOM0jUHqzJAe3\n7GSZpcSe1TO9UGqv8BO3PBI8Th3Z9Fy5EdPaVggh8V/pjW/dcsUg9QbzWA==\n-----END PUBLIC KEY-----"))
|
||||||
|
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fixedSig, err := base64.RawStdEncoding.DecodeString("MEQCIFHuseC8F3iv6Jz9W3yywkacJ5qBOcDRJSNFLdFWS2w9AiBRZEmPGOzti3IJ0VOPccUOmmtVfWs6ZxtjcSDKJLH8BQ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if hex.EncodeToString(digest[:]) != "777150ed1107b51f17dd1ffaefac303310a32ec415e3d83a4b16cb05b9aac379" || !ecdsa.VerifyASN1(pub.(*ecdsa.PublicKey), digest[:], fixedSig) {
|
||||||
|
t.Fatal("published vector invalid")
|
||||||
|
}
|
||||||
|
changed := sha256.Sum256([]byte(expected + "\n"))
|
||||||
|
if ecdsa.VerifyASN1(pub.(*ecdsa.PublicKey), changed[:], fixedSig) {
|
||||||
|
t.Fatal("tampered vector accepted")
|
||||||
|
}
|
||||||
|
if leaseState("activated", "frozen", "revoked", "active", true, now.Add(-time.Hour), far, now) != "revoked" {
|
||||||
|
t.Fatal("revocation must dominate freeze")
|
||||||
|
}
|
||||||
|
}
|
||||||
92
backend/internal/httpapi/instance_freeze.go
Normal file
92
backend/internal/httpapi/instance_freeze.go
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *BusinessAPI) freezeInstance(c *gin.Context) {
|
||||||
|
key, ok := parseOperationKey(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
Frozen *bool `json:"frozen"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || in.Frozen == nil {
|
||||||
|
apiError(c, 400, "invalid_request", "必须指定 frozen")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state := "none"
|
||||||
|
if *in.Frozen {
|
||||||
|
state = "frozen"
|
||||||
|
}
|
||||||
|
fingerprint := sha256.Sum256([]byte(c.Param("instance_id") + "\x00" + state))
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
fail := func() { apiError(c, 500, "internal_error", "冻结操作失败,请使用相同幂等键重试") }
|
||||||
|
actor := c.MustGet("admin_id")
|
||||||
|
var adminID uint64
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? FOR UPDATE", actor).Scan(&adminID); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var id uint64
|
||||||
|
var previous string
|
||||||
|
err = tx.QueryRowContext(c, "SELECT id,freeze_state FROM license_instances WHERE instance_id=? FOR UPDATE", c.Param("instance_id")).Scan(&id, &previous)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "实例不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var oldFingerprint, oldResponse []byte
|
||||||
|
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM instance_state_operations WHERE actor_admin_id=? AND idempotency_key=?", actor, key).Scan(&oldFingerprint, &oldResponse)
|
||||||
|
if err == nil {
|
||||||
|
if !bytesEqual(oldFingerprint, fingerprint[:]) {
|
||||||
|
apiError(c, 409, "idempotency_conflict", "幂等键请求不同")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var replay any
|
||||||
|
if json.Unmarshal(oldResponse, &replay) != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, replay)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE license_instances SET freeze_state=? WHERE id=?", state, id); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response := gin.H{"data": gin.H{"instance_id": c.Param("instance_id"), "freeze_state": state}}
|
||||||
|
encoded, _ := json.Marshal(response)
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO instance_state_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?)", id, actor, key, fingerprint[:], encoded); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(gin.H{"previous_state": previous, "freeze_state": state})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.freeze_changed','license_instance',?,?)", actor, id, details); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, response)
|
||||||
|
}
|
||||||
106
backend/internal/httpapi/integration_archive.go
Normal file
106
backend/internal/httpapi/integration_archive.go
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func languageRequirements(language string) string {
|
||||||
|
return map[string]string{
|
||||||
|
"python": "Python:使用 cryptography 的 ECDSA(SHA256) 和 httpx;base64 补齐填充后解码 DER;pytest 覆盖验签与状态机。密钥库通过可注入接口实现,禁止以硬编码加密密钥充当保护。",
|
||||||
|
"go": "Go:使用 crypto/ecdsa.VerifyASN1、crypto/x509、sha256 和 base64.RawStdEncoding;所有网络调用支持 context、超时及取消;sync.Mutex 与跨进程文件锁保护状态;go test 覆盖行为。",
|
||||||
|
"java": "Java:使用 JCA SHA256withECDSA、KeyFactory EC、X509EncodedKeySpec 与 HttpClient;Base64 解码 DER;受控调度器与原子文件替换;JUnit 覆盖行为。",
|
||||||
|
"dotnet": ".NET:使用 ECDsa.VerifyData 并显式选择 DSASignatureFormat.Rfc3279DerSequence,不使用默认 P1363;HttpClient、CancellationToken、受控 IHostedService 与可注入受保护存储;xUnit 覆盖行为。",
|
||||||
|
"nodejs": "Node.js:使用 node:crypto 的 verify('sha256', canonicalBytes, publicKey, DER),参照 client/verify.mjs;使用安全整数解析 ID;node:test 覆盖行为;不得将服务端 SDK 打包进浏览器。",
|
||||||
|
}[language]
|
||||||
|
}
|
||||||
|
|
||||||
|
func signedKitVectors() ([]byte, error) {
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
publicDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sign := func(payload map[string]any, canonical string) (map[string]any, error) {
|
||||||
|
digest := sha256.Sum256([]byte(canonical))
|
||||||
|
signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"payload": payload, "signature": base64.RawStdEncoding.EncodeToString(signature), "canonical_sha256": hex.EncodeToString(digest[:]), "canonical": canonical}, nil
|
||||||
|
}
|
||||||
|
instance := "11111111-2222-3333-4444-555555555555"
|
||||||
|
licensePayload := map[string]any{"version": "license-v2", "instance_id": instance, "license_id": 1, "customer_id": 2, "product_id": 3, "starts_at": "2026-10-09T03:00:00Z", "expires_at": "2027-10-09T03:00:00Z", "key_id": "integration-test-only"}
|
||||||
|
licenseCanonical := "version=license-v2\ninstance_id=" + instance + "\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-10-09T03:00:00Z\nexpires_at=2027-10-09T03:00:00Z\nkey_id=integration-test-only"
|
||||||
|
leasePayload := map[string]any{"version": "lease-v2", "instance_id": instance, "state": "active", "server_time": "2026-10-09T03:00:00Z", "entitlement_expires_at": "2027-10-09T03:00:00Z", "lease_expires_at": "2026-10-23T03:00:00Z", "key_id": "integration-test-only"}
|
||||||
|
leaseCanonical := "version=lease-v2\ninstance_id=" + instance + "\nstate=active\nserver_time=2026-10-09T03:00:00Z\nentitlement_expires_at=2027-10-09T03:00:00Z\nlease_expires_at=2026-10-23T03:00:00Z\nkey_id=integration-test-only"
|
||||||
|
license, err := sign(licensePayload, licenseCanonical)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
lease, err := sign(leasePayload, leaseCanonical)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return json.MarshalIndent(map[string]any{"warning": "TEST ONLY: never trust this key in production; use frozen now=2026-10-09T03:00:00Z for state tests", "pinned_keys": []map[string]any{{"key_id": "integration-test-only", "public_key_pem": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER})), "revoked": false}}, "license": license, "lease": lease}, "", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
|
||||||
|
language, mode, ok := integrationKitInput(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
vectors, err := signedKitVectors()
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "测试资料生成失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
kit := buildIntegrationKit(language, mode)
|
||||||
|
files := map[string][]byte{
|
||||||
|
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md 与 openapi.json,将 prompt.md 提供给实现工程师。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"),
|
||||||
|
"prompt.md": []byte(kit.Prompt),
|
||||||
|
"test-vectors.json": vectors,
|
||||||
|
}
|
||||||
|
for _, name := range []string{"protocol.md", "openapi.json"} {
|
||||||
|
content, err := integrationAsset(name)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "接入资料不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files[name] = content
|
||||||
|
}
|
||||||
|
var buffer bytes.Buffer
|
||||||
|
archive := zip.NewWriter(&buffer)
|
||||||
|
for _, name := range []string{"README.md", "protocol.md", "openapi.json", "prompt.md", "test-vectors.json"} {
|
||||||
|
file, err := archive.Create(name)
|
||||||
|
if err == nil {
|
||||||
|
_, err = file.Write(files[name])
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "接入包生成失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := archive.Close(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "接入包生成失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Header("Cache-Control", "no-store")
|
||||||
|
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s.zip", language, mode))
|
||||||
|
c.Data(200, "application/zip", buffer.Bytes())
|
||||||
|
}
|
||||||
43
backend/internal/httpapi/integration_assets/openapi.json
Normal file
43
backend/internal/httpapi/integration_assets/openapi.json
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"openapi": "3.0.3",
|
||||||
|
"info": {"title": "License Platform Client API", "version": "1.0.0", "description": "Client-facing endpoints. Admin session is not a client credential. See protocol.md for canonical signature and trust-root rules."},
|
||||||
|
"servers": [{"url": "https://license.example.com", "description": "Replace with deployed HTTPS origin"}],
|
||||||
|
"paths": {
|
||||||
|
"/api/v1/activation/instances/{instance_id}": {"post": {
|
||||||
|
"operationId": "activateInstance", "summary": "Activate pre-provisioned instance",
|
||||||
|
"parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}],
|
||||||
|
"requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["license_key", "secret"], "properties": {"license_key": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}},
|
||||||
|
"responses": {"200": {"description": "Activation certificate; verify data.certificate before accepting", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"instance_id": {"type": "string"}, "status": {"type": "string", "enum": ["activated"]}, "certificate": {"$ref": "#/components/schemas/Certificate"}}}, "idempotent_replay": {"type": "boolean"}}}}}}, "default": {"$ref": "#/components/responses/Error"}}
|
||||||
|
}},
|
||||||
|
"/api/v1/instances/{instance_id}/heartbeat": {"post": {
|
||||||
|
"operationId": "heartbeat", "summary": "Refresh signed runtime lease",
|
||||||
|
"parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}],
|
||||||
|
"requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["secret", "client_time"], "properties": {"secret": {"type": "string", "format": "password"}, "client_time": {"type": "string", "format": "date-time"}}}}}},
|
||||||
|
"responses": {"200": {"description": "Signed lease; HTTP 200 does not imply active state", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Lease"}}}}}}, "429": {"description": "Rate limited; respect Retry-After", "headers": {"Retry-After": {"schema": {"type": "string"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "default": {"$ref": "#/components/responses/Error"}}
|
||||||
|
}},
|
||||||
|
"/api/v1/customers/{customer_id}/releases/{id}/download": {"post": {
|
||||||
|
"operationId": "downloadRelease", "summary": "Download entitled release; repeat credentials for Range retries",
|
||||||
|
"parameters": [{"name": "customer_id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "Range", "in": "header", "schema": {"type": "string"}}],
|
||||||
|
"requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["instance_id", "secret"], "properties": {"instance_id": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}},
|
||||||
|
"responses": {"200": {"description": "Full file (through configured download gateway)", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "206": {"description": "Partial file", "headers": {"Content-Range": {"schema": {"type": "string"}}}, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "416": {"description": "Unsatisfiable Range"}, "default": {"$ref": "#/components/responses/Error"}}
|
||||||
|
}},
|
||||||
|
"/api/v1/activation/keyring": {"get": {
|
||||||
|
"operationId": "discoverKeyring", "summary": "Discovery only, NOT a trust-root bootstrap",
|
||||||
|
"responses": {"200": {"description": "Configured verification keys", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"current_key_id": {"type": "string"}, "keys": {"type": "array", "items": {"type": "object", "properties": {"key_id": {"type": "string"}, "public_key_pem": {"type": "string"}, "revoked": {"type": "boolean"}}}}}}}}}}}, "default": {"$ref": "#/components/responses/Error"}}
|
||||||
|
}}
|
||||||
|
},
|
||||||
|
"components": {
|
||||||
|
"parameters": {
|
||||||
|
"InstanceID": {"name": "instance_id", "in": "path", "required": true, "schema": {"type": "string"}},
|
||||||
|
"IdempotencyKey": {"name": "Idempotency-Key", "in": "header", "required": true, "schema": {"type": "string"}, "description": "Same key and unchanged body for retries of one operation; new key for a new operation"}
|
||||||
|
},
|
||||||
|
"responses": {"Error": {"description": "See error.code and HTTP status; never blindly retry conflicts", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}},
|
||||||
|
"schemas": {
|
||||||
|
"Error": {"type": "object", "properties": {"error": {"type": "object", "properties": {"code": {"type": "string"}, "message": {"type": "string"}}}}},
|
||||||
|
"Certificate": {"type": "object", "required": ["version", "payload", "signature", "canonical_sha256"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "payload": {"$ref": "#/components/schemas/CertificatePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}}},
|
||||||
|
"CertificatePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "license_id", "customer_id", "product_id", "starts_at", "expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "instance_id": {"type": "string"}, "license_id": {"type": "integer", "minimum": 1}, "customer_id": {"type": "integer", "minimum": 1}, "product_id": {"type": "integer", "minimum": 1}, "starts_at": {"type": "string", "format": "date-time"}, "expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}},
|
||||||
|
"Lease": {"type": "object", "required": ["payload", "signature", "canonical_sha256", "algorithm", "next_heartbeat_seconds"], "properties": {"payload": {"$ref": "#/components/schemas/LeasePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}, "algorithm": {"type": "string", "enum": ["ECDSA-P256-SHA256"]}, "next_heartbeat_seconds": {"type": "integer", "minimum": 60}}},
|
||||||
|
"LeasePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "state", "server_time", "entitlement_expires_at", "lease_expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["lease-v2"]}, "instance_id": {"type": "string"}, "state": {"type": "string", "enum": ["active", "frozen", "revoked", "expired", "not_started", "not_activated"]}, "server_time": {"type": "string", "format": "date-time"}, "entitlement_expires_at": {"type": "string", "format": "date-time"}, "lease_expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
75
backend/internal/httpapi/integration_assets/protocol.md
Normal file
75
backend/internal/httpapi/integration_assets/protocol.md
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
# 客户端接入协议 1.0
|
||||||
|
|
||||||
|
本资料对应当前平台实现,不是独立完成生产验收的 SDK。运行 API 基地址由部署方提供,例如 https://license.example.com。必须使用 HTTPS,并验证服务端证书。管理员接口仅用于交付实例凭据,不应封装到客户端中。
|
||||||
|
|
||||||
|
## 交付与激活
|
||||||
|
|
||||||
|
管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和一次性 secret。secret 无法从后台恢复;不得跨安装复制共享凭据。
|
||||||
|
|
||||||
|
POST /api/v1/activation/instances/{instance_id}
|
||||||
|
|
||||||
|
头部:Content-Type: application/json,Idempotency-Key: 唯一业务操作标识。
|
||||||
|
|
||||||
|
请求:{"license_key":"部署方交付值","secret":"部署方交付值"}
|
||||||
|
|
||||||
|
成功 200:{"data":{"instance_id":"...","status":"activated","certificate":{"version":"license-v2","payload":{},"signature":"...","canonical_sha256":"..."}},"idempotent_replay":false}
|
||||||
|
|
||||||
|
同一次激活的网络重试复用请求内容和 Idempotency-Key。只持久化验签且绑定预期实例、产品、客户及有效期的证书。激活证书不等于运行租约,激活后仍需心跳。
|
||||||
|
|
||||||
|
## 心跳与运行租约
|
||||||
|
|
||||||
|
POST /api/v1/instances/{instance_id}/heartbeat
|
||||||
|
|
||||||
|
请求:{"secret":"部署方交付值","client_time":"2026-10-09T03:00:00Z"},要求 Idempotency-Key。
|
||||||
|
|
||||||
|
成功 200:{"data":{"payload":{"version":"lease-v2","instance_id":"...","state":"active","server_time":"...","entitlement_expires_at":"...","lease_expires_at":"...","key_id":"..."},"signature":"...","canonical_sha256":"...","algorithm":"ECDSA-P256-SHA256","next_heartbeat_seconds":60}}
|
||||||
|
|
||||||
|
服务端允许的租约状态:active、frozen、revoked、expired、not_started、not_activated。非 active 的已签名租约必须关闭业务运行;HTTP 200 本身不代表授权有效。
|
||||||
|
|
||||||
|
新心跳操作生成新键。网络重试复用原键及原 client_time,不得修改请求时间后继续使用原键。成功 active 心跳最短间隔 60 秒;根据 next_heartbeat_seconds 调度并加少量正向抖动。
|
||||||
|
|
||||||
|
## 验签规范
|
||||||
|
|
||||||
|
算法 ECDSA P-256 + SHA-256。公钥为 PEM SubjectPublicKeyInfo。signature 是 ASN.1 DER 的 ECDSA 签名,再进行标准 Base64 编码,不带 = 填充,不是 Base64URL,也不是固定 64 字节 r||s。
|
||||||
|
|
||||||
|
拒绝未知版本、缺少或额外字段、非法类型、包含 CR/LF/NUL 的字段、未知或撤销的 key_id、公钥不是 P-256,以及绑定到其他实例的信封。
|
||||||
|
|
||||||
|
按以下固定顺序输出 key=value,用单个 LF 连接,无末尾 LF,以 UTF-8 编码。时间使用收到的原始签名字符串,不能在验签前格式化或重新序列化。
|
||||||
|
|
||||||
|
license-v2:version、instance_id、license_id、customer_id、product_id、starts_at、expires_at、key_id。
|
||||||
|
|
||||||
|
lease-v2:version、instance_id、state、server_time、entitlement_expires_at、lease_expires_at、key_id。
|
||||||
|
|
||||||
|
ID 使用正十进制整数。Node.js 实现限制为安全整数。若部署数据超出安全整数范围,必须先约定解析方案。
|
||||||
|
|
||||||
|
canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校验,不能代替公钥验签。激活应验证 data.certificate,心跳应验证 data。
|
||||||
|
|
||||||
|
服务端未配置 keyring 时会生成 legacy v1;本接入方案拒绝 v1。部署前由运维确认 keyring 已配置并交付可信公钥与 key_id。GET /api/v1/activation/keyring、/activation/public-key 只是发现接口,不能自建信任根。
|
||||||
|
|
||||||
|
## 时间与状态存储
|
||||||
|
|
||||||
|
参照 client/verify.mjs:now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。
|
||||||
|
|
||||||
|
验签、范围检查后,先在受保护存储中原子保存实例 ID、租约、enabled、服务端与本地时间高水位,再启用业务。离线每次授权检查都应检查本地时间回拨,并持久化更新本地高水位。应用重新启动不得清除高水位绕过限制。
|
||||||
|
|
||||||
|
离线冻结和撤销不能立即让旧租约失效,最长残留授权可达 14 天。网络失败不得延长已接受的租约;有有效租约可在策略允许范围内继续,无有效租约必须 fail closed。一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,不能宣称硬件绑定或防克隆。
|
||||||
|
|
||||||
|
## 重试与错误
|
||||||
|
|
||||||
|
错误结构为 {"error":{"code":"...","message":"..."}}。根据状态、code 和操作区分错误,不记录 secret 或原始请求正文。
|
||||||
|
|
||||||
|
400 修复参数;401/403 需要重新交付凭据或人工检查,不做无限重试;409 是冲突,需要检查 code 和实例状态,不自动重激活。429 在至少等待 Retry-After 后有界重试;无该头时指数退避。超时、连接错误和 5xx 有界退避,同一操作维持相同请求与键。心跳拒绝不能替代已签名撤销事件;在未收到可验证的非 active 租约时,已有租约的处理由离线策略决定,不得延长。
|
||||||
|
|
||||||
|
## 发布包下载
|
||||||
|
|
||||||
|
POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。支持 Range 续传,处理 200/206/416 和 Content-Range。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。
|
||||||
|
|
||||||
|
## 模式约束
|
||||||
|
|
||||||
|
桌面:系统密钥库与单实例状态锁。服务:受限服务账户、超时、取消和受控后台任务。容器:稳定持久卷及 Secret 注入;重建不能生成新身份,多个副本不得共享同一实例凭据冒充独立席位。Kubernetes 集群授权需要额外的 License Agent 和席位策略,不在当前 SDK 范围内。
|
||||||
|
|
||||||
|
SPA 应通过同源 BFF 调用,不得在浏览器长期保存实例 secret。移动端、CI 短命实例和完全离线设备需要专门身份与交付策略,不能直接承诺当前协议覆盖。
|
||||||
|
|
||||||
|
## 交付验收
|
||||||
|
|
||||||
|
覆盖正常验签、篡改字段/签名、未知/撤销密钥、v1/额外字段、实例不匹配、过期和超过 14 天、时钟回拨、非 active、幂等重试、429、掉线与原子存储失败。测试向量只使用随机测试密钥,绝不能导入生产信任配置。
|
||||||
154
backend/internal/httpapi/integration_kit.go
Normal file
154
backend/internal/httpapi/integration_kit.go
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed integration_assets/*
|
||||||
|
var integrationAssets embed.FS
|
||||||
|
|
||||||
|
const defaultIntegrationBaseURL = "https://license.yihuiyong.cn"
|
||||||
|
|
||||||
|
var integrationLanguages = map[string]string{
|
||||||
|
"python": "Python 3.11+",
|
||||||
|
"go": "Go 1.22+",
|
||||||
|
"java": "Java 17+",
|
||||||
|
"dotnet": ".NET 8+",
|
||||||
|
"nodejs": "Node.js 20+",
|
||||||
|
}
|
||||||
|
|
||||||
|
var integrationModes = map[string]string{
|
||||||
|
"desktop": "桌面客户端",
|
||||||
|
"service": "常驻服务",
|
||||||
|
"container": "容器部署",
|
||||||
|
}
|
||||||
|
|
||||||
|
type integrationKitResponse struct {
|
||||||
|
ProtocolVersion string `json:"protocol_version"`
|
||||||
|
PlatformBaseURL string `json:"platform_base_url"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
LanguageLabel string `json:"language_label"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
ModeLabel string `json:"mode_label"`
|
||||||
|
Endpoints []kitAPI `json:"endpoints"`
|
||||||
|
SecurityRules []string `json:"security_rules"`
|
||||||
|
Prompt string `json:"prompt"`
|
||||||
|
TestVector kitVector `json:"payload_example"`
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type kitAPI struct {
|
||||||
|
Method string `json:"method"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Purpose string `json:"purpose"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type kitVector struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
InstanceID string `json:"instance_id"`
|
||||||
|
State string `json:"state"`
|
||||||
|
ServerTime string `json:"server_time"`
|
||||||
|
EntitlementExpiresAt string `json:"entitlement_expires_at"`
|
||||||
|
LeaseExpiresAt string `json:"lease_expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func integrationKitInput(c *gin.Context) (string, string, bool) {
|
||||||
|
language, mode := c.DefaultQuery("language", "python"), c.DefaultQuery("mode", "service")
|
||||||
|
if _, ok := integrationLanguages[language]; !ok {
|
||||||
|
apiError(c, http.StatusBadRequest, "invalid_request", "不支持的客户端语言")
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
if _, ok := integrationModes[mode]; !ok {
|
||||||
|
apiError(c, http.StatusBadRequest, "invalid_request", "不支持的接入模式")
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
return language, mode, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildIntegrationKit(language, mode string) integrationKitResponse {
|
||||||
|
label, modeLabel := integrationLanguages[language], integrationModes[mode]
|
||||||
|
protocol, _ := integrationAsset("protocol.md")
|
||||||
|
return integrationKitResponse{
|
||||||
|
ProtocolVersion: "license-v2 / lease-v2",
|
||||||
|
PlatformBaseURL: defaultIntegrationBaseURL,
|
||||||
|
Language: language,
|
||||||
|
LanguageLabel: label,
|
||||||
|
Mode: mode,
|
||||||
|
ModeLabel: modeLabel,
|
||||||
|
Endpoints: []kitAPI{
|
||||||
|
{Method: "POST", Path: "/api/v1/activation/instances/{instance_id}", Purpose: "首次激活,提交 license_key、secret 和 Idempotency-Key"},
|
||||||
|
{Method: "POST", Path: "/api/v1/instances/{instance_id}/heartbeat", Purpose: "刷新已签名运行租约,提交 secret、client_time 和 Idempotency-Key"},
|
||||||
|
{Method: "POST", Path: "/api/v1/customers/{customer_id}/releases/{release_id}/download", Purpose: "以实例凭据下载当前有权访问的发布包"},
|
||||||
|
},
|
||||||
|
SecurityRules: []string{
|
||||||
|
"仅信任随软件或受控部署渠道固定分发的 P-256 公钥;不得将 keyring 发现接口作为信任根。",
|
||||||
|
"secret 只可放在系统密钥库、Vault、Docker/Kubernetes Secret 或受限加密文件中;不得进入 URL、日志、镜像、源码或浏览器 LocalStorage。",
|
||||||
|
"每次网络重试复用同一 Idempotency-Key;新的业务操作必须生成新的键。",
|
||||||
|
"验签后核对 version、key_id、instance_id、state、授权到期和租约到期;仅 active 且未到期时可执行业务。",
|
||||||
|
"保存服务端时间与本地时间高水位,拒绝显著回拨;正常心跳最短 60 秒,租约最长 14 天。",
|
||||||
|
"403/409 进入不可用或人工处理状态;429 遵循 Retry-After;不得无限自动重试。",
|
||||||
|
},
|
||||||
|
Protocol: string(protocol),
|
||||||
|
Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md 与 openapi.json。签名规范化不是 JSON:固定顺序 key=value、LF 连接、UTF-8、无末尾换行;签名是 DER ECDSA 的无填充标准 Base64。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。",
|
||||||
|
TestVector: kitVector{
|
||||||
|
Version: "lease-v2", InstanceID: "11111111-2222-3333-4444-555555555555", State: "active",
|
||||||
|
ServerTime: "2026-10-09T03:00:00Z", EntitlementExpiresAt: "2027-10-09T03:00:00Z", LeaseExpiresAt: "2026-10-23T03:00:00Z",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func integrationAsset(name string) ([]byte, error) {
|
||||||
|
content, err := integrationAssets.ReadFile("integration_assets/" + name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return []byte(strings.ReplaceAll(string(content), "https://license.example.com", defaultIntegrationBaseURL)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func integrationPrompt(language, mode string) string {
|
||||||
|
return fmt.Sprintf(`你正在为 %s %s 接入授权平台。实现可复用的 LicenseClient,不要调用管理员接口,也不要把实例 secret 暴露给浏览器。
|
||||||
|
|
||||||
|
默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。
|
||||||
|
|
||||||
|
实现激活 POST /api/v1/activation/instances/{instance_id},提交 license_key、secret 和 Idempotency-Key;实现心跳 POST /api/v1/instances/{instance_id}/heartbeat,提交 secret、RFC3339 UTC client_time 和 Idempotency-Key。
|
||||||
|
|
||||||
|
必须使用受控渠道预置的 ECDSA P-256 公钥验证 license-v2 / lease-v2 信封,验证 key_id、version、instance_id、state、entitlement_expires_at、lease_expires_at。仅 active 且授权/租约均未过期时允许业务运行。持久化并原子更新已接受租约及本地、服务端时间高水位。secret 不得写入 URL、日志、异常、镜像或源码;403/409 停止自动重试,429 遵循 Retry-After。
|
||||||
|
|
||||||
|
请交付:LicenseClient、受保护状态存储接口、激活与刷新租约实现、验签单元测试、网络/时钟回拨/过期租约负向测试,以及业务侧 canRun 调用示例。`, language, mode, defaultIntegrationBaseURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) integrationKit(c *gin.Context) {
|
||||||
|
language, mode, ok := integrationKitInput(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"data": buildIntegrationKit(language, mode)})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) {
|
||||||
|
language, mode, ok := integrationKitInput(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
kit := buildIntegrationKit(language, mode)
|
||||||
|
var b strings.Builder
|
||||||
|
fmt.Fprintf(&b, "# 授权平台客户端接入包\n\n协议版本:%s\n\n默认授权平台根地址:%s\n\n", kit.ProtocolVersion, kit.PlatformBaseURL)
|
||||||
|
fmt.Fprintf(&b, "目标:%s,%s\n\n## 工程提示词\n\n%s\n\n## 接口\n\n", kit.LanguageLabel, kit.ModeLabel, kit.Prompt)
|
||||||
|
for _, endpoint := range kit.Endpoints {
|
||||||
|
fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose)
|
||||||
|
}
|
||||||
|
b.WriteString("\n## 安全检查\n\n")
|
||||||
|
for _, rule := range kit.SecurityRules {
|
||||||
|
fmt.Fprintf(&b, "- %s\n", rule)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, "\n## 租约字段示例(不是签名测试向量)\n\n```json\n{\n \"version\": \"%s\",\n \"instance_id\": \"%s\",\n \"state\": \"%s\",\n \"server_time\": \"%s\",\n \"entitlement_expires_at\": \"%s\",\n \"lease_expires_at\": \"%s\"\n}\n```\n", kit.TestVector.Version, kit.TestVector.InstanceID, kit.TestVector.State, kit.TestVector.ServerTime, kit.TestVector.EntitlementExpiresAt, kit.TestVector.LeaseExpiresAt)
|
||||||
|
fmt.Fprintf(&b, "\n\n%s\n", kit.Protocol)
|
||||||
|
c.Header("Cache-Control", "no-store")
|
||||||
|
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s-integration.md", language, mode))
|
||||||
|
c.Data(http.StatusOK, "text/markdown; charset=utf-8", []byte(b.String()))
|
||||||
|
}
|
||||||
119
backend/internal/httpapi/integration_kit_test.go
Normal file
119
backend/internal/httpapi/integration_kit_test.go
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"io"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIntegrationAuthentication(t *testing.T) {
|
||||||
|
r := gin.New()
|
||||||
|
registerBusinessRoutes(r, &BusinessAPI{})
|
||||||
|
for _, path := range []string{"/api/v1/integration-kit", "/api/v1/integration-kit/download", "/api/v1/integration-kit/archive"} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
||||||
|
if w.Code != 401 {
|
||||||
|
t.Fatalf("%s: %d", path, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestIntegrationInputs(t *testing.T) {
|
||||||
|
for _, query := range []string{"?language=rust", "?mode=browser", "?language=../../secret"} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/"+query, nil)
|
||||||
|
(&BusinessAPI{}).integrationKit(c)
|
||||||
|
if w.Code != 400 {
|
||||||
|
t.Fatalf("%s: %d", query, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for language := range integrationLanguages {
|
||||||
|
kit := buildIntegrationKit(language, "service")
|
||||||
|
if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") {
|
||||||
|
t.Fatal("incomplete kit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
content, err := integrationAssets.ReadFile("integration_assets/openapi.json")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var spec map[string]any
|
||||||
|
if err = json.Unmarshal(content, &spec); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if spec["openapi"] != "3.0.3" {
|
||||||
|
t.Fatal("invalid OpenAPI")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil)
|
||||||
|
(&BusinessAPI{}).downloadIntegrationArchive(c)
|
||||||
|
if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
archive, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(archive.File) != 5 {
|
||||||
|
t.Fatal("missing files")
|
||||||
|
}
|
||||||
|
for _, file := range archive.File {
|
||||||
|
reader, err := file.Open()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
content, err := io.ReadAll(reader)
|
||||||
|
reader.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) {
|
||||||
|
t.Fatal("OpenAPI does not use the default platform address")
|
||||||
|
}
|
||||||
|
if file.Name != "test-vectors.json" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var vectors struct {
|
||||||
|
PinnedKeys []struct {
|
||||||
|
PublicKey string `json:"public_key_pem"`
|
||||||
|
} `json:"pinned_keys"`
|
||||||
|
License, Lease struct{ Signature, Canonical string }
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(content, &vectors); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, _ := pem.Decode([]byte(vectors.PinnedKeys[0].PublicKey))
|
||||||
|
key, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, vector := range []struct{ Signature, Canonical string }{vectors.License, vectors.Lease} {
|
||||||
|
sig, err := base64.RawStdEncoding.DecodeString(vector.Signature)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256([]byte(vector.Canonical))
|
||||||
|
if !ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), digest[:], sig) {
|
||||||
|
t.Fatal("bad signature")
|
||||||
|
}
|
||||||
|
digest = sha256.Sum256([]byte(vector.Canonical + "tampered"))
|
||||||
|
if ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), digest[:], sig) {
|
||||||
|
t.Fatal("accepted tampering")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
91
backend/internal/httpapi/keyring.go
Normal file
91
backend/internal/httpapi/keyring.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
)
|
||||||
|
|
||||||
|
type VerificationKey struct {
|
||||||
|
KeyID string `json:"key_id"`
|
||||||
|
PublicKeyPEM string `json:"public_key_pem"`
|
||||||
|
Revoked bool `json:"revoked"`
|
||||||
|
}
|
||||||
|
type Keyring struct {
|
||||||
|
Current string `json:"current_key_id"`
|
||||||
|
Keys []VerificationKey `json:"keys"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var keyIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
|
||||||
|
|
||||||
|
func LoadKeyring(path, privatePEM string) (*Keyring, error) {
|
||||||
|
if path == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return nil, errors.New("keyring file must be absolute")
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil || !info.Mode().IsRegular() || info.Size() > 65536 {
|
||||||
|
return nil, errors.New("invalid keyring file")
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("keyring unavailable")
|
||||||
|
}
|
||||||
|
var ring Keyring
|
||||||
|
if json.Unmarshal(data, &ring) != nil {
|
||||||
|
return nil, errors.New("invalid keyring JSON")
|
||||||
|
}
|
||||||
|
if err := ring.Validate(privatePEM); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &ring, nil
|
||||||
|
}
|
||||||
|
func (r *Keyring) Validate(privatePEM string) error {
|
||||||
|
if !keyIDPattern.MatchString(r.Current) || len(r.Keys) == 0 || len(r.Keys) > 32 {
|
||||||
|
return errors.New("invalid keyring")
|
||||||
|
}
|
||||||
|
private, err := readSigningKey(privatePEM)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid current private key")
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
current := false
|
||||||
|
for _, k := range r.Keys {
|
||||||
|
if !keyIDPattern.MatchString(k.KeyID) || seen[k.KeyID] {
|
||||||
|
return errors.New("duplicate or invalid key ID")
|
||||||
|
}
|
||||||
|
seen[k.KeyID] = true
|
||||||
|
block, rest := pem.Decode([]byte(k.PublicKeyPEM))
|
||||||
|
if block == nil || len(rest) != 0 {
|
||||||
|
return errors.New("invalid public key")
|
||||||
|
}
|
||||||
|
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid public key")
|
||||||
|
}
|
||||||
|
pub, ok := parsed.(*ecdsa.PublicKey)
|
||||||
|
if !ok || pub.Curve != elliptic.P256() {
|
||||||
|
return errors.New("public key must be P256")
|
||||||
|
}
|
||||||
|
if k.KeyID == r.Current {
|
||||||
|
if k.Revoked || !pub.Equal(&private.PublicKey) {
|
||||||
|
return errors.New("current key revoked or mismatched")
|
||||||
|
}
|
||||||
|
current = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !current {
|
||||||
|
return errors.New("current key missing")
|
||||||
|
}
|
||||||
|
sort.Slice(r.Keys, func(i, j int) bool { return r.Keys[i].KeyID < r.Keys[j].KeyID })
|
||||||
|
return nil
|
||||||
|
}
|
||||||
36
backend/internal/httpapi/keyring_http_test.go
Normal file
36
backend/internal/httpapi/keyring_http_test.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestKeyringHTTPAndFileBoundary(t *testing.T) {
|
||||||
|
if _, err := LoadKeyring("relative.json", ""); err == nil {
|
||||||
|
t.Fatal("relative ring accepted")
|
||||||
|
}
|
||||||
|
for _, enabled := range []bool{false, true} {
|
||||||
|
router := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil))))
|
||||||
|
var ring *Keyring
|
||||||
|
if enabled {
|
||||||
|
ring = &Keyring{Current: "test", Keys: []VerificationKey{{KeyID: "test", PublicKeyPEM: "public-only", Revoked: false}}}
|
||||||
|
}
|
||||||
|
RegisterBusinessWithKeyring(router, &sql.DB{}, "", ring)
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, httptest.NewRequest("GET", "/api/v1/activation/keyring", nil))
|
||||||
|
expected := 404
|
||||||
|
if enabled {
|
||||||
|
expected = 200
|
||||||
|
}
|
||||||
|
if response.Code != expected {
|
||||||
|
t.Fatal(response.Code)
|
||||||
|
}
|
||||||
|
if strings.Contains(response.Body.String(), "PRIVATE KEY") {
|
||||||
|
t.Fatal("private key disclosure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
87
backend/internal/httpapi/keyring_test.go
Normal file
87
backend/internal/httpapi/keyring_test.go
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
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))
|
||||||
|
}
|
||||||
384
backend/internal/httpapi/licenses.go
Normal file
384
backend/internal/httpapi/licenses.go
Normal file
@@ -0,0 +1,384 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type licenseOperation struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
LicenseID uint64 `json:"license_id"`
|
||||||
|
Operation string `json:"operation"`
|
||||||
|
IdempotencyKey string `json:"-"`
|
||||||
|
RequestFingerprint []byte `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type licenseRecord struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
LicenseKey string `json:"license_key"`
|
||||||
|
CustomerID uint64 `json:"customer_id"`
|
||||||
|
CustomerName string `json:"customer_name"`
|
||||||
|
ProductID uint64 `json:"product_id"`
|
||||||
|
ProductName string `json:"product_name"`
|
||||||
|
ProductCode string `json:"product_code"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
StartsAt time.Time `json:"starts_at"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentLicenseStatus(status string, starts, expires time.Time, now time.Time) string {
|
||||||
|
if status == "revoked" {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
if !now.Before(expires) {
|
||||||
|
return "expired"
|
||||||
|
}
|
||||||
|
if now.Before(starts) {
|
||||||
|
return "scheduled"
|
||||||
|
}
|
||||||
|
return "active"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) issueLicense(c *gin.Context) {
|
||||||
|
key := strings.TrimSpace(c.GetHeader("Idempotency-Key"))
|
||||||
|
if len(key) == 0 || len(key) > 128 {
|
||||||
|
apiError(c, 400, "invalid_idempotency_key", "Idempotency-Key 必须为 1 至 128 个字符")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
CustomerID uint64 `json:"customer_id"`
|
||||||
|
ProductID uint64 `json:"product_id"`
|
||||||
|
StartsAt string `json:"starts_at"`
|
||||||
|
ExpiresAt string `json:"expires_at"`
|
||||||
|
}
|
||||||
|
if c.ShouldBindJSON(&in) != nil || in.CustomerID == 0 || in.ProductID == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "客户、产品和期限必填")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
starts, err := time.Parse(time.RFC3339, in.StartsAt)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "starts_at 必须为 RFC3339 时间")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
expires, err := time.Parse(time.RFC3339, in.ExpiresAt)
|
||||||
|
starts = starts.UTC().Truncate(time.Microsecond)
|
||||||
|
expires = expires.UTC().Truncate(time.Microsecond)
|
||||||
|
if err != nil || !expires.After(starts) || starts.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
|
||||||
|
apiError(c, 400, "invalid_request", "expires_at 必须为晚于开始时间的 RFC3339 时间")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
adminID, ok := c.Get("admin_id")
|
||||||
|
if !ok {
|
||||||
|
apiError(c, 401, "unauthorized", "请先登录")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
// Serialize issuance per administrator so concurrent retries see the committed record.
|
||||||
|
var lockedAdmin uint64
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", adminID).Scan(&lockedAdmin); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 403, "forbidden", "无权签发授权")
|
||||||
|
} else {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rec licenseRecord
|
||||||
|
err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.issued_by=? AND l.idempotency_key=?`, adminID, key).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt)
|
||||||
|
if err == nil {
|
||||||
|
if rec.CustomerID != in.CustomerID || rec.ProductID != in.ProductID || !rec.StartsAt.Equal(starts) || !rec.ExpiresAt.Equal(expires) {
|
||||||
|
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同授权请求")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
|
||||||
|
c.JSON(200, gin.H{"data": rec, "idempotent_replay": true})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var customerStatus string
|
||||||
|
var productActive bool
|
||||||
|
err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", in.CustomerID).Scan(&rec.CustomerName, &customerStatus)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if errors.Is(err, sql.ErrNoRows) || customerStatus != "active" {
|
||||||
|
apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = tx.QueryRowContext(c, "SELECT name,code,active FROM products WHERE id=? FOR UPDATE", in.ProductID).Scan(&rec.ProductName, &rec.ProductCode, &productActive)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if errors.Is(err, sql.ErrNoRows) || !productActive {
|
||||||
|
apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw := make([]byte, 16)
|
||||||
|
if _, err = rand.Read(raw); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rec.LicenseKey = hex.EncodeToString(raw)
|
||||||
|
rec.CustomerID = in.CustomerID
|
||||||
|
rec.ProductID = in.ProductID
|
||||||
|
rec.StartsAt = starts.UTC()
|
||||||
|
rec.ExpiresAt = expires.UTC()
|
||||||
|
rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
|
||||||
|
res, err := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", rec.LicenseKey, in.CustomerID, in.ProductID, rec.StartsAt, rec.ExpiresAt, key, adminID)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "签发失败,请使用相同幂等键重试")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rec.ID = uint64(id)
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT created_at FROM licenses WHERE id=?", rec.ID).Scan(&rec.CreatedAt); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(map[string]any{"customer_id": in.CustomerID, "product_id": in.ProductID, "starts_at": rec.StartsAt, "expires_at": rec.ExpiresAt})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", adminID, rec.ID, details); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Header("Location", "/api/v1/licenses/"+strconv.FormatUint(rec.ID, 10))
|
||||||
|
c.JSON(201, gin.H{"data": rec, "idempotent_replay": false})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) getLicense(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "授权 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rec licenseRecord
|
||||||
|
err = a.db.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=?`, id).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "授权不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
|
||||||
|
c.JSON(200, gin.H{"data": rec})
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseOperationKey(c *gin.Context) (string, bool) {
|
||||||
|
key := strings.TrimSpace(c.GetHeader("Idempotency-Key"))
|
||||||
|
if len(key) < 1 || len(key) > 128 {
|
||||||
|
apiError(c, 400, "invalid_idempotency_key", "Idempotency-Key 必须为 1 至 128 个字符")
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return key, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "授权 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key, ok := parseOperationKey(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
ExpiresAt string `json:"expires_at"`
|
||||||
|
}
|
||||||
|
if operation == "renew" && c.ShouldBindJSON(&in) != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "expires_at 必填")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var expires time.Time
|
||||||
|
if operation == "renew" {
|
||||||
|
expires, err = time.Parse(time.RFC3339, in.ExpiresAt)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "expires_at 必须为 RFC3339 时间")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
expires = expires.UTC().Truncate(time.Microsecond)
|
||||||
|
if expires.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
|
||||||
|
apiError(c, 400, "invalid_request", "expires_at 超出允许范围")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
adminID := c.MustGet("admin_id")
|
||||||
|
fingerprintInput := operation + "\x00" + strconv.FormatUint(id, 10) + "\x00" + expires.Format(time.RFC3339Nano)
|
||||||
|
fingerprint := sha256.Sum256([]byte(fingerprintInput))
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var rec licenseRecord
|
||||||
|
err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=? FOR UPDATE`, id).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "授权不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var op licenseOperation
|
||||||
|
err = tx.QueryRowContext(c, "SELECT id,license_id,operation,idempotency_key,request_fingerprint FROM license_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", adminID, operation, key).Scan(&op.ID, &op.LicenseID, &op.Operation, &op.IdempotencyKey, &op.RequestFingerprint)
|
||||||
|
if err == nil {
|
||||||
|
if op.LicenseID != id || !bytes.Equal(op.RequestFingerprint, fingerprint[:]) {
|
||||||
|
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同授权操作")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
|
||||||
|
c.JSON(200, gin.H{"data": rec, "idempotent_replay": true})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if operation == "revoke" {
|
||||||
|
if rec.Status == "revoked" {
|
||||||
|
apiError(c, 409, "invalid_state", "授权已经撤销")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE licenses SET status='revoked',revoked_at=? WHERE id=?", time.Now().UTC(), id); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "撤销失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if rec.Status == "revoked" || !expires.After(rec.ExpiresAt) {
|
||||||
|
apiError(c, 400, "invalid_request", "续期时间必须晚于当前结束时间且授权未撤销")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "UPDATE licenses SET expires_at=?,status='active' WHERE id=?", expires, id); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "续期失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO license_operations(license_id,actor_admin_id,operation,idempotency_key,request_fingerprint) VALUES(?,?,?,?,?)", id, adminID, operation, key, fingerprint[:]); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "操作失败,请使用相同幂等键重试")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(map[string]any{"operation": operation, "expires_at": expires, "license_id": id})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?, 'license',?,?)", adminID, "license."+operation, id, details); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if operation == "revoke" {
|
||||||
|
rec.Status = "revoked"
|
||||||
|
} else {
|
||||||
|
rec.ExpiresAt = expires
|
||||||
|
rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": rec, "idempotent_replay": false})
|
||||||
|
}
|
||||||
|
|
||||||
|
const licenseFrom = ` FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id`
|
||||||
|
const licenseSelect = `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at` + licenseFrom
|
||||||
|
|
||||||
|
// Use the same instant and predicate for the count and page, including expiry boundaries.
|
||||||
|
func licenseFilter(status, q string, now time.Time) (string, []any, bool) {
|
||||||
|
where := " WHERE 1=1"
|
||||||
|
args := []any{}
|
||||||
|
if q != "" {
|
||||||
|
where += " AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?)"
|
||||||
|
like := "%" + q + "%"
|
||||||
|
args = append(args, like, like, like, like)
|
||||||
|
}
|
||||||
|
switch status {
|
||||||
|
case "":
|
||||||
|
case "revoked":
|
||||||
|
where += " AND l.status='revoked'"
|
||||||
|
case "active", "expiring":
|
||||||
|
where += " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>?"
|
||||||
|
args = append(args, now, now)
|
||||||
|
if status == "expiring" {
|
||||||
|
where += " AND l.expires_at<=?"
|
||||||
|
args = append(args, now.Add(30*24*time.Hour))
|
||||||
|
}
|
||||||
|
case "pending":
|
||||||
|
where += " AND l.status<>'revoked' AND l.starts_at>? AND l.expires_at>?"
|
||||||
|
args = append(args, now, now)
|
||||||
|
case "expired":
|
||||||
|
where += " AND l.status<>'revoked' AND l.expires_at<=?"
|
||||||
|
args = append(args, now)
|
||||||
|
default:
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
return where, args, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLicenseRecords(rows *sql.Rows, now time.Time) ([]licenseRecord, error) {
|
||||||
|
defer rows.Close()
|
||||||
|
out := []licenseRecord{}
|
||||||
|
for rows.Next() {
|
||||||
|
var x licenseRecord
|
||||||
|
if err := rows.Scan(&x.ID, &x.LicenseKey, &x.CustomerID, &x.CustomerName, &x.ProductID, &x.ProductName, &x.ProductCode, &x.Status, &x.StartsAt, &x.ExpiresAt, &x.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
x.Status = currentLicenseStatus(x.Status, x.StartsAt, x.ExpiresAt, now)
|
||||||
|
out = append(out, x)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) listLicenses(c *gin.Context) {
|
||||||
|
p, size := page(c)
|
||||||
|
now := time.Now().UTC()
|
||||||
|
where, args, ok := licenseFilter(strings.TrimSpace(c.Query("status")), strings.TrimSpace(c.Query("q")), now)
|
||||||
|
if !ok {
|
||||||
|
apiError(c, 400, "invalid_request", "授权状态无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var total int
|
||||||
|
if err := a.db.QueryRowContext(c, "SELECT COUNT(*)"+licenseFrom+where, args...).Scan(&total); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pageArgs := append(append([]any{}, args...), size, (p-1)*size)
|
||||||
|
rows, err := a.db.QueryContext(c, licenseSelect+where+" ORDER BY l.id DESC LIMIT ? OFFSET ?", pageArgs...)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := readLicenseRecords(rows, now)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||||||
|
}
|
||||||
102
backend/internal/httpapi/licenses_test.go
Normal file
102
backend/internal/httpapi/licenses_test.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCurrentLicenseStatus(t *testing.T) {
|
||||||
|
now := time.Date(2026, 9, 30, 8, 0, 0, 0, time.UTC)
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, status string
|
||||||
|
starts, expires time.Time
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"scheduled", "active", now.Add(time.Hour), now.Add(2 * time.Hour), "scheduled"},
|
||||||
|
{"start boundary", "active", now, now.Add(time.Hour), "active"},
|
||||||
|
{"expiry boundary", "active", now.Add(-time.Hour), now, "expired"},
|
||||||
|
{"revoked", "revoked", now.Add(time.Hour), now.Add(2 * time.Hour), "revoked"},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
if got := currentLicenseStatus(tc.status, tc.starts, tc.expires, now); got != tc.want {
|
||||||
|
t.Fatalf("got %s want %s", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLicenseFilterPredicates(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 8, 10, 0, 0, 0, time.UTC)
|
||||||
|
for _, tc := range []struct {
|
||||||
|
status, predicate string
|
||||||
|
times []any
|
||||||
|
}{
|
||||||
|
{"", "", nil},
|
||||||
|
{"active", " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>?", []any{now, now}},
|
||||||
|
{"pending", " AND l.status<>'revoked' AND l.starts_at>? AND l.expires_at>?", []any{now, now}},
|
||||||
|
{"expired", " AND l.status<>'revoked' AND l.expires_at<=?", []any{now}},
|
||||||
|
{"revoked", " AND l.status='revoked'", nil},
|
||||||
|
{"expiring", " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>? AND l.expires_at<=?", []any{now, now, now.Add(30 * 24 * time.Hour)}},
|
||||||
|
} {
|
||||||
|
t.Run(tc.status, func(t *testing.T) {
|
||||||
|
where, args, ok := licenseFilter(tc.status, "customer' OR 1=1", now)
|
||||||
|
want := " WHERE 1=1 AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?)" + tc.predicate
|
||||||
|
if !ok || where != want {
|
||||||
|
t.Fatalf("predicate %s", where)
|
||||||
|
}
|
||||||
|
expected := []any{"%customer' OR 1=1%", "%customer' OR 1=1%", "%customer' OR 1=1%", "%customer' OR 1=1%"}
|
||||||
|
expected = append(expected, tc.times...)
|
||||||
|
if !reflect.DeepEqual(args, expected) {
|
||||||
|
t.Fatalf("args %#v", args)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, status := range []string{"scheduled", "unknown", "ACTIVE"} {
|
||||||
|
if _, _, ok := licenseFilter(status, "", now); ok {
|
||||||
|
t.Errorf("accepted %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListLicensesFilteredPage(t *testing.T) {
|
||||||
|
// No time-dependent predicate is needed here; each status predicate is checked
|
||||||
|
// above with exact boundaries. Count and page must both join all search fields.
|
||||||
|
where := " WHERE 1=1 AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?) AND l.status='revoked'"
|
||||||
|
args := []any{"%Acme%", "%Acme%", "%Acme%", "%Acme%"}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
db, _ := newDashboardTestDB(t, []dashboardQuery{
|
||||||
|
{sql: "SELECT COUNT(*)" + licenseFrom + where, args: args, rows: [][]driver.Value{{int64(31)}}},
|
||||||
|
{sql: licenseSelect + where + " ORDER BY l.id DESC LIMIT ? OFFSET ?", args: append(append([]any{}, args...), 10, 10), rows: [][]driver.Value{testLicenseRow(25, "revoked", now.Add(-time.Hour), now.Add(time.Hour), now)}},
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/api/v1/licenses?q=%20Acme%20&status=%20revoked%20&page=2&page_size=10", nil)
|
||||||
|
(&BusinessAPI{db: db}).listLicenses(c)
|
||||||
|
var out struct {
|
||||||
|
Data []licenseRecord `json:"data"`
|
||||||
|
Meta struct {
|
||||||
|
Total, Page int
|
||||||
|
PageSize int `json:"page_size"`
|
||||||
|
} `json:"meta"`
|
||||||
|
}
|
||||||
|
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || out.Meta.Total != 31 || out.Meta.Page != 2 || out.Meta.PageSize != 10 || len(out.Data) != 1 || out.Data[0].Status != "revoked" {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestListLicensesInvalidStatus(t *testing.T) {
|
||||||
|
db, _ := newDashboardTestDB(t, nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest("GET", "/api/v1/licenses?status=invalid", nil)
|
||||||
|
(&BusinessAPI{db: db}).listLicenses(c)
|
||||||
|
if w.Code != 400 || !strings.Contains(w.Body.String(), "invalid_request") {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
189
backend/internal/httpapi/operations.go
Normal file
189
backend/internal/httpapi/operations.go
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type operationSample struct {
|
||||||
|
Count uint64
|
||||||
|
Seconds float64
|
||||||
|
}
|
||||||
|
type Operations struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
samples map[string]operationSample
|
||||||
|
buckets map[string]rateBucket
|
||||||
|
now func() time.Time
|
||||||
|
logger *slog.Logger
|
||||||
|
nextSweep time.Time
|
||||||
|
limiter EntryLimiter
|
||||||
|
}
|
||||||
|
type rateBucket struct {
|
||||||
|
start time.Time
|
||||||
|
count int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewOperations(logger *slog.Logger) *Operations {
|
||||||
|
return &Operations{samples: make(map[string]operationSample), buckets: make(map[string]rateBucket), now: time.Now, logger: logger}
|
||||||
|
}
|
||||||
|
func operation(path string) string {
|
||||||
|
switch path {
|
||||||
|
case "/api/v1/portal/snapshot":
|
||||||
|
return "login"
|
||||||
|
case "/api/v1/auth/login":
|
||||||
|
return "login"
|
||||||
|
case "/api/v1/activation/instances/:instance_id":
|
||||||
|
return "activation"
|
||||||
|
case "/api/v1/instances/:instance_id/heartbeat":
|
||||||
|
return "heartbeat"
|
||||||
|
case "/api/v1/customers/:customer_id/releases/:id/download":
|
||||||
|
return "download"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(path, "/api/v1/licenses") {
|
||||||
|
return "authorization"
|
||||||
|
}
|
||||||
|
return "other"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local fixed-window limits are deliberately per process, never a distributed guarantee.
|
||||||
|
func (o *Operations) allow(key string, limit int) bool {
|
||||||
|
o.mu.Lock()
|
||||||
|
defer o.mu.Unlock()
|
||||||
|
now := o.now()
|
||||||
|
if !now.Before(o.nextSweep) {
|
||||||
|
for k, b := range o.buckets {
|
||||||
|
if now.Sub(b.start) >= time.Minute {
|
||||||
|
delete(o.buckets, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.nextSweep = now.Add(time.Minute)
|
||||||
|
}
|
||||||
|
b, exists := o.buckets[key]
|
||||||
|
if !exists && len(o.buckets) >= 10000 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !exists || now.Sub(b.start) >= time.Minute {
|
||||||
|
b = rateBucket{start: now}
|
||||||
|
}
|
||||||
|
if b.count >= limit {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.count++
|
||||||
|
o.buckets[key] = b
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func (o *Operations) Middleware() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
raw := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
c.AbortWithStatus(http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := hex.EncodeToString(raw)
|
||||||
|
c.Set("request_id", id)
|
||||||
|
c.Header("X-Request-ID", id)
|
||||||
|
started := time.Now()
|
||||||
|
path := c.FullPath()
|
||||||
|
op := operation(path)
|
||||||
|
defer func() {
|
||||||
|
elapsed := time.Since(started).Seconds()
|
||||||
|
outcome := "success"
|
||||||
|
if c.Writer.Status() >= 400 {
|
||||||
|
outcome = "failure"
|
||||||
|
}
|
||||||
|
key := op + "/" + outcome
|
||||||
|
o.mu.Lock()
|
||||||
|
sample := o.samples[key]
|
||||||
|
sample.Count++
|
||||||
|
sample.Seconds += elapsed
|
||||||
|
o.samples[key] = sample
|
||||||
|
o.mu.Unlock()
|
||||||
|
// No bodies, query strings, raw paths, IPs, cookies, headers, SQL errors or panic values.
|
||||||
|
o.logger.Info("http_request", "request_id", id, "trace_id", id, "route", path, "operation", op, "status", c.Writer.Status(), "error_code", c.GetString("error_code"), "duration_seconds", elapsed)
|
||||||
|
}()
|
||||||
|
defer func() {
|
||||||
|
if recover() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "Service unavailable")
|
||||||
|
c.Abort()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if op == "login" || op == "activation" || op == "heartbeat" || op == "download" {
|
||||||
|
limit := 60
|
||||||
|
if op == "login" {
|
||||||
|
limit = 10
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256([]byte(c.ClientIP()))
|
||||||
|
key := op + hex.EncodeToString(sum[:])
|
||||||
|
allowed := false
|
||||||
|
if o.limiter != nil {
|
||||||
|
var err error
|
||||||
|
allowed, err = o.limiter.Allow(c.Request.Context(), key, limit)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "rate_limit_unavailable", "Service unavailable")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
allowed = o.allow(key, limit)
|
||||||
|
}
|
||||||
|
if !allowed {
|
||||||
|
c.Header("Retry-After", "60")
|
||||||
|
apiError(c, 429, "rate_limited", "Too many requests")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.Request.Method != "GET" && c.Request.Method != "HEAD" && c.Request.Method != "OPTIONS" {
|
||||||
|
origin := c.GetHeader("Origin")
|
||||||
|
if origin != "" {
|
||||||
|
u, err := url.Parse(origin)
|
||||||
|
scheme := "http"
|
||||||
|
if secureSessionCookie(c) {
|
||||||
|
scheme = "https"
|
||||||
|
}
|
||||||
|
if err != nil || u.Host != c.Request.Host || u.Scheme != scheme || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
||||||
|
apiError(c, 403, "origin_forbidden", "Cross-origin request denied")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.GetHeader("Sec-Fetch-Site") == "cross-site" {
|
||||||
|
apiError(c, 403, "origin_forbidden", "Cross-site request denied")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Uploads have their own 64 MiB streaming bound; other JSON routes get a 64 KiB ceiling.
|
||||||
|
if !(path == "/api/v1/products/:id/releases" && c.Request.Method == "POST") {
|
||||||
|
if c.Request.ContentLength > 64<<10 {
|
||||||
|
apiError(c, 413, "body_too_large", "Request body too large")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<10)
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expose only on a separate loopback/private monitoring listener, never the public router.
|
||||||
|
func (o *Operations) Metrics(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
|
||||||
|
o.mu.Lock()
|
||||||
|
defer o.mu.Unlock()
|
||||||
|
fmt.Fprintln(w, "# TYPE license_requests_total counter\n# TYPE license_request_duration_seconds_sum counter")
|
||||||
|
for key, s := range o.samples {
|
||||||
|
parts := strings.Split(key, "/")
|
||||||
|
fmt.Fprintf(w, "license_requests_total{operation=%q,outcome=%q} %d\nlicense_request_duration_seconds_sum{operation=%q,outcome=%q} %g\n", parts[0], parts[1], s.Count, parts[0], parts[1], s.Seconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
74
backend/internal/httpapi/operations_boundary_test.go
Normal file
74
backend/internal/httpapi/operations_boundary_test.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPublicEntryLimitsBeforeHandlers(t *testing.T) {
|
||||||
|
for _, path := range []string{"/api/v1/auth/login", "/api/v1/activation/instances/:instance_id", "/api/v1/instances/:instance_id/heartbeat", "/api/v1/customers/:customer_id/releases/:id/download"} {
|
||||||
|
t.Run(path, func(t *testing.T) {
|
||||||
|
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
|
||||||
|
calls := 0
|
||||||
|
r.POST(path, func(c *gin.Context) { calls++; c.Status(401) })
|
||||||
|
n := 60
|
||||||
|
if strings.Contains(path, "login") {
|
||||||
|
n = 10
|
||||||
|
}
|
||||||
|
for i := 0; i <= n; i++ {
|
||||||
|
q := httptest.NewRequest("POST", strings.ReplaceAll(strings.ReplaceAll(path, ":instance_id", "x"), ":customer_id", "1"), nil)
|
||||||
|
q.URL.Path = strings.ReplaceAll(q.URL.Path, ":id", "1")
|
||||||
|
q.RemoteAddr = "127.0.0.1:1234"
|
||||||
|
q.Header.Set("X-Forwarded-For", strings.Repeat("1", i)+".2.3.4")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
if i == n && w.Code != 429 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if calls != n {
|
||||||
|
t.Fatal(calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestChunkedBodyCORSAndMalformedSession(t *testing.T) {
|
||||||
|
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
|
||||||
|
r.POST("/json", func(c *gin.Context) {
|
||||||
|
var data map[string]any
|
||||||
|
if c.ShouldBindJSON(&data) != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "Invalid JSON")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(204)
|
||||||
|
})
|
||||||
|
q := httptest.NewRequest("POST", "/json", strings.NewReader(`{"secret":"`+strings.Repeat("x", 65537)+`"}`))
|
||||||
|
q.ContentLength = -1
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
if w.Code != 400 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
q = httptest.NewRequest("OPTIONS", "/json", nil)
|
||||||
|
q.Header.Set("Origin", "https://evil.example")
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
if w.Header().Get("Access-Control-Allow-Origin") != "" {
|
||||||
|
t.Fatal("CORS must not allow external origin")
|
||||||
|
}
|
||||||
|
a := &BusinessAPI{}
|
||||||
|
r.GET("/session", a.authenticated, func(c *gin.Context) { t.Fatal("malformed session authenticated") })
|
||||||
|
for _, cookie := range []string{"", "lp_session=bad", "lp_session=" + strings.Repeat("z", 64)} {
|
||||||
|
q = httptest.NewRequest("GET", "/session", nil)
|
||||||
|
q.Header.Set("Cookie", cookie)
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
if w.Code != 401 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
127
backend/internal/httpapi/operations_test.go
Normal file
127
backend/internal/httpapi/operations_test.go
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestOperationsSecurity(t *testing.T) {
|
||||||
|
var logs bytes.Buffer
|
||||||
|
ops := NewOperations(slog.New(slog.NewJSONHandler(&logs, nil)))
|
||||||
|
r := NewOperationalRouter(ops)
|
||||||
|
r.POST("/api/v1/auth/login", func(c *gin.Context) { apiError(c, 401, "invalid_credentials", "Denied") })
|
||||||
|
r.GET("/panic/:secret", func(c *gin.Context) { panic("PRIVATE_PEM_password") })
|
||||||
|
request := func(method, path, body, origin string) *httptest.ResponseRecorder {
|
||||||
|
q := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||||
|
q.RemoteAddr = "127.0.0.1:1234"
|
||||||
|
q.Header.Set("Origin", origin)
|
||||||
|
q.Header.Set("Cookie", "lp_session=PRIVATE_COOKIE")
|
||||||
|
q.Header.Set("X-Request-ID", "FORGED_ID")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
if w := request("POST", "/api/v1/auth/login?password=PRIVATE_QUERY", "PRIVATE_PASSWORD", ""); w.Code != 401 {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := request("POST", "/api/v1/auth/login", "", "")
|
||||||
|
if w.Code != 429 || w.Header().Get("Retry-After") == "" {
|
||||||
|
t.Fatal(w.Code)
|
||||||
|
}
|
||||||
|
w = request("GET", "/panic/PRIVATE_PATH", "", "")
|
||||||
|
if w.Code != 500 || strings.Contains(w.Body.String(), "PRIVATE") {
|
||||||
|
t.Fatal(w.Body.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(logs.String(), "PRIVATE") || strings.Contains(logs.String(), "FORGED_ID") {
|
||||||
|
t.Fatal("secret or forged ID in logs")
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(&logs)
|
||||||
|
n := 0
|
||||||
|
for {
|
||||||
|
var row map[string]any
|
||||||
|
err := dec.Decode(&row)
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if row["request_id"] == "" || row["trace_id"] != row["request_id"] {
|
||||||
|
t.Fatal(row)
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if n != 12 {
|
||||||
|
t.Fatal(n)
|
||||||
|
}
|
||||||
|
mw := httptest.NewRecorder()
|
||||||
|
ops.Metrics(mw, httptest.NewRequest("GET", "/metrics", nil))
|
||||||
|
if !strings.Contains(mw.Body.String(), "license_requests_total{operation=\"login\",outcome=\"failure\"} 11") {
|
||||||
|
t.Fatal(mw.Body.String())
|
||||||
|
}
|
||||||
|
if request("GET", "/metrics", "", "").Code != 404 {
|
||||||
|
t.Fatal("public metrics exposed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestOriginAndBodyGuards(t *testing.T) {
|
||||||
|
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
|
||||||
|
r.POST("/write", func(c *gin.Context) { c.Status(204) })
|
||||||
|
for _, tc := range []struct {
|
||||||
|
origin, body string
|
||||||
|
status int
|
||||||
|
}{{"https://evil.example", "", 403}, {"http://example.com", "", 204}, {"", "", 204}, {"", strings.Repeat("x", 65537), 413}} {
|
||||||
|
q := httptest.NewRequest("POST", "http://example.com/write", strings.NewReader(tc.body))
|
||||||
|
q.Header.Set("Origin", tc.origin)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
if w.Code != tc.status {
|
||||||
|
t.Fatalf("origin=%s status=%d", tc.origin, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestLocalLimiterBoundaryAndScope(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
a := NewOperations(slog.Default())
|
||||||
|
a.now = func() time.Time { return now }
|
||||||
|
if !a.allow("test", 1) || a.allow("test", 1) {
|
||||||
|
t.Fatal("limit not enforced")
|
||||||
|
}
|
||||||
|
b := NewOperations(slog.Default())
|
||||||
|
if !b.allow("test", 1) {
|
||||||
|
t.Fatal("independent process scope")
|
||||||
|
}
|
||||||
|
now = now.Add(time.Minute)
|
||||||
|
if !a.allow("test", 1) {
|
||||||
|
t.Fatal("window not reset")
|
||||||
|
}
|
||||||
|
for i := 0; i < 10000; i++ {
|
||||||
|
a.buckets[string(rune(i))] = rateBucket{start: now}
|
||||||
|
}
|
||||||
|
if a.allow("new_key", 1) {
|
||||||
|
t.Fatal("capacity must fail closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestSessionCookieAttributes(t *testing.T) {
|
||||||
|
t.Setenv("SESSION_COOKIE_SECURE", "true")
|
||||||
|
r := gin.New()
|
||||||
|
r.GET("/cookie", func(c *gin.Context) {
|
||||||
|
c.SetSameSite(http.SameSiteStrictMode)
|
||||||
|
c.SetCookie("lp_session", "test", 60, "/", "", secureSessionCookie(c), true)
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, httptest.NewRequest("GET", "/cookie", nil))
|
||||||
|
cookies := w.Result().Cookies()
|
||||||
|
if len(cookies) != 1 || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode {
|
||||||
|
t.Fatal(cookies)
|
||||||
|
}
|
||||||
|
}
|
||||||
346
backend/internal/httpapi/orders.go
Normal file
346
backend/internal/httpapi/orders.go
Normal file
@@ -0,0 +1,346 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type orderRecord struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
OrderNo string `json:"order_no"`
|
||||||
|
CustomerID uint64 `json:"customer_id"`
|
||||||
|
CustomerName string `json:"customer_name"`
|
||||||
|
ProductID uint64 `json:"product_id"`
|
||||||
|
ProductName string `json:"product_name"`
|
||||||
|
AmountCents uint64 `json:"amount_cents"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
PaymentReference *string `json:"payment_reference"`
|
||||||
|
PaidAt *time.Time `json:"paid_at"`
|
||||||
|
LicenseID *uint64 `json:"license_id"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderSelect = `SELECT o.id,o.order_no,o.customer_id,c.name,o.product_id,p.name,o.amount_cents,o.currency,o.status,o.payment_reference,o.paid_at,o.issued_license_id,o.created_at,o.updated_at FROM offline_orders o JOIN customers c ON c.id=o.customer_id JOIN products p ON p.id=o.product_id`
|
||||||
|
|
||||||
|
type orderScanner interface{ Scan(...any) error }
|
||||||
|
|
||||||
|
func scanOrder(s orderScanner) (o orderRecord, err error) {
|
||||||
|
err = s.Scan(&o.ID, &o.OrderNo, &o.CustomerID, &o.CustomerName, &o.ProductID, &o.ProductName, &o.AmountCents, &o.Currency, &o.Status, &o.PaymentReference, &o.PaidAt, &o.LicenseID, &o.CreatedAt, &o.UpdatedAt)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) listOrders(c *gin.Context) {
|
||||||
|
p, size := page(c)
|
||||||
|
var total int
|
||||||
|
if a.db.QueryRowContext(c, "SELECT COUNT(*) FROM offline_orders").Scan(&total) != nil {
|
||||||
|
apiError(c, 500, "internal_error", "订单加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := a.db.QueryContext(c, orderSelect+" ORDER BY o.id DESC LIMIT ? OFFSET ?", size, (p-1)*size)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "订单加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []orderRecord{}
|
||||||
|
for rows.Next() {
|
||||||
|
o, e := scanOrder(rows)
|
||||||
|
if e != nil {
|
||||||
|
apiError(c, 500, "internal_error", "订单加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, o)
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "订单加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||||||
|
}
|
||||||
|
func (a *BusinessAPI) getOrder(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "订单 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
o, err := scanOrder(a.db.QueryRowContext(c, orderSelect+" WHERE o.id=?", id))
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "订单不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "订单加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": o})
|
||||||
|
}
|
||||||
|
|
||||||
|
type orderInput struct {
|
||||||
|
CustomerID uint64 `json:"customer_id"`
|
||||||
|
ProductID uint64 `json:"product_id"`
|
||||||
|
AmountCents uint64 `json:"amount_cents"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
PaymentReference string `json:"payment_reference"`
|
||||||
|
StartsAt string `json:"starts_at"`
|
||||||
|
ExpiresAt string `json:"expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
|
||||||
|
key, ok := parseOperationKey(c)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, r := range key {
|
||||||
|
if r < 33 || r > 126 {
|
||||||
|
apiError(c, 400, "invalid_idempotency_key", "幂等键仅允许可见 ASCII 字符")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var in orderInput
|
||||||
|
if c.ShouldBindJSON(&in) != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "订单参数无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var id uint64
|
||||||
|
var err error
|
||||||
|
if operation != "create" {
|
||||||
|
id, err = strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "订单 ID 无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var starts, expires time.Time
|
||||||
|
switch operation {
|
||||||
|
case "create":
|
||||||
|
if in.CustomerID == 0 || in.ProductID == 0 || in.AmountCents == 0 || in.AmountCents > 100000000000 || in.Currency != "CNY" {
|
||||||
|
apiError(c, 400, "invalid_request", "客户产品必填,金额须为1至100000000000分,币种为CNY")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
in = orderInput{CustomerID: in.CustomerID, ProductID: in.ProductID, AmountCents: in.AmountCents, Currency: in.Currency}
|
||||||
|
case "confirm-payment":
|
||||||
|
in.PaymentReference = strings.TrimSpace(in.PaymentReference)
|
||||||
|
if in.AmountCents == 0 || len(in.PaymentReference) == 0 || len(in.PaymentReference) > 190 {
|
||||||
|
apiError(c, 400, "invalid_request", "实际收款金额和收款凭据编号必填(编号最多190字节)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
in = orderInput{AmountCents: in.AmountCents, PaymentReference: in.PaymentReference}
|
||||||
|
case "issue":
|
||||||
|
starts, err = time.Parse(time.RFC3339, in.StartsAt)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 400, "invalid_request", "开始时间必须为RFC3339")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
expires, err = time.Parse(time.RFC3339, in.ExpiresAt)
|
||||||
|
starts = starts.UTC().Truncate(time.Microsecond)
|
||||||
|
expires = expires.UTC().Truncate(time.Microsecond)
|
||||||
|
if err != nil || !expires.After(starts) || starts.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
|
||||||
|
apiError(c, 400, "invalid_request", "授权期限无效或超出TIMESTAMP范围")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
in = orderInput{StartsAt: starts.Format(time.RFC3339Nano), ExpiresAt: expires.Format(time.RFC3339Nano)}
|
||||||
|
default:
|
||||||
|
apiError(c, 400, "invalid_request", "未知订单操作")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload, _ := json.Marshal(struct {
|
||||||
|
ID uint64
|
||||||
|
Input orderInput
|
||||||
|
}{id, in})
|
||||||
|
fingerprint := sha256.Sum256(payload)
|
||||||
|
tx, err := a.db.BeginTx(c, nil)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
fail := func() { apiError(c, 500, "internal_error", "订单操作失败,请保留相同幂等键重试") }
|
||||||
|
actor := c.MustGet("admin_id")
|
||||||
|
// Consistent administrator-first lock order serializes same-actor retry keys across orders.
|
||||||
|
var locked uint64
|
||||||
|
err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", actor).Scan(&locked)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 403, "forbidden", "无权操作订单")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var storedFingerprint, storedResponse []byte
|
||||||
|
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM order_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", actor, operation, key).Scan(&storedFingerprint, &storedResponse)
|
||||||
|
if err == nil {
|
||||||
|
if !bytes.Equal(storedFingerprint, fingerprint[:]) {
|
||||||
|
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同订单请求")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result gin.H
|
||||||
|
if json.Unmarshal(storedResponse, &result) != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result["idempotent_replay"] = true
|
||||||
|
c.JSON(200, result)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var o orderRecord
|
||||||
|
if operation != "create" {
|
||||||
|
o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=? FOR UPDATE", id))
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
apiError(c, 404, "not_found", "订单不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var license *licenseRecord
|
||||||
|
if operation == "create" || operation == "issue" {
|
||||||
|
customerID, productID := o.CustomerID, o.ProductID
|
||||||
|
if operation == "create" {
|
||||||
|
customerID, productID = in.CustomerID, in.ProductID
|
||||||
|
}
|
||||||
|
var customerStatus string
|
||||||
|
var active bool
|
||||||
|
err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", customerID).Scan(&o.CustomerName, &customerStatus)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) || err == nil && customerStatus != "active" {
|
||||||
|
apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = tx.QueryRowContext(c, "SELECT name,active FROM products WHERE id=? FOR UPDATE", productID).Scan(&o.ProductName, &active)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) || err == nil && !active {
|
||||||
|
apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch operation {
|
||||||
|
case "create":
|
||||||
|
raw := make([]byte, 16)
|
||||||
|
if _, err = rand.Read(raw); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res, e := tx.ExecContext(c, "INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,created_by) VALUES(?,?,?,?,?,?)", hex.EncodeToString(raw), in.CustomerID, in.ProductID, in.AmountCents, in.Currency, actor)
|
||||||
|
if e != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, e := res.LastInsertId()
|
||||||
|
if e != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id = uint64(n)
|
||||||
|
case "confirm-payment":
|
||||||
|
if o.Status != "pending_payment" {
|
||||||
|
apiError(c, 409, "invalid_state", "只有待收款订单可确认收款")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if o.AmountCents != in.AmountCents {
|
||||||
|
apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='paid',payment_reference=?,paid_at=?,paid_by=? WHERE id=?", in.PaymentReference, time.Now().UTC(), actor, id)
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "issue":
|
||||||
|
if o.Status != "paid" || o.LicenseID != nil {
|
||||||
|
apiError(c, 409, "invalid_state", "只有已收款且未发放的订单可发放授权")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw := make([]byte, 16)
|
||||||
|
if _, err = rand.Read(raw); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Random internal key avoids collisions with administrator-supplied direct-issuance keys.
|
||||||
|
internalKey := "order-" + strconv.FormatUint(id, 10) + "-" + hex.EncodeToString(raw)
|
||||||
|
res, e := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", hex.EncodeToString(raw), o.CustomerID, o.ProductID, starts, expires, internalKey, actor)
|
||||||
|
if e != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, e := res.LastInsertId()
|
||||||
|
if e != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='issued',issued_license_id=? WHERE id=?", n, id)
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l := licenseRecord{}
|
||||||
|
err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=?`, n).Scan(&l.ID, &l.LicenseKey, &l.CustomerID, &l.CustomerName, &l.ProductID, &l.ProductName, &l.ProductCode, &l.Status, &l.StartsAt, &l.ExpiresAt, &l.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.Status = currentLicenseStatus(l.Status, l.StartsAt, l.ExpiresAt, time.Now().UTC())
|
||||||
|
license = &l
|
||||||
|
details, _ := json.Marshal(gin.H{"order_id": id, "customer_id": o.CustomerID, "product_id": o.ProductID, "starts_at": starts, "expires_at": expires})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", actor, n, details); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=?", id))
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result := gin.H{"data": o, "idempotent_replay": false}
|
||||||
|
if license != nil {
|
||||||
|
result["license"] = license
|
||||||
|
}
|
||||||
|
response, err := json.Marshal(result)
|
||||||
|
if err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO order_operations(order_id,actor_admin_id,operation,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?,?)", id, actor, operation, key, fingerprint[:], response); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
details, _ := json.Marshal(gin.H{"customer_id": o.CustomerID, "product_id": o.ProductID, "amount_cents": o.AmountCents, "currency": o.Currency, "license_id": o.LicenseID})
|
||||||
|
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'order',?,?)", actor, "order."+operation, id, details); err != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tx.Commit() != nil {
|
||||||
|
fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if operation == "create" {
|
||||||
|
c.Header("Location", "/api/v1/orders/"+strconv.FormatUint(id, 10))
|
||||||
|
c.JSON(201, result)
|
||||||
|
} else {
|
||||||
|
c.JSON(200, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
150
backend/internal/httpapi/orders_integration_test.go
Normal file
150
backend/internal/httpapi/orders_integration_test.go
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testOrdersMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Cookie, customerID, productID uint64) {
|
||||||
|
request := func(method, path, body, key string, authenticated bool) *httptest.ResponseRecorder {
|
||||||
|
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Idempotency-Key", key)
|
||||||
|
if authenticated {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
check := func(w *httptest.ResponseRecorder, code int) {
|
||||||
|
t.Helper()
|
||||||
|
if w.Code != code {
|
||||||
|
t.Fatalf("code=%d want=%d body=%s", w.Code, code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exec := func(query string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := db.Exec(query, args...); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
body := fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"amount_cents":12800,"currency":"CNY"}`, customerID, productID)
|
||||||
|
check(request("POST", "/api/v1/orders", body, "create", false), 401)
|
||||||
|
exec("UPDATE admins SET role='viewer' WHERE email='integration@example.test'")
|
||||||
|
check(request("POST", "/api/v1/orders", body, "create", true), 403)
|
||||||
|
exec("UPDATE admins SET role='admin' WHERE email='integration@example.test'")
|
||||||
|
check(request("POST", "/api/v1/orders", body, "", true), 400)
|
||||||
|
check(request("POST", "/api/v1/orders", strings.Replace(body, "12800", "0", 1), "invalid", true), 400)
|
||||||
|
exec("UPDATE customers SET status='inactive' WHERE id=?", customerID)
|
||||||
|
check(request("POST", "/api/v1/orders", body, "inactive-customer", true), 400)
|
||||||
|
exec("UPDATE customers SET status='active' WHERE id=?", customerID)
|
||||||
|
w := request("POST", "/api/v1/orders", body, "create", true)
|
||||||
|
check(w, 201)
|
||||||
|
var result struct {
|
||||||
|
Data orderRecord `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id := result.Data.ID
|
||||||
|
path := fmt.Sprintf("/api/v1/orders/%d", id)
|
||||||
|
check(request("POST", "/api/v1/orders", body, "create", true), 200)
|
||||||
|
check(request("POST", "/api/v1/orders", strings.Replace(body, "12800", "12900", 1), "create", true), 409)
|
||||||
|
check(request("GET", path, "", "", true), 200)
|
||||||
|
check(request("GET", "/api/v1/orders?page=1&page_size=20", "", "", true), 200)
|
||||||
|
dates := `{"starts_at":"2026-09-30T00:00:00Z","expires_at":"2027-09-30T00:00:00Z"}`
|
||||||
|
check(request("POST", path+"/issue", dates, "issue", true), 409)
|
||||||
|
payment := `{"amount_cents":12800,"payment_reference":"BANK-TEST-001"}`
|
||||||
|
check(request("POST", path+"/confirm-payment", strings.Replace(payment, "12800", "12799", 1), "payment", true), 400)
|
||||||
|
exec("CREATE TRIGGER order_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'")
|
||||||
|
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS order_audit_failure") })
|
||||||
|
check(request("POST", path+"/confirm-payment", payment, "payment", true), 500)
|
||||||
|
exec("DROP TRIGGER order_audit_failure")
|
||||||
|
var status string
|
||||||
|
if err := db.QueryRow("SELECT status FROM offline_orders WHERE id=?", id).Scan(&status); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if status != "pending_payment" {
|
||||||
|
t.Fatal("failed payment changed order")
|
||||||
|
}
|
||||||
|
check(request("POST", path+"/confirm-payment", payment, "payment", true), 200)
|
||||||
|
check(request("POST", path+"/confirm-payment", payment, "payment", true), 200)
|
||||||
|
check(request("POST", path+"/confirm-payment", payment, "different-payment", true), 409)
|
||||||
|
check(request("POST", path+"/confirm-payment", strings.Replace(payment, "001", "002", 1), "payment", true), 409)
|
||||||
|
exec("UPDATE products SET active=0 WHERE id=?", productID)
|
||||||
|
check(request("POST", path+"/issue", dates, "issue", true), 400)
|
||||||
|
exec("UPDATE products SET active=1 WHERE id=?", productID)
|
||||||
|
var before int
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&before); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
exec("CREATE TRIGGER order_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'")
|
||||||
|
check(request("POST", path+"/issue", dates, "issue", true), 500)
|
||||||
|
exec("DROP TRIGGER order_audit_failure")
|
||||||
|
var after int
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&after); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if before != after {
|
||||||
|
t.Fatal("failed audit leaked license")
|
||||||
|
}
|
||||||
|
if err := db.QueryRow("SELECT status FROM offline_orders WHERE id=?", id).Scan(&status); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if status != "paid" {
|
||||||
|
t.Fatal("failed issuance changed order")
|
||||||
|
}
|
||||||
|
results := make(chan *httptest.ResponseRecorder, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
go func() { results <- request("POST", path+"/issue", dates, "issue", true) }()
|
||||||
|
}
|
||||||
|
replay := 0
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
w := <-results
|
||||||
|
check(w, 200)
|
||||||
|
if strings.Contains(w.Body.String(), `"idempotent_replay":true`) {
|
||||||
|
replay++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if replay != 1 {
|
||||||
|
t.Fatalf("replays=%d", replay)
|
||||||
|
}
|
||||||
|
check(request("POST", path+"/issue", dates, "different-issue", true), 409)
|
||||||
|
check(request("POST", path+"/issue", strings.Replace(dates, "2027", "2028", 1), "issue", true), 409)
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&after); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if after != before+1 {
|
||||||
|
t.Fatal("duplicate issuance")
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE resource_type='order' AND resource_id=?", id).Scan(&count); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if count != 3 {
|
||||||
|
t.Fatalf("order audits=%d", count)
|
||||||
|
}
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM order_operations WHERE order_id=?", id).Scan(&count); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if count != 3 {
|
||||||
|
t.Fatalf("operations=%d", count)
|
||||||
|
}
|
||||||
|
var licenseID uint64
|
||||||
|
if err := db.QueryRow("SELECT issued_license_id FROM offline_orders WHERE id=? AND status='issued'", id).Scan(&licenseID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.QueryRow("SELECT COUNT(*) FROM licenses WHERE id=? AND customer_id=? AND product_id=?", licenseID, customerID, productID).Scan(&count); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatal("license scope mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
104
backend/internal/httpapi/portal.go
Normal file
104
backend/internal/httpapi/portal.go
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Instance credentials authorize only this instance, never an entire customer account.
|
||||||
|
func (a *BusinessAPI) portalSnapshot(c *gin.Context) {
|
||||||
|
c.Header("Cache-Control", "private, no-store")
|
||||||
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
|
||||||
|
var in struct {
|
||||||
|
InstanceID string `json:"instance_id"`
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
}
|
||||||
|
if c.Query("customer_id") != "" || c.ShouldBindJSON(&in) != nil || len(in.InstanceID) != 36 || len(in.Secret) > 128 {
|
||||||
|
apiError(c, 400, "invalid_request", "Invalid portal request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
|
||||||
|
if err != nil || len(raw) != 32 {
|
||||||
|
apiError(c, 403, "forbidden", "Invalid credentials")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var rowID, actor, owner, productID, licenseID uint64
|
||||||
|
var stored []byte
|
||||||
|
var customerName, customerState, productName, productCode, instanceState, freeze, licenseState, observed string
|
||||||
|
var active bool
|
||||||
|
var starts, expires, now time.Time
|
||||||
|
var seen, lease sql.NullTime
|
||||||
|
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.license_id,i.secret_hash,c.name,c.status,p.name,p.code,p.active,i.status,i.freeze_state,l.status,l.starts_at,l.expires_at,i.observed_state,i.last_seen_at,i.lease_expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id AND l.customer_id=i.customer_id AND l.product_id=i.product_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=?`, in.InstanceID).Scan(&rowID, &actor, &owner, &productID, &licenseID, &stored, &customerName, &customerState, &productName, &productCode, &active, &instanceState, &freeze, &licenseState, &starts, &expires, &observed, &seen, &lease)
|
||||||
|
if err == sql.ErrNoRows || (err == nil && !bytesEqual(stored, sum[:])) {
|
||||||
|
apiError(c, 403, "forbidden", "Invalid credentials")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state := leaseState(instanceState, freeze, licenseState, customerState, active, starts, expires, now)
|
||||||
|
p, size := page(c)
|
||||||
|
// Bound offset independently of integer overflow and expensive arbitrary scans.
|
||||||
|
if p > 10000 {
|
||||||
|
apiError(c, 400, "invalid_page", "Page out of range")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var total int
|
||||||
|
if err = tx.QueryRowContext(c, "SELECT COUNT(*) FROM product_releases WHERE product_id=? AND published=1", productID).Scan(&total); err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(c, "SELECT id,version,sha256,size_bytes FROM product_releases WHERE product_id=? AND published=1 ORDER BY id DESC LIMIT ? OFFSET ?", productID, size, (p-1)*size)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
releases := []gin.H{}
|
||||||
|
for rows.Next() {
|
||||||
|
var id, sizeBytes uint64
|
||||||
|
var version, digest string
|
||||||
|
if err = rows.Scan(&id, &version, &digest, &sizeBytes); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
releases = append(releases, gin.H{"id": id, "version": version, "sha256": digest, "size_bytes": sizeBytes, "download_allowed": state == "active"})
|
||||||
|
}
|
||||||
|
scanErr := rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil || scanErr != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Audit attributes the client to an instance, not to the provisioning administrator.
|
||||||
|
if _, err = tx.ExecContext(c, `INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'portal.viewed','license_instance',?,JSON_OBJECT('client_actor','instance','customer_id',?))`, actor, rowID, owner); err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
apiError(c, 503, "portal_unavailable", "Portal unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nullable := func(v sql.NullTime) any {
|
||||||
|
if v.Valid {
|
||||||
|
return v.Time
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": gin.H{"scope": "instance", "customer": gin.H{"id": owner, "name": customerName}, "product": gin.H{"id": productID, "code": productCode, "name": productName}, "license": gin.H{"id": licenseID, "status": licenseState, "starts_at": starts, "expires_at": expires}, "instance": gin.H{"instance_id": in.InstanceID, "status": instanceState, "freeze_state": freeze}, "lease": gin.H{"observed_state": observed, "last_seen_at": nullable(seen), "expires_at": nullable(lease), "current_state": state}, "releases": releases}, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||||||
|
}
|
||||||
193
backend/internal/httpapi/portal_keyring_integration_test.go
Normal file
193
backend/internal/httpapi/portal_keyring_integration_test.go
Normal 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))
|
||||||
|
}
|
||||||
37
backend/internal/httpapi/portal_test.go
Normal file
37
backend/internal/httpapi/portal_test.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPortalCredentialCookieBoundary(t *testing.T) {
|
||||||
|
r := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil))))
|
||||||
|
a := &BusinessAPI{}
|
||||||
|
r.POST("/api/v1/portal/snapshot", a.portalSnapshot)
|
||||||
|
for _, tc := range []struct {
|
||||||
|
body, path, origin string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"{}", "/api/v1/portal/snapshot", "", 400},
|
||||||
|
{`{"instance_id":"00000000-0000-4000-8000-000000000001","secret":"wrong"}`, "/api/v1/portal/snapshot", "", 403},
|
||||||
|
{"{}", "/api/v1/portal/snapshot?customer_id=2", "", 400},
|
||||||
|
{"{}", "/api/v1/portal/snapshot", "https://evil.test", 403},
|
||||||
|
} {
|
||||||
|
q := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))
|
||||||
|
q.Header.Set("Cookie", "lp_session=administrator-cookie")
|
||||||
|
q.Header.Set("Content-Type", "application/json")
|
||||||
|
q.Header.Set("Origin", tc.origin)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, q)
|
||||||
|
if w.Code != tc.want {
|
||||||
|
t.Fatalf("status %d want %d", w.Code, tc.want)
|
||||||
|
}
|
||||||
|
if len(w.Result().Cookies()) != 0 {
|
||||||
|
t.Fatal("portal issued cookie")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
47
backend/internal/httpapi/readiness.go
Normal file
47
backend/internal/httpapi/readiness.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
const RequiredSchemaVersion = 10
|
||||||
|
|
||||||
|
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
|
||||||
|
r.GET("/api/v1/health/ready", func(c *gin.Context) {
|
||||||
|
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := CheckSchema(ctx, db); err != nil {
|
||||||
|
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "not_ready"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"status": "ready"})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func CheckSchema(ctx context.Context, db *sql.DB) error {
|
||||||
|
if db == nil {
|
||||||
|
return sql.ErrConnDone
|
||||||
|
}
|
||||||
|
var version uint64
|
||||||
|
var dirty bool
|
||||||
|
rows, err := db.QueryContext(ctx, "SELECT version, dirty FROM schema_migrations")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
if !rows.Next() {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
if err := rows.Scan(&version, &dirty); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if rows.Next() || rows.Err() != nil || version != RequiredSchemaVersion || dirty {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
95
backend/internal/httpapi/readiness_test.go
Normal file
95
backend/internal/httpapi/readiness_test.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"database/sql/driver"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type readinessDriver struct{}
|
||||||
|
type readinessConn struct{ mode string }
|
||||||
|
type readinessRows struct {
|
||||||
|
mode string
|
||||||
|
read bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (readinessDriver) Open(mode string) (driver.Conn, error) { return readinessConn{mode}, nil }
|
||||||
|
func (readinessConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("not supported") }
|
||||||
|
func (readinessConn) Close() error { return nil }
|
||||||
|
func (readinessConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") }
|
||||||
|
func (c readinessConn) QueryContext(context.Context, string, []driver.NamedValue) (driver.Rows, error) {
|
||||||
|
if c.mode == "unavailable" {
|
||||||
|
return nil, errors.New("private connection detail")
|
||||||
|
}
|
||||||
|
return &readinessRows{mode: c.mode}, nil
|
||||||
|
}
|
||||||
|
func (*readinessRows) Columns() []string { return []string{"version", "dirty"} }
|
||||||
|
func (*readinessRows) Close() error { return nil }
|
||||||
|
func (r *readinessRows) Next(values []driver.Value) error {
|
||||||
|
if r.read || r.mode == "empty" {
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
r.read = true
|
||||||
|
version := int64(RequiredSchemaVersion)
|
||||||
|
if r.mode == "old" {
|
||||||
|
version--
|
||||||
|
}
|
||||||
|
if r.mode == "future" {
|
||||||
|
version++
|
||||||
|
}
|
||||||
|
values[0] = version
|
||||||
|
values[1] = r.mode == "dirty"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func init() { sql.Register("readiness-test", readinessDriver{}) }
|
||||||
|
func TestReadinessSchemaGate(t *testing.T) {
|
||||||
|
for _, mode := range []string{"ready", "old", "future", "dirty", "empty", "unavailable", "nil"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
var db *sql.DB
|
||||||
|
if mode != "nil" {
|
||||||
|
var err error
|
||||||
|
db, err = sql.Open("readiness-test", mode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
}
|
||||||
|
r := gin.New()
|
||||||
|
RegisterReadiness(r, db)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/health/ready", nil))
|
||||||
|
want := 503
|
||||||
|
body := `{"status":"not_ready"}`
|
||||||
|
if mode == "ready" {
|
||||||
|
want = 200
|
||||||
|
body = `{"status":"ready"}`
|
||||||
|
}
|
||||||
|
if w.Code != want || w.Body.String() != body {
|
||||||
|
t.Fatalf("%d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestSecureSessionCookie(t *testing.T) {
|
||||||
|
t.Setenv("SESSION_COOKIE_SECURE", "true")
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Request = httptest.NewRequest("GET", "http://localhost/", nil)
|
||||||
|
if !secureSessionCookie(c) {
|
||||||
|
t.Fatal("forced secure lost")
|
||||||
|
}
|
||||||
|
t.Setenv("SESSION_COOKIE_SECURE", "false")
|
||||||
|
c.Request.Header.Set("X-Forwarded-Proto", "https")
|
||||||
|
if secureSessionCookie(c) {
|
||||||
|
t.Fatal("untrusted header enabled cookie security")
|
||||||
|
}
|
||||||
|
c.Request = httptest.NewRequest("GET", "https://localhost/", nil)
|
||||||
|
if !secureSessionCookie(c) {
|
||||||
|
t.Fatal("direct TLS must be secure")
|
||||||
|
}
|
||||||
|
}
|
||||||
84
backend/internal/httpapi/redis_limiter.go
Normal file
84
backend/internal/httpapi/redis_limiter.go
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EntryLimiter interface {
|
||||||
|
Allow(context.Context, string, int) (bool, error)
|
||||||
|
}
|
||||||
|
type RedisLimiter struct {
|
||||||
|
client *redis.Client
|
||||||
|
prefix string
|
||||||
|
}
|
||||||
|
|
||||||
|
var entryLimitScript = redis.NewScript(`
|
||||||
|
local n = redis.call('INCR', KEYS[1])
|
||||||
|
if n == 1 then redis.call('PEXPIRE', KEYS[1], 60000) end
|
||||||
|
if n > tonumber(ARGV[1]) then return 0 end
|
||||||
|
return 1
|
||||||
|
`)
|
||||||
|
|
||||||
|
func NewRedisLimiter(client *redis.Client, prefix string) *RedisLimiter {
|
||||||
|
return &RedisLimiter{client: client, prefix: prefix}
|
||||||
|
}
|
||||||
|
func (l *RedisLimiter) Allow(ctx context.Context, key string, limit int) (bool, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
result, err := entryLimitScript.Run(ctx, l.client, []string{l.prefix + key}, limit).Int()
|
||||||
|
return result == 1, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redis errors never fall back to per-process counters.
|
||||||
|
func ConfigureEntryLimiter(ops *Operations, getenv func(string) string) (func(), error) {
|
||||||
|
mode := getenv("ENTRY_LIMIT_MODE")
|
||||||
|
if mode == "local-dev" {
|
||||||
|
return func() {}, nil
|
||||||
|
}
|
||||||
|
if mode != "" && mode != "redis" {
|
||||||
|
return nil, fmt.Errorf("invalid entry limit mode")
|
||||||
|
}
|
||||||
|
addr := getenv("ENTRY_REDIS_ADDR")
|
||||||
|
if addr == "" {
|
||||||
|
return nil, fmt.Errorf("Redis entry limiting required; local-dev must be explicitly opted into")
|
||||||
|
}
|
||||||
|
host, _, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid Redis address")
|
||||||
|
}
|
||||||
|
opts := &redis.Options{Addr: addr, Username: getenv("ENTRY_REDIS_USERNAME"), DialTimeout: 500 * time.Millisecond, ReadTimeout: 500 * time.Millisecond, WriteTimeout: 500 * time.Millisecond, MaxRetries: -1, ContextTimeoutEnabled: true}
|
||||||
|
if path := getenv("ENTRY_REDIS_PASSWORD_FILE"); path != "" {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return nil, fmt.Errorf("Redis password file must be absolute")
|
||||||
|
}
|
||||||
|
bytes, err := os.ReadFile(path)
|
||||||
|
if err != nil || len(bytes) == 0 || len(bytes) > 4096 {
|
||||||
|
return nil, fmt.Errorf("invalid Redis password file")
|
||||||
|
}
|
||||||
|
opts.Password = strings.TrimSpace(string(bytes))
|
||||||
|
}
|
||||||
|
// Current profile permits only numeric loopback/private IP transport. Remote TLS remains a release gate.
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip == nil || (!ip.IsLoopback() && !ip.IsPrivate()) {
|
||||||
|
return nil, fmt.Errorf("Redis must use a numeric private or loopback IP")
|
||||||
|
}
|
||||||
|
client := redis.NewClient(opts)
|
||||||
|
prefix := getenv("ENTRY_REDIS_NAMESPACE")
|
||||||
|
if prefix == "" {
|
||||||
|
prefix = "license-platform:entry:"
|
||||||
|
}
|
||||||
|
if len(prefix) > 100 {
|
||||||
|
client.Close()
|
||||||
|
return nil, fmt.Errorf("invalid Redis namespace")
|
||||||
|
}
|
||||||
|
ops.limiter = NewRedisLimiter(client, prefix)
|
||||||
|
return func() { client.Close() }, nil
|
||||||
|
}
|
||||||
83
backend/internal/httpapi/redis_limiter_test.go
Normal file
83
backend/internal/httpapi/redis_limiter_test.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRedisEntryIntegration(t *testing.T) {
|
||||||
|
addr := os.Getenv("ENTRY_REDIS_TEST_ADDR")
|
||||||
|
if addr == "" {
|
||||||
|
t.Skip("isolated Redis required")
|
||||||
|
}
|
||||||
|
prefix := fmt.Sprintf("test:entry:%d:", time.Now().UnixNano())
|
||||||
|
clients := []*redis.Client{redis.NewClient(&redis.Options{Addr: addr}), redis.NewClient(&redis.Options{Addr: addr})}
|
||||||
|
for _, c := range clients {
|
||||||
|
defer c.Close()
|
||||||
|
if err := c.Ping(context.Background()).Err(); err != nil {
|
||||||
|
t.Fatal("isolated Redis unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
servers := make([]*httptest.Server, 2)
|
||||||
|
calls := 0
|
||||||
|
for i := range servers {
|
||||||
|
ops := NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||||
|
ops.limiter = NewRedisLimiter(clients[i], prefix)
|
||||||
|
r := NewOperationalRouter(ops)
|
||||||
|
r.POST("/api/v1/auth/login", func(c *gin.Context) { calls++; c.Status(401) })
|
||||||
|
servers[i] = httptest.NewServer(r)
|
||||||
|
defer servers[i].Close()
|
||||||
|
}
|
||||||
|
for i := 0; i < 11; i++ {
|
||||||
|
req, _ := http.NewRequest("POST", servers[i%2].URL+"/api/v1/auth/login", nil)
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
want := 401
|
||||||
|
if i == 10 {
|
||||||
|
want = 429
|
||||||
|
}
|
||||||
|
if res.StatusCode != want {
|
||||||
|
t.Fatal(i, res.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if calls != 10 {
|
||||||
|
t.Fatal(calls)
|
||||||
|
}
|
||||||
|
clients[0].Close()
|
||||||
|
res, err := http.Post(servers[0].URL+"/api/v1/auth/login", "application/json", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
if res.StatusCode != 503 || calls != 10 {
|
||||||
|
t.Fatal("Redis failure must block handler", res.StatusCode, calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestEntryModeRequiresExplicitDevelopment(t *testing.T) {
|
||||||
|
ops := NewOperations(slog.Default())
|
||||||
|
if _, err := ConfigureEntryLimiter(ops, func(string) string { return "" }); err == nil {
|
||||||
|
t.Fatal("implicit fallback")
|
||||||
|
}
|
||||||
|
close, err := ConfigureEntryLimiter(ops, func(k string) string {
|
||||||
|
if k == "ENTRY_LIMIT_MODE" {
|
||||||
|
return "local-dev"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
close()
|
||||||
|
}
|
||||||
42
backend/internal/httpapi/releases_list.go
Normal file
42
backend/internal/httpapi/releases_list.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *BusinessAPI) listReleases(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
apiError(c, 400, "invalid_request", "产品无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, size := page(c)
|
||||||
|
var total int
|
||||||
|
if err = a.db.QueryRowContext(c, "SELECT COUNT(*) FROM product_releases WHERE product_id=?", id).Scan(&total); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := a.db.QueryContext(c, "SELECT id,version,sha256,size_bytes,published FROM product_releases WHERE product_id=? ORDER BY id DESC LIMIT ? OFFSET ?", id, size, (p-1)*size)
|
||||||
|
if err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
data := []gin.H{}
|
||||||
|
for rows.Next() {
|
||||||
|
var rid, n uint64
|
||||||
|
var version, digest string
|
||||||
|
var published bool
|
||||||
|
if err = rows.Scan(&rid, &version, &digest, &n, &published); err != nil {
|
||||||
|
apiError(c, 500, "internal_error", "加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data = append(data, gin.H{"id": rid, "version": version, "sha256": digest, "size_bytes": n, "published": published})
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
apiError(c, 500, "internal_error", "加载失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"data": data, "meta": gin.H{"total": total, "page": p, "page_size": size}})
|
||||||
|
}
|
||||||
@@ -1,14 +1,22 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewRouter() *gin.Engine {
|
func NewRouter() *gin.Engine {
|
||||||
|
return NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(os.Stdout, nil))))
|
||||||
|
}
|
||||||
|
func NewOperationalRouter(ops *Operations) *gin.Engine {
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
r.Use(gin.Logger(), gin.Recovery())
|
_ = r.SetTrustedProxies(nil)
|
||||||
|
r.Use(ops.Middleware())
|
||||||
|
r.NoRoute(func(c *gin.Context) { apiError(c, 404, "not_found", "Not found") })
|
||||||
r.GET("/api/v1/health/live", func(c *gin.Context) {
|
r.GET("/api/v1/health/live", func(c *gin.Context) {
|
||||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ func TestLiveness(t *testing.T) {
|
|||||||
if w.Code != http.StatusOK {
|
if w.Code != http.StatusOK {
|
||||||
t.Fatalf("status = %d, want 200", w.Code)
|
t.Fatalf("status = %d, want 200", w.Code)
|
||||||
}
|
}
|
||||||
var body struct{ Status string `json:"status"` }
|
var body struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Status != "ok" {
|
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Status != "ok" {
|
||||||
t.Fatalf("body = %q, err = %v", w.Body.String(), err)
|
t.Fatalf("body = %q, err = %v", w.Body.String(), err)
|
||||||
}
|
}
|
||||||
|
|||||||
42
backend/internal/httpapi/server.go
Normal file
42
backend/internal/httpapi/server.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Serve(ctx context.Context, server *http.Server, shutdownTimeout time.Duration) error {
|
||||||
|
listener, err := net.Listen("tcp", server.Addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return serveListener(ctx, server, listener, shutdownTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveListener(ctx context.Context, server *http.Server, listener net.Listener, timeout time.Duration) error {
|
||||||
|
result := make(chan error, 1)
|
||||||
|
go func() { result <- server.Serve(listener) }()
|
||||||
|
select {
|
||||||
|
case err := <-result:
|
||||||
|
if errors.Is(err, http.ErrServerClosed) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
case <-ctx.Done():
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
|
defer cancel()
|
||||||
|
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||||
|
_ = server.Close()
|
||||||
|
<-result
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err := <-result
|
||||||
|
if errors.Is(err, http.ErrServerClosed) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
105
backend/internal/httpapi/server_test.go
Normal file
105
backend/internal/httpapi/server_test.go
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestShutdown(t *testing.T) {
|
||||||
|
for _, graceful := range []bool{true, false} {
|
||||||
|
name := "timeout"
|
||||||
|
if graceful {
|
||||||
|
name = "drain"
|
||||||
|
}
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer listener.Close()
|
||||||
|
started, release := make(chan struct{}), make(chan struct{})
|
||||||
|
defer close(release)
|
||||||
|
handlerDone := make(chan struct{})
|
||||||
|
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
close(started)
|
||||||
|
defer close(handlerDone)
|
||||||
|
select {
|
||||||
|
case <-release:
|
||||||
|
case <-r.Context().Done():
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
})}
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
finished := make(chan error, 1)
|
||||||
|
go func() { finished <- serveListener(ctx, server, listener, 150*time.Millisecond) }()
|
||||||
|
requested := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
client := &http.Client{Timeout: 3 * time.Second}
|
||||||
|
response, err := client.Get("http://" + listener.Addr().String())
|
||||||
|
if err == nil {
|
||||||
|
response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusNoContent {
|
||||||
|
err = errors.New("unexpected status")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requested <- err
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-started:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("request did not start")
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
if graceful {
|
||||||
|
select {
|
||||||
|
case err := <-finished:
|
||||||
|
t.Fatalf("exited with active request: %v", err)
|
||||||
|
case <-time.After(20 * time.Millisecond):
|
||||||
|
}
|
||||||
|
release <- struct{}{}
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case err := <-finished:
|
||||||
|
if graceful && err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !graceful && !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Fatalf("expected deadline: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("shutdown did not finish")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case err := <-requested:
|
||||||
|
if graceful && err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("request did not finish")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-handlerDone:
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("handler did not exit")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServeListenFailure(t *testing.T) {
|
||||||
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer listener.Close()
|
||||||
|
err = Serve(context.Background(), &http.Server{Addr: listener.Addr().String()}, time.Second)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected address in use error")
|
||||||
|
}
|
||||||
|
}
|
||||||
178
backend/internal/httpapi/signing_restart_test.go
Normal file
178
backend/internal/httpapi/signing_restart_test.go
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
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)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}
|
||||||
50
backend/internal/httpapi/tls_boundary_test.go
Normal file
50
backend/internal/httpapi/tls_boundary_test.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTLSOriginCookieBoundary(t *testing.T) {
|
||||||
|
r := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil))))
|
||||||
|
r.POST("/write", func(c *gin.Context) {
|
||||||
|
c.SetSameSite(http.SameSiteStrictMode)
|
||||||
|
c.SetCookie("test_session", "not-a-real-session", 10, "/", "", secureSessionCookie(c), true)
|
||||||
|
c.JSON(200, gin.H{"ip": c.ClientIP()})
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(r)
|
||||||
|
defer s.Close()
|
||||||
|
client := s.Client()
|
||||||
|
for _, tc := range []struct {
|
||||||
|
origin string
|
||||||
|
status int
|
||||||
|
}{{s.URL, 200}, {"https://foreign.invalid", 403}, {strings.Replace(s.URL, "https:", "http:", 1), 403}} {
|
||||||
|
q, _ := http.NewRequest("POST", s.URL+"/write", strings.NewReader("{}"))
|
||||||
|
q.Header.Set("Origin", tc.origin)
|
||||||
|
q.Header.Set("X-Forwarded-For", "198.51.100.1")
|
||||||
|
q.Header.Set("X-Forwarded-Proto", "https")
|
||||||
|
resp, err := client.Do(q)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != tc.status {
|
||||||
|
t.Fatal(resp.StatusCode)
|
||||||
|
}
|
||||||
|
if tc.status == 200 {
|
||||||
|
cookies := resp.Cookies()
|
||||||
|
if len(cookies) != 1 || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode {
|
||||||
|
t.Fatal("unsafe cookie")
|
||||||
|
}
|
||||||
|
if strings.Contains(string(body), "198.51.100.1") {
|
||||||
|
t.Fatal("untrusted forwarded IP accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
89
backend/internal/migrations/runner.go
Normal file
89
backend/internal/migrations/runner.go
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/golang-migrate/migrate/v4"
|
||||||
|
_ "github.com/golang-migrate/migrate/v4/database/mysql"
|
||||||
|
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrDirtyDatabase = errors.New("database migration is dirty; inspect and force the last known good version")
|
||||||
|
|
||||||
|
type Runner struct {
|
||||||
|
migrate *migrate.Migrate
|
||||||
|
}
|
||||||
|
|
||||||
|
func Open(dsn, directory string) (*Runner, error) {
|
||||||
|
if dsn == "" {
|
||||||
|
return nil, errors.New("migration DSN is required")
|
||||||
|
}
|
||||||
|
absolute, err := filepath.Abs(directory)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve migration directory: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(absolute); err != nil {
|
||||||
|
return nil, fmt.Errorf("migration directory: %w", err)
|
||||||
|
}
|
||||||
|
sourceURL := (&url.URL{Scheme: "file", Path: filepath.ToSlash(absolute)}).String()
|
||||||
|
m, err := migrate.New(sourceURL, dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("open migration database: %w", err)
|
||||||
|
}
|
||||||
|
return &Runner{migrate: m}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) Close() error {
|
||||||
|
sourceErr, databaseErr := r.migrate.Close()
|
||||||
|
if sourceErr != nil {
|
||||||
|
return sourceErr
|
||||||
|
}
|
||||||
|
return databaseErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) Up() error {
|
||||||
|
if err := r.migrate.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||||
|
return r.wrap(err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) Down() error {
|
||||||
|
if err := r.migrate.Down(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||||
|
return r.wrap(err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) Version() (uint, bool, error) {
|
||||||
|
return r.migrate.Version()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Force is deliberately explicit: it only repairs migration metadata after an
|
||||||
|
// operator has inspected the failed DDL and selected a known-good version.
|
||||||
|
func (r *Runner) Force(version int) error {
|
||||||
|
if version < -1 {
|
||||||
|
return fmt.Errorf("migration version must be >= -1: %d", version)
|
||||||
|
}
|
||||||
|
return r.migrate.Force(version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) wrap(err error) error {
|
||||||
|
if _, dirty, versionErr := r.migrate.Version(); versionErr == nil && dirty {
|
||||||
|
return fmt.Errorf("%w: version=%s: %v", ErrDirtyDatabase, strconv.FormatUint(uint64(versionFrom(r.migrate)), 10), err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func versionFrom(m *migrate.Migrate) uint {
|
||||||
|
version, _, err := m.Version()
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return version
|
||||||
|
}
|
||||||
83
backend/internal/migrations/v6_integration_test.go
Normal file
83
backend/internal/migrations/v6_integration_test.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
migrate "github.com/golang-migrate/migrate/v4"
|
||||||
|
_ "github.com/golang-migrate/migrate/v4/database/mysql"
|
||||||
|
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||||
|
"net/url"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestV6Rehearsal(t *testing.T) {
|
||||||
|
dsn := os.Getenv("MIGRATION_REHEARSAL_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("isolated rehearsal DSN required")
|
||||||
|
}
|
||||||
|
directory, err := filepath.Abs("../../migrations")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
m, err := migrate.New((&url.URL{Scheme: "file", Path: filepath.ToSlash(directory)}).String(), "mysql://"+dsn+"?multiStatements=true")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer m.Close()
|
||||||
|
if err = m.Migrate(5); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
db, err := sql.Open("mysql", dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
statements := []string{
|
||||||
|
"INSERT INTO admins(id,email,password_hash) VALUES(1,'rehearsal@example.invalid','not-a-login-hash')",
|
||||||
|
"INSERT INTO customers(id,name,contact_email) VALUES(1,'rehearsal','rehearsal@example.invalid')",
|
||||||
|
"INSERT INTO products(id,code,name,description) VALUES(1,'rehearsal','rehearsal','')",
|
||||||
|
"INSERT INTO licenses(id,license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(1,REPEAT('a',32),1,1,UTC_TIMESTAMP(),DATE_ADD(UTC_TIMESTAMP(),INTERVAL 1 YEAR),'rehearsal',1)",
|
||||||
|
"INSERT INTO license_instances(id,instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(1,'00000000-0000-4000-8000-000000000001',1,1,1,UNHEX(REPEAT('00',32)),1)",
|
||||||
|
"INSERT INTO activation_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(1,1,'rehearsal',UNHEX(REPEAT('00',32)),JSON_OBJECT('fixture',true))",
|
||||||
|
"INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(1,'fixture','license_instance',1,JSON_OBJECT('fixture',true))",
|
||||||
|
}
|
||||||
|
for _, s := range statements {
|
||||||
|
if _, err = db.Exec(s); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = m.Migrate(6); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec("INSERT INTO heartbeat_operations(instance_id,idempotency_key,request_fingerprint,response,state) VALUES(1,'fixture',UNHEX(REPEAT('00',32)),JSON_OBJECT('fixture',true),'active')"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec("INSERT INTO instance_state_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(1,1,'fixture',UNHEX(REPEAT('00',32)),JSON_OBJECT('fixture',true))"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = m.Steps(-1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, table := range []string{"admins", "customers", "products", "licenses", "license_instances", "activation_operations", "audit_events"} {
|
||||||
|
var n int
|
||||||
|
if err = db.QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 1 {
|
||||||
|
t.Fatalf("old table %s n=%d err=%v", table, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = m.Steps(1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, table := range []string{"heartbeat_operations", "instance_state_operations"} {
|
||||||
|
var n int
|
||||||
|
if err = db.QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatalf("v6 table %s n=%d err=%v", table, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v, dirty, err := m.Version()
|
||||||
|
if err != nil || v != 6 || dirty {
|
||||||
|
t.Fatalf("version=%d dirty=%v err=%v", v, dirty, err)
|
||||||
|
}
|
||||||
|
t.Log("005 -> 006 -> 005 -> 006 clean; seven pre-v6 fixture rows preserved; v6 operation history and lease/freeze fields intentionally removed by down")
|
||||||
|
}
|
||||||
4
backend/migrations/000001_core.down.sql
Normal file
4
backend/migrations/000001_core.down.sql
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
DROP TABLE IF EXISTS sessions;
|
||||||
|
DROP TABLE IF EXISTS products;
|
||||||
|
DROP TABLE IF EXISTS customers;
|
||||||
|
DROP TABLE IF EXISTS admins;
|
||||||
42
backend/migrations/000001_core.up.sql
Normal file
42
backend/migrations/000001_core.up.sql
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
CREATE TABLE admins (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
email VARCHAR(190) NOT NULL,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
role VARCHAR(32) NOT NULL DEFAULT 'admin',
|
||||||
|
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id), UNIQUE KEY uq_admins_email (email)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
admin_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
token_hash BINARY(32) NOT NULL,
|
||||||
|
expires_at TIMESTAMP(6) NOT NULL,
|
||||||
|
revoked_at TIMESTAMP(6) NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id), UNIQUE KEY uq_sessions_token_hash (token_hash),
|
||||||
|
KEY idx_sessions_admin (admin_id), KEY idx_sessions_expiry (expires_at),
|
||||||
|
CONSTRAINT fk_sessions_admin FOREIGN KEY (admin_id) REFERENCES admins(id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE customers (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
name VARCHAR(190) NOT NULL,
|
||||||
|
contact_email VARCHAR(190) NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id), KEY idx_customers_status (status), KEY idx_customers_name (name)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE products (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
code VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(190) NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id), UNIQUE KEY uq_products_code (code), KEY idx_products_active (active)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
2
backend/migrations/000002_licenses.down.sql
Normal file
2
backend/migrations/000002_licenses.down.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
DROP TABLE IF EXISTS audit_events;
|
||||||
|
DROP TABLE IF EXISTS licenses;
|
||||||
32
backend/migrations/000002_licenses.up.sql
Normal file
32
backend/migrations/000002_licenses.up.sql
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
CREATE TABLE licenses (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
license_key CHAR(32) NOT NULL,
|
||||||
|
customer_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
product_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||||
|
starts_at TIMESTAMP(6) NOT NULL,
|
||||||
|
expires_at TIMESTAMP(6) NOT NULL,
|
||||||
|
idempotency_key VARCHAR(128) NOT NULL,
|
||||||
|
issued_by BIGINT UNSIGNED NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
revoked_at TIMESTAMP(6) NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_licenses_key (license_key),
|
||||||
|
UNIQUE KEY uq_licenses_idempotency (issued_by, idempotency_key),
|
||||||
|
KEY idx_licenses_customer (customer_id), KEY idx_licenses_product (product_id), KEY idx_licenses_status (status),
|
||||||
|
CONSTRAINT fk_licenses_customer FOREIGN KEY (customer_id) REFERENCES customers(id),
|
||||||
|
CONSTRAINT fk_licenses_product FOREIGN KEY (product_id) REFERENCES products(id),
|
||||||
|
CONSTRAINT fk_licenses_admin FOREIGN KEY (issued_by) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE audit_events (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
actor_admin_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
action VARCHAR(64) NOT NULL,
|
||||||
|
resource_type VARCHAR(64) NOT NULL,
|
||||||
|
resource_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
details JSON NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id), KEY idx_audit_resource (resource_type, resource_id), KEY idx_audit_actor (actor_admin_id),
|
||||||
|
CONSTRAINT fk_audit_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
1
backend/migrations/000003_license_operations.down.sql
Normal file
1
backend/migrations/000003_license_operations.down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS license_operations;
|
||||||
14
backend/migrations/000003_license_operations.up.sql
Normal file
14
backend/migrations/000003_license_operations.up.sql
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
CREATE TABLE license_operations (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
license_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
actor_admin_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
operation VARCHAR(32) NOT NULL,
|
||||||
|
idempotency_key VARCHAR(128) NOT NULL,
|
||||||
|
request_fingerprint BINARY(32) NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_license_operation_key (actor_admin_id, operation, idempotency_key),
|
||||||
|
KEY idx_license_operations_license (license_id),
|
||||||
|
CONSTRAINT fk_license_operations_license FOREIGN KEY (license_id) REFERENCES licenses(id),
|
||||||
|
CONSTRAINT fk_license_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
2
backend/migrations/000004_orders.down.sql
Normal file
2
backend/migrations/000004_orders.down.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
DROP TABLE order_operations;
|
||||||
|
DROP TABLE offline_orders;
|
||||||
39
backend/migrations/000004_orders.up.sql
Normal file
39
backend/migrations/000004_orders.up.sql
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
CREATE TABLE offline_orders (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
order_no CHAR(32) NOT NULL,
|
||||||
|
customer_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
product_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
amount_cents BIGINT UNSIGNED NOT NULL,
|
||||||
|
currency CHAR(3) NOT NULL DEFAULT 'CNY',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'pending_payment',
|
||||||
|
payment_reference VARCHAR(190) NULL,
|
||||||
|
paid_at TIMESTAMP(6) NULL,
|
||||||
|
paid_by BIGINT UNSIGNED NULL,
|
||||||
|
issued_license_id BIGINT UNSIGNED NULL,
|
||||||
|
created_by BIGINT UNSIGNED NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id), UNIQUE KEY uq_offline_orders_no (order_no),
|
||||||
|
UNIQUE KEY uq_offline_orders_license (issued_license_id),
|
||||||
|
KEY idx_offline_orders_customer (customer_id), KEY idx_offline_orders_status (status),
|
||||||
|
CONSTRAINT fk_offline_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id),
|
||||||
|
CONSTRAINT fk_offline_orders_product FOREIGN KEY (product_id) REFERENCES products(id),
|
||||||
|
CONSTRAINT fk_offline_orders_license FOREIGN KEY (issued_license_id) REFERENCES licenses(id),
|
||||||
|
CONSTRAINT fk_offline_orders_admin FOREIGN KEY (created_by) REFERENCES admins(id),
|
||||||
|
CONSTRAINT fk_offline_orders_paid_by FOREIGN KEY (paid_by) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE order_operations (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
order_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
actor_admin_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
operation VARCHAR(32) NOT NULL,
|
||||||
|
idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
request_fingerprint BINARY(32) NOT NULL,
|
||||||
|
response JSON NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_order_operations_key (actor_admin_id, operation, idempotency_key),
|
||||||
|
CONSTRAINT fk_order_operations_order FOREIGN KEY (order_id) REFERENCES offline_orders(id),
|
||||||
|
CONSTRAINT fk_order_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
2
backend/migrations/000005_activation.down.sql
Normal file
2
backend/migrations/000005_activation.down.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
DROP TABLE IF EXISTS activation_operations;
|
||||||
|
DROP TABLE IF EXISTS license_instances;
|
||||||
39
backend/migrations/000005_activation.up.sql
Normal file
39
backend/migrations/000005_activation.up.sql
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
CREATE TABLE license_instances (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
instance_id CHAR(36) NOT NULL,
|
||||||
|
license_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
customer_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
product_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
secret_hash BINARY(32) NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'provisioned',
|
||||||
|
activated_at TIMESTAMP(6) NULL,
|
||||||
|
certificate_version VARCHAR(32) NULL,
|
||||||
|
certificate_payload JSON NULL,
|
||||||
|
certificate_signature TEXT NULL,
|
||||||
|
created_by BIGINT UNSIGNED NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_license_instances_instance (instance_id),
|
||||||
|
UNIQUE KEY uq_license_instances_license (license_id),
|
||||||
|
KEY idx_license_instances_customer (customer_id),
|
||||||
|
KEY idx_license_instances_product (product_id),
|
||||||
|
CONSTRAINT fk_license_instances_license FOREIGN KEY (license_id) REFERENCES licenses(id),
|
||||||
|
CONSTRAINT fk_license_instances_customer FOREIGN KEY (customer_id) REFERENCES customers(id),
|
||||||
|
CONSTRAINT fk_license_instances_product FOREIGN KEY (product_id) REFERENCES products(id),
|
||||||
|
CONSTRAINT fk_license_instances_admin FOREIGN KEY (created_by) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE activation_operations (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
instance_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
actor_admin_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
request_fingerprint BINARY(32) NOT NULL,
|
||||||
|
response JSON NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_activation_operations_key (instance_id, idempotency_key),
|
||||||
|
CONSTRAINT fk_activation_operations_instance FOREIGN KEY (instance_id) REFERENCES license_instances(id),
|
||||||
|
CONSTRAINT fk_activation_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
10
backend/migrations/000006_heartbeat_lease.down.sql
Normal file
10
backend/migrations/000006_heartbeat_lease.down.sql
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
DROP TABLE IF EXISTS instance_state_operations;
|
||||||
|
DROP TABLE IF EXISTS heartbeat_operations;
|
||||||
|
ALTER TABLE license_instances
|
||||||
|
DROP KEY idx_license_instances_last_seen,
|
||||||
|
DROP KEY idx_license_instances_lease,
|
||||||
|
DROP COLUMN freeze_state,
|
||||||
|
DROP COLUMN lease_expires_at,
|
||||||
|
DROP COLUMN last_seen_at,
|
||||||
|
DROP COLUMN client_seen_at,
|
||||||
|
DROP COLUMN observed_state;
|
||||||
35
backend/migrations/000006_heartbeat_lease.up.sql
Normal file
35
backend/migrations/000006_heartbeat_lease.up.sql
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
ALTER TABLE license_instances
|
||||||
|
ADD COLUMN last_seen_at TIMESTAMP(6) NULL,
|
||||||
|
ADD COLUMN client_seen_at TIMESTAMP(6) NULL,
|
||||||
|
ADD COLUMN observed_state VARCHAR(32) NOT NULL DEFAULT 'unknown',
|
||||||
|
ADD COLUMN lease_expires_at TIMESTAMP(6) NULL,
|
||||||
|
ADD COLUMN freeze_state VARCHAR(32) NOT NULL DEFAULT 'none',
|
||||||
|
ADD KEY idx_license_instances_last_seen (last_seen_at),
|
||||||
|
ADD KEY idx_license_instances_lease (lease_expires_at);
|
||||||
|
|
||||||
|
CREATE TABLE heartbeat_operations (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
instance_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
request_fingerprint BINARY(32) NOT NULL,
|
||||||
|
response JSON NOT NULL,
|
||||||
|
state VARCHAR(32) NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_heartbeat_operations_key (instance_id, idempotency_key),
|
||||||
|
CONSTRAINT fk_heartbeat_operations_instance FOREIGN KEY (instance_id) REFERENCES license_instances(id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE instance_state_operations (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
instance_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
actor_admin_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
request_fingerprint BINARY(32) NOT NULL,
|
||||||
|
response JSON NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_instance_state_operations_key (actor_admin_id,idempotency_key),
|
||||||
|
CONSTRAINT fk_instance_state_operations_instance FOREIGN KEY (instance_id) REFERENCES license_instances(id),
|
||||||
|
CONSTRAINT fk_instance_state_operations_admin FOREIGN KEY (actor_admin_id) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
1
backend/migrations/000007_local_releases.down.sql
Normal file
1
backend/migrations/000007_local_releases.down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS product_releases;
|
||||||
15
backend/migrations/000007_local_releases.up.sql
Normal file
15
backend/migrations/000007_local_releases.up.sql
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
CREATE TABLE product_releases (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
product_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
storage_key CHAR(68) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
size_bytes BIGINT UNSIGNED NOT NULL,
|
||||||
|
published BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_by BIGINT UNSIGNED NOT NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY(id),
|
||||||
|
UNIQUE KEY uq_releases_version(product_id,version),
|
||||||
|
CONSTRAINT fk_release_product FOREIGN KEY(product_id) REFERENCES products(id),
|
||||||
|
CONSTRAINT fk_release_admin FOREIGN KEY(created_by) REFERENCES admins(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
1
backend/migrations/000008_package_objects.down.sql
Normal file
1
backend/migrations/000008_package_objects.down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS package_objects;
|
||||||
5
backend/migrations/000008_package_objects.up.sql
Normal file
5
backend/migrations/000008_package_objects.up.sql
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
CREATE TABLE package_objects (
|
||||||
|
sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
|
||||||
|
size_bytes BIGINT UNSIGNED NOT NULL
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
INSERT INTO package_objects(sha256,size_bytes) SELECT sha256,MAX(size_bytes) FROM product_releases GROUP BY sha256;
|
||||||
2
backend/migrations/000009_admin_settings.down.sql
Normal file
2
backend/migrations/000009_admin_settings.down.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
DROP INDEX idx_audit_created_id ON audit_events;
|
||||||
|
DROP TABLE IF EXISTS system_settings;
|
||||||
11
backend/migrations/000009_admin_settings.up.sql
Normal file
11
backend/migrations/000009_admin_settings.up.sql
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE system_settings (
|
||||||
|
id TINYINT UNSIGNED NOT NULL,
|
||||||
|
site_name VARCHAR(100) NOT NULL DEFAULT '授权管理平台',
|
||||||
|
support_email VARCHAR(254) NOT NULL DEFAULT '',
|
||||||
|
announcement TEXT NOT NULL,
|
||||||
|
updated_at TIMESTAMP(6) NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
CONSTRAINT chk_system_settings_singleton CHECK (id = 1)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
INSERT INTO system_settings(id,announcement) VALUES(1,'');
|
||||||
|
CREATE INDEX idx_audit_created_id ON audit_events(created_at,id);
|
||||||
2
backend/migrations/000010_admin_usernames.down.sql
Normal file
2
backend/migrations/000010_admin_usernames.down.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE admins DROP INDEX uq_admins_username;
|
||||||
|
ALTER TABLE admins DROP COLUMN username;
|
||||||
4
backend/migrations/000010_admin_usernames.up.sql
Normal file
4
backend/migrations/000010_admin_usernames.up.sql
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
ALTER TABLE admins ADD COLUMN username VARCHAR(32) NULL AFTER id;
|
||||||
|
UPDATE admins SET username=CONCAT('admin-', id) WHERE username IS NULL;
|
||||||
|
ALTER TABLE admins MODIFY COLUMN username VARCHAR(32) NOT NULL;
|
||||||
|
ALTER TABLE admins ADD UNIQUE KEY uq_admins_username (username);
|
||||||
29
backend/migrations/README.md
Normal file
29
backend/migrations/README.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# MySQL migration baseline
|
||||||
|
|
||||||
|
Status: DEV schemas are implemented through version 8 (local releases and digest-object locking). Formal entitlement policy acceptance and seed data remain pending. Read-only verification on 2026-09-30: business license_platform is version=7 dirty=false; isolated license_download_260930 is version=8 dirty=false. No business database migration was executed during the deployment-delivery slice.
|
||||||
|
|
||||||
|
## Version 007 to 008
|
||||||
|
|
||||||
|
007 stores release metadata; 008 adds package_objects digest rows used for SELECT FOR UPDATE serialization and backfills them from existing releases using MAX(size_bytes). Before applying 008, quiesce uploads, back up database and private files, and verify every digest has a single consistent size and an existing matching object; MAX is not an integrity check or repair. Explicit up must finish clean before using the new publication code. Historical migrations are unchanged. 008 down drops the lock inventory and must not be used while new upload handlers are running; 007 down destroys release metadata. Do not run either against business data without backup and approval.
|
||||||
|
|
||||||
|
A file is linked into its digest path before the metadata/audit transaction commits. Ordinary publication failures remove only files linked by that request, preserving pre-existing shared digest objects. Commit acknowledgement failure retains content because commit may have succeeded. Crashes can leave temporary fragments or unreferenced digest files; SQL and filesystem are not one atomic transaction. Orphan reconciliation/automatic GC is NOT implemented.
|
||||||
|
|
||||||
|
Future reconciliation must quiesce publishers or participate in the same digest locks, inventory product_releases/package_objects and private files, enforce a safety age window, recheck references immediately before quarantine, and verify checksums. Never remove a file based only on a missing row observed during an active upload or an uncertain commit. Keep quarantine recoverable and require reviewed deletion. U07 chunk/resume and crash cleanup remain open.
|
||||||
|
|
||||||
|
Version 6 adds independent lease/last-seen fields and heartbeat/freeze operation records. It was explicitly applied to the dedicated MySQL integration database on 2026-09-30. Its down migration drops operation history and lease state; do not execute against existing business data without backup and approval. The v6 isolated down/up rehearsal is still pending. Startup never applies migrations.
|
||||||
|
|
||||||
|
Use versioned pairs named `000001_description.up.sql` and `000001_description.down.sql`. Never edit an applied migration; add a new version. Seed permissions with stable unique codes, never commit an administrator password. SQL targets MySQL 8.0 with UTC timestamps and utf8mb4.
|
||||||
|
|
||||||
|
MySQL DDL may commit implicitly. Do not assume a failed schema migration is transactionally reversible. Before release, run the chosen migration runner against an empty MySQL 8 database, test each down/up pair with fixtures, and record dirty-version recovery. Down migrations that remove business data require backup and explicit operator confirmation.
|
||||||
|
|
||||||
|
The runner is `go run ./cmd/migrate` from `backend`. It accepts a golang-migrate MySQL URL such as `mysql://user:password@tcp(host:3306)/database?multiStatements=true` or `MIGRATION_DSN`. Supported actions are `up`, `down`, `version`, and explicit `force -version N` (flags must precede the action); `force` is only for an operator-reviewed dirty migration and never runs automatically.
|
||||||
|
|
||||||
|
```text
|
||||||
|
go run ./cmd/migrate -dsn "$MIGRATION_DSN" up
|
||||||
|
go run ./cmd/migrate -dsn "$MIGRATION_DSN" version
|
||||||
|
go run ./cmd/migrate -dsn "$MIGRATION_DSN" -version 12 force
|
||||||
|
``` The server does not run migrations on startup.
|
||||||
|
|
||||||
|
On 2026-09-30, a dedicated MySQL 8.0 container was used to verify an empty database up/down cycle and an intentionally invalid migration: failure left version 2 dirty, normal `up` was blocked, and explicit force to the last known-good version restored clean metadata. The probe migrations and container were removed after the test. Version 3 adds transactional license operation idempotency records for revoke/renew; it must be applied explicitly after version 2. No placeholder SQL is considered an executed business migration; formal entitlement schemas and CI database integration remain T04/T03 acceptance work.
|
||||||
|
|
||||||
|
Schema 10 adds unique administrator usernames. Existing accounts become `admin-{id}` and retain their passwords; login requests must send `username` instead of `email`. Run migrations before starting the current server or `admin-init`.
|
||||||
52
client/verify.mjs
Normal file
52
client/verify.mjs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { createHash, createPublicKey, verify } from 'node:crypto';
|
||||||
|
|
||||||
|
const fields = {
|
||||||
|
'license-v2': ['version', 'instance_id', 'license_id', 'customer_id', 'product_id', 'starts_at', 'expires_at', 'key_id'],
|
||||||
|
'lease-v2': ['version', 'instance_id', 'state', 'server_time', 'entitlement_expires_at', 'lease_expires_at', 'key_id'],
|
||||||
|
};
|
||||||
|
export function canonical(payload) {
|
||||||
|
const names = fields[payload.version];
|
||||||
|
if (!names || Object.keys(payload).length !== names.length) throw new Error('unsupported_payload');
|
||||||
|
return names.map(name => {
|
||||||
|
const value = payload[name];
|
||||||
|
if (['license_id', 'customer_id', 'product_id'].includes(name)) {
|
||||||
|
if (!Number.isSafeInteger(value) || value <= 0) throw new Error('invalid_id');
|
||||||
|
} else if (typeof value !== 'string' || !value || /[\r\n\0]/.test(value)) throw new Error('invalid_field');
|
||||||
|
return `${name}=${value}`;
|
||||||
|
}).join('\n');
|
||||||
|
}
|
||||||
|
export function verifyEnvelope(envelope, pinnedKeys) {
|
||||||
|
const p = envelope.payload;
|
||||||
|
if (!p || !/^[a-zA-Z0-9_-]{1,64}$/.test(p.key_id ?? '')) throw new Error('invalid_key_id');
|
||||||
|
const matches = pinnedKeys.filter(k => k.key_id === p.key_id);
|
||||||
|
if (matches.length !== 1 || matches[0].revoked) throw new Error('unknown_or_revoked_key');
|
||||||
|
const key = createPublicKey(matches[0].public_key_pem);
|
||||||
|
if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails.namedCurve !== 'prime256v1') throw new Error('invalid_key');
|
||||||
|
const text = canonical(p);
|
||||||
|
if (typeof envelope.signature !== 'string' || !/^[A-Za-z0-9+/]+$/.test(envelope.signature)) throw new Error('invalid_signature');
|
||||||
|
if (!verify('sha256', Buffer.from(text), key, Buffer.from(envelope.signature, 'base64'))) throw new Error('invalid_signature');
|
||||||
|
if (envelope.canonical_sha256 && createHash('sha256').update(text).digest('hex') !== envelope.canonical_sha256) throw new Error('invalid_digest');
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
function instant(value) {
|
||||||
|
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/.test(value)) throw new Error('invalid_time');
|
||||||
|
const time = Date.parse(value);
|
||||||
|
if (!Number.isFinite(time)) throw new Error('invalid_time');
|
||||||
|
return time;
|
||||||
|
}
|
||||||
|
// Persist the returned state atomically in trusted storage BEFORE enabling work.
|
||||||
|
export function acceptLease(envelope, pinnedKeys, expectedInstance, prior, now) {
|
||||||
|
const p = verifyEnvelope(envelope, pinnedKeys);
|
||||||
|
if (p.version !== 'lease-v2' || p.instance_id !== expectedInstance || !Number.isFinite(now)) throw new Error('instance_or_version');
|
||||||
|
const server = instant(p.server_time), expiry = instant(p.lease_expires_at), entitlement = instant(p.entitlement_expires_at);
|
||||||
|
const previous = prior ?? { instance_id: expectedInstance, server_high_water: 0, local_high_water: 0, lease_expires: 0, enabled: false };
|
||||||
|
if (previous.instance_id !== expectedInstance || !Number.isFinite(previous.server_high_water) || !Number.isFinite(previous.local_high_water)) throw new Error('invalid_state');
|
||||||
|
if (now < previous.local_high_water || server < previous.server_high_water) throw new Error('clock_or_server_rollback');
|
||||||
|
if (Math.abs(server - now) > 300000 || expiry > entitlement || expiry > server + 14 * 86400000) throw new Error('lease_bounds');
|
||||||
|
if (!['active', 'frozen', 'revoked', 'expired', 'not_started', 'not_activated'].includes(p.state)) throw new Error('invalid_state');
|
||||||
|
const enabled = p.state === 'active' && now < expiry && now < entitlement;
|
||||||
|
return { instance_id: expectedInstance, server_high_water: server, local_high_water: now, lease_expires: expiry, enabled };
|
||||||
|
}
|
||||||
|
export function canRunOffline(state, expectedInstance, now) {
|
||||||
|
return state?.instance_id === expectedInstance && state.enabled === true && Number.isFinite(now) && now >= state.local_high_water && now < state.lease_expires;
|
||||||
|
}
|
||||||
100
compose.yaml
Normal file
100
compose.yaml
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
# Local delivery rehearsal only. Not a production security profile.
|
||||||
|
name: license-platform-dev
|
||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:8.0
|
||||||
|
environment:
|
||||||
|
MYSQL_DATABASE: license_platform
|
||||||
|
MYSQL_USER: license_app
|
||||||
|
MYSQL_PASSWORD_FILE: /run/secrets/mysql_app
|
||||||
|
MYSQL_ROOT_PASSWORD_FILE: /run/secrets/mysql_root
|
||||||
|
secrets: [mysql_app, mysql_root]
|
||||||
|
volumes: [mysql_data:/var/lib/mysql]
|
||||||
|
networks: [private]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, 'MYSQL_PWD=$$(cat /run/secrets/mysql_app) mysql -h 127.0.0.1 -u license_app license_platform -e "SELECT 1" >/dev/null 2>&1']
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 30
|
||||||
|
redis:
|
||||||
|
profiles: [cache]
|
||||||
|
image: redis:7-alpine
|
||||||
|
command: [redis-server, --save, '', --appendonly, 'no']
|
||||||
|
networks: [private]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, redis-cli, ping]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: deploy/Dockerfile.api
|
||||||
|
environment:
|
||||||
|
HTTP_ADDR: 0.0.0.0:18080
|
||||||
|
HTTP_TRUSTED_PROXY_CIDRS: ${HTTP_TRUSTED_PROXY_CIDRS:-}
|
||||||
|
SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false}
|
||||||
|
MYSQL_PASSWORD_FILE: /run/secrets/mysql_app
|
||||||
|
LICENSE_SIGNING_PRIVATE_KEY_FILE: /run/secrets/signing_key
|
||||||
|
PACKAGE_STORAGE_ROOT: /srv/license-packages
|
||||||
|
GIN_MODE: release
|
||||||
|
METRICS_ADDR: 127.0.0.1:19090
|
||||||
|
ENTRY_LIMIT_MODE: ${ENTRY_LIMIT_MODE:-redis}
|
||||||
|
ENTRY_REDIS_ADDR: ${ENTRY_REDIS_ADDR:-}
|
||||||
|
ENTRY_REDIS_NAMESPACE: ${ENTRY_REDIS_NAMESPACE:-license-platform:entry:}
|
||||||
|
secrets: [mysql_app, signing_key]
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: ${PACKAGE_STORAGE_HOST:?Set an absolute trusted existing package directory}
|
||||||
|
target: /srv/license-packages
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
read_only: true
|
||||||
|
tmpfs: [/tmp]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
networks: [private]
|
||||||
|
depends_on:
|
||||||
|
mysql: {condition: service_healthy}
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:19090/api/v1/health/ready']
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
migrate:
|
||||||
|
extends: api
|
||||||
|
profiles: [tools]
|
||||||
|
command: [/app/migrate, up]
|
||||||
|
healthcheck: {disable: true}
|
||||||
|
web:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: deploy/Dockerfile.web
|
||||||
|
ports: ['127.0.0.1:18083:8080']
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: ${PACKAGE_STORAGE_HOST:?Set an absolute trusted existing package directory}
|
||||||
|
target: /srv/license-packages
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
depends_on:
|
||||||
|
api: {condition: service_healthy}
|
||||||
|
networks: [private, edge]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:8080/api/v1/health/live']
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
networks:
|
||||||
|
private: {internal: true}
|
||||||
|
edge: {}
|
||||||
|
volumes:
|
||||||
|
mysql_data: {}
|
||||||
|
secrets:
|
||||||
|
mysql_app:
|
||||||
|
file: ${MYSQL_APP_SECRET_FILE:?Set protected app database password file}
|
||||||
|
mysql_root:
|
||||||
|
file: ${MYSQL_ROOT_SECRET_FILE:?Set protected root database password file}
|
||||||
|
signing_key:
|
||||||
|
file: ${LICENSE_SIGNING_KEY_HOST_FILE:?Set protected persistent P256 PEM file}
|
||||||
17
deploy/Dockerfile.api
Normal file
17
deploy/Dockerfile.api
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
FROM golang:1.23-alpine AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY backend/go.mod backend/go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY backend/ ./
|
||||||
|
RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server && CGO_ENABLED=0 go build -o /out/migrate ./cmd/migrate
|
||||||
|
|
||||||
|
FROM alpine:3.21
|
||||||
|
RUN apk add --no-cache ca-certificates wget && addgroup -g 10001 app && adduser -D -u 10001 -G app app
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /out/ /app/
|
||||||
|
COPY backend/migrations /app/migrations
|
||||||
|
COPY deploy/entrypoint.sh /app/entrypoint.sh
|
||||||
|
RUN chmod 0555 /app/entrypoint.sh
|
||||||
|
USER 10001:10001
|
||||||
|
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||||
|
CMD ["/app/server"]
|
||||||
9
deploy/Dockerfile.web
Normal file
9
deploy/Dockerfile.web
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
FROM node:22-alpine AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
FROM nginx:stable-alpine
|
||||||
|
COPY --from=build /src/dist /usr/share/nginx/html
|
||||||
|
COPY deploy/nginx/compose.conf /etc/nginx/conf.d/default.conf
|
||||||
10
deploy/entrypoint.sh
Normal file
10
deploy/entrypoint.sh
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
if [ -n "${MYSQL_PASSWORD_FILE:-}" ]; then
|
||||||
|
password=$(cat "$MYSQL_PASSWORD_FILE")
|
||||||
|
case "$password" in ''|*[!a-zA-Z0-9_-]*) echo 'Database secret must be a nonempty URL-safe value' >&2; exit 1;; esac
|
||||||
|
export MYSQL_DSN="license_app:${password}@tcp(mysql:3306)/license_platform?parseTime=true"
|
||||||
|
export MIGRATION_DSN="mysql://license_app:${password}@tcp(mysql:3306)/license_platform?multiStatements=true"
|
||||||
|
unset password
|
||||||
|
fi
|
||||||
|
exec "$@"
|
||||||
22
deploy/nginx/compose.conf
Normal file
22
deploy/nginx/compose.conf
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
server {
|
||||||
|
listen 8080;
|
||||||
|
server_name localhost;
|
||||||
|
client_max_body_size 64m;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://api:18080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
location /_packages/ {
|
||||||
|
internal;
|
||||||
|
alias /srv/license-packages/;
|
||||||
|
autoindex off;
|
||||||
|
disable_symlinks on;
|
||||||
|
add_header Cache-Control "private, no-store" always;
|
||||||
|
add_header X-Package-SHA256 $upstream_http_x_package_sha256 always;
|
||||||
|
}
|
||||||
|
location / { try_files $uri $uri/ /index.html; }
|
||||||
|
}
|
||||||
18
deploy/nginx/download-local.conf
Normal file
18
deploy/nginx/download-local.conf
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Isolated development reverse-proxy fragment. Mount PACKAGE_STORAGE_ROOT read-only at /srv/license-packages.
|
||||||
|
# The upstream application must set X-Accel-Redirect only after authorization and audit commit.
|
||||||
|
server {
|
||||||
|
listen 18181;
|
||||||
|
server_name 127.0.0.1;
|
||||||
|
location = /_packages { return 404; }
|
||||||
|
location /_packages/ {
|
||||||
|
internal;
|
||||||
|
alias /srv/license-packages/;
|
||||||
|
autoindex off;
|
||||||
|
disable_symlinks on;
|
||||||
|
add_header Cache-Control "private, no-store" always;
|
||||||
|
add_header X-Package-SHA256 $upstream_http_x_package_sha256 always;
|
||||||
|
limit_except GET HEAD { deny all; }
|
||||||
|
}
|
||||||
|
client_max_body_size 64m;
|
||||||
|
location / { proxy_pass http://host.docker.internal:18082; }
|
||||||
|
}
|
||||||
30
deploy/nginx/tls-proxy.conf.example
Normal file
30
deploy/nginx/tls-proxy.conf.example
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Example only. Use certificates issued/managed by your production certificate authority.
|
||||||
|
# Do not copy a self-signed development certificate into this profile.
|
||||||
|
# Mount this as a server block and bind /run/tls read-only from the managed certificate path.
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name license.example.invalid;
|
||||||
|
ssl_certificate /run/tls/fullchain.pem;
|
||||||
|
ssl_certificate_key /run/tls/privatekey.pem;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
client_max_body_size 64m;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://api:18080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-Proto https;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
location /_packages/ {
|
||||||
|
internal;
|
||||||
|
alias /srv/license-packages/;
|
||||||
|
autoindex off;
|
||||||
|
disable_symlinks on;
|
||||||
|
add_header Cache-Control "private, no-store" always;
|
||||||
|
add_header X-Package-SHA256 $upstream_http_x_package_sha256 always;
|
||||||
|
}
|
||||||
|
location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html; }
|
||||||
|
}
|
||||||
|
# Restrict listener/network reachability to the actual proxy tier. Configure the API's
|
||||||
|
# HTTP_TRUSTED_PROXY_CIDRS to exact proxy source CIDRs only when this proxy is in use.
|
||||||
33
docs/activation-contract-draft.md
Normal file
33
docs/activation-contract-draft.md
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# v5 实例激活与签名证书契约(DEV 草案)
|
||||||
|
|
||||||
|
## 管理员 API
|
||||||
|
|
||||||
|
- `POST /api/v1/licenses/{license_id}/instances`:需要管理员会话。服务生成 UUIDv4 `instance_id` 与 256-bit bootstrap secret;响应仅此一次返回 `secret`。数据库仅保存 SHA-256(secret),列表/详情永不返回 secret。
|
||||||
|
- `GET /api/v1/licenses/{license_id}/instances`:需要管理员会话;只返回 instance_id、状态、激活时间、证书版本,不返回 secret、secret_hash、证书签名私密材料。
|
||||||
|
- `GET /api/v1/activation/public-key`:返回 ECDSA P-256/SHA-256 公钥 PEM、证书版本和签名编码。
|
||||||
|
|
||||||
|
## 集成客户端 API
|
||||||
|
|
||||||
|
`POST /api/v1/activation/instances/{instance_id}`,无需管理员 Cookie。JSON 必须包含 `license_key` 和一次性提交的 `secret`;`Idempotency-Key` 必须为 1 至 128 个字符。服务端校验授权密钥、实例 secret、客户/产品归属、客户和产品启用状态、有效期和 issued 订单(若有关联)。成功返回 v1 certificate;secret 不在任何成功响应中回显。
|
||||||
|
|
||||||
|
同一实例和幂等键重放相同请求返回首次成功响应;改变 secret/license_key 或使用已激活实例返回 409/403。实例按数据库行锁串行化,一个实例最多成功激活一次。业务写入、幂等记录、审计事件同一事务,审计失败会回滚激活。
|
||||||
|
|
||||||
|
## 签名格式
|
||||||
|
|
||||||
|
Canonical payload 是 UTF-8、无 BOM、无尾随换行的固定顺序 `key=value` 行:
|
||||||
|
|
||||||
|
```text
|
||||||
|
version=license-v1
|
||||||
|
instance_id=00000000-0000-4000-8000-000000000001
|
||||||
|
license_id=1
|
||||||
|
customer_id=2
|
||||||
|
product_id=3
|
||||||
|
starts_at=2026-09-30T00:00:00Z
|
||||||
|
expires_at=2027-09-30T00:00:00Z
|
||||||
|
```
|
||||||
|
|
||||||
|
对完整 UTF-8 canonical bytes 做 SHA-256,再用环境注入的 P-256 ECDSA 私钥签名。signature 为 ASN.1 DER,base64 无填充。响应同时提供 `canonical_sha256`,便于跨语言测试向量定位。公钥只经接口发布;私钥不入数据库、日志或浏览器。
|
||||||
|
|
||||||
|
## 明确未实现
|
||||||
|
|
||||||
|
heartbeat、offline lease、冻结传播、实时撤销推送、租户隔离和离线授权均不属于本 v5 slice。证书签发不构成这些功能的模拟实现。
|
||||||
56
docs/admin-modules.md
Normal file
56
docs/admin-modules.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
# 审计日志与系统设置
|
||||||
|
|
||||||
|
管理模块均要求有效的 `lp_session` 管理员会话;非管理员返回403,未登录返回401。写请求继续使用全局同源保护。
|
||||||
|
|
||||||
|
## 数据库
|
||||||
|
|
||||||
|
新增 `000009_admin_settings`:单例 `system_settings` 表以及审计时间/ID索引。当前服务要求 clean schema 9。启动服务不自动迁移。已有环境升级前备份并运行标准 migrate up,再启动新代码。down 会删除平台设置,需明确接受数据丢失后执行。
|
||||||
|
|
||||||
|
2026-10-09 本机仅升级独立开发库 `license_platform_local_261009`;原 `license_platform` 未修改。
|
||||||
|
|
||||||
|
## 审计日志
|
||||||
|
|
||||||
|
`GET /api/v1/audit-events` 返回 `{data: [...], meta:{page,page_size,total}}`。
|
||||||
|
|
||||||
|
支持 `page`、`page_size`(默认20,最大100)、`q`(邮箱/动作/资源类型包含查询,最多200字)、`action`、`resource_type`(精确匹配,最多64字节),以及 `from`、`to`(RFC3339时间,包含端点)。返回按时间、ID倒序,count和分页共享只读一致性快照。
|
||||||
|
|
||||||
|
记录字段:`id`、`actor_admin_id`、`actor_email`、`action`、`resource_type`、`resource_id`、`details`、`created_at`。详情仅允许已知业务字段;密码、会话令牌、实例凭据不提供。
|
||||||
|
|
||||||
|
已接入事件来自原有授权、订单、实例、版本发布/下载/门户业务审计,以及新增 `settings.updated`、`admin.password_changed`。这不是覆盖所有HTTP请求的访问日志;旧客户/产品CRUD、登录失败和命令行admin-init没有历史审计事件。实例产生的事件通过 `details.client_actor=instance` 区分;关联管理员字段来自既有业务归属规则。
|
||||||
|
|
||||||
|
审计只读,不提供编辑或删除接口。
|
||||||
|
|
||||||
|
## 系统设置
|
||||||
|
|
||||||
|
`GET /api/v1/settings` 和 `PUT /api/v1/settings` 使用 `{data:{site_name,support_email,announcement,updated_at}}`。PUT提交三个文本字段;平台名称1至100字、联系邮箱可空且最多254字节、公告最多2000字。所有管理员共享;更新时间由服务端生成。设置更新和不包含文本内容的审计记录同事务提交。
|
||||||
|
|
||||||
|
这些是展示配置,不控制TLS、签名密钥、数据库、限流器和授权有效期;运行参数仍由服务进程环境配置。
|
||||||
|
|
||||||
|
`POST /api/v1/settings/password` 提交 `{current_password,new_password}`,成功204。必须验证当前密码,新密码非空、最多72字节,无复杂度要求。更新bcrypt哈希、撤销该管理员其他会话、写入不含密码的审计记录同事务提交;当前会话保留。
|
||||||
|
|
||||||
|
## 日期时间展示
|
||||||
|
|
||||||
|
前端业务时间统一通过 `frontend/src/date-format.ts` 的 `formatDateTime` 展示,格式为 `YYYY-MM-DD HH:mm:ss`,按浏览器所在时区换算,使用24小时制。License 列表及详情、实例、订单详情、客户门户、审计时间和设置更新时间均采用此约定;缺失或无效时间显示 `—`,部分业务保留“未确认”“暂无租约”“尚未更新”等提示。审计详情中的原始 JSON 保留接口时间值,方便排查。
|
||||||
|
|
||||||
|
API 的 RFC3339 时间传输及 UTC 存储语义保持不变;审计本地时间筛选仍转换为 UTC 提交,仪表盘月份统计继续使用 UTC。新增页面展示业务时间时复用统一函数,不直接输出原始 ISO 字符串。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
后端单元测试覆盖设置边界、审计敏感字段过滤、筛选时间范围及未认证请求。独立开发库真实接口验证覆盖迁移、设置写入读取、非法参数、错误当前密码、密码修改、其他会话撤销、当前会话保留、审计筛选。验证后管理员密码恢复为原来的本地开发密码。
|
||||||
|
|
||||||
|
|
||||||
|
## 多管理员与用户名登录(schema 10)
|
||||||
|
|
||||||
|
管理台登录提交 `{username,password}`,不再使用邮箱登录。用户名统一去除首尾空格并转换为小写,允许 3–32 位字母、数字、下划线和短横线。邮箱作为唯一联系信息保留。现有管理员迁移后用户名为 `admin-{id}`,密码保持原值。
|
||||||
|
|
||||||
|
管理员账户页面 `/admins` 支持列表、新增、启用、停用、密码重置。所有管理员拥有同等后台权限。不能停用当前登录账户;停用账户和重置密码均撤销目标账户的所有会话。自身修改密码仍通过设置页面完成,保留当前会话。账号操作与审计写入同一事务,密码与哈希不会返回或写入审计详情。
|
||||||
|
|
||||||
|
接口:`GET /api/v1/admins`、`POST /api/v1/admins`(username/email/password)、`POST /api/v1/admins/:id/active`(active)、`POST /api/v1/admins/:id/reset-password`(password)。用户名或邮箱重复返回 409。
|
||||||
|
|
||||||
|
新部署先迁移到 schema 10,然后初始化:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/admin-init -username admin -email admin@example.test -password 'YOUR_PASSWORD'
|
||||||
|
```
|
||||||
|
|
||||||
|
初始化命令按邮箱识别已有账户,用户名冲突将报错,不会重置另一个账户。重新初始化会撤销该账户的旧会话。已有部署只执行迁移即可,不需要重置密码。原始业务数据库没有在本次开发中迁移;本地隔离数据库的既有账号为 `admin-1`,密码保持 `123456`。
|
||||||
28
docs/business-contract-draft.md
Normal file
28
docs/business-contract-draft.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# 基础管理台契约草案(待业务确认)
|
||||||
|
|
||||||
|
状态:实现用临时契约,不代表业务签字、正式 OpenAPI 或授权规则冻结。
|
||||||
|
|
||||||
|
## 本阶段开发假设
|
||||||
|
|
||||||
|
- 首个管理界面仅供内部管理员使用;管理员账号由部署操作者通过一次性命令初始化,不开放公网自助注册。
|
||||||
|
- 当前只有 `admin` 角色;服务端对所有主数据接口强制检查有效会话与 admin 角色。未来角色/权限需由业务签字后细分。
|
||||||
|
- 管理员以邮箱标识,bcrypt 哈希密码;服务端仅保存随机会话令牌 SHA-256 摘要。会话固定 8 小时,登出即时撤销。
|
||||||
|
- 客户暂用名称、联系邮箱、active/inactive 状态;产品暂用唯一编码、名称、说明、启用标志。
|
||||||
|
- 客户列表分页参数为 page/page_size,默认 1/20、每页上限 100,可按名称或邮箱搜索。
|
||||||
|
- 删除当前为物理删除,仅适用于无授权关联的基础数据阶段。建立授权关联后必须重新决策为软删除/停用或限制删除。
|
||||||
|
- 默认仅绑定 loopback。任何实际环境必须使用 HTTPS、受控网络和备份;不提供生产部署验收。
|
||||||
|
- v4 DEV 假设:线下订单是一客户、一产品、一笔 CNY 整数分金额;状态为 `pending_payment -> paid -> issued`。录单、收款确认、一次性发放仅允许 admin,服务端锁定并校验 customer/product active 状态。
|
||||||
|
- v4 DEV 状态机:仅 `pending_payment` 可确认收款,实收金额必须等于订单金额;仅 `paid` 可发放一次授权;撤销/退款、作废、审批驳回不在本切片执行。
|
||||||
|
- v4 DEV 幂等:每个订单操作要求 `Idempotency-Key`,同一管理员/操作/键匹配请求重放首次响应,指纹冲突返回 409;订单、授权、操作状态和 audit_events 同一事务提交。
|
||||||
|
- v4 DEV 权限:当前统一 admin 门禁;审批角色、财务确认角色、退款角色和客户/租户范围尚未冻结。
|
||||||
|
- v4 DEV 时间:发放请求显式提供 RFC3339 UTC 开始/结束时间,结束必须晚于开始且在 MySQL TIMESTAMP 范围;续期起始日是否允许早于当前时间仍待确认。
|
||||||
|
|
||||||
|
## 错误响应草案
|
||||||
|
|
||||||
|
业务错误统一为 `{"error":{"code":"...","message":"..."}}`。登录失败统一返回 401,不区分账号不存在和密码错误。未经认证返回 401,权限不足返回 403,字段校验错误 400,重复编码等冲突 409。
|
||||||
|
|
||||||
|
## 尚未确认
|
||||||
|
|
||||||
|
订单正式状态机及订单号规则、套餐/价格快照、支付渠道与对账、收款凭据格式、发放审批角色、renewal start-date 规则、退款后授权撤销/回收关系、跨客户/产品租户范围、财务报表口径均为可替换 DEV 假设,等待 T01/T02 正式确认。
|
||||||
|
|
||||||
|
管理员组织/租户归属、多管理员邀请与恢复流程、完整 RBAC 权限矩阵、客户身份唯一性及字段、产品版本/套餐/生命周期、删除/审计保留规则、锁定与速率限制策略、会话空闲续期、正式 API/OpenAPI/error catalog,均待产品、安全和接入负责人确认。授权激活、心跳、续期、退款、克隆、实例绑定规则不在本阶段实现。
|
||||||
15
docs/business-quickstart.md
Normal file
15
docs/business-quickstart.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
# 本地基础管理台运行
|
||||||
|
|
||||||
|
开发阶段需本机 Go 1.23+、Node 20+、npm 与 Docker。
|
||||||
|
|
||||||
|
1. 启动专用 MySQL:`docker run -d --name license-platform-mysql-app -e MYSQL_ROOT_PASSWORD=<本地临时密码> -e MYSQL_DATABASE=license_platform -p 13307:3306 mysql:8.0`
|
||||||
|
2. 在 `backend` 设置 `MIGRATION_DSN='mysql://root:<密码>@tcp(127.0.0.1:13307)/license_platform?multiStatements=true'` 和 `MYSQL_DSN='root:<密码>@tcp(127.0.0.1:13307)/license_platform?parseTime=true'`。
|
||||||
|
3. 执行 `go run ./cmd/migrate -dsn "$MIGRATION_DSN" -dir ./migrations up`。
|
||||||
|
4. 交互式输入密码初始化管理员,避免密码落入 shell history(当前命令行参数仍可能被本机进程查看,生产初始化需改为安全输入通道):`read -rsp 'Admin password: ' ADMIN_PASSWORD; echo; go run ./cmd/admin-init -dsn "$MYSQL_DSN" -email admin@example.test -password "$ADMIN_PASSWORD"; unset ADMIN_PASSWORD`。密码只要求非空,允许简单数字密码(例如 `123456`),不要求大小写或特殊字符;最多 72 字节。重复初始化同一邮箱会重置密码并启用账号。不要在共享机器使用本文示例邮箱。
|
||||||
|
5. 启动后端:`HTTP_ADDR=127.0.0.1:18081 MYSQL_DSN="$MYSQL_DSN" go run ./cmd/server`。
|
||||||
|
6. 新终端启动前端:`cd frontend && npm run dev -- --port 15173`,访问 `http://127.0.0.1:15173/`。
|
||||||
|
|
||||||
|
管理员登录后可新增、搜索、删除客户和新增、查看、删除产品;选择 active 客户和产品、填写开始/结束时间后可签发期限授权并分页查看。迁移需要 version 2 clean,见 `license-contract-draft.md`(DEV-LICENSE-v0.1)。客户下拉目前使用当前搜索结果的第一页,超过 20 条需要搜索定位。已有授权引用的主数据不可物理删除。后端目前也提供客户/产品 PUT 接口,编辑表单尚未接入。开发本地 HTTP Cookie 不设 Secure;直接 TLS 请求设 Secure,不信任任意 X-Forwarded-Proto。TLS 终止代理部署的 Secure Cookie 策略尚未配置,不能直接按此启动方式投入生产。生产使用 HTTPS、明确可信代理边界,并遵循组织密钥管理、数据库备份及安全运维流程。本快速启动不构成生产部署指南或 UAT。
|
||||||
|
|
||||||
|
|
||||||
|
管理员登录现使用用户名和密码。schema 10 迁移后既有账户用户名为 `admin-{id}`;新初始化可指定 `-username admin`(默认 admin)。后台“管理员账户”页面支持新增、启停与密码重置,详见 [管理员模块](admin-modules.md)。
|
||||||
34
docs/client-integration-center.md
Normal file
34
docs/client-integration-center.md
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# 客户端接入中心
|
||||||
|
|
||||||
|
管理员登录后进入 `/integration`,选择 Python、Go、Java、.NET 或 Node.js,以及桌面、常驻服务或容器模式。页面提供接口清单、可复制工程提示词、完整协议、安全约束、字段示例和 ZIP/Markdown 下载。首版交付生成资料,不包含五种语言已经实现并完成生产验收的 SDK。
|
||||||
|
|
||||||
|
SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权平台根地址;部署可以通过 `LICENSE_API_BASE_URL` 覆盖。该值必须是根地址,不能附加 `/api/v1`。协议、OpenAPI、Markdown 与 ZIP 内的资料都使用相同默认值。
|
||||||
|
|
||||||
|
## 管理员接口
|
||||||
|
|
||||||
|
以下 GET 路由使用现有管理员会话保护,不属于外部客户端运行 API:
|
||||||
|
|
||||||
|
- `/api/v1/integration-kit?language=python&mode=service`:JSON 资料。
|
||||||
|
- `/api/v1/integration-kit/download?language=python&mode=service`:UTF-8 Markdown,包含选定提示词、协议和字段示例。
|
||||||
|
- `/api/v1/integration-kit/archive?language=python&mode=service`:ZIP,包含 README.md、protocol.md、openapi.json、prompt.md、test-vectors.json。
|
||||||
|
|
||||||
|
省略参数默认 python/service。未知语言或模式返回 400,不接受文件路径参数。下载使用 no-store,文件名按受控语言/模式生成。无需新数据库表,不包含任何真实实例 secret、数据库凭据或生产私钥。
|
||||||
|
|
||||||
|
每次 ZIP 下载为测试向量生成独立随机 P-256 密钥,返回公钥及 license-v2/lease-v2 的有效 DER ECDSA 签名、固定规范化内容及 SHA-256。私钥仅在生成时的内存中使用,不输出,不落盘。向量使用固定历史时间,时间相关测试必须使用给定固定 now;生产不得信任测试公钥。
|
||||||
|
|
||||||
|
## 协议维护
|
||||||
|
|
||||||
|
协议源文件在 `backend/internal/httpapi/integration_assets/protocol.md`,OpenAPI 3.0.3 在同目录 `openapi.json`,由 Go embed 嵌入二进制。修改接口实现时必须同时核对这两个文件,重新构建后端后生效。`client/verify.mjs` 提供 v2 验签与运行状态算法参考。
|
||||||
|
|
||||||
|
选择语言会加入对应加密库、HTTP/取消/状态存储/测试要求;运行模式在提示词中明确,完整协议包括桌面/服务/容器的身份和持久化约束。页面请求使用序列号忽略旧请求返回,避免快速切换后显示过期资料。
|
||||||
|
|
||||||
|
部署方须确认 keyring 已配置并通过受控渠道交付公钥;legacy v1 默认部署不满足本资料要求。keyring 发现不是信任引导。14 天离线租约意味着冻结/撤销最多可延迟 14 天生效,不能宣传立即离线撤销或硬件防克隆。Kubernetes 集群代理、移动设备、CI 临时身份、完全离线授权需要额外方案。
|
||||||
|
|
||||||
|
## 验证记录
|
||||||
|
|
||||||
|
- 后端 `go test ./...` 与 `go vet ./...` 通过。新增测试检查三个管理员接口未认证均为 401、非法选择 400、五种语言提示、OpenAPI JSON、ZIP 五文件及两类签名/篡改失败。
|
||||||
|
- 前端类型检查、12 个测试文件共 33 项测试、生产构建通过。新增面板测试检查加载/失败/选择更新及下载参数,路由测试包括 `/integration`。
|
||||||
|
- 使用隔离数据库 `license_platform_local_261009` 的真实管理员会话:JSON 与 ZIP 下载均 200,ZIP 包内容与 no-store 响应头已核对。
|
||||||
|
- 浏览器实际切换 .NET:专属 DER 格式提示与下载 URL 更新。390×844 窄屏无整体横向溢出,控制台 0 error。
|
||||||
|
|
||||||
|
未迁移或修改原业务数据库,未提交或推送代码。现有大包构建提示与旧测试的组件 stub 警告仍存在。全仓 `git diff --check` 的两项旧文档末尾空行不在本次功能范围内。
|
||||||
53
docs/deployment-delivery.md
Normal file
53
docs/deployment-delivery.md
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# Deployment delivery rehearsal
|
||||||
|
|
||||||
|
Status: development scaffolding, not production accepted. Existing API 18081 is not restarted by this work. Do not reuse its in-memory signing key lifecycle for deployment.
|
||||||
|
|
||||||
|
## Files and configuration
|
||||||
|
|
||||||
|
The root compose.yaml builds deploy/Dockerfile.api and deploy/Dockerfile.web. Only the web port is bound to host loopback (18083). MySQL, Redis, API and package storage have no published host ports. The private service network is internal. Redis is optional under the `cache` profile; the API currently does not use Redis for sessions or rate limiting.
|
||||||
|
|
||||||
|
Set these non-secret environment paths externally (not secret values in .env): MYSQL_APP_SECRET_FILE, MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST. All refer to protected, pre-existing absolute host paths outside Git and the build context. App DB password must be a randomly generated URL-safe value using letters, digits, underscores and hyphens. The image reads it at runtime, never logs it; driver DSNs remain process environment secrets. Compose local secrets are bind mounts, not an encrypted secret manager. Secure their host ACLs, process access, backups and crash dumps.
|
||||||
|
|
||||||
|
The package directory must be writable by API UID 10001 and readable by Nginx, on a filesystem supporting hard links. Nginx mounts it read-only, serves it only through an internal location, disables directory listing and symlinks. Do not put it in the frontend/public tree. The API is non-root with read-only rootfs, all capabilities dropped and no-new-privileges; this is not a complete container-hardening assessment.
|
||||||
|
|
||||||
|
Run from the repository root, using an independent Compose project/database and protected persistent key:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose build
|
||||||
|
docker compose up -d mysql
|
||||||
|
# Optional only: docker compose --profile cache up -d redis
|
||||||
|
docker compose --profile tools run --rm migrate
|
||||||
|
docker compose up -d api web
|
||||||
|
```
|
||||||
|
|
||||||
|
Migrations are explicit; startup never migrates. The migration profile uses the development app account, which also has DDL privileges in this local profile. Production needs separate least-privilege runtime and migration accounts. No administrator account/password is created by Compose. Stop/restart only this rehearsal project, never the existing 18081 process. Do not run down -v against retained data.
|
||||||
|
|
||||||
|
## Operations slice
|
||||||
|
|
||||||
|
See [operations-security.md](operations-security.md) for JSON logging, optional loopback metrics, local per-process entry limits, cookie/origin/body controls and CI evidence. New server main exposes only liveness publicly; readiness and metrics use numeric-loopback METRICS_ADDR (Compose 19090). Redis Lua shared entry limits are now default, with runtime failure returning 503 and no automatic fallback; local-dev must be explicitly selected for controlled development. ENTRY_REDIS_ADDR must be a numeric private/loopback IP; ENTRY_REDIS_PASSWORD_FILE optionally injects a protected absolute password file. Production Redis TLS/ACL/HA/capacity remain gates; the current Compose cache profile is not automatically wired to the API. Two isolated new API subprocess starts passed key-continuity and internal HTTP checks; unchanged 18081 still runs old source. See the release-gate update in operations-security.md for evidence limits.
|
||||||
|
|
||||||
|
## TLS, proxy trust and Redis
|
||||||
|
|
||||||
|
The loopback HTTP listener is for local rehearsal, not internet exposure. `deploy/nginx/tls-proxy.conf.example` is an example requiring managed CA certificates mounted read-only; it is deliberately not enabled by default and contains no development/self-signed key. Production must restrict upstream reachability, set `SESSION_COOKIE_SECURE=true`, and set `HTTP_TRUSTED_PROXY_CIDRS` to exact proxy source CIDRs only. Config rejects malformed CIDRs and `0.0.0.0/0`/`::/0`; Gin trusts no proxies by default. Nginx overwrites forwarded headers rather than forwarding client-supplied values. Direct TLS also sets Secure. Automated unit tests cover forced Secure and reject treating a bare X-Forwarded-Proto header as trusted. TLS deployment wiring, real certificate verification, ingress restrictions, CSRF/origin controls and end-to-end proxy spoof tests remain outstanding.
|
||||||
|
|
||||||
|
Redis is optional and not used by the current API for sessions, rate limits, or authoritative state. It is under Compose profile `cache`; API startup/readiness does not depend on it. Do not claim Redis-backed behavior.
|
||||||
|
|
||||||
|
The API has `/api/v1/health/live` for process liveness and `/api/v1/health/ready` for database connectivity plus exactly one clean migration row at schema version 8. Startup refuses a database that cannot be pinged or is not exactly at clean version 8; startup never migrates. Readiness returns only generic 503 on DB/schema failure, without internal error details. Compose API/web health checks use readiness. Unit tests cover unavailable DB, no migration row, old/future version and dirty schema; full Compose fault injection is pending. Load/capacity testing, pre-auth rate limiting, pinned image digests and vulnerability remediation remain open.
|
||||||
|
|
||||||
|
## Backup and restore
|
||||||
|
|
||||||
|
`scripts/backup-delivery.sh` creates a MySQL logical dump and deterministic tar of private package storage with checksums. Run only during a maintenance window that quiesces uploads and administrative writes: MySQL `--single-transaction` does not make a filesystem snapshot atomic with SQL. Protect/encrypt the destination and record schema version/checkpoint separately. Signing keys are intentionally excluded; recover them separately from protected secret management, never from SQL or these scripts. Redis is optional and holds no authoritative platform data.
|
||||||
|
|
||||||
|
`scripts/restore-delivery.sh` requires `CONFIRM_EMPTY_RESTORE=YES` and independently refuses both nonempty package directories and databases containing tables. YES does not bypass either check. Supply only a trusted backup and an isolated empty DB/private directory with no listener; the script does not validate arbitrary or malicious SQL/tar inputs. After restore, run explicit migration/version checks and compare all `product_releases`/`package_objects` references, file size/SHA-256 and key fingerprint before any traffic. The restore command is not a substitute for application-level reconciliation. Scripts use MySQL CLI and protected `MYSQL_PASSWORD_FILE`; ensure the image/host has mysql client tools. A minimal isolated dump/restore drill has passed; full-platform reconciliation, production recovery objectives, encrypted backup handling and a complete application recovery drill remain pending.
|
||||||
|
|
||||||
|
## Executed evidence (2026-09-30)
|
||||||
|
|
||||||
|
- docker compose config --quiet: passed with placeholder external paths; no real secrets were printed.
|
||||||
|
- Web image build: passed, including npm ci and typecheck/Vite build. npm reported two moderate dependency vulnerabilities; no forced upgrade performed. Existing 1.13 MB bundle warning remains.
|
||||||
|
- API image build: NOT passed. Earlier attempts failed on a base-image layer and DNS. The latest retry resolved proxy.golang.org but TCP/443 was refused during go mod download. No fallback registry or weakened checksum verification was configured.
|
||||||
|
- Full Compose start, migration and admin/login smoke: NOT executed. API image remains blocked by outbound Docker network refusal to proxy.golang.org; no local Go module cache image was available. Protected deployment inputs are not provisioned.
|
||||||
|
- Readiness unit tests passed for clean v8, old/future/dirty/empty/unavailable schema and nil DB; startup schema gate now requires exactly version 8 clean. Compose config with protected placeholder paths passed and uses readiness healthchecks. Redis is now an explicit optional `cache` profile because the current API does not use it.
|
||||||
|
- Isolated backup/restore rehearsal passed in a disposable MySQL 8.0 container: logical dump plus package tar checksums verified, restored schema row was 8 clean, package object size/digest and restored file SHA-256 matched. The signing key was excluded. The final restore used a new empty `license_restore_empty` database and an empty private directory; a second attempt against the nonempty database was rejected. This used a minimal synthetic dataset, not the full business database. Rehearsal containers were stopped; business MySQL and 18081 were untouched.
|
||||||
|
- Independently executed isolated MySQL/Nginx download integration: passed actual bytes/digest, Range 206, internal-path 404 and unauthenticated denial, plus expired/unpublished/missing release denial audits. This is not equivalent to full Compose acceptance.
|
||||||
|
- Go test/vet, npm test (10 cases), npm build: passed. Manual logged-in browser acceptance remains separate and pending.
|
||||||
32
docs/download-contract-draft.md
Normal file
32
docs/download-contract-draft.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Local release/download DEV slice
|
||||||
|
|
||||||
|
Status: in progress, not ready for formal acceptance. U07 resumable chunk upload, crash/orphan reconciliation, formal key rotation and authenticated browser acceptance remain incomplete.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- Admin GET `/api/v1/products/:id/releases?page=1`: paginated metadata, no physical storage path/key.
|
||||||
|
- Admin POST `/api/v1/products/:id/releases?version=...`: raw binary, 1 byte through 64 MiB. SHA-256 content address; transactional publication metadata/audit. Apply migrations 007 and 008 before starting this code.
|
||||||
|
- Instance POST `/api/v1/customers/:customer_id/releases/:id/download`: JSON instance ID/secret. Current customer/product entitlement, freeze/revocation and instance ownership checked before transactional audit and X-Accel-Redirect. Secret must not appear in URLs.
|
||||||
|
- Downloads use POST with Range headers; clients must repeat credentials for every resumed request. Not a public download URL.
|
||||||
|
|
||||||
|
## Storage and consistency
|
||||||
|
|
||||||
|
`PACKAGE_STORAGE_ROOT` must be an absolute trusted non-public existing directory writable only by the application/storage owner. Digest keys are 64 lowercase hex characters plus `.bin`. Package symlinks are rejected. Directory modification by an untrusted process is outside the safe operating boundary; Nginx also disables symlinks.
|
||||||
|
|
||||||
|
Migration 008 package_objects rows serialize same-digest writes across products. New files are removed for metadata/audit failure before rollback. A commit acknowledgement failure or process crash can leave an unreachable object; preserve it for reconciliation rather than risking deletion of an actually committed package. No crash recovery/automatic garbage collection claim is made.
|
||||||
|
|
||||||
|
## Executed evidence (2026-09-30)
|
||||||
|
|
||||||
|
Dedicated `license_download_260930` database migrated to 008; no destructive cleanup of normal development data.
|
||||||
|
|
||||||
|
`TestDownloadsMySQLIntegration`: customer/product isolation, bad secret, freeze/revoke/customer inactive/product inactive, unauthenticated publication, audit failure blocking redirect and publication, failure file cleanup, concurrent cross-product same digest, conflicting version, empty file, 67108864-byte success and 67108865-byte denial passed.
|
||||||
|
|
||||||
|
Linux container `TestLocalPackageRejectsTraversalAndSymlink` passed without skip.
|
||||||
|
|
||||||
|
Isolated Nginx stable-alpine on http://127.0.0.1:18181 with temporary API 18082: authenticated exact bytes and SHA256 header matched; Range bytes=0-6 returned 206 with `package`; guessed internal path 404; empty credentials 400. Container and temporary API stopped after automated test. Configuration: deploy/nginx/download-local.conf, storage read-only mounted at /srv/license-packages; no unrelated Nginx modified.
|
||||||
|
|
||||||
|
Frontend release list/upload panel compiled; existing frontend tests/build passed, existing bundle-size warning remains. Authenticated browser upload/list/instance interaction needs user login at http://127.0.0.1:15173.
|
||||||
|
|
||||||
|
## Runtime/key boundary
|
||||||
|
|
||||||
|
Existing development 18081 remains v6, development database remains 007; 008 and new code have not been applied to that runtime. Its ephemeral signing key cannot be recovered through supported APIs. Do not rerun the old launcher, since it silently generates a different key. Upgrade requires protected persistent key injection and an explicit decision concerning old DEV certificates/leases, or coordinator approval for deliberate test-only key rotation. See signing-key-operations.md. No private key saved or logged.
|
||||||
53
docs/heartbeat-lease-contract-draft.md
Normal file
53
docs/heartbeat-lease-contract-draft.md
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# v6 心跳、租约、冻结传播(DEV 草案)
|
||||||
|
|
||||||
|
未经 T01/T02 签字,不代表正式产品策略或 UAT 验收。
|
||||||
|
|
||||||
|
## API 与认证
|
||||||
|
|
||||||
|
客户端 `POST /api/v1/instances/{instance_id}/heartbeat`,JSON `{ "secret": "<bootstrap secret>", "client_time": "<RFC3339>" }`,必须带 `Idempotency-Key`。只用 instance_id + secret 认证,解码 32-byte base64url secret 并比较 SHA-256;不记录、不回显明文。请求体最多 4096 bytes。
|
||||||
|
|
||||||
|
管理员 `POST /api/v1/instances/{instance_id}/freeze`,JSON `{ "frozen": true|false }`,必须带管理员 Cookie 与 Idempotency-Key。冻结状态和操作/audit 同事务。冻结不篡改已发租约时间,也不模拟主动推送。
|
||||||
|
|
||||||
|
每实例成功心跳间隔至少 60 秒,429 提供 Retry-After。新状态传播不受正常限频限制。相同键/相同 client_time 返回首次成功响应且不更新 last_seen;改变载荷 409。若冻结/撤销等状态变化,则旧成功响应重放返回 409 state_changed,客户端必须新键重试。
|
||||||
|
|
||||||
|
## 状态与时间
|
||||||
|
|
||||||
|
成功响应 data.payload:version、instance_id、state、server_time、entitlement_expires_at、lease_expires_at;附 signature、canonical_sha256、algorithm、next_heartbeat_seconds。
|
||||||
|
|
||||||
|
- `active`:lease_expires_at = min(server_time + 14 天, entitlement_expires_at)。权益截止独立于租约;远期/永久式权益绝不产生永久离线权限。现有数据库只支持有期限权益,真正 null 永久权益尚未实现。
|
||||||
|
- `frozen`、`revoked`、`expired`、`pending`、`not_activated`:不给新使用权限,lease_expires_at = server_time。撤销优先于冻结。
|
||||||
|
- DEV 假设:联网收到签名冻结/撤销立即停用并清除允许缓存。离线无法获知新的冻结/撤销,旧租约可用至原截止,且最长 14 天;不得声称即时离线撤销。
|
||||||
|
- 时间以服务端 MySQL UTC_TIMESTAMP(6) 为准;客户端绝对偏差/相对前次时间回拨超过 5 分钟返回 409 clock_skew。服务端较 last_seen 回拨超过 5 分钟暂停签发;容差内高水位单调不降。
|
||||||
|
- 客户端必须验签、核对实例和版本、只接受 active 状态,校验 now < lease_expires_at 且 now < entitlement_expires_at,校验租约跨度 <=14 天,并持久化可信时间高水位/单调时间;本切片没有客户端执行器,不承诺对系统时钟篡改或存储回滚的完整防护。
|
||||||
|
|
||||||
|
last_seen、租约、observed_state、幂等响应和 audit 同事务。审计 actor 暂借实例 provisioner 外键,details 标明 client_actor=instance,正式客户端主体模型待确认。
|
||||||
|
|
||||||
|
## Canonical / 跨语言公开向量
|
||||||
|
|
||||||
|
UTF-8,无 BOM、无尾换行,固定顺序如下。SHA-256 后以 P-256 ECDSA 签名,ASN.1 DER / base64 无填充;公钥是 SPKI PEM。公钥与签名均为公开测试材料,随机生成私钥不持久化。
|
||||||
|
|
||||||
|
```text
|
||||||
|
version=lease-v1
|
||||||
|
instance_id=00000000-0000-4000-8000-000000000001
|
||||||
|
state=active
|
||||||
|
server_time=2026-09-30T12:00:00Z
|
||||||
|
entitlement_expires_at=2036-09-30T12:00:00Z
|
||||||
|
lease_expires_at=2026-10-14T12:00:00Z
|
||||||
|
```
|
||||||
|
|
||||||
|
SHA-256: `777150ed1107b51f17dd1ffaefac303310a32ec415e3d83a4b16cb05b9aac379`
|
||||||
|
|
||||||
|
Signature: `MEQCIFHuseC8F3iv6Jz9W3yywkacJ5qBOcDRJSNFLdFWS2w9AiBRZEmPGOzti3IJ0VOPccUOmmtVfWs6ZxtjcSDKJLH8BQ`
|
||||||
|
|
||||||
|
```pem
|
||||||
|
-----BEGIN PUBLIC KEY-----
|
||||||
|
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz39VZCPp0fPgbDhKOM0jUHqzJAe3
|
||||||
|
7GSZpcSe1TO9UGqv8BO3PBI8Th3Z9Fy5EdPaVggh8V/pjW/dcsUg9QbzWA==
|
||||||
|
-----END PUBLIC KEY-----
|
||||||
|
```
|
||||||
|
|
||||||
|
任何一个字段被篡改必须验签失败;license-v1 激活证书不能替代 lease-v1 租约。
|
||||||
|
|
||||||
|
## 明确阻塞
|
||||||
|
|
||||||
|
克隆检测、实例迁移、扩容、真正永久权益、客户端可信存储/执行器、密钥轮换 key_id、分布式入口限流、异常激活监测、缓存推送失效、正式策略签字及 UAT 尚未实现。不得以当前 instance secret 认证声称防克隆。
|
||||||
37
docs/keyring-client-contract-draft.md
Normal file
37
docs/keyring-client-contract-draft.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# DEV-KEYRING-v2 / client execution draft
|
||||||
|
|
||||||
|
Status: configurable development implementation, not T01/T02-approved production protocol. Existing 18081 unchanged. No commits/releases.
|
||||||
|
|
||||||
|
## Environment and wire format
|
||||||
|
|
||||||
|
LICENSE_KEYRING_FILE is an absolute JSON file (regular file, <=64 KiB). Structure:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"current_key_id":"release_2026_10","keys":[{"key_id":"release_2026_10","public_key_pem":"PUBLIC PEM ONLY","revoked":false},{"key_id":"previous","public_key_pem":"PUBLIC PEM ONLY","revoked":false}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
The current private key still comes exclusively from existing protected LICENSE_SIGNING_PRIVATE_KEY_FILE or the existing PEM injection mechanism; do not put private keys in the keyring. Each unique key ID uses [a-zA-Z0-9_-]{1,64}. Maximum 32 entries. Current entry must exist, be non-revoked, be P256 and match the private key or startup fails. Retired verification-only entries need no private key.
|
||||||
|
|
||||||
|
With keyring configured, NEW certificates use license-v2 and NEW heartbeat leases use lease-v2. The existing fixed canonical v1 field order is retained, with the new version and a final newline followed by key_id=<ID>. No trailing newline. SHA256, ECDSA P256, ASN.1 DER signature, raw standard base64 (no padding). key_id belongs INSIDE payload and is signed. IDs in Node are positive safe integers; client rejects larger numeric IDs rather than accepting rounded JSON integers. RFC3339 UTC times remain exact signed text, not reformatted by client.
|
||||||
|
|
||||||
|
Without keyring, old v1 signing remains for development compatibility. The new client intentionally refuses all v1 payloads. /api/v1/activation/keyring exposes public metadata, but is discovery ONLY; never trust it automatically. Public keys and revocation policy must be pinned/distributed through a separately authenticated deployment path. Unknown/revoked key fails closed. A revoked signing key cannot be current.
|
||||||
|
|
||||||
|
## Migration and rollback
|
||||||
|
|
||||||
|
No historical SQL migration changed and no new schema migration required: certificate_payload and operation response JSON persist version and key_id; certificate_version stores v2. Existing idempotent activation/heartbeat operations replay original responses without re-signing, including v1. Retry with the SAME idempotency key, never assume replay upgrades a certificate.
|
||||||
|
|
||||||
|
Stage clients and pinned old+new keys BEFORE switching the API current key. Keep old unrevoked PUBLIC key for the full approved historical certificate/lease lifetime, then retire only after explicit lifecycle review. Do not overwrite key IDs with different public keys. Server validates current configuration only; deployment approval must enforce key ID immutability/history. Runtime reload is NOT supported; use approved rolling deployments with persistent protected injection. No current production key was generated or rotated.
|
||||||
|
|
||||||
|
Rollback is configuration/software rollout, not business-data down migration: restore previous API image plus its matching current private key and public keyring while preserving public keys needed for already-issued v2 payloads. Rolling back to a v1-only binary DOES NOT make v2 artifacts verifiable by old clients. Do not delete stored responses/certificates or force schema version. Preserve quiesced backup, issued artifacts and approvals. Formal retention windows, emergency revocation publication, config generation monotonicity and live business rotation drill remain gates.
|
||||||
|
|
||||||
|
## Independent client module
|
||||||
|
|
||||||
|
client/verify.mjs is a Node server-side reference package, NOT the management console and NOT a deployed customer integration. No instance secret/session stored by this module. verifyEnvelope takes caller-pinned keys, rejects unknown/revoked, altered key_id or payload. acceptLease verifies instance binding, signed state, entitlement bound, max14-day lease, 5-minute server skew, monotonic client/server milliseconds. canRunOffline checks previously accepted lease until expiration. Caller must atomically persist returned state BEFORE enabling licensed work, update local high-water before EVERY subsequent execution, protect it from tampering and disable on all errors. This does not resist privileged cloning, disk snapshot rollback or clock manipulation by host owner; monotonic trusted time/storage design still requires T01 approval. Millisecond comparison loses sub-ms precision; server-issued microsecond exact ordering and replay digest persistence are future hardening gates.
|
||||||
|
|
||||||
|
Go test TestKeyringCrossLanguageRotation generates public Go->Node vectors with ephemeral private keys only in memory. Checks old/current certificate verification, revoked/unknown rejection, signed key substitution/payload tamper rejection, lease verification, instance mismatch, local/server high-water rollback, offline expiry. No private test fixture committed. This is cross-language component evidence, not authenticated activation/heartbeat rotation E2E. Node required for backend tests; CI explicitly installs Node24.
|
||||||
|
|
||||||
|
## Integrator API / customer portal boundary
|
||||||
|
|
||||||
|
Provisioning remains administrator-only POST /api/v1/licenses/:id/instances, returning a one-time secret that must reach the authorized integrator via secure channel. Client activation POST /api/v1/activation/instances/:instance_id uses secret + license_key and Idempotency-Key. Heartbeat POST /api/v1/instances/:instance_id/heartbeat uses secret + client_time and Idempotency-Key; follow the current heartbeat draft field contract. Download POST /api/v1/customers/:customer_id/releases/:id/download uses existing credential draft and Nginx internal handoff. No secret belongs in query strings/logs/browser localStorage. Timeouts/429 use bounded backoff; 403/409 must not silently reactivate, bypass checks or reuse mismatched payloads.
|
||||||
|
|
||||||
|
There is NO customer-account authentication domain or customer portal in the current implementation. The Vue UI is administrator management only. T25 remains unstarted, pending tenant identity/account reset/RBAC/renewal contracts. Do not build an unauthenticated customer-data page using administrator cookies or pretend this module is a customer portal. Minimum future portal: customer login/session isolation, only-own licenses/orders/leases/releases, no administrator routes, secure secret delivery/recovery, expiry/renewal requests, logout/reset and tenant-negative tests.
|
||||||
10
docs/license-contract-draft.md
Normal file
10
docs/license-contract-draft.md
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
# 授权签发闭环草案
|
||||||
|
|
||||||
|
版本:DEV-LICENSE-v0.1(2026-09-30)。状态:开发假设,未替代正式业务决策或 OpenAPI 签字。
|
||||||
|
|
||||||
|
- 当前授权是后台管理员为 active 客户和 active 产品签发的一条期限记录。
|
||||||
|
- `starts_at` 和 `expires_at` 必须是 RFC3339 时间,服务端转 UTC 保存;结束时间必须晚于开始时间,精度为微秒;当前 TIMESTAMP 存储范围限定为 1970-01-01T00:00:01Z 至 2038-01-19T03:14:07Z(上界不含)。
|
||||||
|
- 授权初始状态为 `active`,拥有不可预测的 128-bit 十六进制 `license_key`。本阶段仅提供后台查看,不把它当作客户端激活凭证。
|
||||||
|
- 请求必须带 `Idempotency-Key`(1 至 128 字符)。同一管理员、同一键、同一请求字段重放返回原授权;字段不一致返回 409。管理员行锁串行化并发签发,客户/产品行锁确保状态校验一致;事务不会产生第二条授权或第二条签发审计。前端网络失败后保留原键重试。
|
||||||
|
- 签发事务同时写 `audit_events`,审计只记录管理员、资源、动作和非敏感期限/主数据 ID,不记录密码、会话令牌或完整 HTTP 内容。
|
||||||
|
- 本阶段不实现实例身份绑定、激活协议、离线租约、设备扩容/克隆、心跳、退款、客户门户或下载权限。新增的撤销/续期仅是后台期限记录开发假设:管理员级权限、Idempotency-Key、锁定授权行的事务操作记录与审计;续期只允许延后结束时间,撤销后不得续期。它们不等同续费、订单发放、激活或正式冻结/解绑。正式状态机、授权码展示/轮换、租户隔离和审计保留策略待确认。
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user