2024-06-23 12:37:10 +00:00
|
|
|
package nebula
|
|
|
|
|
2024-10-24 17:52:08 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
2024-12-07 19:36:29 +00:00
|
|
|
"reflect"
|
2024-10-24 17:52:08 +00:00
|
|
|
|
|
|
|
"github.com/slackhq/nebula/cert"
|
|
|
|
)
|
2024-06-23 12:37:10 +00:00
|
|
|
|
|
|
|
// Certificate wraps a NebulaCertificate to provide convenient (and consistent)
|
2024-10-24 17:52:08 +00:00
|
|
|
// text (un)marshaling methods as well as normalization for equality checking.
|
2024-06-23 12:37:10 +00:00
|
|
|
type Certificate struct {
|
|
|
|
inner cert.NebulaCertificate
|
|
|
|
}
|
|
|
|
|
2024-10-24 17:52:08 +00:00
|
|
|
// NewCertificate returns a Certificate wrapping the given one.
|
|
|
|
func NewCertificate(inner cert.NebulaCertificate) (Certificate, error) {
|
|
|
|
// normalize the inner cert by marshaling to and unmarshaling from the PEM.
|
|
|
|
// This allows equality checking in tests to work between certs which have
|
|
|
|
// never been written to disk and those which have.
|
|
|
|
b, err := inner.MarshalToPEM()
|
|
|
|
if err != nil {
|
|
|
|
return Certificate{}, fmt.Errorf("marshaling to PEM: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
normInner, _, err := cert.UnmarshalNebulaCertificateFromPEM(b)
|
|
|
|
if err != nil {
|
|
|
|
return Certificate{}, fmt.Errorf("unmarshaling from PEM: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return Certificate{inner: *normInner}, nil
|
|
|
|
}
|
|
|
|
|
2024-06-23 12:37:10 +00:00
|
|
|
// Unwrap returns the wrapped NebulaCertificate type.
|
|
|
|
func (c Certificate) Unwrap() *cert.NebulaCertificate {
|
|
|
|
return &c.inner
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalText implements the encoding.TextMarshaler interface.
|
|
|
|
func (c Certificate) MarshalText() ([]byte, error) {
|
2024-12-07 19:36:29 +00:00
|
|
|
if reflect.DeepEqual(c, Certificate{}) {
|
|
|
|
return []byte(""), nil
|
|
|
|
}
|
2024-06-23 12:37:10 +00:00
|
|
|
return c.inner.MarshalToPEM()
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalText implements the encoding.TextUnmarshaler interface.
|
|
|
|
func (c *Certificate) UnmarshalText(b []byte) error {
|
2024-12-07 19:36:29 +00:00
|
|
|
if len(b) == 0 {
|
|
|
|
*c = Certificate{}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-06-23 12:37:10 +00:00
|
|
|
nebCrt, _, err := cert.UnmarshalNebulaCertificateFromPEM(b)
|
|
|
|
if err != nil {
|
2024-12-07 19:36:29 +00:00
|
|
|
return fmt.Errorf("unmarshaling nebula certificate from PEM: %w", err)
|
2024-06-23 12:37:10 +00:00
|
|
|
}
|
|
|
|
c.inner = *nebCrt
|
|
|
|
return nil
|
|
|
|
}
|