add metadata interceptors, auth client interceptors

Signed-off-by: Adphi <philippe.adrien.nousse@gmail.com>
This commit is contained in:
2022-03-11 12:33:18 +01:00
parent c0e79d8834
commit 97ced73270
11 changed files with 101 additions and 68 deletions

View File

@ -8,13 +8,15 @@ import (
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"go.linka.cloud/grpc/errors"
"go.linka.cloud/grpc/interceptors"
"go.linka.cloud/grpc/interceptors/metadata"
)
func BasicAuth(user, password string) string {
return "basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))
}
type BasicValidator func(ctx context.Context, user, password string) (context.Context,error)
type BasicValidator func(ctx context.Context, user, password string) (context.Context, error)
func makeBasicAuthFunc(v BasicValidator) grpc_auth.AuthFunc {
return func(ctx context.Context) (context.Context, error) {
@ -34,3 +36,7 @@ func makeBasicAuthFunc(v BasicValidator) grpc_auth.AuthFunc {
return v(ctx, cs[:s], cs[s+1:])
}
}
func NewBasicAuthClientIntereptors(user, password string) interceptors.ClientInterceptors {
return metadata.NewInterceptors("authorization", BasicAuth(user, password))
}

View File

@ -2,6 +2,7 @@ package auth
import (
"context"
"crypto/subtle"
"strings"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
@ -40,8 +41,8 @@ func NewServerInterceptors(opts ...Option) interceptors.ServerInterceptors {
return &interceptor{o: o, authFn: ChainedAuthFuncs(o.authFns...)}
}
type interceptor struct{
o options
type interceptor struct {
o options
authFn grpc_auth.AuthFunc
}
@ -92,3 +93,7 @@ func (i *interceptor) isNotProtected(endpoint string) bool {
}
return true
}
func Equals(s1, s2 string) bool {
return subtle.ConstantTimeCompare([]byte(s1), []byte(s2)) == 1
}

View File

@ -102,11 +102,11 @@ func TestChainedAuthFuncs(t *testing.T) {
code: codes.PermissionDenied,
},
{
name: "internal error",
auth: "bearer internal",
name: "internal error",
auth: "bearer internal",
internalError: true,
err: true,
code: codes.PermissionDenied,
err: true,
code: codes.PermissionDenied,
},
{
name: "multiple auth: first basic valid",

View File

@ -4,6 +4,9 @@ import (
"context"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"go.linka.cloud/grpc/interceptors"
"go.linka.cloud/grpc/interceptors/metadata"
)
type TokenValidator func(ctx context.Context, token string) (context.Context, error)
@ -17,3 +20,7 @@ func makeTokenAuthFunc(v TokenValidator) grpc_auth.AuthFunc {
return v(ctx, a)
}
}
func NewBearerClientInterceptors(token string) interceptors.ClientInterceptors {
return metadata.NewInterceptors("authorization", "Bearer "+token)
}