Files
seaweedfs/seaweed-block/core/rpc/answer/credentials.go
T

61 lines
1.6 KiB
Go

package answer
import (
"crypto/x509"
"encoding/pem"
"fmt"
"time"
)
// CertificatePool validates locally supplied authentication material before
// any dial. The same provenance is used by RPC and HTTP client constructors.
func CertificatePool(raw []byte, now time.Time) (*x509.CertPool, error) {
count := 0
current := 0
var dateErr error
for rest := raw; len(rest) > 0; {
block, remaining := pem.Decode(rest)
if block == nil {
break
}
rest = remaining
if block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, LocalCredential(err)
}
if err := ValidateCertificate(cert, now); err != nil {
if dateErr == nil {
dateErr = err
}
} else {
current++
}
count++
}
pool := x509.NewCertPool()
if count == 0 || !pool.AppendCertsFromPEM(raw) {
return nil, LocalCredential(fmt.Errorf("CA bundle holds no valid PEM certificate"))
}
// Roots are alternatives during rotation, not one certificate chain.
// An unused stale root does not invalidate a current one. TLS still
// verifies the dates of the chain it actually selects. Preserve the
// local configuration refusal when the bundle has no current entry.
if current == 0 {
return nil, dateErr
}
return pool, nil
}
func ValidateCertificate(cert *x509.Certificate, now time.Time) error {
if now.Before(cert.NotBefore) {
return LocalCredential(fmt.Errorf("certificate is not yet valid (valid from %s)", cert.NotBefore.Format(time.RFC3339)))
}
if now.After(cert.NotAfter) {
return LocalCredential(fmt.Errorf("certificate has expired (valid until %s)", cert.NotAfter.Format(time.RFC3339)))
}
return nil
}