github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/doltcore/sqle/cluster/jwks.go (about)

     1  // Copyright 2022 Dolthub, Inc.
     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  package cluster
    16  
    17  import (
    18  	"crypto/ed25519"
    19  	"encoding/json"
    20  	"net/http"
    21  
    22  	"gopkg.in/square/go-jose.v2"
    23  	"gopkg.in/square/go-jose.v2/jwt"
    24  
    25  	"github.com/dolthub/dolt/go/libraries/doltcore/creds"
    26  )
    27  
    28  type JWKSHandler struct {
    29  	KeyID     string
    30  	PublicKey ed25519.PublicKey
    31  }
    32  
    33  func (h JWKSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    34  	b, err := json.Marshal(jose.JSONWebKeySet{
    35  		Keys: []jose.JSONWebKey{
    36  			{
    37  				Key:   h.PublicKey,
    38  				KeyID: h.KeyID,
    39  			},
    40  		},
    41  	})
    42  	if err != nil {
    43  		http.Error(w, "error marshaling json", http.StatusInternalServerError)
    44  		return
    45  	}
    46  	w.Write(b)
    47  }
    48  
    49  func JWKSHandlerInterceptor(keyID string, pub ed25519.PublicKey) func(http.Handler) http.Handler {
    50  	jh := JWKSHandler{KeyID: keyID, PublicKey: pub}
    51  	return func(h http.Handler) http.Handler {
    52  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    53  			if r.URL.EscapedPath() == "/.well-known/jwks.json" {
    54  				jh.ServeHTTP(w, r)
    55  				return
    56  			}
    57  			h.ServeHTTP(w, r)
    58  		})
    59  	}
    60  }
    61  
    62  func JWTExpectations() jwt.Expected {
    63  	return jwt.Expected{Issuer: creds.ClientIssuer, Audience: jwt.Audience{DoltClusterRemoteApiAudience}}
    64  }