feat: localize license states and restore revoked licenses
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-12 16:11:09 +08:00
parent f4b99e50cd
commit 09910db251
8 changed files with 141 additions and 6 deletions

View File

@@ -101,6 +101,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
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/restore", func(c *gin.Context) { a.operateLicense(c, "restore") })
secured.POST("/licenses/:id/renew", func(c *gin.Context) { a.operateLicense(c, "renew") })
}

View File

@@ -137,4 +137,13 @@ func testHeartbeatMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Co
if response.Data.Payload.State != "revoked" {
t.Fatal("revocation not propagated")
}
restorePath := "/api/v1/licenses/" + strconv.FormatUint(licenseID, 10) + "/restore"
if w = request(restorePath, `{}`, "heartbeat-restore", true); w.Code != 200 {
t.Fatalf("restore=%d body=%s", w.Code, w.Body)
}
w = request(path, body, "restored", false)
json.Unmarshal(w.Body.Bytes(), &response)
if w.Code != 200 || response.Data.Payload.State != "active" {
t.Fatalf("restoration not propagated: %d %s", w.Code, w.Body)
}
}

View File

@@ -0,0 +1,72 @@
package httpapi
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"github.com/gin-gonic/gin"
"net/http/httptest"
"strings"
"testing"
"time"
)
type restoreDB struct {
*dashboardDB
commands []string
failAudit bool
}
func (d *restoreDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
func (d *restoreDB) ExecContext(_ context.Context, q string, args []driver.NamedValue) (driver.Result, error) {
d.commands = append(d.commands, q)
if strings.Contains(q, "INSERT INTO audit_events") && d.failAudit {
return nil, errors.New("audit unavailable")
}
return driver.RowsAffected(1), nil
}
func TestRestoreLicense(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
for _, tc := range []struct {
name, status string
expiry time.Time
fail bool
want int
result string
}{
{"valid", "revoked", now.Add(time.Hour), false, 200, "active"},
{"expired", "revoked", now.Add(-time.Hour), false, 200, "expired"},
{"not revoked", "active", now.Add(time.Hour), false, 409, ""},
{"audit failure", "revoked", now.Add(time.Hour), true, 500, ""},
} {
t.Run(tc.name, func(t *testing.T) {
d := &restoreDB{dashboardDB: &dashboardDB{t: t, queries: []dashboardQuery{
{sql: licenseSelect + " WHERE l.id=? FOR UPDATE", args: []any{int64(2)}, rows: [][]driver.Value{testLicenseRow(2, tc.status, now.Add(-2*time.Hour), tc.expiry, now)}},
{sql: "SELECT id,license_id,operation,idempotency_key,request_fingerprint FROM license_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", args: []any{int64(1), "restore", "restore-test"}},
}}, failAudit: tc.fail}
db := sql.OpenDB(d)
defer db.Close()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/licenses/2/restore", strings.NewReader("{}"))
c.Request.Header.Set("Idempotency-Key", "restore-test")
c.Params = gin.Params{{Key: "id", Value: "2"}}
c.Set("admin_id", uint64(1))
(&BusinessAPI{db: db}).operateLicense(c, "restore")
c.Writer.WriteHeaderNow()
if w.Code != tc.want || d.committed != (tc.want == 200) {
t.Fatalf("code=%d committed=%v body=%s", w.Code, d.committed, w.Body)
}
if tc.want == 200 && (!strings.Contains(w.Body.String(), `"status":"`+tc.result+`"`) || !strings.Contains(w.Body.String(), tc.expiry.Format(time.RFC3339))) {
t.Fatalf("validity changed: %s", w.Body)
}
if tc.want == 409 && len(d.commands) != 0 {
t.Fatal("invalid state mutated")
}
if tc.want == 200 && (len(d.commands) != 3 || d.commands[0] != "UPDATE licenses SET status='active',revoked_at=NULL WHERE id=?") {
t.Fatal("unexpected restore writes", d.commands)
}
})
}
}

View File

@@ -345,6 +345,15 @@ func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) {
apiError(c, 500, "internal_error", "撤销失败")
return
}
} else if operation == "restore" {
if rec.Status != "revoked" {
apiError(c, 409, "invalid_state", "仅已撤销的授权可以恢复")
return
}
if _, err = tx.ExecContext(c, "UPDATE licenses SET status='active',revoked_at=NULL WHERE id=?", id); err != nil {
apiError(c, 500, "internal_error", "恢复失败")
return
}
} else {
if rec.Status == "revoked" || !expires.After(rec.ExpiresAt) {
apiError(c, 400, "invalid_request", "续期时间必须晚于当前结束时间且授权未撤销")
@@ -371,7 +380,9 @@ func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) {
if operation == "revoke" {
rec.Status = "revoked"
} else {
rec.ExpiresAt = expires
if operation == "renew" {
rec.ExpiresAt = expires
}
rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
}
c.JSON(200, gin.H{"data": rec, "idempotent_replay": false})