storj/pkg/auth/grpcauth/apikey.go
JT Olio 946ec201e2
metainfo: move api keys to part of the request (#3069)
What: we move api keys out of the grpc connection-level metadata on the client side and into the request protobufs directly. the server side still supports both mechanisms for backwards compatibility.

Why: dRPC won't support connection-level metadata. the only thing we currently use connection-level metadata for is api keys. we need to move all information needed by a request into the request protobuf itself for drpc support. check out the .proto changes for the main details.

One fun side-fact: Did you know that protobuf fields 1-15 are special and only use one byte for both the field number and type? Additionally did you know we don't use field 15 anywhere yet? So the new request header will use field 15, and should use field 15 on all protobufs going forward.

Please describe the tests: all existing tests should pass

Please describe the performance impact: none
2019-09-19 10:19:29 -06:00

57 lines
1.7 KiB
Go

// 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)
}
// DeprecatedAPIKeyCredentials implements grpc/credentials.PerRPCCredentials
// for authenticating with the grpc server. This does not work with drpc.
type DeprecatedAPIKeyCredentials struct {
value string
}
// NewDeprecatedAPIKeyCredentials returns a new DeprecatedAPIKeyCredentials
func NewDeprecatedAPIKeyCredentials(apikey string) *DeprecatedAPIKeyCredentials {
return &DeprecatedAPIKeyCredentials{apikey}
}
// GetRequestMetadata gets the current request metadata, refreshing tokens if required.
func (creds *DeprecatedAPIKeyCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"apikey": creds.value,
}, nil
}
// RequireTransportSecurity indicates whether the credentials requires transport security.
func (creds *DeprecatedAPIKeyCredentials) RequireTransportSecurity() bool {
return false // Deprecated anyway, but how was this the right choice?
}