1// Copyright 2022 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14// 15//////////////////////////////////////////////////////////////////////////////// 16 17package jwt 18 19import ( 20 "fmt" 21 22 "github.com/google/tink/go/core/primitiveset" 23 "github.com/google/tink/go/keyset" 24) 25 26// NewVerifier generates a new instance of the JWT Verifier primitive. 27func NewVerifier(handle *keyset.Handle) (Verifier, error) { 28 if handle == nil { 29 return nil, fmt.Errorf("keyset handle can't be nil") 30 } 31 ps, err := handle.PrimitivesWithKeyManager(nil) 32 if err != nil { 33 return nil, fmt.Errorf("jwt_verifier_factory: cannot obtain primitive set: %v", err) 34 } 35 return newWrappedVerifier(ps) 36} 37 38// wrappedVerifier is a JWT Verifier implementation that uses the underlying primitive set for JWT Verifier. 39type wrappedVerifier struct { 40 ps *primitiveset.PrimitiveSet 41} 42 43var _ Verifier = (*wrappedVerifier)(nil) 44 45func newWrappedVerifier(ps *primitiveset.PrimitiveSet) (*wrappedVerifier, error) { 46 if _, ok := (ps.Primary.Primitive).(*verifierWithKID); !ok { 47 return nil, fmt.Errorf("jwt_verifier_factory: not a JWT Verifier primitive") 48 } 49 for _, primitives := range ps.Entries { 50 for _, p := range primitives { 51 if _, ok := (p.Primitive).(*verifierWithKID); !ok { 52 return nil, fmt.Errorf("jwt_verifier_factory: not a JWT Verifier primitive") 53 } 54 } 55 } 56 return &wrappedVerifier{ps: ps}, nil 57} 58 59func (w *wrappedVerifier) VerifyAndDecode(compact string, validator *Validator) (*VerifiedJWT, error) { 60 var interestingErr error 61 for _, s := range w.ps.Entries { 62 for _, e := range s { 63 p, ok := e.Primitive.(*verifierWithKID) 64 if !ok { 65 return nil, fmt.Errorf("jwt_verifier_factory: not a JWT Verifier primitive") 66 } 67 verifiedJWT, err := p.VerifyAndDecodeWithKID(compact, validator, keyID(e.KeyID, e.PrefixType)) 68 if err == nil { 69 return verifiedJWT, nil 70 } 71 if err != errJwtVerification { 72 // any error that is not the generic errJwtVerification is considered interesting 73 interestingErr = err 74 } 75 } 76 } 77 if interestingErr != nil { 78 return nil, interestingErr 79 } 80 return nil, errJwtVerification 81} 82