larry-zy commented on code in PR #1609:
URL: https://github.com/apache/dubbo-admin/pull/1609#discussion_r4376650185


##########
ai/component/server/engine/auth.go:
##########
@@ -0,0 +1,284 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package engine
+
+import (
+       "context"
+       "crypto/rsa"
+       "encoding/base64"
+       "errors"
+       "fmt"
+       "math/big"
+       "net/http"
+       "strings"
+       "sync"
+       "time"
+
+       "dubbo-admin-ai/security"
+
+       "github.com/gin-gonic/gin"
+       "github.com/golang-jwt/jwt/v5"
+)
+
+const jwtClaimsContextKey = "dubbo-admin-ai.jwt-claims"
+
+// Cache lifetime after success and retry cooldown after failure.
+const jwksRefreshInterval = 30 * time.Second
+
+type jwksRefresh struct {
+       done chan struct{}
+       err  error
+}
+
+type JWTAuthConfig struct {
+       JWKSURL  string
+       Issuer   string
+       Audience string
+       // TenantID is the trusted deployment tenant for tokens without 
tenant_id.
+       // Leave empty to require a signed tenant_id claim.
+       TenantID string
+}
+
+type Claims struct {
+       jwt.RegisteredClaims
+       TenantID string   `json:"tenant_id"`
+       Scopes   []string `json:"scopes"`
+       Username string   `json:"username"`
+       Email    string   `json:"email"`
+       Groups   []string `json:"groups"`
+       Roles    []string `json:"roles"`
+       AuthType string   `json:"auth_type"`
+       Provider string   `json:"provider"`
+}
+
+type JWTVerifier struct {
+       config      JWTAuthConfig
+       client      *JWKSClient
+       mu          sync.RWMutex
+       keys        map[string]*rsa.PublicKey
+       nextRefresh time.Time
+       now         func() time.Time
+       refreshing  *jwksRefresh
+}
+
+// NewJWTVerifier deliberately fails startup if Admin JWKS is unavailable.
+// Subsequent requests share the bounded refresh cache and cooldown.
+func NewJWTVerifier(config JWTAuthConfig, client *http.Client) (*JWTVerifier, 
error) {
+       verifier := &JWTVerifier{config: config, client: 
NewJWKSClient(config.JWKSURL, client), keys: map[string]*rsa.PublicKey{}}
+       if err := verifier.refresh(context.Background()); err != nil {
+               return nil, fmt.Errorf("load remote JWKS: %w", err)
+       }
+       return verifier, nil
+}
+
+// Authenticate implements the router's trusted identity boundary.
+func (v *JWTVerifier) Authenticate(r *http.Request) (security.AccessContext, 
error) {
+       claims, err := v.verify(r)
+       if err != nil {
+               return security.AccessContext{}, err
+       }
+       return v.accessContext(claims)
+}
+
+func (v *JWTVerifier) verify(r *http.Request) (*Claims, error) {
+       if v == nil || r == nil {
+               return nil, security.ErrAuthenticationRequired
+       }
+       parts := strings.Fields(r.Header.Get("Authorization"))
+       if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
+               return nil, security.ErrAuthenticationRequired
+       }
+       claims := &Claims{}
+       token, err := jwt.ParseWithClaims(parts[1], claims, func(token 
*jwt.Token) (any, error) {
+               return v.keyForToken(r.Context(), token)
+       }, jwt.WithValidMethods([]string{jwt.SigningMethodRS256.Alg()}),
+               jwt.WithIssuer(v.config.Issuer), 
jwt.WithAudience(v.config.Audience),
+               jwt.WithExpirationRequired(), jwt.WithIssuedAt(), 
jwt.WithLeeway(30*time.Second))
+       if err != nil || token == nil || !token.Valid || 
strings.TrimSpace(claims.Subject) == "" || claims.IssuedAt == nil {
+               return nil, security.ErrAuthenticationRequired
+       }
+       return claims, nil
+}
+
+func (v *JWTVerifier) accessContext(claims *Claims) (security.AccessContext, 
error) {
+       tenantID := claims.TenantID
+       if tenantID == "" {
+               tenantID = v.config.TenantID
+       }
+       return security.NewAccessContext(security.Subject{TenantID: tenantID, 
UserID: claims.Subject,
+               Roles: claims.Roles, Scopes: claims.Scopes, AuthMethod: 
security.AuthMethodJWT})
+}
+
+func (v *JWTVerifier) Middleware() gin.HandlerFunc {
+       return func(c *gin.Context) {
+               // Explicit public probes only; all other paths require 
authentication.
+               switch c.Request.URL.Path {
+               case "/health", "/healthz", "/readyz":
+                       c.Next()
+                       return
+               }
+               if c.Request.Method == http.MethodOptions {
+                       c.Next()
+                       return
+               }
+               claims, err := v.verify(c.Request)
+               if err != nil {
+                       abortUnauthorized(c)
+                       return
+               }
+               access, err := v.accessContext(claims)
+               if err != nil {
+                       abortUnauthorized(c)
+                       return
+               }
+               c.Set(jwtClaimsContextKey, claims)
+               c.Request = 
c.Request.WithContext(security.WithAccessContext(c.Request.Context(), access))
+               c.Next()
+       }
+}
+
+func ClaimsFromContext(c *gin.Context) (*Claims, bool) {
+       value, ok := c.Get(jwtClaimsContextKey)
+       if !ok {
+               return nil, false
+       }
+       claims, ok := value.(*Claims)
+       return claims, ok
+}
+
+func (v *JWTVerifier) keyForToken(ctx context.Context, token *jwt.Token) (any, 
error) {
+       if token.Method != jwt.SigningMethodRS256 {
+               return nil, errors.New("only RS256 is accepted")
+       }
+       kid, ok := token.Header["kid"].(string)
+       if !ok || kid == "" {
+               return nil, errors.New("JWT kid is missing")
+       }
+       v.mu.RLock()
+       key := v.keys[kid]
+       fresh := v.clock().Before(v.nextRefresh)
+       v.mu.RUnlock()
+       if fresh {
+               if key == nil {
+                       return nil, errors.New("JWT kid is unknown")
+               }
+               return key, nil
+       }
+       if err := v.refresh(ctx); err != nil {
+               return nil, err
+       }
+       v.mu.RLock()
+       key = v.keys[kid]
+       fresh = v.clock().Before(v.nextRefresh)
+       v.mu.RUnlock()
+       if !fresh {
+               return nil, errors.New("JWKS cache expired")
+       }
+       if key == nil {
+               return nil, fmt.Errorf("JWT kid %q is unknown", kid)
+       }
+       return key, nil
+}
+
+func (v *JWTVerifier) clock() time.Time {
+       if v.now != nil {
+               return v.now()
+       }
+       return time.Now()
+}
+
+func (v *JWTVerifier) refresh(ctx context.Context) error {
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       v.mu.Lock()
+       if flight := v.refreshing; flight != nil {
+               v.mu.Unlock()
+               select {
+               case <-ctx.Done():
+                       return ctx.Err()
+               case <-flight.done:
+                       return flight.err
+               }
+       }
+       if v.clock().Before(v.nextRefresh) {
+               v.mu.Unlock()
+               return nil // Use the cache, or reject if a failed refresh left 
it empty.
+       }
+       flight := &jwksRefresh{done: make(chan struct{})}
+       v.refreshing = flight
+       // Expired keys must not remain usable when refreshing fails.
+       v.keys = nil
+       v.mu.Unlock()
+
+       // All concurrent misses share this attempt. The initiating request 
owns its
+       // context; cancellation also ends the fetch for the waiting requests.
+       err := v.fetchKeys(ctx)
+       v.mu.Lock()
+       flight.err = err
+       v.nextRefresh = v.clock().Add(jwksRefreshInterval)

Review Comment:
   [P2] Keep request cancellation from starting a shared authentication cooldown
   
   The refresh uses the initiating HTTP request context and then advances 
`nextRefresh` by 30 seconds for every error, including that request being 
canceled; the shared keys have already been cleared. After cache expiry, a 
parseable, unsigned JWT with an unknown `kid` can reach this path before 
authentication succeeds. If that client disconnects during the fetch, 
subsequent valid-token requests fail for the whole cooldown without trying the 
healthy JWKS endpoint. I reproduced this with a local endpoint that succeeds at 
startup, blocks only the canceled refresh, and is healthy thereafter: a 
previously accepted token is rejected and no third JWKS request occurs. Please 
give the shared refresh its own bounded lifetime, or allow a fresh caller to 
retry immediately after request-scoped cancellation, while preserving the 
expired-key rejection.



##########
ai/component/server/engine/auth.go:
##########
@@ -0,0 +1,284 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package engine
+
+import (
+       "context"
+       "crypto/rsa"
+       "encoding/base64"
+       "errors"
+       "fmt"
+       "math/big"
+       "net/http"
+       "strings"
+       "sync"
+       "time"
+
+       "dubbo-admin-ai/security"
+
+       "github.com/gin-gonic/gin"
+       "github.com/golang-jwt/jwt/v5"
+)
+
+const jwtClaimsContextKey = "dubbo-admin-ai.jwt-claims"
+
+// Cache lifetime after success and retry cooldown after failure.
+const jwksRefreshInterval = 30 * time.Second
+
+type jwksRefresh struct {
+       done chan struct{}
+       err  error
+}
+
+type JWTAuthConfig struct {
+       JWKSURL  string
+       Issuer   string
+       Audience string
+       // TenantID is the trusted deployment tenant for tokens without 
tenant_id.
+       // Leave empty to require a signed tenant_id claim.
+       TenantID string
+}
+
+type Claims struct {
+       jwt.RegisteredClaims
+       TenantID string   `json:"tenant_id"`
+       Scopes   []string `json:"scopes"`
+       Username string   `json:"username"`
+       Email    string   `json:"email"`
+       Groups   []string `json:"groups"`
+       Roles    []string `json:"roles"`
+       AuthType string   `json:"auth_type"`
+       Provider string   `json:"provider"`
+}
+
+type JWTVerifier struct {
+       config      JWTAuthConfig
+       client      *JWKSClient
+       mu          sync.RWMutex
+       keys        map[string]*rsa.PublicKey
+       nextRefresh time.Time
+       now         func() time.Time
+       refreshing  *jwksRefresh
+}
+
+// NewJWTVerifier deliberately fails startup if Admin JWKS is unavailable.
+// Subsequent requests share the bounded refresh cache and cooldown.
+func NewJWTVerifier(config JWTAuthConfig, client *http.Client) (*JWTVerifier, 
error) {
+       verifier := &JWTVerifier{config: config, client: 
NewJWKSClient(config.JWKSURL, client), keys: map[string]*rsa.PublicKey{}}
+       if err := verifier.refresh(context.Background()); err != nil {
+               return nil, fmt.Errorf("load remote JWKS: %w", err)
+       }
+       return verifier, nil
+}
+
+// Authenticate implements the router's trusted identity boundary.
+func (v *JWTVerifier) Authenticate(r *http.Request) (security.AccessContext, 
error) {
+       claims, err := v.verify(r)
+       if err != nil {
+               return security.AccessContext{}, err
+       }

Review Comment:
   [P2] Apply the public-probe exception on the actual Router authentication 
path
   
   The production Router installs `authenticationMiddleware(r.authenticator)` 
globally and invokes this `Authenticate` method; it never installs 
`JWTVerifier.Middleware()`. Consequently, the public `/health` exception in 
`Middleware()` is unused. `ServerComponent.Start` registers `/health` on the 
same engine, so enabling JWT makes a tokenless health probe return 401 and can 
make a healthy deployment fail its readiness/liveness checks. I reproduced the 
401 using `NewRouter` with a real JWKS verifier and the health registration 
used by `Start`. Please exempt the explicit public probes in the middleware 
actually used by the Router and add an integration test through that Router; 
the standalone verifier-middleware tests do not cover this wiring.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to