GetTLSConfig gets the TLS config for connection. The datasource must already have path-backed TLS material resolved via ResolveTLSMaterial.
(ds *storepb.DataSource)
| 101 | // GetTLSConfig gets the TLS config for connection. |
| 102 | // The datasource must already have path-backed TLS material resolved via ResolveTLSMaterial. |
| 103 | func GetTLSConfig(ds *storepb.DataSource) (*tls.Config, error) { |
| 104 | if !ds.GetUseSsl() { |
| 105 | return nil, nil |
| 106 | } |
| 107 | if HasTLSPath(ds) { |
| 108 | return nil, errors.New("TLS material must be resolved before building TLS config") |
| 109 | } |
| 110 | |
| 111 | cfg := &tls.Config{} |
| 112 | |
| 113 | // Handle client certificates for mutual TLS authentication |
| 114 | // Client certificates can be used with or without server verification |
| 115 | if err := configureClientCertificates(ds, cfg); err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | |
| 119 | // Handle server certificate verification |
| 120 | if !ds.GetVerifyTlsCertificate() { |
| 121 | // Certificate verification is disabled (default for backward compatibility) |
| 122 | // This accepts any certificate presented by the server but still uses encryption |
| 123 | cfg.InsecureSkipVerify = true |
| 124 | return cfg, nil |
| 125 | } |
| 126 | |
| 127 | // Server certificate verification is enabled |
| 128 | // Set up the root CA pool for verifying the server's certificate |
| 129 | var rootCertPool *x509.CertPool |
| 130 | if ds.GetSslCa() == "" { |
| 131 | // No custom CA provided, use system's default trusted CAs |
| 132 | p, err := x509.SystemCertPool() |
| 133 | if err != nil { |
| 134 | return nil, err |
| 135 | } |
| 136 | rootCertPool = p |
| 137 | } else { |
| 138 | // Use the provided CA certificate |
| 139 | rootCertPool = x509.NewCertPool() |
| 140 | if ok := rootCertPool.AppendCertsFromPEM([]byte(ds.GetSslCa())); !ok { |
| 141 | return nil, errors.Errorf("rootCertPool.AppendCertsFromPEM() failed to append server CA pem") |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | cfg.RootCAs = rootCertPool |
| 146 | |
| 147 | // Expected behavior: |
| 148 | // - InsecureSkipVerify = true disables Go's default verification |
| 149 | // - VerifyPeerCertificate implements custom verification that handles intermediate certificates |
| 150 | // - This pattern allows proper verification even when servers send certificates out of order |
| 151 | cfg.InsecureSkipVerify = true |
| 152 | cfg.VerifyPeerCertificate = CreateCertificateVerifier(rootCertPool, ds.GetHost()) |
| 153 | return cfg, nil |
| 154 | } |
| 155 | |
| 156 | // CreateCertificateVerifier returns a verification function that properly handles intermediate certificates |
| 157 | // and validates the hostname matches the certificate. |