cacert-gosigner/pkg/x509/revoking/revoking_test.go

103 lines
2.6 KiB
Go
Raw Normal View History

2022-04-24 07:25:04 +00:00
/*
Copyright 2021-2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
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 revoking
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type testRepo struct {
revoked []big.Int
}
func (t *testRepo) RevokedCertificates() ([]pkix.RevokedCertificate, error) {
result := make([]pkix.RevokedCertificate, len(t.revoked))
for i, s := range t.revoked {
2022-04-24 07:25:04 +00:00
serialNumber := s
result[i] = pkix.RevokedCertificate{
2022-04-24 07:25:04 +00:00
SerialNumber: &serialNumber,
RevocationTime: time.Now(),
}
}
return result, nil
}
func (t *testRepo) StoreRevocation(revoked *pkix.RevokedCertificate) error {
t.revoked = append(t.revoked, *revoked.SerialNumber)
2022-04-24 07:25:04 +00:00
return nil
}
func randomSerial(t *testing.T) *big.Int {
t.Helper()
2022-04-24 07:25:04 +00:00
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
t.Fatalf("could not generate random serial number: %v", err)
}
2022-04-24 07:25:04 +00:00
return serial
}
func TestRevoking(t *testing.T) {
testRepository := testRepo{revoked: make([]big.Int, 0)}
caKey, err := rsa.GenerateKey(rand.Reader, 3072)
if err != nil {
t.Fatalf("could not generate key pair: %v", err)
}
2022-04-24 07:25:04 +00:00
caTemplate := &x509.Certificate{Subject: pkix.Name{CommonName: "Test CA"}, SerialNumber: randomSerial(t)}
certificateBytes, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, caKey.Public(), caKey)
if err != nil {
t.Fatalf("could not self-sign CA certificate: %v", err)
}
2022-04-24 07:25:04 +00:00
caCertificate, err := x509.ParseCertificate(certificateBytes)
if err != nil {
t.Fatalf("could not create test CA certificate: %v", err)
}
r := NewX509Revoking(&testRepository, x509.ECDSAWithSHA256, caCertificate, caKey)
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
t.Errorf("could not create random serial: %v", err)
}
revoke, err := r.Revoke(&RevokeCertificate{serialNumber: serial, reason: CRLReasonKeyCompromise})
assert.NoError(t, err)
assert.Equal(t, CRLReasonKeyCompromise.BuildExtension(), revoke.Extensions[0])
assert.Equal(t, serial, revoke.SerialNumber)
assert.Contains(t, testRepository.revoked, *serial)
}