jwt

package
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeJWTKeyNotFound            = "JWT_KEY_NOT_FOUND"
	CodeJWTKeyAlreadyExists       = "JWT_KEY_ALREADY_EXISTS"
	CodeJWTKeyExpired             = "JWT_KEY_EXPIRED"
	CodeJWTKeyInactive            = "JWT_KEY_INACTIVE"
	CodeNoActiveSigningKey        = "NO_ACTIVE_SIGNING_KEY"
	CodeJWTGenerationFailed       = "JWT_GENERATION_FAILED"
	CodeJWTVerificationFailed     = "JWT_VERIFICATION_FAILED"
	CodeInvalidJWTAlgorithm       = "INVALID_JWT_ALGORITHM"
	CodeInvalidJWTKeyType         = "INVALID_JWT_KEY_TYPE"
	CodeJWTKeyDecryptionFailed    = "JWT_KEY_DECRYPTION_FAILED"
	CodeJWTKeyEncryptionFailed    = "JWT_KEY_ENCRYPTION_FAILED"
	CodeJWTParsingFailed          = "JWT_PARSING_FAILED"
	CodeJWTSigningFailed          = "JWT_SIGNING_FAILED"
	CodeMissingKIDHeader          = "MISSING_KID_HEADER"
	CodeInvalidJWTAudience        = "INVALID_JWT_AUDIENCE"
	CodeInvalidJWTTokenType       = "INVALID_JWT_TOKEN_TYPE"
	CodeJWKSGenerationFailed      = "JWKS_GENERATION_FAILED"
	CodeInvalidJWTClaims          = "INVALID_JWT_CLAIMS"
	CodeJWTKeyGenerationFailed    = "JWT_KEY_GENERATION_FAILED"
	CodeCannotSignWithoutPrivate  = "CANNOT_SIGN_WITHOUT_PRIVATE_KEY"
	CodeCannotVerifyWithoutPublic = "CANNOT_VERIFY_WITHOUT_PUBLIC_KEY"
)

Variables

View Source
var (
	ErrJWTKeyNotFound            = &errs.AuthsomeError{Code: CodeJWTKeyNotFound}
	ErrJWTKeyAlreadyExists       = &errs.AuthsomeError{Code: CodeJWTKeyAlreadyExists}
	ErrJWTKeyExpired             = &errs.AuthsomeError{Code: CodeJWTKeyExpired}
	ErrJWTKeyInactive            = &errs.AuthsomeError{Code: CodeJWTKeyInactive}
	ErrNoActiveSigningKey        = &errs.AuthsomeError{Code: CodeNoActiveSigningKey}
	ErrJWTGenerationFailed       = &errs.AuthsomeError{Code: CodeJWTGenerationFailed}
	ErrJWTVerificationFailed     = &errs.AuthsomeError{Code: CodeJWTVerificationFailed}
	ErrInvalidJWTAlgorithm       = &errs.AuthsomeError{Code: CodeInvalidJWTAlgorithm}
	ErrInvalidJWTKeyType         = &errs.AuthsomeError{Code: CodeInvalidJWTKeyType}
	ErrJWTKeyDecryptionFailed    = &errs.AuthsomeError{Code: CodeJWTKeyDecryptionFailed}
	ErrJWTKeyEncryptionFailed    = &errs.AuthsomeError{Code: CodeJWTKeyEncryptionFailed}
	ErrJWTParsingFailed          = &errs.AuthsomeError{Code: CodeJWTParsingFailed}
	ErrJWTSigningFailed          = &errs.AuthsomeError{Code: CodeJWTSigningFailed}
	ErrMissingKIDHeader          = &errs.AuthsomeError{Code: CodeMissingKIDHeader}
	ErrInvalidJWTAudience        = &errs.AuthsomeError{Code: CodeInvalidJWTAudience}
	ErrInvalidJWTTokenType       = &errs.AuthsomeError{Code: CodeInvalidJWTTokenType}
	ErrJWKSGenerationFailed      = &errs.AuthsomeError{Code: CodeJWKSGenerationFailed}
	ErrInvalidJWTClaims          = &errs.AuthsomeError{Code: CodeInvalidJWTClaims}
	ErrJWTKeyGenerationFailed    = &errs.AuthsomeError{Code: CodeJWTKeyGenerationFailed}
	ErrCannotSignWithoutPrivate  = &errs.AuthsomeError{Code: CodeCannotSignWithoutPrivate}
	ErrCannotVerifyWithoutPublic = &errs.AuthsomeError{Code: CodeCannotVerifyWithoutPublic}
)

