File: idtoken.go

package info (click to toggle)
golang-github-openpubkey-openpubkey 0.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 964 kB
  • sloc: makefile: 10
file content (161 lines) | stat: -rw-r--r-- 3,981 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Copyright 2024 OpenPubkey
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package mocks

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rsa"
	"encoding/json"
	"fmt"
	"time"

	"github.com/lestrrat-go/jwx/v2/jwa"
	"github.com/lestrrat-go/jwx/v2/jws"
	"github.com/openpubkey/openpubkey/oidc"
)

type CommitmentType struct {
	ClaimCommitment bool
	ClaimName       string
}

type IDTokenTemplate struct {
	CommitFunc           func(*IDTokenTemplate, string)
	Issuer               string
	Nonce                string
	NoNonce              bool
	Aud                  string
	KeyID                string
	NoKeyID              bool
	Alg                  string
	NoAlg                bool // Even if NOAlg is true, we still need Alg to be set to generate the signature
	ExtraClaims          map[string]any
	ExtraProtectedClaims map[string]any
	SigningKey           crypto.Signer // The key we will use to sign the ID Token
}

func DefaultIDTokenTemplate() IDTokenTemplate {
	return IDTokenTemplate{
		CommitFunc: AddAudCommit,
		Issuer:     "mockIssuer",
		Nonce:      "empty",
		NoNonce:    false,
		Aud:        "empty",
		KeyID:      "mockKeyID",
		NoKeyID:    false,
		Alg:        "RS256",
		NoAlg:      false,
	}
}

// AddCommit adds the commitment to the CIC to the ID Token. The
// CommitmentFunc is specified allowing custom commitment functions to be specified
func (t *IDTokenTemplate) AddCommit(cicHash string) {
	t.CommitFunc(t, cicHash)
}

func (t *IDTokenTemplate) IssueTokens() (*oidc.Tokens, error) {

	headers := jws.NewHeaders()
	if !t.NoAlg {
		if err := headers.Set(jws.AlgorithmKey, t.Alg); err != nil {
			return nil, err
		}
	}
	if !t.NoKeyID {
		if err := headers.Set(jws.KeyIDKey, t.KeyID); err != nil {
			return nil, err
		}
	}
	if err := headers.Set(jws.TypeKey, "JWT"); err != nil {
		return nil, err
	}

	if t.ExtraProtectedClaims != nil {
		for k, v := range t.ExtraProtectedClaims {
			if err := headers.Set(k, v); err != nil {
				return nil, err
			}
		}
	}

	payloadMap := map[string]any{
		"sub": "me",
		"aud": t.Aud,
		"iss": t.Issuer,
		"iat": time.Now().Unix(),
		"exp": time.Now().Add(2 * time.Hour).Unix(),
	}

	if !t.NoNonce {
		payloadMap["nonce"] = t.Nonce
	}

	if t.ExtraClaims != nil {
		for k, v := range t.ExtraClaims {
			payloadMap[k] = v
		}
	}

	payloadBytes, err := json.Marshal(payloadMap)
	if err != nil {
		return nil, err
	}

	var providerAlg jwa.KeyAlgorithm
	if _, ok := t.SigningKey.Public().(*rsa.PublicKey); ok {
		providerAlg = jwa.RS256
	} else if _, ok := t.SigningKey.Public().(*ecdsa.PublicKey); ok {
		providerAlg = jwa.ES256
	} else {
		return nil, fmt.Errorf("unsupported public key type")
	}

	if jwa.KeyAlgorithmFrom(t.Alg) != providerAlg {
		return nil, fmt.Errorf("alg in template (%s) does not match providers signing key alg (%s)", t.Alg, providerAlg)
	}

	idToken, err := jws.Sign(
		payloadBytes,
		jws.WithKey(
			providerAlg,
			t.SigningKey,
			jws.WithProtectedHeaders(headers),
		),
	)
	if err != nil {
		return nil, err
	}
	return &oidc.Tokens{
		IDToken:      idToken,
		RefreshToken: []byte("mock-refresh-token"),
		AccessToken:  []byte("mock-access-token")}, nil
}

func AddNonceCommit(idtTemp *IDTokenTemplate, cicHash string) {
	idtTemp.Nonce = cicHash
	idtTemp.NoNonce = false
}

func AddAudCommit(idtTemp *IDTokenTemplate, cicHash string) {
	idtTemp.Aud = cicHash
}

func NoClaimCommit(idtTemp *IDTokenTemplate, cicHash string) {
	// Do nothing
}