//
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package goodkey implements public key validation using the boulder/goodkey policy.
package goodkey

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/rsa" // nolint:gosec
	"errors"
	"fmt"

	"github.com/letsencrypt/boulder/goodkey"
)

// ValidatePubKey validates the parameters of an RSA, ECDSA, or ED25519 public key.
func ValidatePubKey(pub crypto.PublicKey) error {
	// goodkey policy enforces:
	// * RSA
	//   * Size of key: 2048 <= size <= 4096, size % 8 = 0
	//   * Exponent E = 65537 (Default exponent for OpenSSL and Golang)
	//   * Small primes check for modulus
	//   * Weak keys generated by Infineon hardware (see https://crocs.fi.muni.cz/public/papers/rsa_ccs17)
	//   * Key is easily factored with Fermat's factorization method
	// * EC
	//   * Public key Q is not the identity element (Ø)
	//   * Public key Q's x and y are within [0, p-1]
	//   * Public key Q is on the curve
	//   * Public key Q's order matches the subgroups (nQ = Ø)
	allowedKeys := &goodkey.AllowedKeys{
		RSA2048:   true,
		RSA3072:   true,
		RSA4096:   true,
		ECDSAP256: true,
		ECDSAP384: true,
		ECDSAP521: true,
	}
	cfg := &goodkey.Config{
		FermatRounds: 100,
		AllowedKeys:  allowedKeys,
	}
	p, err := goodkey.NewPolicy(cfg, nil)
	if err != nil {
		// Should not occur, only chances to return errors are if fermat rounds
		// are <0 or when loading blocked/weak keys from disk (not used here)
		return errors.New("unable to initialize key policy")
	}

	switch pk := pub.(type) {
	case *rsa.PublicKey:
		// ctx is unused
		return p.GoodKey(context.Background(), pub)
	case *ecdsa.PublicKey:
		// ctx is unused
		return p.GoodKey(context.Background(), pub)
	case ed25519.PublicKey:
		return validateEd25519Key(pk)
	}
	return fmt.Errorf("unsupported public key type: %T", pub)
}

// No validations currently, ED25519 supports only one key size.
func validateEd25519Key(_ ed25519.PublicKey) error {
	return nil
}
