Files
mtusi2026lab7/internal/security/mtls.go
T
d1frend cc41f601e3
Skeleton contracts / contracts (pull_request) Canceled after 0s
на оценку 4
2026-11-22 23:33:11 +03:00

65 lines
2.0 KiB
Go

package security
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"strings"
)
func ServerMTLSConfig(clientCAFile string, allowedClientURI string, allowedClientURIFile string) (*tls.Config, error) {
clientCAFile = strings.TrimSpace(clientCAFile)
allowedClientURI = strings.TrimSpace(allowedClientURI)
allowedClientURIFile = strings.TrimSpace(allowedClientURIFile)
if clientCAFile == "" || (allowedClientURI == "" && allowedClientURIFile == "") {
return nil, errors.New("TLS_CLIENT_CA_FILE and an allowed client URI source are required")
}
allowedClientURIs := make(map[string]struct{})
if allowedClientURI != "" {
allowedClientURIs[allowedClientURI] = struct{}{}
}
if allowedClientURIFile != "" {
allowedPEM, readErr := os.ReadFile(allowedClientURIFile)
if readErr != nil {
return nil, fmt.Errorf("read allowed client URI file: %w", readErr)
}
for _, line := range strings.Split(string(allowedPEM), "\n") {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "#") {
allowedClientURIs[line] = struct{}{}
}
}
}
if len(allowedClientURIs) == 0 {
return nil, errors.New("allowed client URI set is empty")
}
caPEM, err := os.ReadFile(clientCAFile)
if err != nil {
return nil, fmt.Errorf("read client CA: %w", err)
}
clientRoots := x509.NewCertPool()
if !clientRoots.AppendCertsFromPEM(caPEM) {
return nil, errors.New("client CA file contains no certificate")
}
return &tls.Config{
MinVersion: tls.VersionTLS13,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientRoots,
NextProtos: []string{"h2", "http/1.1"},
VerifyConnection: func(state tls.ConnectionState) error {
if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 {
return errors.New("verified client certificate is required")
}
leaf := state.PeerCertificates[0]
for _, identity := range leaf.URIs {
if _, allowed := allowedClientURIs[identity.String()]; allowed {
return nil
}
}
return fmt.Errorf("client certificate URI SAN is not allowed")
},
}, nil
}