feat(v3alpha): web key resource (#8262)

# Which Problems Are Solved

Implement a new API service that allows management of OIDC signing web
keys.
This allows users to manage rotation of the instance level keys. which
are currently managed based on expiry.

The API accepts the generation of the following key types and
parameters:

- RSA keys with 2048, 3072 or 4096 bit in size and:
  - Signing with SHA-256 (RS256)
  - Signing with SHA-384 (RS384)
  - Signing with SHA-512 (RS512)
- ECDSA keys with
  - P256 curve
  - P384 curve
  - P512 curve
- ED25519 keys

# How the Problems Are Solved

Keys are serialized for storage using the JSON web key format from the
`jose` library. This is the format that will be used by OIDC for
signing, verification and publication.

Each instance can have a number of key pairs. All existing public keys
are meant to be used for token verification and publication the keys
endpoint. Keys can be activated and the active private key is meant to
sign new tokens. There is always exactly 1 active signing key:

1. When the first key for an instance is generated, it is automatically
activated.
2. Activation of the next key automatically deactivates the previously
active key.
3. Keys cannot be manually deactivated from the API
4. Active keys cannot be deleted

# Additional Changes

- Query methods that later will be used by the OIDC package are already
implemented. Preparation for #8031
- Fix indentation in french translation for instance event
- Move user_schema translations to consistent positions in all
translation files

# Additional Context

- Closes #8030
- Part of #7809

---------

Co-authored-by: Elio Bischof <elio@zitadel.com>
This commit is contained in:
Tim Möhlmann
2024-08-14 17:18:14 +03:00
committed by GitHub
parent e2e1100124
commit 64a3bb3149
91 changed files with 5133 additions and 256 deletions

View File

@@ -68,6 +68,14 @@ func Encrypt(value []byte, alg EncryptionAlgorithm) (*CryptoValue, error) {
}, nil
}
func EncryptJSON(obj any, alg EncryptionAlgorithm) (*CryptoValue, error) {
data, err := json.Marshal(obj)
if err != nil {
return nil, zerrors.ThrowInternal(err, "CRYPT-Ei6doF", "error encrypting value")
}
return Encrypt(data, alg)
}
func Decrypt(value *CryptoValue, alg EncryptionAlgorithm) ([]byte, error) {
if err := checkEncryptionAlgorithm(value, alg); err != nil {
return nil, err
@@ -75,6 +83,17 @@ func Decrypt(value *CryptoValue, alg EncryptionAlgorithm) ([]byte, error) {
return alg.Decrypt(value.Crypted, value.KeyID)
}
func DecryptJSON(value *CryptoValue, dst any, alg EncryptionAlgorithm) error {
data, err := Decrypt(value, alg)
if err != nil {
return err
}
if err = json.Unmarshal(data, dst); err != nil {
return zerrors.ThrowInternal(err, "CRYPT-Jaik2R", "error decrypting value")
}
return nil
}
// DecryptString decrypts the value using the key identified by keyID.
// When the decrypted value contains non-UTF8 characters an error is returned.
func DecryptString(value *CryptoValue, alg EncryptionAlgorithm) (string, error) {

View File

@@ -0,0 +1,116 @@
// Code generated by "enumer -type EllipticCurve -trimprefix EllipticCurve -text -json -linecomment"; DO NOT EDIT.
package crypto
import (
"encoding/json"
"fmt"
"strings"
)
const _EllipticCurveName = "P256P384P512"
var _EllipticCurveIndex = [...]uint8{0, 0, 4, 8, 12}
const _EllipticCurveLowerName = "p256p384p512"
func (i EllipticCurve) String() string {
if i < 0 || i >= EllipticCurve(len(_EllipticCurveIndex)-1) {
return fmt.Sprintf("EllipticCurve(%d)", i)
}
return _EllipticCurveName[_EllipticCurveIndex[i]:_EllipticCurveIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _EllipticCurveNoOp() {
var x [1]struct{}
_ = x[EllipticCurveUnspecified-(0)]
_ = x[EllipticCurveP256-(1)]
_ = x[EllipticCurveP384-(2)]
_ = x[EllipticCurveP512-(3)]
}
var _EllipticCurveValues = []EllipticCurve{EllipticCurveUnspecified, EllipticCurveP256, EllipticCurveP384, EllipticCurveP512}
var _EllipticCurveNameToValueMap = map[string]EllipticCurve{
_EllipticCurveName[0:0]: EllipticCurveUnspecified,
_EllipticCurveLowerName[0:0]: EllipticCurveUnspecified,
_EllipticCurveName[0:4]: EllipticCurveP256,
_EllipticCurveLowerName[0:4]: EllipticCurveP256,
_EllipticCurveName[4:8]: EllipticCurveP384,
_EllipticCurveLowerName[4:8]: EllipticCurveP384,
_EllipticCurveName[8:12]: EllipticCurveP512,
_EllipticCurveLowerName[8:12]: EllipticCurveP512,
}
var _EllipticCurveNames = []string{
_EllipticCurveName[0:0],
_EllipticCurveName[0:4],
_EllipticCurveName[4:8],
_EllipticCurveName[8:12],
}
// EllipticCurveString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func EllipticCurveString(s string) (EllipticCurve, error) {
if val, ok := _EllipticCurveNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _EllipticCurveNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to EllipticCurve values", s)
}
// EllipticCurveValues returns all values of the enum
func EllipticCurveValues() []EllipticCurve {
return _EllipticCurveValues
}
// EllipticCurveStrings returns a slice of all String values of the enum
func EllipticCurveStrings() []string {
strs := make([]string, len(_EllipticCurveNames))
copy(strs, _EllipticCurveNames)
return strs
}
// IsAEllipticCurve returns "true" if the value is listed in the enum definition. "false" otherwise
func (i EllipticCurve) IsAEllipticCurve() bool {
for _, v := range _EllipticCurveValues {
if i == v {
return true
}
}
return false
}
// MarshalJSON implements the json.Marshaler interface for EllipticCurve
func (i EllipticCurve) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface for EllipticCurve
func (i *EllipticCurve) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("EllipticCurve should be a string, got %s", data)
}
var err error
*i, err = EllipticCurveString(s)
return err
}
// MarshalText implements the encoding.TextMarshaler interface for EllipticCurve
func (i EllipticCurve) MarshalText() ([]byte, error) {
return []byte(i.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface for EllipticCurve
func (i *EllipticCurve) UnmarshalText(text []byte) error {
var err error
*i, err = EllipticCurveString(string(text))
return err
}

View File

@@ -0,0 +1,136 @@
// Code generated by "enumer -type RSABits -trimprefix RSABits -text -json -linecomment"; DO NOT EDIT.
package crypto
import (
"encoding/json"
"fmt"
"strings"
)
const (
_RSABitsName_0 = ""
_RSABitsLowerName_0 = ""
_RSABitsName_1 = "2048"
_RSABitsLowerName_1 = "2048"
_RSABitsName_2 = "3072"
_RSABitsLowerName_2 = "3072"
_RSABitsName_3 = "4096"
_RSABitsLowerName_3 = "4096"
)
var (
_RSABitsIndex_0 = [...]uint8{0, 0}
_RSABitsIndex_1 = [...]uint8{0, 4}
_RSABitsIndex_2 = [...]uint8{0, 4}
_RSABitsIndex_3 = [...]uint8{0, 4}
)
func (i RSABits) String() string {
switch {
case i == 0:
return _RSABitsName_0
case i == 2048:
return _RSABitsName_1
case i == 3072:
return _RSABitsName_2
case i == 4096:
return _RSABitsName_3
default:
return fmt.Sprintf("RSABits(%d)", i)
}
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _RSABitsNoOp() {
var x [1]struct{}
_ = x[RSABitsUnspecified-(0)]
_ = x[RSABits2048-(2048)]
_ = x[RSABits3072-(3072)]
_ = x[RSABits4096-(4096)]
}
var _RSABitsValues = []RSABits{RSABitsUnspecified, RSABits2048, RSABits3072, RSABits4096}
var _RSABitsNameToValueMap = map[string]RSABits{
_RSABitsName_0[0:0]: RSABitsUnspecified,
_RSABitsLowerName_0[0:0]: RSABitsUnspecified,
_RSABitsName_1[0:4]: RSABits2048,
_RSABitsLowerName_1[0:4]: RSABits2048,
_RSABitsName_2[0:4]: RSABits3072,
_RSABitsLowerName_2[0:4]: RSABits3072,
_RSABitsName_3[0:4]: RSABits4096,
_RSABitsLowerName_3[0:4]: RSABits4096,
}
var _RSABitsNames = []string{
_RSABitsName_0[0:0],
_RSABitsName_1[0:4],
_RSABitsName_2[0:4],
_RSABitsName_3[0:4],
}
// RSABitsString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func RSABitsString(s string) (RSABits, error) {
if val, ok := _RSABitsNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _RSABitsNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to RSABits values", s)
}
// RSABitsValues returns all values of the enum
func RSABitsValues() []RSABits {
return _RSABitsValues
}
// RSABitsStrings returns a slice of all String values of the enum
func RSABitsStrings() []string {
strs := make([]string, len(_RSABitsNames))
copy(strs, _RSABitsNames)
return strs
}
// IsARSABits returns "true" if the value is listed in the enum definition. "false" otherwise
func (i RSABits) IsARSABits() bool {
for _, v := range _RSABitsValues {
if i == v {
return true
}
}
return false
}
// MarshalJSON implements the json.Marshaler interface for RSABits
func (i RSABits) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface for RSABits
func (i *RSABits) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("RSABits should be a string, got %s", data)
}
var err error
*i, err = RSABitsString(s)
return err
}
// MarshalText implements the encoding.TextMarshaler interface for RSABits
func (i RSABits) MarshalText() ([]byte, error) {
return []byte(i.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface for RSABits
func (i *RSABits) UnmarshalText(text []byte) error {
var err error
*i, err = RSABitsString(string(text))
return err
}

View File

@@ -0,0 +1,116 @@
// Code generated by "enumer -type RSAHasher -trimprefix RSAHasher -text -json -linecomment"; DO NOT EDIT.
package crypto
import (
"encoding/json"
"fmt"
"strings"
)
const _RSAHasherName = "SHA256SHA384SHA512"
var _RSAHasherIndex = [...]uint8{0, 0, 6, 12, 18}
const _RSAHasherLowerName = "sha256sha384sha512"
func (i RSAHasher) String() string {
if i < 0 || i >= RSAHasher(len(_RSAHasherIndex)-1) {
return fmt.Sprintf("RSAHasher(%d)", i)
}
return _RSAHasherName[_RSAHasherIndex[i]:_RSAHasherIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _RSAHasherNoOp() {
var x [1]struct{}
_ = x[RSAHasherUnspecified-(0)]
_ = x[RSAHasherSHA256-(1)]
_ = x[RSAHasherSHA384-(2)]
_ = x[RSAHasherSHA512-(3)]
}
var _RSAHasherValues = []RSAHasher{RSAHasherUnspecified, RSAHasherSHA256, RSAHasherSHA384, RSAHasherSHA512}
var _RSAHasherNameToValueMap = map[string]RSAHasher{
_RSAHasherName[0:0]: RSAHasherUnspecified,
_RSAHasherLowerName[0:0]: RSAHasherUnspecified,
_RSAHasherName[0:6]: RSAHasherSHA256,
_RSAHasherLowerName[0:6]: RSAHasherSHA256,
_RSAHasherName[6:12]: RSAHasherSHA384,
_RSAHasherLowerName[6:12]: RSAHasherSHA384,
_RSAHasherName[12:18]: RSAHasherSHA512,
_RSAHasherLowerName[12:18]: RSAHasherSHA512,
}
var _RSAHasherNames = []string{
_RSAHasherName[0:0],
_RSAHasherName[0:6],
_RSAHasherName[6:12],
_RSAHasherName[12:18],
}
// RSAHasherString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func RSAHasherString(s string) (RSAHasher, error) {
if val, ok := _RSAHasherNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _RSAHasherNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to RSAHasher values", s)
}
// RSAHasherValues returns all values of the enum
func RSAHasherValues() []RSAHasher {
return _RSAHasherValues
}
// RSAHasherStrings returns a slice of all String values of the enum
func RSAHasherStrings() []string {
strs := make([]string, len(_RSAHasherNames))
copy(strs, _RSAHasherNames)
return strs
}
// IsARSAHasher returns "true" if the value is listed in the enum definition. "false" otherwise
func (i RSAHasher) IsARSAHasher() bool {
for _, v := range _RSAHasherValues {
if i == v {
return true
}
}
return false
}
// MarshalJSON implements the json.Marshaler interface for RSAHasher
func (i RSAHasher) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface for RSAHasher
func (i *RSAHasher) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("RSAHasher should be a string, got %s", data)
}
var err error
*i, err = RSAHasherString(s)
return err
}
// MarshalText implements the encoding.TextMarshaler interface for RSAHasher
func (i RSAHasher) MarshalText() ([]byte, error) {
return []byte(i.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface for RSAHasher
func (i *RSAHasher) UnmarshalText(text []byte) error {
var err error
*i, err = RSAHasherString(string(text))
return err
}

238
internal/crypto/web_key.go Normal file
View File

@@ -0,0 +1,238 @@
package crypto
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"github.com/go-jose/go-jose/v4"
"github.com/muhlemmer/gu"
"github.com/zitadel/zitadel/internal/zerrors"
)
type KeyUsage int32
const (
KeyUsageSigning KeyUsage = iota
KeyUsageSAMLMetadataSigning
KeyUsageSAMLResponseSinging
KeyUsageSAMLCA
)
func (u KeyUsage) String() string {
switch u {
case KeyUsageSigning:
return "sig"
case KeyUsageSAMLCA:
return "saml_ca"
case KeyUsageSAMLResponseSinging:
return "saml_response_sig"
case KeyUsageSAMLMetadataSigning:
return "saml_metadata_sig"
}
return ""
}
//go:generate enumer -type WebKeyConfigType -trimprefix WebKeyConfigType -text -json -linecomment
type WebKeyConfigType int
const (
WebKeyConfigTypeUnspecified WebKeyConfigType = iota //
WebKeyConfigTypeRSA
WebKeyConfigTypeECDSA
WebKeyConfigTypeED25519
)
//go:generate enumer -type RSABits -trimprefix RSABits -text -json -linecomment
type RSABits int
const (
RSABitsUnspecified RSABits = 0 //
RSABits2048 RSABits = 2048
RSABits3072 RSABits = 3072
RSABits4096 RSABits = 4096
)
type RSAHasher int
//go:generate enumer -type RSAHasher -trimprefix RSAHasher -text -json -linecomment
const (
RSAHasherUnspecified RSAHasher = iota //
RSAHasherSHA256
RSAHasherSHA384
RSAHasherSHA512
)
type EllipticCurve int
//go:generate enumer -type EllipticCurve -trimprefix EllipticCurve -text -json -linecomment
const (
EllipticCurveUnspecified EllipticCurve = iota //
EllipticCurveP256
EllipticCurveP384
EllipticCurveP512
)
type WebKeyConfig interface {
Alg() jose.SignatureAlgorithm
Type() WebKeyConfigType // Type is needed to make Unmarshal work
IsValid() error
}
func UnmarshalWebKeyConfig(data []byte, configType WebKeyConfigType) (config WebKeyConfig, err error) {
switch configType {
case WebKeyConfigTypeUnspecified:
return nil, zerrors.ThrowInternal(nil, "CRYPT-Ii3AiH", "Errors.Internal")
case WebKeyConfigTypeRSA:
config = new(WebKeyRSAConfig)
case WebKeyConfigTypeECDSA:
config = new(WebKeyECDSAConfig)
case WebKeyConfigTypeED25519:
config = new(WebKeyED25519Config)
default:
return nil, zerrors.ThrowInternal(nil, "CRYPT-Eig8ho", "Errors.Internal")
}
if err = json.Unmarshal(data, config); err != nil {
return nil, zerrors.ThrowInternal(err, "CRYPT-waeR0N", "Errors.Internal")
}
return config, nil
}
type WebKeyRSAConfig struct {
Bits RSABits
Hasher RSAHasher
}
func (c WebKeyRSAConfig) Alg() jose.SignatureAlgorithm {
switch c.Hasher {
case RSAHasherUnspecified:
return ""
case RSAHasherSHA256:
return jose.RS256
case RSAHasherSHA384:
return jose.RS384
case RSAHasherSHA512:
return jose.RS512
default:
return ""
}
}
func (WebKeyRSAConfig) Type() WebKeyConfigType {
return WebKeyConfigTypeRSA
}
func (c WebKeyRSAConfig) IsValid() error {
if !c.Bits.IsARSABits() || c.Bits == RSABitsUnspecified {
return zerrors.ThrowInvalidArgument(nil, "CRYPTO-eaz3T", "Errors.WebKey.Config")
}
if !c.Hasher.IsARSAHasher() || c.Hasher == RSAHasherUnspecified {
return zerrors.ThrowInvalidArgument(nil, "CRYPTO-ODie7", "Errors.WebKey.Config")
}
return nil
}
type WebKeyECDSAConfig struct {
Curve EllipticCurve
}
func (c WebKeyECDSAConfig) Alg() jose.SignatureAlgorithm {
switch c.Curve {
case EllipticCurveUnspecified:
return ""
case EllipticCurveP256:
return jose.ES256
case EllipticCurveP384:
return jose.ES384
case EllipticCurveP512:
return jose.ES512
default:
return ""
}
}
func (WebKeyECDSAConfig) Type() WebKeyConfigType {
return WebKeyConfigTypeECDSA
}
func (c WebKeyECDSAConfig) IsValid() error {
if !c.Curve.IsAEllipticCurve() || c.Curve == EllipticCurveUnspecified {
return zerrors.ThrowInvalidArgument(nil, "CRYPTO-Ii2ai", "Errors.WebKey.Config")
}
return nil
}
func (c WebKeyECDSAConfig) GetCurve() elliptic.Curve {
switch c.Curve {
case EllipticCurveUnspecified:
return nil
case EllipticCurveP256:
return elliptic.P256()
case EllipticCurveP384:
return elliptic.P384()
case EllipticCurveP512:
return elliptic.P521()
default:
return nil
}
}
type WebKeyED25519Config struct{}
func (WebKeyED25519Config) Alg() jose.SignatureAlgorithm {
return jose.EdDSA
}
func (WebKeyED25519Config) Type() WebKeyConfigType {
return WebKeyConfigTypeED25519
}
func (WebKeyED25519Config) IsValid() error {
return nil
}
func GenerateEncryptedWebKey(keyID string, alg EncryptionAlgorithm, genConfig WebKeyConfig) (encryptedPrivate *CryptoValue, public *jose.JSONWebKey, err error) {
private, public, err := generateWebKey(keyID, genConfig)
if err != nil {
return nil, nil, err
}
encryptedPrivate, err = EncryptJSON(private, alg)
if err != nil {
return nil, nil, err
}
return encryptedPrivate, public, nil
}
func generateWebKey(keyID string, genConfig WebKeyConfig) (private, public *jose.JSONWebKey, err error) {
if err = genConfig.IsValid(); err != nil {
return nil, nil, err
}
var key any
switch conf := genConfig.(type) {
case *WebKeyRSAConfig:
key, err = rsa.GenerateKey(rand.Reader, int(conf.Bits))
case *WebKeyECDSAConfig:
key, err = ecdsa.GenerateKey(conf.GetCurve(), rand.Reader)
case *WebKeyED25519Config:
_, key, err = ed25519.GenerateKey(rand.Reader)
}
if err != nil {
return nil, nil, err
}
private = newJSONWebkey(key, keyID, genConfig.Alg())
return private, gu.Ptr(private.Public()), err
}
func newJSONWebkey(key any, keyID string, algorithm jose.SignatureAlgorithm) *jose.JSONWebKey {
return &jose.JSONWebKey{
Key: key,
KeyID: keyID,
Algorithm: string(algorithm),
Use: KeyUsageSigning.String(),
}
}

View File

@@ -0,0 +1,269 @@
package crypto
import (
"crypto/elliptic"
"testing"
"github.com/go-jose/go-jose/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zitadel/zitadel/internal/zerrors"
)
func TestUnmarshalWebKeyConfig(t *testing.T) {
type args struct {
data []byte
configType WebKeyConfigType
}
tests := []struct {
name string
args args
wantConfig WebKeyConfig
wantErr error
}{
{
name: "unspecified",
args: args{
[]byte(`{}`),
WebKeyConfigTypeUnspecified,
},
wantErr: zerrors.ThrowInternal(nil, "CRYPT-Ii3AiH", "Errors.Internal"),
},
{
name: "rsa",
args: args{
[]byte(`{"bits":"2048", "hasher":"sha256"}`),
WebKeyConfigTypeRSA,
},
wantConfig: &WebKeyRSAConfig{
Bits: RSABits2048,
Hasher: RSAHasherSHA256,
},
},
{
name: "ecdsa",
args: args{
[]byte(`{"curve":"p256"}`),
WebKeyConfigTypeECDSA,
},
wantConfig: &WebKeyECDSAConfig{
Curve: EllipticCurveP256,
},
},
{
name: "ed25519",
args: args{
[]byte(`{}`),
WebKeyConfigTypeED25519,
},
wantConfig: &WebKeyED25519Config{},
},
{
name: "unknown type error",
args: args{
[]byte(`{"curve":0}`),
99,
},
wantErr: zerrors.ThrowInternal(nil, "CRYPT-Eig8ho", "Errors.Internal"),
},
{
name: "unmarshal error",
args: args{
[]byte(`~~`),
WebKeyConfigTypeED25519,
},
wantErr: zerrors.ThrowInternal(nil, "CRYPT-waeR0N", "Errors.Internal"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotConfig, err := UnmarshalWebKeyConfig(tt.args.data, tt.args.configType)
require.ErrorIs(t, err, tt.wantErr)
assert.Equal(t, gotConfig, tt.wantConfig)
})
}
}
func TestWebKeyECDSAConfig_Alg(t *testing.T) {
type fields struct {
Curve EllipticCurve
}
tests := []struct {
name string
fields fields
want jose.SignatureAlgorithm
}{
{
name: "unspecified",
fields: fields{
Curve: EllipticCurveUnspecified,
},
want: "",
},
{
name: "P256",
fields: fields{
Curve: EllipticCurveP256,
},
want: jose.ES256,
},
{
name: "P384",
fields: fields{
Curve: EllipticCurveP384,
},
want: jose.ES384,
},
{
name: "P512",
fields: fields{
Curve: EllipticCurveP512,
},
want: jose.ES512,
},
{
name: "default",
fields: fields{
Curve: 99,
},
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := WebKeyECDSAConfig{
Curve: tt.fields.Curve,
}
got := c.Alg()
assert.Equal(t, tt.want, got)
})
}
}
func TestWebKeyECDSAConfig_GetCurve(t *testing.T) {
type fields struct {
Curve EllipticCurve
}
tests := []struct {
name string
fields fields
want elliptic.Curve
}{
{
name: "unspecified",
fields: fields{EllipticCurveUnspecified},
want: nil,
},
{
name: "P256",
fields: fields{EllipticCurveP256},
want: elliptic.P256(),
},
{
name: "P384",
fields: fields{EllipticCurveP384},
want: elliptic.P384(),
},
{
name: "P512",
fields: fields{EllipticCurveP512},
want: elliptic.P521(),
},
{
name: "default",
fields: fields{99},
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := WebKeyECDSAConfig{
Curve: tt.fields.Curve,
}
got := c.GetCurve()
assert.Equal(t, tt.want, got)
})
}
}
func Test_generateEncryptedWebKey(t *testing.T) {
type args struct {
keyID string
genConfig WebKeyConfig
}
tests := []struct {
name string
args args
assertPrivate func(t *testing.T, got *jose.JSONWebKey)
assertPublic func(t *testing.T, got *jose.JSONWebKey)
wantErr error
}{
{
name: "invalid",
args: args{
keyID: "keyID",
genConfig: &WebKeyRSAConfig{
Bits: RSABitsUnspecified,
Hasher: RSAHasherSHA256,
},
},
wantErr: zerrors.ThrowInvalidArgument(nil, "CRYPTO-eaz3T", "Errors.WebKey.Config"),
},
{
name: "RSA",
args: args{
keyID: "keyID",
genConfig: &WebKeyRSAConfig{
Bits: RSABits2048,
Hasher: RSAHasherSHA256,
},
},
assertPrivate: assertJSONWebKey("keyID", "RS256", "sig", false),
assertPublic: assertJSONWebKey("keyID", "RS256", "sig", true),
},
{
name: "ECDSA",
args: args{
keyID: "keyID",
genConfig: &WebKeyECDSAConfig{
Curve: EllipticCurveP256,
},
},
assertPrivate: assertJSONWebKey("keyID", "ES256", "sig", false),
assertPublic: assertJSONWebKey("keyID", "ES256", "sig", true),
},
{
name: "ED25519",
args: args{
keyID: "keyID",
genConfig: &WebKeyED25519Config{},
},
assertPrivate: assertJSONWebKey("keyID", "EdDSA", "sig", false),
assertPublic: assertJSONWebKey("keyID", "EdDSA", "sig", true),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotPrivate, gotPublic, err := generateWebKey(tt.args.keyID, tt.args.genConfig)
require.ErrorIs(t, err, tt.wantErr)
if tt.assertPrivate != nil {
tt.assertPrivate(t, gotPrivate)
}
if tt.assertPublic != nil {
tt.assertPublic(t, gotPublic)
}
})
}
}
func assertJSONWebKey(keyID, algorithm, use string, isPublic bool) func(t *testing.T, got *jose.JSONWebKey) {
return func(t *testing.T, got *jose.JSONWebKey) {
assert.NotNil(t, got)
assert.NotNil(t, got.Key, "key")
assert.Equal(t, keyID, got.KeyID, "keyID")
assert.Equal(t, algorithm, got.Algorithm, "algorithm")
assert.Equal(t, use, got.Use, "user")
assert.Equal(t, isPublic, got.IsPublic(), "isPublic")
}
}

View File

@@ -0,0 +1,116 @@
// Code generated by "enumer -type WebKeyConfigType -trimprefix WebKeyConfigType -text -json -linecomment"; DO NOT EDIT.
package crypto
import (
"encoding/json"
"fmt"
"strings"
)
const _WebKeyConfigTypeName = "RSAECDSAED25519"
var _WebKeyConfigTypeIndex = [...]uint8{0, 0, 3, 8, 15}
const _WebKeyConfigTypeLowerName = "rsaecdsaed25519"
func (i WebKeyConfigType) String() string {
if i < 0 || i >= WebKeyConfigType(len(_WebKeyConfigTypeIndex)-1) {
return fmt.Sprintf("WebKeyConfigType(%d)", i)
}
return _WebKeyConfigTypeName[_WebKeyConfigTypeIndex[i]:_WebKeyConfigTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _WebKeyConfigTypeNoOp() {
var x [1]struct{}
_ = x[WebKeyConfigTypeUnspecified-(0)]
_ = x[WebKeyConfigTypeRSA-(1)]
_ = x[WebKeyConfigTypeECDSA-(2)]
_ = x[WebKeyConfigTypeED25519-(3)]
}
var _WebKeyConfigTypeValues = []WebKeyConfigType{WebKeyConfigTypeUnspecified, WebKeyConfigTypeRSA, WebKeyConfigTypeECDSA, WebKeyConfigTypeED25519}
var _WebKeyConfigTypeNameToValueMap = map[string]WebKeyConfigType{
_WebKeyConfigTypeName[0:0]: WebKeyConfigTypeUnspecified,
_WebKeyConfigTypeLowerName[0:0]: WebKeyConfigTypeUnspecified,
_WebKeyConfigTypeName[0:3]: WebKeyConfigTypeRSA,
_WebKeyConfigTypeLowerName[0:3]: WebKeyConfigTypeRSA,
_WebKeyConfigTypeName[3:8]: WebKeyConfigTypeECDSA,
_WebKeyConfigTypeLowerName[3:8]: WebKeyConfigTypeECDSA,
_WebKeyConfigTypeName[8:15]: WebKeyConfigTypeED25519,
_WebKeyConfigTypeLowerName[8:15]: WebKeyConfigTypeED25519,
}
var _WebKeyConfigTypeNames = []string{
_WebKeyConfigTypeName[0:0],
_WebKeyConfigTypeName[0:3],
_WebKeyConfigTypeName[3:8],
_WebKeyConfigTypeName[8:15],
}
// WebKeyConfigTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func WebKeyConfigTypeString(s string) (WebKeyConfigType, error) {
if val, ok := _WebKeyConfigTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _WebKeyConfigTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to WebKeyConfigType values", s)
}
// WebKeyConfigTypeValues returns all values of the enum
func WebKeyConfigTypeValues() []WebKeyConfigType {
return _WebKeyConfigTypeValues
}
// WebKeyConfigTypeStrings returns a slice of all String values of the enum
func WebKeyConfigTypeStrings() []string {
strs := make([]string, len(_WebKeyConfigTypeNames))
copy(strs, _WebKeyConfigTypeNames)
return strs
}
// IsAWebKeyConfigType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i WebKeyConfigType) IsAWebKeyConfigType() bool {
for _, v := range _WebKeyConfigTypeValues {
if i == v {
return true
}
}
return false
}
// MarshalJSON implements the json.Marshaler interface for WebKeyConfigType
func (i WebKeyConfigType) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface for WebKeyConfigType
func (i *WebKeyConfigType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("WebKeyConfigType should be a string, got %s", data)
}
var err error
*i, err = WebKeyConfigTypeString(s)
return err
}
// MarshalText implements the encoding.TextMarshaler interface for WebKeyConfigType
func (i WebKeyConfigType) MarshalText() ([]byte, error) {
return []byte(i.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface for WebKeyConfigType
func (i *WebKeyConfigType) UnmarshalText(text []byte) error {
var err error
*i, err = WebKeyConfigTypeString(string(text))
return err
}