Debian Codegraph @

examples/mfa/mfacosigner/jwks/jwksserver.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 jwks
18
19 import (
20 "crypto"
21 "crypto/ecdsa"
22 "crypto/elliptic"
23 "encoding/hex"
24 "encoding/json"
25 "fmt"
26 "net"
27 "net/http"
28
29 "github.com/lestrrat-go/jwx/v3/jwk"
30 "github.com/openpubkey/openpubkey/jose"
31 "golang.org/x/crypto/sha3"
32 )
33
34 type JwksServer struct {
35 uri string
36 jwksBytes []byte
37 }
38
39 // A very simple JWKS server for our MFA Cosigner example code.
40 func NewJwksServer(signer crypto.Signer, alg jose.KeyAlgorithm) (*JwksServer, string, error) {
41 // Compute the kid (Key ID) as the SHA-3 of the public key
42 pubkey := signer.Public().(*ecdsa.PublicKey) // TODO: handle non-ecdsa signers
43 pubkeyBytes := elliptic.Marshal(pubkey, pubkey.X, pubkey.Y)
44 pubkeyHash := sha3.Sum256(pubkeyBytes)
45 kid := hex.EncodeToString(pubkeyHash[:])
46
47 // Generate our JWKS using our signing key
48 jwkKey, err := jwk.PublicKeyOf(signer)
49 if err != nil {
50 return nil, "", err
51 }
52 jwkKey.Set(jwk.AlgorithmKey, alg)
53 jwkKey.Set(jwk.KeyIDKey, kid)
54
55 // Put our jwk into a set
56 keySet := jwk.NewSet()
57 keySet.AddKey(jwkKey)
58
59 // Now convert our key set into the raw bytes for printing later
60 keySetBytes, _ := json.MarshalIndent(keySet, "", " ")
61 if err != nil {
62 return nil, "", err
63 }
64
65 // Find an empty port
66 listener, err := net.Listen("tcp", ":0")
67 if err != nil {
68 return nil, "", fmt.Errorf("failed to bind to an available port: %w", err)
69 }
70
71 server := &JwksServer{
72 uri: fmt.Sprintf("http://localhost:%d", listener.Addr().(*net.TCPAddr).Port),
73 jwksBytes: keySetBytes,
74 }
75
76 // Host our JWKS at a localhost url
77 mux := http.NewServeMux()
78 mux.HandleFunc("/.well-known/jwks.json", server.printJWKS)
79 go func() {
80 http.Serve(listener, mux)
81 }()
82 return server, kid, nil
83 }
84
85 func (s *JwksServer) URI() string {
86 return s.uri
87 }
88
89 func (s *JwksServer) printJWKS(w http.ResponseWriter, r *http.Request) {
90 w.Header().Set("Content-Type", "application/json")
91 w.Write(s.jwksBytes)
92 }