go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/auth/openid/common_test.go (about)

     1  // Copyright 2015 The LUCI Authors.
     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 openid
    16  
    17  import (
    18  	"context"
    19  	"crypto/rsa"
    20  	"encoding/base64"
    21  	"encoding/binary"
    22  	"encoding/json"
    23  	"fmt"
    24  
    25  	"go.chromium.org/luci/server/auth/signing/signingtest"
    26  )
    27  
    28  func jwksForTest(keyID string, pubKey *rsa.PublicKey) *JSONWebKeySetStruct {
    29  	modulus := pubKey.N.Bytes()
    30  	exp := []byte{0, 0, 0, 0}
    31  	binary.BigEndian.PutUint32(exp, uint32(pubKey.E))
    32  	return &JSONWebKeySetStruct{
    33  		Keys: []JSONWebKeyStruct{
    34  			{
    35  				Kty: "RSA",
    36  				Alg: "RS256",
    37  				Use: "sig",
    38  				Kid: keyID,
    39  				N:   base64.RawURLEncoding.EncodeToString(modulus),
    40  				E:   base64.RawURLEncoding.EncodeToString(exp),
    41  			},
    42  		},
    43  	}
    44  }
    45  
    46  func jwtForTest(ctx context.Context, body []byte, keyID string, signer *signingtest.Signer) string {
    47  	b64hdr := base64.RawURLEncoding.EncodeToString([]byte(
    48  		fmt.Sprintf(`{"alg": "RS256","kid": "%s"}`, keyID)))
    49  	b64bdy := base64.RawURLEncoding.EncodeToString(body)
    50  	_, sig, err := signer.SignBytes(ctx, []byte(b64hdr+"."+b64bdy))
    51  	if err != nil {
    52  		panic(err)
    53  	}
    54  	return b64hdr + "." + b64bdy + "." + base64.RawURLEncoding.EncodeToString(sig)
    55  }
    56  
    57  func idTokenForTest(ctx context.Context, tok *IDToken, keyID string, signer *signingtest.Signer) string {
    58  	body, err := json.Marshal(tok)
    59  	if err != nil {
    60  		panic(err)
    61  	}
    62  	return jwtForTest(ctx, body, keyID, signer)
    63  }