1
2
3
4 package grpc_auth
5
6 import (
7 "context"
8 "testing"
9
10 "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
11 "github.com/stretchr/testify/assert"
12 "google.golang.org/grpc/codes"
13 "google.golang.org/grpc/metadata"
14 "google.golang.org/grpc/status"
15 )
16
17 func TestAuthFromMD(t *testing.T) {
18 for _, run := range []struct {
19 md metadata.MD
20 value string
21 errCode codes.Code
22 msg string
23 }{
24 {
25 md: metadata.Pairs("authorization", "bearer some_token"),
26 value: "some_token",
27 msg: "must extract simple bearer tokens without case checking",
28 },
29 {
30 md: metadata.Pairs("authorization", "Bearer some_token"),
31 value: "some_token",
32 msg: "must extract simple bearer tokens with case checking",
33 },
34 {
35 md: metadata.Pairs("authorization", "Bearer some multi string bearer"),
36 value: "some multi string bearer",
37 msg: "must handle string based bearers",
38 },
39 {
40 md: metadata.Pairs("authorization", "Basic login:passwd"),
41 value: "",
42 errCode: codes.Unauthenticated,
43 msg: "must check authentication type",
44 },
45 {
46 md: metadata.Pairs("authorization", "Basic login:passwd", "authorization", "bearer some_token"),
47 value: "",
48 errCode: codes.Unauthenticated,
49 msg: "must not allow multiple authentication methods",
50 },
51 {
52 md: metadata.Pairs("authorization", ""),
53 value: "",
54 errCode: codes.Unauthenticated,
55 msg: "authorization string must not be empty",
56 },
57 {
58 md: metadata.Pairs("authorization", "Bearer"),
59 value: "",
60 errCode: codes.Unauthenticated,
61 msg: "bearer token must not be empty",
62 },
63 } {
64 ctx := metautils.NiceMD(run.md).ToIncoming(context.TODO())
65 out, err := AuthFromMD(ctx, "bearer")
66 if run.errCode != codes.OK {
67 assert.Equal(t, run.errCode, status.Code(err), run.msg)
68 } else {
69 assert.NoError(t, err, run.msg)
70 }
71 assert.Equal(t, run.value, out, run.msg)
72 }
73 }
74
View as plain text