-
Notifications
You must be signed in to change notification settings - Fork 406
feat(grpc): add JWT-based authentication for inter-component RPC (#4417) #4488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sabarixr
wants to merge
7
commits into
dragonflyoss:main
Choose a base branch
from
sabarixr:feature/grpc-jwt-auth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ab4c0e4
rpc/auth: add HS256 JWT utilities, gRPC server interceptors, and per-…
sabarixr 9c75fc3
grpc(server): enforce JWT for Manager and Scheduler via unary/stream …
sabarixr d20ae5d
config(wiring): pass Manager/Scheduler auth.jwt.key into gRPC server …
sabarixr 405bed3
scheduler/config: add auth.jwt (realm, key, timeout, maxRefresh) with…
sabarixr e4f9c85
scheduler(client): attach JWT per-RPC credentials for Manager dials (…
sabarixr 8fc24ee
build: add github.com/golang-jwt/jwt/v5 dependency
sabarixr 8c6a0ad
fix(grpc/jwt): make JWT optional and address review feedback
sabarixr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| package auth | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "google.golang.org/grpc/credentials" | ||
| ) | ||
|
|
||
| // PerRPCCreds attaches a Bearer JWT to outgoing gRPC calls. | ||
| type PerRPCCreds struct { | ||
| token string | ||
| // If needed later, add refresh hooks. | ||
| } | ||
|
|
||
| // NewPerRPCCreds constructs credentials with a given token value. | ||
| func NewPerRPCCreds(token string) credentials.PerRPCCredentials { | ||
| return &PerRPCCreds{token: token} | ||
| } | ||
|
|
||
| func (c *PerRPCCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { | ||
| return map[string]string{ | ||
| "authorization": "Bearer " + c.token, | ||
| }, nil | ||
| } | ||
|
|
||
| // RequireTransportSecurity returns false for backward compatibility with existing deployments. | ||
| // In production, configure TLS separately via server.TLS config to secure JWT transmission. | ||
| func (c *PerRPCCreds) RequireTransportSecurity() bool { return false } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| package auth | ||
|
|
||
| import ( | ||
| "context" | ||
| "strings" | ||
|
|
||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/codes" | ||
| "google.golang.org/grpc/metadata" | ||
| "google.golang.org/grpc/status" | ||
| ) | ||
|
|
||
| // UnaryServerJWTInterceptor returns a unary server interceptor that validates JWT in metadata. | ||
| func UnaryServerJWTInterceptor(key string, expectedAudience string) grpc.UnaryServerInterceptor { | ||
| return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { | ||
| if err := validateFromMetadata(ctx, key, expectedAudience, info.FullMethod); err != nil { | ||
| return nil, err | ||
| } | ||
| return handler(ctx, req) | ||
| } | ||
| } | ||
|
|
||
| // StreamServerJWTInterceptor returns a stream server interceptor that validates JWT in metadata. | ||
| func StreamServerJWTInterceptor(key string, expectedAudience string) grpc.StreamServerInterceptor { | ||
| return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { | ||
| if err := validateFromMetadata(ss.Context(), key, expectedAudience, info.FullMethod); err != nil { | ||
| return err | ||
| } | ||
| return handler(srv, ss) | ||
| } | ||
| } | ||
|
|
||
| func validateFromMetadata(ctx context.Context, key string, expectedAudience string, method string) error { | ||
| // Skip auth for health checks and gRPC reflection to allow probes and debugging tools | ||
| if isPublicMethod(method) { | ||
| return nil | ||
| } | ||
|
|
||
| // If no key is configured, JWT auth is disabled (backward compatible) | ||
| if key == "" { | ||
| return nil | ||
| } | ||
|
|
||
| md, ok := metadata.FromIncomingContext(ctx) | ||
| if !ok { | ||
| return status.Error(codes.Unauthenticated, "missing metadata") | ||
| } | ||
| vals := md.Get("authorization") | ||
| if len(vals) == 0 { | ||
| return status.Error(codes.Unauthenticated, "missing authorization") | ||
| } | ||
| parts := strings.Fields(vals[0]) | ||
| if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { | ||
| return status.Error(codes.Unauthenticated, "invalid authorization header") | ||
| } | ||
| token := parts[1] | ||
| if _, err := ValidateHS256(key, token, expectedAudience); err != nil { | ||
| return status.Error(codes.Unauthenticated, err.Error()) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // isPublicMethod determines if a gRPC method should bypass JWT authentication. | ||
| // Health checks and reflection services are exempt to support infrastructure probes and debugging. | ||
| func isPublicMethod(method string) bool { | ||
| publicPrefixes := []string{ | ||
| "/grpc.health.v1.Health/", | ||
| "/grpc.reflection.v1alpha.ServerReflection/", | ||
| "/grpc.reflection.v1.ServerReflection/", | ||
| } | ||
| for _, prefix := range publicPrefixes { | ||
| if strings.HasPrefix(method, prefix) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| package auth | ||
|
|
||
| import ( | ||
| "errors" | ||
| "sync" | ||
| "time" | ||
|
|
||
| jwtlib "github.com/golang-jwt/jwt/v5" | ||
| ) | ||
|
|
||
| // Claims is a minimal JWT claims set used for inter-component gRPC auth. | ||
| type Claims struct { | ||
| Issuer string `json:"iss"` | ||
| Audience string `json:"aud"` | ||
| IssuedAt time.Time `json:"iat"` | ||
| Expires time.Time `json:"exp"` | ||
| } | ||
|
|
||
| // Global registry for per-component server keys with thread-safe access. | ||
| // This allows components to register their JWT keys at startup for use in interceptors. | ||
| var ( | ||
| serverKeysMu sync.RWMutex | ||
| serverKeys = map[string]string{} | ||
| ) | ||
|
|
||
| // SetServerKey sets the shared signing key for a component's server (e.g., "manager", "scheduler"). | ||
| func SetServerKey(component, key string) { | ||
| serverKeysMu.Lock() | ||
| defer serverKeysMu.Unlock() | ||
| serverKeys[component] = key | ||
| } | ||
|
|
||
| // GetServerKey retrieves the key for a component server. | ||
| func GetServerKey(component string) string { | ||
| serverKeysMu.RLock() | ||
| defer serverKeysMu.RUnlock() | ||
| return serverKeys[component] | ||
| } | ||
|
|
||
| // SignHS256 signs the provided claims with the given shared secret key using HS256. | ||
| func SignHS256(key string, c Claims) (string, error) { | ||
| if key == "" { | ||
| return "", errors.New("jwt: empty signing key") | ||
| } | ||
| claims := jwtlib.MapClaims{ | ||
| "iss": c.Issuer, | ||
| "aud": c.Audience, | ||
| "iat": c.IssuedAt.Unix(), | ||
| "exp": c.Expires.Unix(), | ||
| } | ||
| token := jwtlib.NewWithClaims(jwtlib.SigningMethodHS256, claims) | ||
| return token.SignedString([]byte(key)) | ||
| } | ||
|
|
||
| // ValidateHS256 validates token signature and basic claims. Returns parsed claims. | ||
| func ValidateHS256(key string, tokenStr string, expectedAudience string) (Claims, error) { | ||
| var out Claims | ||
| if key == "" { | ||
| return out, errors.New("jwt: empty validation key") | ||
| } | ||
| parser := jwtlib.NewParser(jwtlib.WithValidMethods([]string{jwtlib.SigningMethodHS256.Alg()})) | ||
| token, err := parser.Parse(tokenStr, func(t *jwtlib.Token) (any, error) { | ||
| return []byte(key), nil | ||
| }) | ||
| if err != nil || !token.Valid { | ||
| return out, errors.New("jwt: invalid token") | ||
| } | ||
| claims, ok := token.Claims.(jwtlib.MapClaims) | ||
| if !ok { | ||
| return out, errors.New("jwt: invalid claims type") | ||
| } | ||
| // Audience check | ||
| if audAny, ok := claims["aud"]; ok { | ||
| if audStr, ok := audAny.(string); ok { | ||
| if expectedAudience != "" && audStr != expectedAudience { | ||
| return out, errors.New("jwt: audience mismatch") | ||
| } | ||
| out.Audience = audStr | ||
| } | ||
| } | ||
| // Issuer | ||
| if issAny, ok := claims["iss"]; ok { | ||
| if issStr, ok := issAny.(string); ok { | ||
| out.Issuer = issStr | ||
| } | ||
| } | ||
| // Time checks | ||
| now := time.Now() | ||
| if expAny, ok := claims["exp"]; ok { | ||
| switch v := expAny.(type) { | ||
| case float64: | ||
| out.Expires = time.Unix(int64(v), 0) | ||
| case int64: | ||
| out.Expires = time.Unix(v, 0) | ||
| case uint64: | ||
| out.Expires = time.Unix(int64(v), 0) | ||
| } | ||
| if now.After(out.Expires) { | ||
| return out, errors.New("jwt: token expired") | ||
| } | ||
| } | ||
| if iatAny, ok := claims["iat"]; ok { | ||
| switch v := iatAny.(type) { | ||
| case float64: | ||
| out.IssuedAt = time.Unix(int64(v), 0) | ||
| case int64: | ||
| out.IssuedAt = time.Unix(v, 0) | ||
| } | ||
| } | ||
| return out, nil | ||
| } | ||
|
|
||
| // DurationClaims constructs Claims with given ttl. | ||
| func DurationClaims(issuer, audience string, ttl time.Duration) Claims { | ||
| now := time.Now() | ||
| return Claims{ | ||
| Issuer: issuer, | ||
| Audience: audience, | ||
| IssuedAt: now, | ||
| Expires: now.Add(ttl), | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The interceptors will enforce JWT authentication on ALL gRPC endpoints, including health checks and reflection services. This will break health check probes (e.g., Kubernetes liveness/readiness probes) and gRPC reflection tools that typically don't provide authentication.
Consider allowing certain methods to bypass authentication:
Alternatively, use per-service interceptors instead of global ones to exclude health/reflection services.