xref: /aosp_15_r20/external/tink/go/jwt/jwt_signer_factory.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
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// NewSigner generates a new instance of the JWT Signer primitive.
27func NewSigner(handle *keyset.Handle) (Signer, 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_signer_factory: cannot obtain primitive set: %v", err)
34	}
35	return newWrappedSigner(ps)
36}
37
38// wrappedSigner is a JWT Signer implementation that uses the underlying primitive set for JWT Sign.
39type wrappedSigner struct {
40	ps *primitiveset.PrimitiveSet
41}
42
43var _ Signer = (*wrappedSigner)(nil)
44
45func newWrappedSigner(ps *primitiveset.PrimitiveSet) (*wrappedSigner, error) {
46	if _, ok := (ps.Primary.Primitive).(*signerWithKID); !ok {
47		return nil, fmt.Errorf("jwt_signer_factory: not a JWT Signer primitive")
48	}
49	for _, primitives := range ps.Entries {
50		for _, p := range primitives {
51			if _, ok := (p.Primitive).(*signerWithKID); !ok {
52				return nil, fmt.Errorf("jwt_signer_factory: not a JWT Signer primitive")
53			}
54		}
55	}
56	return &wrappedSigner{ps: ps}, nil
57}
58
59func (w *wrappedSigner) SignAndEncode(rawJWT *RawJWT) (string, error) {
60	primary := w.ps.Primary
61	p, ok := (primary.Primitive).(*signerWithKID)
62	if !ok {
63		return "", fmt.Errorf("jwt_signer_factory: not a JWT Signer primitive")
64	}
65	return p.SignAndEncodeWithKID(rawJWT, keyID(primary.KeyID, primary.PrefixType))
66}
67