github.com/taubyte/tau-cli@v0.1.13-0.20240326000942-487f0d57edfc/lib/domain/validate.go (about) 1 package domainLib 2 3 import ( 4 "crypto/tls" 5 "crypto/x509" 6 "errors" 7 "fmt" 8 "io" 9 10 structureSpec "github.com/taubyte/go-specs/structure" 11 "github.com/taubyte/tau-cli/constants" 12 "github.com/taubyte/utils/uri" 13 ) 14 15 func ValidateCertificateKeyPairAndHostname(domain *structureSpec.Domain) ([]byte, []byte, error) { 16 pair, err := tls.LoadX509KeyPair(domain.CertFile, domain.KeyFile) 17 if err != nil { 18 return nil, nil, fmt.Errorf("failed to load certificate and key file; %s", err) 19 } 20 21 cert, err := x509.ParseCertificate(pair.Certificate[0]) 22 if err != nil { 23 return nil, nil, fmt.Errorf("failed to parse certificate; %s", err) 24 } 25 26 roots, err := x509.SystemCertPool() 27 if err != nil { 28 return nil, nil, fmt.Errorf("failed to get system certificate pool; %s", err) 29 } 30 31 // Runs in testing only! 32 if constants.SelfSignedOkay { 33 if len(pair.Certificate) == 0 { 34 return nil, nil, errors.New("No cert pairs found") 35 } 36 inter, err := x509.ParseCertificate(pair.Certificate[0]) 37 if err != nil { 38 return nil, nil, fmt.Errorf("failed to parse intermediate certificate; %s", err) 39 } 40 roots.AddCert(inter) 41 } 42 43 opts := x509.VerifyOptions{ 44 DNSName: domain.Fqdn, 45 Roots: roots, 46 } 47 48 _, err = cert.Verify(opts) 49 if err != nil { 50 return nil, nil, fmt.Errorf("failed to verify certificate; %s", err.Error()) 51 } 52 53 // Convert Certificate files into bytes 54 reader, err := uri.Open(domain.CertFile) 55 if err != nil { 56 return nil, nil, fmt.Errorf("Failed opening file. %w", err) 57 } 58 defer reader.Close() 59 certBytes, err := io.ReadAll(reader) 60 if err != nil { 61 return nil, nil, fmt.Errorf("Failed reading file. %w", err) 62 } 63 64 //Convert Key files into bytes 65 reader, err = uri.Open(domain.KeyFile) 66 if err != nil { 67 return nil, nil, fmt.Errorf("Failed opening file. %w", err) 68 } 69 defer reader.Close() 70 keyBytes, err := io.ReadAll(reader) 71 if err != nil { 72 return nil, nil, fmt.Errorf("Failed reading file. %w", err) 73 } 74 return certBytes, keyBytes, nil 75 }