|
| 1 | +package options |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/tls" |
| 6 | + "crypto/x509" |
| 7 | + "fmt" |
| 8 | + "google.golang.org/grpc" |
| 9 | + "google.golang.org/grpc/credentials" |
| 10 | + "google.golang.org/grpc/keepalive" |
| 11 | + "open-cluster-management.io/sdk-go/pkg/cloudevents/generic/types" |
| 12 | + "open-cluster-management.io/sdk-go/pkg/cloudevents/server" |
| 13 | + grpcserver "open-cluster-management.io/sdk-go/pkg/cloudevents/server/grpc" |
| 14 | + "open-cluster-management.io/sdk-go/pkg/cloudevents/server/grpc/authn" |
| 15 | + "os" |
| 16 | +) |
| 17 | + |
| 18 | +// PreStartHook is an interface to start hook before grpc server is started. |
| 19 | +type PreStartHook interface { |
| 20 | + // Start should be a non-blocking call |
| 21 | + Run(ctx context.Context) |
| 22 | +} |
| 23 | + |
| 24 | +type Server struct { |
| 25 | + options *GRPCServerOptions |
| 26 | + authenticators []authn.Authenticator |
| 27 | + services map[types.CloudEventsDataType]server.Service |
| 28 | + hooks []PreStartHook |
| 29 | +} |
| 30 | + |
| 31 | +func NewServer(opt *GRPCServerOptions) *Server { |
| 32 | + return &Server{options: opt, services: make(map[types.CloudEventsDataType]server.Service)} |
| 33 | +} |
| 34 | + |
| 35 | +func (s *Server) WithAuthenticator(authenticator authn.Authenticator) *Server { |
| 36 | + s.authenticators = append(s.authenticators, authenticator) |
| 37 | + return s |
| 38 | +} |
| 39 | + |
| 40 | +func (s *Server) WithService(t types.CloudEventsDataType, service server.Service) *Server { |
| 41 | + s.services[t] = service |
| 42 | + return s |
| 43 | +} |
| 44 | + |
| 45 | +func (s *Server) WithPreStartHooks(hooks ...PreStartHook) *Server { |
| 46 | + s.hooks = append(s.hooks, hooks...) |
| 47 | + return s |
| 48 | +} |
| 49 | + |
| 50 | +func (s *Server) Run(ctx context.Context) error { |
| 51 | + var grpcServerOptions []grpc.ServerOption |
| 52 | + grpcServerOptions = append(grpcServerOptions, grpc.MaxRecvMsgSize(s.options.MaxReceiveMessageSize)) |
| 53 | + grpcServerOptions = append(grpcServerOptions, grpc.MaxSendMsgSize(s.options.MaxSendMessageSize)) |
| 54 | + grpcServerOptions = append(grpcServerOptions, grpc.MaxConcurrentStreams(s.options.MaxConcurrentStreams)) |
| 55 | + grpcServerOptions = append(grpcServerOptions, grpc.ConnectionTimeout(s.options.ConnectionTimeout)) |
| 56 | + grpcServerOptions = append(grpcServerOptions, grpc.WriteBufferSize(s.options.WriteBufferSize)) |
| 57 | + grpcServerOptions = append(grpcServerOptions, grpc.ReadBufferSize(s.options.ReadBufferSize)) |
| 58 | + grpcServerOptions = append(grpcServerOptions, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ |
| 59 | + MinTime: s.options.ClientMinPingInterval, |
| 60 | + PermitWithoutStream: s.options.PermitPingWithoutStream, |
| 61 | + })) |
| 62 | + grpcServerOptions = append(grpcServerOptions, grpc.KeepaliveParams(keepalive.ServerParameters{ |
| 63 | + MaxConnectionAge: s.options.MaxConnectionAge, |
| 64 | + Time: s.options.ServerPingInterval, |
| 65 | + Timeout: s.options.ServerPingTimeout, |
| 66 | + })) |
| 67 | + |
| 68 | + // Serve with TLS |
| 69 | + serverCerts, err := tls.LoadX509KeyPair(s.options.TLSCertFile, s.options.TLSKeyFile) |
| 70 | + if err != nil { |
| 71 | + return fmt.Errorf("failed to load broker certificates: %v", err) |
| 72 | + } |
| 73 | + tlsConfig := &tls.Config{ |
| 74 | + Certificates: []tls.Certificate{serverCerts}, |
| 75 | + MinVersion: tls.VersionTLS13, |
| 76 | + MaxVersion: tls.VersionTLS13, |
| 77 | + } |
| 78 | + |
| 79 | + if s.options.ClientCAFile != "" { |
| 80 | + certPool, err := x509.SystemCertPool() |
| 81 | + if err != nil { |
| 82 | + return fmt.Errorf("failed to load system cert pool: %v", err) |
| 83 | + } |
| 84 | + caPEM, err := os.ReadFile(s.options.ClientCAFile) |
| 85 | + if err != nil { |
| 86 | + return fmt.Errorf("failed to read broker client CA file: %v", err) |
| 87 | + } |
| 88 | + if ok := certPool.AppendCertsFromPEM(caPEM); !ok { |
| 89 | + return fmt.Errorf("failed to append broker client CA to cert pool") |
| 90 | + } |
| 91 | + tlsConfig.ClientCAs = certPool |
| 92 | + tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven |
| 93 | + } |
| 94 | + |
| 95 | + grpcServerOptions = append(grpcServerOptions, grpc.Creds(credentials.NewTLS(tlsConfig))) |
| 96 | + |
| 97 | + grpcServerOptions = append(grpcServerOptions, |
| 98 | + grpc.ChainUnaryInterceptor(newAuthUnaryInterceptor(s.authenticators...)), |
| 99 | + grpc.ChainStreamInterceptor(newAuthStreamInterceptor(s.authenticators...))) |
| 100 | + |
| 101 | + grpcServer := grpc.NewServer(grpcServerOptions...) |
| 102 | + grpcEventServer := grpcserver.NewGRPCBroker(grpcServer, ":"+s.options.ServerBindPort) |
| 103 | + |
| 104 | + for t, service := range s.services { |
| 105 | + grpcEventServer.RegisterService(t, service) |
| 106 | + } |
| 107 | + |
| 108 | + // start hook |
| 109 | + for _, hook := range s.hooks { |
| 110 | + hook.Run(ctx) |
| 111 | + } |
| 112 | + |
| 113 | + go grpcEventServer.Start(ctx) |
| 114 | + <-ctx.Done() |
| 115 | + return nil |
| 116 | +} |
| 117 | + |
| 118 | +func newAuthUnaryInterceptor(authenticators ...authn.Authenticator) grpc.UnaryServerInterceptor { |
| 119 | + return func( |
| 120 | + ctx context.Context, |
| 121 | + req interface{}, |
| 122 | + info *grpc.UnaryServerInfo, |
| 123 | + handler grpc.UnaryHandler, |
| 124 | + ) (interface{}, error) { |
| 125 | + var err error |
| 126 | + for _, authenticator := range authenticators { |
| 127 | + ctx, err = authenticator.Authenticate(ctx) |
| 128 | + if err == nil { |
| 129 | + return handler(ctx, req) |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + if err != nil { |
| 134 | + return nil, err |
| 135 | + } |
| 136 | + |
| 137 | + return handler(ctx, req) |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +// wrappedAuthStream wraps a grpc.ServerStream associated with an incoming RPC, and |
| 142 | +// a custom context containing the user and groups derived from the client certificate |
| 143 | +// specified in the incoming RPC metadata |
| 144 | +type wrappedAuthStream struct { |
| 145 | + grpc.ServerStream |
| 146 | + ctx context.Context |
| 147 | +} |
| 148 | + |
| 149 | +// Context returns the context associated with the stream |
| 150 | +func (w *wrappedAuthStream) Context() context.Context { |
| 151 | + return w.ctx |
| 152 | +} |
| 153 | + |
| 154 | +// newWrappedAuthStream creates a new wrappedAuthStream |
| 155 | +func newWrappedAuthStream(ctx context.Context, s grpc.ServerStream) grpc.ServerStream { |
| 156 | + return &wrappedAuthStream{s, ctx} |
| 157 | +} |
| 158 | + |
| 159 | +// newAuthStreamInterceptor creates a stream interceptor that retrieves the user and groups |
| 160 | +// based on the specified authentication type. It supports retrieving from either the access |
| 161 | +// token or the client certificate depending on the provided authNType. |
| 162 | +// The interceptor then adds the retrieved identity information (user and groups) to the |
| 163 | +// context and invokes the provided handler. |
| 164 | +func newAuthStreamInterceptor(authenticators ...authn.Authenticator) grpc.StreamServerInterceptor { |
| 165 | + return func( |
| 166 | + srv interface{}, |
| 167 | + ss grpc.ServerStream, |
| 168 | + info *grpc.StreamServerInfo, |
| 169 | + handler grpc.StreamHandler, |
| 170 | + ) error { |
| 171 | + var err error |
| 172 | + ctx := ss.Context() |
| 173 | + for _, authenticator := range authenticators { |
| 174 | + ctx, err = authenticator.Authenticate(ctx) |
| 175 | + if err == nil { |
| 176 | + return handler(srv, newWrappedAuthStream(ctx, ss)) |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + if err != nil { |
| 181 | + return err |
| 182 | + } |
| 183 | + |
| 184 | + return handler(srv, newWrappedAuthStream(ctx, ss)) |
| 185 | + } |
| 186 | +} |
0 commit comments