feat: add stable OIDC authentication

This commit is contained in:
2026-07-12 13:53:48 +08:00
parent 27529846ee
commit 5189b3540e
13 changed files with 861 additions and 23 deletions
+67 -10
View File
@@ -3,10 +3,16 @@ package auth
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
@@ -50,11 +56,15 @@ const userContextKey contextKey = "easyai-auth-user"
var ErrUnauthorized = errors.New("unauthorized")
type Authenticator struct {
JWTSecret string
ServerMainBaseURL string
ServerMainInternalToken string
HTTPClient *http.Client
LocalAPIKeyVerifier func(ctx context.Context, apiKey string) (*User, error)
JWTSecret string
ServerMainBaseURL string
ServerMainInternalToken string
ServerMainInternalKey string
ServerMainInternalSecret string
HTTPClient *http.Client
LocalAPIKeyVerifier func(ctx context.Context, apiKey string) (*User, error)
OIDCVerifier *OIDCVerifier
LegacyJWTEnabled bool
}
func New(jwtSecret string, serverMainBaseURL string, internalToken string) *Authenticator {
@@ -65,6 +75,7 @@ func New(jwtSecret string, serverMainBaseURL string, internalToken string) *Auth
HTTPClient: &http.Client{
Timeout: 10 * time.Second,
},
LegacyJWTEnabled: true,
}
}
@@ -77,6 +88,9 @@ func (a *Authenticator) Require(permission Permission, next http.Handler) http.H
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := a.Authenticate(r)
if err != nil {
if strings.HasPrefix(err.Error(), ErrUnauthorized.Error()+":") {
slog.WarnContext(r.Context(), "OIDC authentication rejected", "reason", err.Error())
}
if permission == PermissionPublic {
next.ServeHTTP(w, r)
return
@@ -109,6 +123,16 @@ func (a *Authenticator) Authenticate(r *http.Request) (*User, error) {
if strings.HasPrefix(token, "sk-") {
return a.verifyAPIKey(r.Context(), token)
}
algorithm := jwtAlgorithm(token)
if algorithm == "RS256" || algorithm == "ES256" {
if a.OIDCVerifier == nil {
return nil, ErrUnauthorized
}
return a.OIDCVerifier.Verify(r.Context(), token)
}
if !a.LegacyJWTEnabled {
return nil, ErrUnauthorized
}
return a.verifyJWT(token)
}
@@ -196,16 +220,34 @@ func (a *Authenticator) verifyAPIKey(ctx context.Context, apiKey string) (*User,
return nil, ErrUnauthorized
}
}
if a.ServerMainBaseURL == "" || a.ServerMainInternalToken == "" {
secret := a.ServerMainInternalSecret
if secret == "" {
secret = a.ServerMainInternalToken
}
if a.ServerMainBaseURL == "" || a.ServerMainInternalKey == "" || secret == "" {
return nil, ErrUnauthorized
}
body, _ := json.Marshal(map[string]string{"apiKey": apiKey})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.ServerMainBaseURL+"/internal/platform/auth/verify-api-key", bytes.NewReader(body))
const path = "/internal/auth/verify-apikey"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.ServerMainBaseURL+path, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+a.ServerMainInternalToken)
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
nonceBytes := make([]byte, 16)
if _, err := rand.Read(nonceBytes); err != nil {
return nil, err
}
nonce := hex.EncodeToString(nonceBytes)
bodyHash := sha256.Sum256(body)
signingText := strings.Join([]string{http.MethodPost, path, timestamp, nonce, hex.EncodeToString(bodyHash[:]), a.ServerMainInternalKey}, "\n")
mac := hmac.New(sha256.New, []byte(secret))
_, _ = mac.Write([]byte(signingText))
req.Header.Set("X-Internal-Key", a.ServerMainInternalKey)
req.Header.Set("X-Timestamp", timestamp)
req.Header.Set("X-Nonce", nonce)
req.Header.Set("X-Signature", hex.EncodeToString(mac.Sum(nil)))
resp, err := a.HTTPClient.Do(req)
if err != nil {
@@ -215,10 +257,16 @@ func (a *Authenticator) verifyAPIKey(ctx context.Context, apiKey string) (*User,
if resp.StatusCode != http.StatusOK {
return nil, ErrUnauthorized
}
var user User
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
var payload struct {
Success bool `json:"success"`
Data struct {
User User `json:"user"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return nil, err
}
user := payload.Data.User
if user.ID == "" {
return nil, ErrUnauthorized
}
@@ -236,6 +284,15 @@ func extractBearer(value string) string {
return ""
}
func jwtAlgorithm(token string) string {
parsed, _, err := new(jwt.Parser).ParseUnverified(token, jwt.MapClaims{})
if err != nil || parsed == nil {
return ""
}
algorithm, _ := parsed.Header["alg"].(string)
return algorithm
}
func hasPermission(roles []string, required Permission) bool {
if required == PermissionPublic {
return true
+330
View File
@@ -0,0 +1,330 @@
package auth
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
)
const maxOIDCResponseBytes = 1 << 20
type OIDCConfig struct {
Issuer string
Audience string
TenantID string
RolePrefix string
RequiredScopes []string
JWKSCacheTTL time.Duration
HTTPClient *http.Client
}
type OIDCVerifier struct {
config OIDCConfig
client *http.Client
mu sync.Mutex
keys map[string]any
expiresAt time.Time
}
type discoveryDocument struct {
Issuer string `json:"issuer"`
JWKSURI string `json:"jwks_uri"`
}
type jsonWebKeySet struct {
Keys []jsonWebKey `json:"keys"`
}
type jsonWebKey struct {
KID string `json:"kid"`
KTY string `json:"kty"`
Use string `json:"use"`
Alg string `json:"alg"`
N string `json:"n"`
E string `json:"e"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
}
func NewOIDCVerifier(config OIDCConfig) (*OIDCVerifier, error) {
config.Issuer = strings.TrimRight(strings.TrimSpace(config.Issuer), "/")
config.Audience = strings.TrimSpace(config.Audience)
config.TenantID = strings.TrimSpace(config.TenantID)
config.RolePrefix = strings.TrimSpace(config.RolePrefix)
if err := validatePublicURL(config.Issuer); err != nil || config.Audience == "" || config.TenantID == "" || config.RolePrefix == "" {
return nil, errors.New("issuer, audience, tenant and role prefix are required")
}
if config.JWKSCacheTTL <= 0 {
config.JWKSCacheTTL = 5 * time.Minute
}
client := config.HTTPClient
if client == nil {
client = &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}}
}
return &OIDCVerifier{config: config, client: client, keys: map[string]any{}}, nil
}
func (v *OIDCVerifier) Verify(ctx context.Context, raw string) (*User, error) {
parser := jwt.NewParser(jwt.WithValidMethods([]string{"RS256", "ES256"}))
unverified, _, err := parser.ParseUnverified(raw, jwt.MapClaims{})
if err != nil || unverified == nil {
return nil, oidcUnauthorized("token envelope is invalid", err)
}
kid, _ := unverified.Header["kid"].(string)
if kid == "" {
return nil, oidcUnauthorized("kid is missing", nil)
}
key, err := v.key(ctx, kid)
if err != nil {
return nil, oidcUnauthorized("signing key lookup failed", err)
}
token, err := jwt.Parse(raw, func(token *jwt.Token) (any, error) {
if token.Header["kid"] != kid {
return nil, ErrUnauthorized
}
return key, nil
}, jwt.WithValidMethods([]string{"RS256", "ES256"}), jwt.WithIssuer(v.config.Issuer),
jwt.WithAudience(v.config.Audience), jwt.WithExpirationRequired(), jwt.WithLeeway(30*time.Second))
if err != nil || !token.Valid {
return nil, oidcUnauthorized("signature or registered claims are invalid", err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || stringClaim(claims, "sub") == "" || stringClaim(claims, "tid") != v.config.TenantID {
return nil, oidcUnauthorized("stable identity claims are invalid", nil)
}
if _, ok := numericDateClaim(claims["nbf"]); !ok {
return nil, oidcUnauthorized("nbf is missing", nil)
}
scopes := scopeClaims(claims)
if !containsAll(scopes, v.config.RequiredScopes) {
return nil, oidcUnauthorized("required scope is missing", nil)
}
roles := gatewayRoles(stringSliceClaim(claims, "roles"), v.config.RolePrefix)
if len(roles) == 0 {
roles = gatewayRoles(stringSliceClaim(claims, "role"), v.config.RolePrefix)
}
if len(roles) == 0 {
return nil, oidcUnauthorized("mapped role is missing", nil)
}
username := stringClaim(claims, "preferred_username")
if username == "" {
username = stringClaim(claims, "username")
}
return &User{
ID: stringClaim(claims, "sub"), Username: username, Roles: roles,
TenantID: v.config.TenantID, Source: "oidc",
}, nil
}
func oidcUnauthorized(reason string, cause error) error {
if cause != nil {
return fmt.Errorf("%w: %s: %v", ErrUnauthorized, reason, cause)
}
return fmt.Errorf("%w: %s", ErrUnauthorized, reason)
}
func (v *OIDCVerifier) key(ctx context.Context, kid string) (any, error) {
if err := v.refresh(ctx, false); err != nil {
return nil, err
}
v.mu.Lock()
key, ok := v.keys[kid]
v.mu.Unlock()
if ok {
return key, nil
}
if err := v.refresh(ctx, true); err != nil {
return nil, err
}
v.mu.Lock()
defer v.mu.Unlock()
key, ok = v.keys[kid]
if !ok {
return nil, errors.New("signing key not found")
}
return key, nil
}
func (v *OIDCVerifier) refresh(ctx context.Context, force bool) error {
v.mu.Lock()
defer v.mu.Unlock()
if !force && len(v.keys) > 0 && time.Now().Before(v.expiresAt) {
return nil
}
discoveryURL := v.config.Issuer + "/.well-known/openid-configuration"
var discovery discoveryDocument
if err := v.fetchJSON(ctx, discoveryURL, &discovery); err != nil {
return err
}
if discovery.Issuer != v.config.Issuer || validatePublicURL(discovery.JWKSURI) != nil {
return errors.New("OIDC discovery metadata is invalid")
}
var set jsonWebKeySet
if err := v.fetchJSON(ctx, discovery.JWKSURI, &set); err != nil {
return err
}
keys := make(map[string]any, len(set.Keys))
for _, item := range set.Keys {
if item.KID == "" || item.Use != "" && item.Use != "sig" {
continue
}
key, err := item.publicKey()
if err == nil {
keys[item.KID] = key
}
}
if len(keys) == 0 {
return errors.New("OIDC JWKS contains no supported signing keys")
}
v.keys = keys
v.expiresAt = time.Now().Add(v.config.JWKSCacheTTL)
return nil
}
func (v *OIDCVerifier) fetchJSON(ctx context.Context, endpoint string, output any) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return err
}
request.Header.Set("Accept", "application/json")
response, err := v.client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("OIDC endpoint returned HTTP %d", response.StatusCode)
}
payload, err := io.ReadAll(io.LimitReader(response.Body, maxOIDCResponseBytes+1))
if err != nil || len(payload) > maxOIDCResponseBytes {
return errors.New("OIDC response is invalid")
}
decoder := json.NewDecoder(strings.NewReader(string(payload)))
return decoder.Decode(output)
}
func (j jsonWebKey) publicKey() (any, error) {
switch {
case j.KTY == "RSA" && (j.Alg == "" || j.Alg == "RS256"):
n, err := decodeBigInt(j.N)
if err != nil {
return nil, err
}
e, err := decodeBigInt(j.E)
if err != nil || !e.IsInt64() || e.Int64() <= 0 {
return nil, errors.New("invalid RSA exponent")
}
return &rsa.PublicKey{N: n, E: int(e.Int64())}, nil
case j.KTY == "EC" && j.Crv == "P-256" && (j.Alg == "" || j.Alg == "ES256"):
x, err := decodeBigInt(j.X)
if err != nil {
return nil, err
}
y, err := decodeBigInt(j.Y)
if err != nil || !elliptic.P256().IsOnCurve(x, y) {
return nil, errors.New("invalid EC point")
}
return &ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}, nil
default:
return nil, errors.New("unsupported JWK")
}
}
func decodeBigInt(value string) (*big.Int, error) {
payload, err := base64.RawURLEncoding.DecodeString(value)
if err != nil || len(payload) == 0 {
return nil, errors.New("invalid JWK integer")
}
return new(big.Int).SetBytes(payload), nil
}
func validatePublicURL(raw string) error {
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
return errors.New("invalid URL")
}
if parsed.Scheme == "https" {
return nil
}
if parsed.Scheme == "http" && (parsed.Hostname() == "127.0.0.1" || parsed.Hostname() == "localhost") {
return nil
}
return errors.New("URL must use HTTPS")
}
func numericDateClaim(value any) (time.Time, bool) {
switch typed := value.(type) {
case float64:
return time.Unix(int64(typed), 0), true
case json.Number:
seconds, err := typed.Int64()
return time.Unix(seconds, 0), err == nil
default:
return time.Time{}, false
}
}
func scopeClaims(claims jwt.MapClaims) []string {
result := make([]string, 0)
seen := map[string]bool{}
for _, scope := range strings.Fields(stringClaim(claims, "scope")) {
if !seen[scope] {
result = append(result, scope)
seen[scope] = true
}
}
for _, scope := range stringSliceClaim(claims, "scp") {
if !seen[scope] {
result = append(result, scope)
seen[scope] = true
}
}
return result
}
func containsAll(actual, required []string) bool {
set := make(map[string]struct{}, len(actual))
for _, item := range actual {
set[item] = struct{}{}
}
for _, item := range required {
if _, ok := set[item]; !ok {
return false
}
}
return true
}
func gatewayRoles(external []string, prefix string) []string {
allowed := map[string]bool{"user": true, "creator": true, "operator": true, "manager": true, "admin": true}
roles := make([]string, 0, len(external))
seen := map[string]bool{}
for _, role := range external {
if !strings.HasPrefix(role, prefix) {
continue
}
local := strings.TrimPrefix(role, prefix)
if allowed[local] && !seen[local] {
roles = append(roles, local)
seen[local] = true
}
}
return roles
}
+142
View File
@@ -0,0 +1,142 @@
package auth
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"math/big"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
)
func TestOIDCVerifierAcceptsRS256AndES256StableClaims(t *testing.T) {
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
var issuer string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/.well-known/openid-configuration":
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "jwks_uri": issuer + "/jwks"})
case "/jwks":
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{
rsaJWK("rsa-key", &rsaKey.PublicKey), ecJWK("ec-key", &ecKey.PublicKey),
}})
default:
http.NotFound(w, request)
}
}))
defer server.Close()
issuer = server.URL
verifier, err := NewOIDCVerifier(OIDCConfig{
Issuer: issuer, Audience: "gateway-api", TenantID: "tenant-1",
RolePrefix: "gateway.", RequiredScopes: []string{"gateway.access"}, HTTPClient: server.Client(),
})
if err != nil {
t.Fatal(err)
}
for _, test := range []struct {
name string
kid string
method jwt.SigningMethod
key any
}{{"rs256", "rsa-key", jwt.SigningMethodRS256, rsaKey}, {"es256", "ec-key", jwt.SigningMethodES256, ecKey}} {
t.Run(test.name, func(t *testing.T) {
token := signedOIDCToken(t, issuer, test.kid, test.method, test.key, nil)
user, err := verifier.Verify(context.Background(), token)
if err != nil {
t.Fatal(err)
}
if user.ID != "platform-subject" || user.TenantID != "tenant-1" || user.Source != "oidc" ||
len(user.Roles) != 1 || user.Roles[0] != "admin" {
t.Fatalf("unexpected OIDC user: %#v", user)
}
})
}
}
func TestOIDCVerifierRejectsMissingOrMismatchedSecurityClaims(t *testing.T) {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
var issuer string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
if request.URL.Path == "/.well-known/openid-configuration" {
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "jwks_uri": issuer + "/jwks"})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{ecJWK("ec-key", &key.PublicKey)}})
}))
defer server.Close()
issuer = server.URL
verifier, _ := NewOIDCVerifier(OIDCConfig{
Issuer: issuer, Audience: "gateway-api", TenantID: "tenant-1", RolePrefix: "gateway.",
RequiredScopes: []string{"gateway.access"}, HTTPClient: server.Client(),
})
tests := []struct {
name string
mutate func(jwt.MapClaims)
}{
{"missing nbf", func(claims jwt.MapClaims) { delete(claims, "nbf") }},
{"wrong audience", func(claims jwt.MapClaims) { claims["aud"] = "other-api" }},
{"wrong tenant", func(claims jwt.MapClaims) { claims["tid"] = "tenant-2" }},
{"missing scope", func(claims jwt.MapClaims) { claims["scope"] = "openid" }},
{"unmapped role", func(claims jwt.MapClaims) { claims["roles"] = []string{"other.admin"} }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
raw := signedOIDCToken(t, issuer, "ec-key", jwt.SigningMethodES256, key, test.mutate)
if _, err := verifier.Verify(context.Background(), raw); err == nil {
t.Fatal("expected token to be rejected")
}
})
}
}
func signedOIDCToken(t *testing.T, issuer, kid string, method jwt.SigningMethod, key any, mutate func(jwt.MapClaims)) string {
t.Helper()
now := time.Now()
claims := jwt.MapClaims{
"iss": issuer, "aud": "gateway-api", "sub": "platform-subject", "tid": "tenant-1",
"preferred_username": "acceptance", "roles": []string{"gateway.admin"},
"scope": "openid gateway.access", "iat": now.Unix(), "nbf": now.Add(-time.Second).Unix(),
"exp": now.Add(time.Hour).Unix(),
}
if mutate != nil {
mutate(claims)
}
token := jwt.NewWithClaims(method, claims)
token.Header["kid"] = kid
raw, err := token.SignedString(key)
if err != nil {
t.Fatal(err)
}
return raw
}
func rsaJWK(kid string, key *rsa.PublicKey) map[string]any {
return map[string]any{
"kid": kid, "kty": "RSA", "use": "sig", "alg": "RS256",
"n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()),
"e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(key.E)).Bytes()),
}
}
func ecJWK(kid string, key *ecdsa.PublicKey) map[string]any {
return map[string]any{
"kid": kid, "kty": "EC", "use": "sig", "alg": "ES256", "crv": "P-256",
"x": base64.RawURLEncoding.EncodeToString(key.X.FillBytes(make([]byte, 32))),
"y": base64.RawURLEncoding.EncodeToString(key.Y.FillBytes(make([]byte, 32))),
}
}
+50
View File
@@ -0,0 +1,50 @@
package auth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestServerMainAPIKeyUsesSignedCurrentContract(t *testing.T) {
const key = "gateway-test"
const secret = "server-main-internal-secret"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
if request.URL.Path != "/internal/auth/verify-apikey" || request.Header.Get("X-Internal-Key") != key {
t.Fatalf("unexpected request %s", request.URL.Path)
}
body, _ := io.ReadAll(request.Body)
hash := sha256.Sum256(body)
text := strings.Join([]string{
request.Method, request.URL.RequestURI(), request.Header.Get("X-Timestamp"), request.Header.Get("X-Nonce"),
hex.EncodeToString(hash[:]), key,
}, "\n")
mac := hmac.New(sha256.New, []byte(secret))
_, _ = mac.Write([]byte(text))
if !hmac.Equal([]byte(request.Header.Get("X-Signature")), []byte(hex.EncodeToString(mac.Sum(nil)))) {
t.Fatal("invalid internal request signature")
}
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{"user": map[string]any{
"sub": "server-user", "username": "server", "role": []string{"user"}, "tenantId": "server-tenant",
}}})
}))
t.Cleanup(server.Close)
authenticator := New("jwt", server.URL, "")
authenticator.ServerMainInternalKey = key
authenticator.ServerMainInternalSecret = secret
request := httptest.NewRequest(http.MethodGet, "/api/v1/me", nil)
request.Header.Set("Authorization", "Bearer sk-server-main")
user, err := authenticator.Authenticate(request)
if err != nil {
t.Fatal(err)
}
if user.ID != "server-user" || user.Source != "server-main" || user.TenantID != "server-tenant" {
t.Fatalf("user = %#v", user)
}
}
+31
View File
@@ -21,6 +21,16 @@ type Config struct {
JWTSecret string
ServerMainBaseURL string
ServerMainInternalToken string
ServerMainInternalKey string
ServerMainInternalSecret string
OIDCEnabled bool
OIDCIssuer string
OIDCAudience string
OIDCTenantID string
OIDCRolePrefix string
OIDCRequiredScopes []string
OIDCJWKSCacheTTLSeconds int
OIDCAcceptLegacyHS256 bool
PublicBaseURL string
WebBaseURL string
LocalGeneratedStorageDir string
@@ -49,6 +59,16 @@ func Load() Config {
"/",
),
ServerMainInternalToken: env("SERVER_MAIN_INTERNAL_TOKEN", ""),
ServerMainInternalKey: env("SERVER_MAIN_INTERNAL_KEY", "gateway"),
ServerMainInternalSecret: env("SERVER_MAIN_INTERNAL_SECRET", env("SERVER_MAIN_INTERNAL_TOKEN", "")),
OIDCEnabled: env("OIDC_ENABLED", "false") == "true",
OIDCIssuer: strings.TrimRight(env("OIDC_ISSUER", ""), "/"),
OIDCAudience: env("OIDC_AUDIENCE", ""),
OIDCTenantID: env("OIDC_TENANT_ID", ""),
OIDCRolePrefix: env("OIDC_ROLE_PREFIX", "gateway."),
OIDCRequiredScopes: splitCSV(env("OIDC_REQUIRED_SCOPES", "gateway.access")),
OIDCJWKSCacheTTLSeconds: envInt("OIDC_JWKS_CACHE_TTL_SECONDS", 300),
OIDCAcceptLegacyHS256: env("OIDC_ACCEPT_LEGACY_HS256", "true") == "true",
PublicBaseURL: strings.TrimRight(env("AI_GATEWAY_PUBLIC_BASE_URL", env("PUBLIC_BASE_URL", "")), "/"),
WebBaseURL: strings.TrimRight(env("AI_GATEWAY_WEB_BASE_URL", env("GATEWAY_WEB_BASE_URL", env("PUBLIC_WEB_BASE_URL", ""))), "/"),
LocalGeneratedStorageDir: env("AI_GATEWAY_GENERATED_STORAGE_DIR", env("LOCAL_GENERATED_STORAGE_DIR", env("AI_GATEWAY_STATIC_STORAGE_DIR", DefaultLocalGeneratedStorageDir))),
@@ -121,6 +141,17 @@ func normalizePostgresURL(raw string) string {
return parsed.String()
}
func splitCSV(value string) []string {
items := strings.Split(value, ",")
result := make([]string, 0, len(items))
for _, item := range items {
if trimmed := strings.TrimSpace(item); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
func withDatabase(raw string, databaseName string) string {
parsed, err := url.Parse(raw)
if err != nil || databaseName == "" {
+15
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"strings"
"sync"
"time"
"github.com/easyai/easyai-ai-gateway/apps/api/internal/auth"
"github.com/easyai/easyai-ai-gateway/apps/api/internal/config"
@@ -36,6 +37,20 @@ func NewServerWithContext(ctx context.Context, cfg config.Config, db *store.Stor
runner: runner.New(cfg, db, logger),
logger: logger,
}
server.auth.LegacyJWTEnabled = !cfg.OIDCEnabled || cfg.OIDCAcceptLegacyHS256
server.auth.ServerMainInternalKey = cfg.ServerMainInternalKey
server.auth.ServerMainInternalSecret = cfg.ServerMainInternalSecret
if cfg.OIDCEnabled {
verifier, err := auth.NewOIDCVerifier(auth.OIDCConfig{
Issuer: cfg.OIDCIssuer, Audience: cfg.OIDCAudience, TenantID: cfg.OIDCTenantID,
RolePrefix: cfg.OIDCRolePrefix, RequiredScopes: cfg.OIDCRequiredScopes,
JWKSCacheTTL: time.Duration(cfg.OIDCJWKSCacheTTLSeconds) * time.Second,
})
if err != nil {
panic("invalid OIDC configuration: " + err.Error())
}
server.auth.OIDCVerifier = verifier
}
server.auth.LocalAPIKeyVerifier = db.VerifyLocalAPIKey
server.runner.StartAsyncQueueWorker(ctx)
server.startLocalTempAssetCleanup(ctx)