Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: add authentication interceptor (#4033)
Danny Xu539cbf3d0f17
diff --git a/common/context.go b/common/context.gonew file mode 100644index 0000000000..38e9dd7130--- /dev/null+++ b/common/context.go@@ -0,0 +1,9 @@+package common++// ContextKey is the key type of context value.+type ContextKey int++const (+ // PrincipalIDContextKey is the key name used to store principal id in the context.+ PrincipalIDContextKey ContextKey = iota+)diff --git a/server/api/auth/auth.go b/server/api/auth/auth.gonew file mode 100644index 0000000000..f5602622e0--- /dev/null+++ b/server/api/auth/auth.go@@ -0,0 +1,117 @@+// Package auth handles the auth of gRPC server.+package auth++import (+ "context"+ "errors"+ "fmt"+ "strconv"+ "strings"++ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/metadata"+ "google.golang.org/grpc/status"++ "github.com/golang-jwt/jwt/v4"++ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/store"+)++const (+ accessTokenAudienceFmt = "bb.user.access.%s"+)++// APIAuthInterceptor is the auth interceptor for gRPC server.+type APIAuthInterceptor struct {+ store *store.Store+ secret string+ mode common.ReleaseMode+}++// New returns a new API auth interceptor.+func New(store *store.Store, secret string, mode common.ReleaseMode) *APIAuthInterceptor {+ return &APIAuthInterceptor{+ store: store,+ secret: secret,+ mode: mode,+ }+}++// UnaryInterceptor is the unary interceptor for gRPC API.+func (in *APIAuthInterceptor) UnaryInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {+ // TODO(d): skips auth, actuator, GET /subscription request, OpenAPI SQL endpoint.+ md, ok := metadata.FromIncomingContext(ctx)+ if !ok {+ return nil, status.Error(codes.PermissionDenied, "failed to parse metadata from incoming context")+ }+ if len(md.Get("Authorization")) == 0 {+ return nil, status.Error(codes.PermissionDenied, "failed to get authorization metadata from incoming context")+ }+ authorization := md.Get("Authorization")[0]+ authHeaderParts := strings.Fields(authorization)+ if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {+ return nil, status.Error(codes.PermissionDenied, "authorization header format must be Bearer {token}")+ }+ token := authHeaderParts[1]++ claims := &claims{}+ if _, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {+ if t.Method.Alg() != jwt.SigningMethodHS256.Name {+ return nil, status.Errorf(codes.PermissionDenied, "unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)+ }+ if kid, ok := t.Header["kid"].(string); ok {+ if kid == "v1" {+ return []byte(in.secret), nil+ }+ }+ return nil, status.Errorf(codes.PermissionDenied, "unexpected access token kid=%v", t.Header["kid"])+ }); err != nil {+ var ve *jwt.ValidationError+ if errors.As(err, &ve) {+ // If expiration error is the only error, we will clear the err+ // and generate new access token and refresh token+ if ve.Errors == jwt.ValidationErrorExpired {+ return nil, status.Errorf(codes.PermissionDenied, "access token is expired")+ }+ }+ return nil, status.Errorf(codes.PermissionDenied, "failed to parse claim")+ }+ if !audienceContains(claims.Audience, fmt.Sprintf(accessTokenAudienceFmt, in.mode)) {+ return nil, status.Errorf(codes.PermissionDenied,+ "invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",+ claims.Audience,+ fmt.Sprintf(accessTokenAudienceFmt, in.mode),+ )+ }++ principalID, err := strconv.Atoi(claims.Subject)+ if err != nil {+ return nil, status.Errorf(codes.PermissionDenied, "malformed ID %q in the access token", claims.Subject)+ }+ user, err := in.store.GetPrincipalByID(ctx, principalID)+ if err != nil {+ return nil, status.Errorf(codes.PermissionDenied, "failed to find user ID %q in the access token", principalID)+ }+ if user == nil {+ return nil, status.Errorf(codes.PermissionDenied, "user ID %q not exists in the access token", principalID)+ }+ // Stores principalID into context.+ childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, principalID)+ return handler(childCtx, req)+}++func audienceContains(audience jwt.ClaimStrings, token string) bool {+ for _, v := range audience {+ if v == token {+ return true+ }+ }+ return false+}++type claims struct {+ Name string `json:"name"`+ jwt.RegisteredClaims+}diff --git a/server/api/v1/hello_service.go b/server/api/v1/hello_service.goindex 9abd55e1cb..a05d1cbfdc 100644--- a/server/api/v1/hello_service.go+++ b/server/api/v1/hello_service.go@@ -4,6 +4,7 @@ import ("context""fmt"+ "github.com/bytebase/bytebase/common"gw "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -13,8 +14,9 @@ type GreeterServerImpl struct {}// Hello is the implementation of Greater Hello method.-func (*GreeterServerImpl) Hello(_ context.Context, request *gw.HelloRequest) (*gw.HelloResponse, error) {+func (*GreeterServerImpl) Hello(ctx context.Context, request *gw.HelloRequest) (*gw.HelloResponse, error) {+ principalID := ctx.Value(common.PrincipalIDContextKey).(int)return &gw.HelloResponse{- Answer: fmt.Sprintf("hello %s", request.Name),+ Answer: fmt.Sprintf("hello %s from %v", request.Name, principalID),}, nil}diff --git a/server/server.go b/server/server.goindex 027f520bff..666fdd1f78 100644--- a/server/server.go+++ b/server/server.go@@ -40,6 +40,7 @@ import ("github.com/bytebase/bytebase/resources/mongoutil""github.com/bytebase/bytebase/resources/mysqlutil""github.com/bytebase/bytebase/resources/postgres"+ "github.com/bytebase/bytebase/server/api/auth"apiv1 "github.com/bytebase/bytebase/server/api/v1""github.com/bytebase/bytebase/server/component/activity""github.com/bytebase/bytebase/server/component/config"@@ -294,7 +295,8 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {}))// Setup the gRPC and grpc-gateway.- s.grpcServer = grpc.NewServer()+ authProvider := auth.New(s.store, s.secret, profile.Mode)+ s.grpcServer = grpc.NewServer(grpc.UnaryInterceptor(authProvider.UnaryInterceptor))mux := runtime.NewServeMux()if err := apiv1.Register(ctx, s.grpcServer, mux, profile.GrpcPort); err != nil {return nil, err