1package syncpkg
2
3import (
4 "crypto/tls"
5 "fmt"
6 "net/http"
7 "os"
8 "path/filepath"
9)
10
11func NewMTLSClient(certFile, keyFile string) (*http.Client, error) {
12 if certFile == "" || keyFile == "" {
13 d, err := mtlsDefaultDir()
14 if err != nil {
15 return nil, err
16 }
17 if certFile == "" {
18 certFile = filepath.Join(d, "client.crt")
19 }
20 if keyFile == "" {
21 keyFile = filepath.Join(d, "client.key")
22 }
23 }
24
25 cert, err := tls.LoadX509KeyPair(certFile, keyFile)
26 if err != nil {
27 return nil, fmt.Errorf("arche+mtls: load client cert %s / %s: %w", certFile, keyFile, err)
28 }
29
30 tlsCfg := &tls.Config{
31 Certificates: []tls.Certificate{cert},
32 InsecureSkipVerify: true, //nolint:gosec
33 MinVersion: tls.VersionTLS12,
34 }
35
36 transport := &http.Transport{TLSClientConfig: tlsCfg}
37 return &http.Client{Transport: transport}, nil
38}
39
40func mtlsDefaultDir() (string, error) {
41 home, err := os.UserHomeDir()
42 if err != nil {
43 return "", fmt.Errorf("arche+mtls: resolve home dir: %w", err)
44 }
45 d := filepath.Join(home, ".config", "arche", "mtls")
46 if err := os.MkdirAll(d, 0o700); err != nil {
47 return "", fmt.Errorf("arche+mtls: create cert dir %s: %w", d, err)
48 }
49 return d, nil
50}