Path: blob/main/components/public-api-server/pkg/jws/keyset.go
2506 views
// Copyright (c) 2023 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package jws56import (7"crypto/rsa"8"crypto/x509"9"encoding/pem"10"fmt"11"io/ioutil"1213"github.com/gitpod-io/gitpod/components/public-api/go/config"14)1516type Key struct {17ID string18Private *rsa.PrivateKey19Raw []byte20// We don't need PublicKey because we can derive the public key from the private key21}2223// KeySet encodes a collection of keys to use24// There's always a Signing key, but optionally there are also25// older keys which can be used to verify.26type KeySet struct {27Signing Key28Validating []Key29}3031func NewKeySetFromAuthPKI(pki config.AuthPKIConfiguration) (KeySet, error) {32signing, err := readKeyPair(pki.Signing)33if err != nil {34return KeySet{}, fmt.Errorf("failed to read signing key: %w", err)35}3637var validating []Key38for _, keypair := range pki.Validating {39key, err := readKeyPair(keypair)40if err != nil {41return KeySet{}, fmt.Errorf("failed to read validating key: %w", err)42}4344validating = append(validating, key)45}4647return KeySet{48Signing: signing,49Validating: validating,50}, nil51}5253func readKeyPair(keypair config.KeyPair) (Key, error) {54pk, raw, err := readPrivateKeyFromFile(keypair.PrivateKeyPath)55if err != nil {56return Key{}, err57}5859return Key{60ID: keypair.ID,61Private: pk,62Raw: raw,63}, nil64}6566func readPrivateKeyFromFile(filepath string) (*rsa.PrivateKey, []byte, error) {67bytes, err := ioutil.ReadFile(filepath)68if err != nil {69return nil, nil, fmt.Errorf("failed to read private key from %s: %w", filepath, err)70}7172block, _ := pem.Decode(bytes)73parseResult, _ := x509.ParsePKCS8PrivateKey(block.Bytes)74key, ok := parseResult.(*rsa.PrivateKey)75if !ok {76return nil, nil, fmt.Errorf("file %s does not contain RSA Private Key", filepath)77}7879return key, bytes, nil80}818283