Functions

func CannotSignWithoutPrivateKey

func CannotSignWithoutPrivateKey() *errs.AuthsomeError

func CannotVerifyWithoutPublicKey

func CannotVerifyWithoutPublicKey() *errs.AuthsomeError

func InvalidJWTAlgorithm

func InvalidJWTAlgorithm(algorithm string) *errs.AuthsomeError

Algorithm and Key Type errors

func InvalidJWTAudience

func InvalidJWTAudience(expected, actual []string) *errs.AuthsomeError

func InvalidJWTClaims

func InvalidJWTClaims(reason string) *errs.AuthsomeError

func InvalidJWTKeyType

func InvalidJWTKeyType(keyType string) *errs.AuthsomeError

func InvalidJWTTokenType

func InvalidJWTTokenType(expected, actual string) *errs.AuthsomeError

func JWKSGenerationFailed

func JWKSGenerationFailed(err error) *errs.AuthsomeError

JWKS errors

func JWTGenerationFailed

func JWTGenerationFailed(reason string) *errs.AuthsomeError

JWT Generation errors

func JWTKeyAlreadyExists

func JWTKeyAlreadyExists(keyID string) *errs.AuthsomeError

func JWTKeyDecryptionFailed

func JWTKeyDecryptionFailed(err error) *errs.AuthsomeError

Encryption errors

func JWTKeyEncryptionFailed

func JWTKeyEncryptionFailed(err error) *errs.AuthsomeError

func JWTKeyExpired

func JWTKeyExpired(keyID string) *errs.AuthsomeError

func JWTKeyGenerationFailed

func JWTKeyGenerationFailed(err error) *errs.AuthsomeError

Key generation errors

func JWTKeyInactive

func JWTKeyInactive(keyID string) *errs.AuthsomeError

func JWTKeyNotFound

func JWTKeyNotFound() *errs.AuthsomeError

JWT Key errors

func JWTParsingFailed

func JWTParsingFailed(err error) *errs.AuthsomeError

func JWTSigningFailed

func JWTSigningFailed(err error) *errs.AuthsomeError

func JWTVerificationFailed

func JWTVerificationFailed(reason string) *errs.AuthsomeError

JWT Verification errors

func MissingKIDHeader

func MissingKIDHeader() *errs.AuthsomeError

func NoActiveSigningKey

func NoActiveSigningKey(appID string) *errs.AuthsomeError

Types

type Config

type Config struct {
	EncryptionKey string `json:"encryption_key"`
	DefaultTTL    string `json:"default_ttl"`
}

Config holds JWT service configuration

type CreateJWTKeyRequest

