Debian Codegraph @

pktoken/clientinstance/claims.go

raw
1 // Copyright 2024 OpenPubkey
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 // SPDX-License-Identifier: Apache-2.0
16
17 package clientinstance
18
19 import (
20 "crypto"
21 "crypto/ecdsa"
22 "crypto/ed25519"
23 "crypto/rand"
24 "crypto/rsa"
25 "encoding/hex"
26 "encoding/json"
27 "fmt"
28
29 "github.com/lestrrat-go/jwx/v3/jwa"
30 "github.com/lestrrat-go/jwx/v3/jwk"
31 "github.com/lestrrat-go/jwx/v3/jws"
32 "github.com/openpubkey/openpubkey/internal/jwx"
33 "github.com/openpubkey/openpubkey/jose"
34 "github.com/openpubkey/openpubkey/util"
35 )
36
37 // Client Instance Claims, referred also as "cic" in the OpenPubKey paper
38 type Claims struct {
39 publicKey crypto.PublicKey
40 algorithm string
41
42 // Claims are stored in the protected header portion of JWS signature
43 protected map[string]any
44 }
45
46 // Client instance claims must relate to a single key pair
47 func NewClaims(publicKey crypto.PublicKey, claims map[string]any) (*Claims, error) {
48 jwkKey, err := jwk.PublicKeyOf(publicKey)
49 if err != nil {
50 return nil, err
51 }
52
53 // Make sure no claims are using our reserved values
54 for _, reserved := range []string{"alg", "upk", "rz", "typ"} {
55 if _, ok := claims[reserved]; ok {
56 return nil, fmt.Errorf("use of reserved header name, %s, in additional headers", reserved)
57 }
58 }
59
60 rand, err := generateRand()
61 if err != nil {
62 return nil, fmt.Errorf("failed to generate random value: %w", err)
63 }
64
65 alg, ok := jwkKey.Algorithm()
66 if !ok {
67 return nil, fmt.Errorf("failed to get algorithm from jwk key")
68 }
69
70 // Assign required values
71 claims["typ"] = "CIC"
72 claims["alg"] = alg
73 claims["upk"] = jwkKey
74 claims["rz"] = rand
75
76 return &Claims{
77 publicKey: publicKey,
78 algorithm: alg.String(),
79 protected: claims,
80 }, nil
81 }
82
83 func ParseClaims(protected map[string]any) (*Claims, error) {
84 // Get our standard headers and make sure they match up
85 if _, ok := protected["rz"]; !ok {
86 return nil, fmt.Errorf(`missing required "rz" claim`)
87 }
88 upk, ok := protected["upk"]
89 if !ok {
90 return nil, fmt.Errorf(`missing required "upk" claim`)
91 }
92 upkBytes, err := json.Marshal(upk)
93 if err != nil {
94 return nil, err
95 }
96 upkjwk, err := jwk.ParseKey(upkBytes)
97 if err != nil {
98 return nil, err
99 }
100 alg, ok := protected["alg"]
101 if !ok {
102 return nil, fmt.Errorf(`missing required "alg" claim`)
103 }
104 upkAlg, ok := upkjwk.Algorithm()
105 if !ok {
106 return nil, fmt.Errorf(`failed to get algorithm from jwk key`)
107 }
108 if alg != upkAlg {
109 return nil, fmt.Errorf(`provided "alg" value different from algorithm provided in "upk" jwk`)
110 }
111 // Export to any first, then convert to the appropriate concrete type
112 // This is necessary because jwk.Export needs to know the concrete type
113 var pubKeyAny any
114 if err := jwk.Export(upkjwk, &pubKeyAny); err != nil {
115 return nil, fmt.Errorf("failed to extract public key from JWK: %w", err)
116 }
117
118 // If we got a private key (crypto.Signer), extract its public key
119 if signer, ok := pubKeyAny.(crypto.Signer); ok {
120 pubKeyAny = signer.Public()
121 }
122
123 var pubKey crypto.PublicKey
124 // Validate that key type matches the declared algorithm
125 switch upkAlg {
126 case jwa.RS256():
127 rsaKey, ok := pubKeyAny.(*rsa.PublicKey)
128 if !ok {
129 return nil, fmt.Errorf("algorithm %s requires RSA key, got %T", upkAlg, pubKeyAny)
130 }
131 pubKey = rsaKey
132 case jwa.ES256():
133 ecdsaKey, ok := pubKeyAny.(*ecdsa.PublicKey)
134 if !ok {
135 return nil, fmt.Errorf("algorithm %s requires ECDSA key, got %T", upkAlg, pubKeyAny)
136 }
137 pubKey = ecdsaKey
138 case jwa.EdDSA():
139 edKey, ok := pubKeyAny.(ed25519.PublicKey)
140 if !ok {
141 return nil, fmt.Errorf("algorithm %s requires Ed25519 key, got %T", upkAlg, pubKeyAny)
142 }
143 pubKey = edKey
144 default:
145 return nil, fmt.Errorf("unsupported algorithm: %s", upkAlg)
146 }
147
148 return &Claims{
149 publicKey: pubKey,
150 algorithm: upkAlg.String(),
151 protected: protected,
152 }, nil
153 }
154
155 func (c *Claims) PublicKey() crypto.PublicKey {
156 return c.publicKey
157 }
158
159 func (c *Claims) KeyAlgorithm() jose.KeyAlgorithm {
160 return jose.KeyAlgorithm(c.algorithm)
161 }
162
163 // Returns a hash of all client instance claims which includes a random value
164 func (c *Claims) Hash() ([]byte, error) {
165 buf, err := json.Marshal(c.protected)
166 if err != nil {
167 return nil, err
168 }
169
170 return util.B64SHA3_256(buf), nil
171 }
172
173 // This function signs the payload of the provided token with the protected headers
174 // as defined by the client instance claims and returns a jwt in compact form.
175 func (c *Claims) Sign(signer crypto.Signer, algorithm jose.KeyAlgorithm, token []byte) ([]byte, error) {
176 _, payload, _, err := jws.SplitCompact(token)
177 if err != nil {
178 return nil, err
179 }
180
181 // We need to make sure we're signing the decoded bytes
182 payloadDecoded, err := util.Base64DecodeForJWT(payload)
183 if err != nil {
184 return nil, err
185 }
186
187 headers := jws.NewHeaders()
188 for key, val := range c.protected {
189 if err := headers.Set(key, val); err != nil {
190 return nil, err
191 }
192 }
193
194 jwxAlg, ok := jwx.FromJoseAlgorithm(algorithm)
195 if !ok {
196 return nil, fmt.Errorf("unsupported key algorithm: %s", algorithm)
197 }
198
199 cicToken, err := jws.Sign(
200 payloadDecoded,
201 jws.WithKey(
202 jwxAlg,
203 signer,
204 jws.WithProtectedHeaders(headers),
205 ),
206 )
207 if err != nil {
208 return nil, err
209 }
210
211 return cicToken, nil
212 }
213
214 func generateRand() (string, error) {
215 bits := 256
216 rBytes := make([]byte, bits/8)
217 _, err := rand.Read(rBytes)
218 if err != nil {
219 return "", err
220 }
221
222 rz := hex.EncodeToString(rBytes)
223 return rz, nil
224 }