feat(auth): implement master key authentication system with child key issuance

Add admin and master authentication layers with JWT support. Replace direct
key creation with hierarchical master/child key system. Update database
schema to support master accounts with configurable limits and epoch-based
key revocation. Add health check endpoint with system status monitoring.

BREAKING CHANGE: Removed direct POST /keys endpoint in favor of master-based
key issuance through /v1/tokens. Database migration requires dropping old User
table and creating Master table with new relationships.
This commit is contained in:
zenfun
2025-12-05 00:16:47 +08:00
parent 5360cc6f1a
commit 8645b22b83
16 changed files with 618 additions and 229 deletions

View File

@@ -4,13 +4,32 @@ import (
"gorm.io/gorm"
)
type User struct {
// Admin is not a database model. It's configured via environment variables.
// Master represents a tenant account.
type Master struct {
gorm.Model
Username string `gorm:"uniqueIndex;not null" json:"username"`
Quota int64 `gorm:"default:0" json:"quota"`
Role string `gorm:"default:'user'" json:"role"` // admin, user
Name string `gorm:"size:255" json:"name"`
MasterKey string `gorm:"size:255;uniqueIndex" json:"-"` // Hashed master key
Group string `gorm:"size:100;default:'default'" json:"group"`
Epoch int64 `gorm:"default:1" json:"epoch"`
Status string `gorm:"size:50;default:'active'" json:"status"` // active, suspended
MaxChildKeys int `gorm:"default:5" json:"max_child_keys"`
GlobalQPS int `gorm:"default:3" json:"global_qps"`
}
// Key represents a child access token issued by a Master.
type Key struct {
gorm.Model
MasterID uint `gorm:"not null;index" json:"master_id"`
KeySecret string `gorm:"size:255;uniqueIndex" json:"key_secret"`
Group string `gorm:"size:100;default:'default'" json:"group"`
Scopes string `gorm:"size:1024" json:"scopes"` // Comma-separated scopes
IssuedAtEpoch int64 `gorm:"not null" json:"issued_at_epoch"`
Status string `gorm:"size:50;default:'active'" json:"status"` // active, suspended
}
// Provider remains the same.
type Provider struct {
gorm.Model
Name string `gorm:"not null" json:"name"`
@@ -21,15 +40,7 @@ type Provider struct {
Models string `json:"models"` // comma-separated list of supported models (e.g. "gpt-4,gpt-3.5-turbo")
}
type Key struct {
gorm.Model
KeySecret string `gorm:"not null" json:"key_secret"`
Group string `gorm:"default:'default'" json:"group"` // routing group/tier
Balance float64 `json:"balance"`
Status string `gorm:"default:'active'" json:"status"` // active, suspended
Weight int `gorm:"default:10" json:"weight"`
}
// Model remains the same.
type Model struct {
gorm.Model
Name string `gorm:"uniqueIndex;not null" json:"name"`