2019-07-31 12:57:13 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package grpcauth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
|
|
|
|
"storj.io/storj/pkg/auth"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewAPIKeyInterceptor creates instance of apikey interceptor
|
|
|
|
func NewAPIKeyInterceptor() grpc.UnaryServerInterceptor {
|
|
|
|
return InterceptAPIKey
|
|
|
|
}
|
|
|
|
|
|
|
|
// InterceptAPIKey reads apikey from requests and puts the value into the context.
|
|
|
|
func InterceptAPIKey(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
|
|
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
apikeys, ok := md["apikey"]
|
|
|
|
if !ok || len(apikeys) == 0 {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
return handler(auth.WithAPIKey(ctx, []byte(apikeys[0])), req)
|
|
|
|
}
|
|
|
|
|
2019-09-19 17:19:29 +01:00
|
|
|
// DeprecatedAPIKeyCredentials implements grpc/credentials.PerRPCCredentials
|
|
|
|
// for authenticating with the grpc server. This does not work with drpc.
|
|
|
|
type DeprecatedAPIKeyCredentials struct {
|
2019-07-31 12:57:13 +01:00
|
|
|
value string
|
|
|
|
}
|
|
|
|
|
2019-09-19 17:19:29 +01:00
|
|
|
// NewDeprecatedAPIKeyCredentials returns a new DeprecatedAPIKeyCredentials
|
|
|
|
func NewDeprecatedAPIKeyCredentials(apikey string) *DeprecatedAPIKeyCredentials {
|
|
|
|
return &DeprecatedAPIKeyCredentials{apikey}
|
2019-07-31 12:57:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetRequestMetadata gets the current request metadata, refreshing tokens if required.
|
2019-09-19 17:19:29 +01:00
|
|
|
func (creds *DeprecatedAPIKeyCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
|
2019-07-31 12:57:13 +01:00
|
|
|
return map[string]string{
|
|
|
|
"apikey": creds.value,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequireTransportSecurity indicates whether the credentials requires transport security.
|
2019-09-19 17:19:29 +01:00
|
|
|
func (creds *DeprecatedAPIKeyCredentials) RequireTransportSecurity() bool {
|
|
|
|
return false // Deprecated anyway, but how was this the right choice?
|
2019-07-31 12:57:13 +01:00
|
|
|
}
|