github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/apiguard/builder_test.go (about) 1 package apiguard 2 3 import ( 4 "errors" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestSecurelyBuildFromHeader(t *testing.T) { 11 cases := []struct { 12 name string 13 header map[string][]string 14 tokens []string 15 16 expectedXJwtEmailVerified bool 17 expectedXJwtEmail string 18 expectedXJwtSub string 19 expectedXJwtAud string 20 expectedXOrgId string 21 expectedXTeamId string 22 expectedXUserId string 23 expectedXKeyId string 24 25 err error 26 }{ 27 { 28 name: "no tokens", 29 header: map[string][]string{}, 30 tokens: []string{}, 31 err: errors.New("APIGuard: Trust token not provided"), 32 }, 33 { 34 name: "token does not match", 35 header: map[string][]string{ 36 headerTrustToken: {"invalid"}, 37 }, 38 tokens: []string{"valid"}, 39 err: errors.New("APIGuard: Trust token mismatch"), 40 }, 41 { 42 name: "token matches", 43 header: map[string][]string{ 44 headerTrustToken: {"valid"}, 45 }, 46 tokens: []string{"valid"}, 47 err: nil, 48 }, 49 { 50 name: "verify context", 51 header: map[string][]string{ 52 headerTrustToken: {"valid"}, 53 headerTokenEmail: {"email"}, 54 headerTokenEmailVerified: {"true"}, 55 headerTokenSub: {"sub"}, 56 headerTokenAud: {"aud"}, 57 headerMetaOrgId: {"org"}, 58 headerMetaTeamId: {"team"}, 59 headerMetaUserId: {"user"}, 60 headerMetaKeyId: {"key"}, 61 }, 62 tokens: []string{"valid"}, 63 expectedXJwtEmail: "email", 64 expectedXJwtEmailVerified: true, 65 expectedXJwtSub: "sub", 66 expectedXJwtAud: "aud", 67 expectedXOrgId: "org", 68 expectedXTeamId: "team", 69 expectedXUserId: "user", 70 expectedXKeyId: "key", 71 }, 72 } 73 74 for _, test := range cases { 75 t.Run(test.name, func(t *testing.T) { 76 header := make(map[string][]string) 77 for k, v := range test.header { 78 header[k] = v 79 } 80 81 ctx, err := SecurelyBuildFromHeader(header, test.tokens...) 82 if test.err != nil { 83 assert.Error(t, err) 84 assert.ErrorContains(t, err, test.err.Error()) 85 } else { 86 assert.NoError(t, err) 87 88 assert.Equal(t, test.expectedXJwtEmail, ctx.Token.Email) 89 assert.Equal(t, test.expectedXJwtEmailVerified, ctx.Token.EmailVerified) 90 assert.Equal(t, test.expectedXJwtSub, ctx.Token.Subject) 91 assert.Equal(t, test.expectedXJwtAud, ctx.Token.Audience) 92 assert.Equal(t, test.expectedXOrgId, ctx.Key.OrganizationID) 93 assert.Equal(t, test.expectedXTeamId, ctx.Key.TeamID) 94 assert.Equal(t, test.expectedXUserId, ctx.Key.UserID) 95 assert.Equal(t, test.expectedXKeyId, ctx.Key.KeyID) 96 } 97 }) 98 } 99 }