NewTLSConfigWithContext creates a new tls.Config from the given TLSConfig.
(ctx context.Context, cfg *TLSConfig, optFuncs ...TLSConfigOption)
| 1263 | |
| 1264 | // NewTLSConfigWithContext creates a new tls.Config from the given TLSConfig. |
| 1265 | func NewTLSConfigWithContext(ctx context.Context, cfg *TLSConfig, optFuncs ...TLSConfigOption) (*tls.Config, error) { |
| 1266 | opts := tlsConfigOptions{} |
| 1267 | for _, opt := range optFuncs { |
| 1268 | opt.applyToTLSConfigOptions(&opts) |
| 1269 | } |
| 1270 | |
| 1271 | if err := cfg.Validate(); err != nil { |
| 1272 | return nil, err |
| 1273 | } |
| 1274 | |
| 1275 | tlsConfig := &tls.Config{ |
| 1276 | InsecureSkipVerify: cfg.InsecureSkipVerify, |
| 1277 | MinVersion: uint16(cfg.MinVersion), |
| 1278 | MaxVersion: uint16(cfg.MaxVersion), |
| 1279 | } |
| 1280 | |
| 1281 | if cfg.MaxVersion != 0 && cfg.MinVersion != 0 { |
| 1282 | if cfg.MaxVersion < cfg.MinVersion { |
| 1283 | return nil, errors.New("tls_config.max_version must be greater than or equal to tls_config.min_version if both are specified") |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | // If a CA cert is provided then let's read it in so we can validate the |
| 1288 | // scrape target's certificate properly. |
| 1289 | caSecret, err := toSecret(opts.secretManager, Secret(cfg.CA), cfg.CAFile, cfg.CARef) |
| 1290 | if err != nil { |
| 1291 | return nil, fmt.Errorf("unable to use CA cert: %w", err) |
| 1292 | } |
| 1293 | if caSecret != nil { |
| 1294 | ca, err := caSecret.Fetch(ctx) |
| 1295 | if err != nil { |
| 1296 | return nil, fmt.Errorf("unable to read CA cert: %w", err) |
| 1297 | } |
| 1298 | if !updateRootCA(tlsConfig, []byte(ca)) { |
| 1299 | return nil, fmt.Errorf("unable to use specified CA cert %s", caSecret.Description()) |
| 1300 | } |
| 1301 | } |
| 1302 | |
| 1303 | if len(cfg.ServerName) > 0 { |
| 1304 | tlsConfig.ServerName = cfg.ServerName |
| 1305 | } |
| 1306 | |
| 1307 | // If a client cert & key is provided then configure TLS config accordingly. |
| 1308 | if cfg.usingClientCert() && cfg.usingClientKey() { |
| 1309 | // Verify that client cert and key are valid. |
| 1310 | if _, err := cfg.getClientCertificate(ctx, opts.secretManager); err != nil { |
| 1311 | return nil, err |
| 1312 | } |
| 1313 | tlsConfig.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { |
| 1314 | var ctx context.Context |
| 1315 | if cri != nil { |
| 1316 | ctx = cri.Context() |
| 1317 | } |
| 1318 | return cfg.getClientCertificate(ctx, opts.secretManager) |
| 1319 | } |
| 1320 | } |
| 1321 | |
| 1322 | return tlsConfig, nil |
no test coverage detected
searching dependent graphs…