type CreateJWTKeyRequest struct {
	AppID         xid.ID                 `json:"appId" validate:"required"`
	IsPlatformKey bool                   `json:"isPlatformKey"`
	Algorithm     string                 `json:"algorithm" validate:"required,oneof=RS256 RS384 RS512 ES256 ES384 ES512 HS256 HS384 HS512"`
	KeyType       string                 `json:"keyType" validate:"required,oneof=RSA ECDSA HMAC"`
	Curve         string                 `json:"curve,omitempty" validate:"omitempty,oneof=P-256 P-384 P-521"`
	ExpiresAt     *time.Time             `json:"expiresAt,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

CreateJWTKeyRequest represents a request to create a JWT key

type GenerateTokenRequest

type GenerateTokenRequest struct {
	UserID      string                 `json:"userId" validate:"required"`
	AppID       xid.ID                 `json:"appId" validate:"required"`
	SessionID   string                 `json:"sessionId,omitempty"`
	TokenType   string                 `json:"tokenType" validate:"required,oneof=access refresh id"`
	Scopes      []string               `json:"scopes,omitempty"`
	Permissions []string               `json:"permissions,omitempty"`
	Audience    []string               `json:"audience,omitempty"`
	ExpiresIn   time.Duration          `json:"expiresIn,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

GenerateTokenRequest represents a request to generate a JWT token

type GenerateTokenResponse

type GenerateTokenResponse struct {
	Token     string    `json:"token"`
	TokenType string    `json:"tokenType"`
	ExpiresAt time.Time `json:"expiresAt"`
	ExpiresIn int64     `json:"expiresIn"`
}

GenerateTokenResponse represents the response from token generation

type JWK

type JWK struct {
	KeyType   string   `json:"kty"`
	KeyID     string   `json:"kid"`
	Use       string   `json:"use"`
	Algorithm string   `json:"alg"`
	N         string   `json:"n,omitempty"`       // RSA modulus
	E         string   `json:"e,omitempty"`       // RSA exponent
	X         string   `json:"x,omitempty"`       // ECDSA x coordinate
	Y         string   `json:"y,omitempty"`       // ECDSA y coordinate
	Curve     string   `json:"crv,omitempty"`     // ECDSA curve
	KeyOps    []string `json:"key_ops,omitempty"` // Key operations
}

JWK represents a JSON Web Key

type JWKSResponse

type JWKSResponse = pagination.PageResponse[JWK]

JWKSResponse represents a JSON Web Key Set response

type JWTKey

type JWTKey struct {
	ID            xid.ID                 `json:"id"`
	AppID         xid.ID                 `json:"appId"`
	IsPlatformKey bool                   `json:"isPlatformKey"`
	KeyID         string                 `json:"keyId"`
	Algorithm     string                 `json:"algorithm"`
	KeyType       string                 `json:"keyType"`
	Curve         string                 `json:"curve,omitempty"`
	PrivateKey    string                 `json:"-"` // Never expose in JSON
	PublicKey     string                 `json:"publicKey"`
	IsActive      bool                   `json:"isActive"`
	UsageCount    int64                  `json:"usageCount"`
	LastUsedAt    *time.Time             `json:"lastUsedAt,omitempty"`
	ExpiresAt     *time.Time             `json:"expiresAt,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
	// Audit fields
	CreatedAt time.Time  `json:"createdAt"`
	UpdatedAt time.Time  `json:"updatedAt"`
	DeletedAt *time.Time `json:"deletedAt,omitempty"`
}

JWTKey represents a JWT signing key DTO This is separate from schema.JWTKey to maintain proper separation of concerns

func FromSchemaJWTKey

func FromSchemaJWTKey(sk *schema.JWTKey) *JWTKey

FromSchemaJWTKey converts a schema.JWTKey model to JWTKey DTO

func FromSchemaJWTKeys

func FromSchemaJWTKeys(keys []*schema.JWTKey) []*JWTKey

FromSchemaJWTKeys converts a slice of schema.JWTKey to JWTKey DTOs

func (*JWTKey) CanSign

func (k *JWTKey) CanSign() bool

CanSign checks if the key can be used for signing

func (*JWTKey) CanVerify

func (k *JWTKey) CanVerify() bool

CanVerify checks if the key can be used for verification

func (*JWTKey) IsExpired

func (k *JWTKey) IsExpired() bool

IsExpired checks if the JWT key is expired

func (*JWTKey) ToSchema

func (k *JWTKey) ToSchema() *schema.JWTKey

ToSchema converts the JWTKey DTO to a schema.JWTKey model

type ListJWTKeysFilter

type ListJWTKeysFilter struct {
	pagination.PaginationParams
	AppID         xid.ID `json:"appId" query:"app_id"`
	IsPlatformKey *bool  `json:"isPlatformKey,omitempty" query:"is_platform_key"`
	Active        *bool  `json:"active,omitempty" query:"active"`
}

ListJWTKeysFilter represents filter parameters for listing JWT keys

type ListJWTKeysResponse

type ListJWTKeysResponse = pagination.PageResponse[*JWTKey]

type Repository

type Repository interface {
	// CreateJWTKey creates a new JWT key
	CreateJWTKey(ctx context.Context, key *schema.JWTKey) error

	// FindJWTKeyByID finds a JWT key by ID
	FindJWTKeyByID(ctx context.Context, id xid.ID) (*schema.JWTKey, error)

	// FindJWTKeyByKeyID finds a JWT key by key ID and app ID
	FindJWTKeyByKeyID(ctx context.Context, keyID string, appID xid.ID) (*schema.JWTKey, error)

	// FindPlatformJWTKeyByKeyID finds a platform JWT key by key ID
	FindPlatformJWTKeyByKeyID(ctx context.Context, keyID string) (*schema.JWTKey, error)

	// ListJWTKeys lists JWT keys with pagination and filtering
	ListJWTKeys(ctx context.Context, filter *ListJWTKeysFilter) (*pagination.PageResponse[*schema.JWTKey], error)

	// ListPlatformJWTKeys lists platform JWT keys with pagination
	ListPlatformJWTKeys(ctx context.Context, filter *ListJWTKeysFilter) (*pagination.PageResponse[*schema.JWTKey], error)

	// UpdateJWTKey updates a JWT key
	UpdateJWTKey(ctx context.Context, key *schema.JWTKey) error

	// UpdateJWTKeyUsage updates the usage statistics for a JWT key
	UpdateJWTKeyUsage(ctx context.Context, keyID string) error

	// DeactivateJWTKey deactivates a JWT key
	DeactivateJWTKey(ctx context.Context, id xid.ID) error

	// DeleteJWTKey soft deletes a JWT key
	DeleteJWTKey(ctx context.Context, id xid.ID) error

	// CleanupExpiredJWTKeys removes expired JWT keys
	CleanupExpiredJWTKeys(ctx context.Context) (int64, error)

	// CountJWTKeys counts JWT keys for an app
	CountJWTKeys(ctx context.Context, appID xid.ID) (int, error)
}

Repository defines the interface for JWT key storage operations This follows the Interface Segregation Principle from core/app architecture

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service handles JWT operations

func NewService

func NewService(config Config, repo Repository, auditSvc *audit.Service) *Service

NewService creates a new JWT service

func (*Service) CleanupExpired

func (s *Service) CleanupExpired(ctx context.Context) (int64, error)

CleanupExpired removes expired JWT keys

func (*Service) CreateJWTKey

func (s *Service) CreateJWTKey(ctx context.Context, req *CreateJWTKeyRequest) (*JWTKey, error)

CreateJWTKey creates a new JWT signing key

func (*Service) GenerateToken

func (s *Service) GenerateToken(ctx context.Context, req *GenerateTokenRequest) (*GenerateTokenResponse, error)

GenerateToken creates a new JWT token

func (*Service) GetJWKS

func (s *Service) GetJWKS(ctx context.Context, appID xid.ID) (*JWKSResponse, error)

GetJWKS returns the JSON Web Key Set for an app

func (*Service) ListJWTKeys

func (s *Service) ListJWTKeys(ctx context.Context, filter *ListJWTKeysFilter) (*ListJWTKeysResponse, error)

ListJWTKeys lists JWT keys for an organization with pagination

func (*Service) VerifyToken

func (s *Service) VerifyToken(ctx context.Context, req *VerifyTokenRequest) (*VerifyTokenResponse, error)

VerifyToken verifies a JWT token

type TokenClaims

type TokenClaims struct {
	UserID      string                 `json:"userId"`
	AppID       string                 `json:"appId"`
	SessionID   string                 `json:"sessionId,omitempty"`
	Scopes      []string               `json:"scopes,omitempty"`
	Permissions []string               `json:"permissions,omitempty"`
	TokenType   string                 `json:"tokenType"` // access, refresh, id
	Audience    []string               `json:"aud,omitempty"`
	Subject     string                 `json:"sub"`
	Issuer      string                 `json:"iss"`
	IssuedAt    *jwt.NumericDate       `json:"iat"`
	ExpiresAt   *jwt.NumericDate       `json:"exp"`
	NotBefore   *jwt.NumericDate       `json:"nbf,omitempty"`
	JwtID       string                 `json:"jti"`
	KeyID       string                 `json:"kid"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	jwt.RegisteredClaims
}

TokenClaims represents JWT token claims

type VerifyTokenRequest

type VerifyTokenRequest struct {
	Token     string   `json:"token" validate:"required"`
	AppID     xid.ID   `json:"appId" validate:"required"`
	Audience  []string `json:"audience,omitempty"`
	TokenType string   `json:"tokenType,omitempty"`
}

VerifyTokenRequest represents a request to verify a JWT token

type VerifyTokenResponse

type VerifyTokenResponse struct {
	Valid       bool         `json:"valid"`
	Claims      *TokenClaims `json:"claims,omitempty"`
	Error       string       `json:"error,omitempty"`
	UserID      string       `json:"userId,omitempty"`
	AppID       string       `json:"appId,omitempty"`
	SessionID   string       `json:"sessionId,omitempty"`
	Scopes      []string     `json:"scopes,omitempty"`
	Permissions []string     `json:"permissions,omitempty"`
	ExpiresAt   *time.Time   `json:"expiresAt,omitempty"`
}

VerifyTokenResponse represents the response from token verification

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL