/
apiserver_https.go
100 lines (82 loc) · 2.59 KB
/
apiserver_https.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright 2019 NetApp, Inc. All Rights Reserved.
package rest
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
log "github.com/sirupsen/logrus"
"github.com/netapp/trident/config"
"github.com/netapp/trident/core"
)
type APIServerHTTPS struct {
server *http.Server
caCertFile string
serverCertFile string
serverKeyFile string
}
func NewHTTPSServer(
p core.Orchestrator, address, port, caCertFile, serverCertFile, serverKeyFile string,
) (*APIServerHTTPS, error) {
orchestrator = p
apiServer := &APIServerHTTPS{
server: &http.Server{
Addr: fmt.Sprintf("%s:%s", address, port),
Handler: &tlsAuthHandler{handler: NewRouter()},
TLSConfig: &tls.Config{ClientAuth: tls.RequireAndVerifyClientCert},
ReadTimeout: config.HTTPTimeout,
WriteTimeout: config.HTTPTimeout,
},
caCertFile: caCertFile,
serverCertFile: serverCertFile,
serverKeyFile: serverKeyFile,
}
if caCertFile != "" {
caCert, err := ioutil.ReadFile(caCertFile)
if err != nil {
return nil, fmt.Errorf("could not read CA certificate file: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
apiServer.server.TLSConfig.ClientCAs = caCertPool
}
log.WithField("address", apiServer.server.Addr).Info("Initializing HTTPS REST frontend.")
return apiServer, nil
}
func (s *APIServerHTTPS) Activate() error {
go func() {
log.WithField("address", s.server.Addr).Infof("Activating HTTPS REST frontend.")
err := s.server.ListenAndServeTLS(s.serverCertFile, s.serverKeyFile)
if err != nil {
log.Fatal(err)
}
}()
return nil
}
func (s *APIServerHTTPS) Deactivate() error {
log.WithField("address", s.server.Addr).Infof("Deactivating HTTPS REST frontend.")
ctx, cancel := context.WithTimeout(context.Background(), config.HTTPTimeout)
defer cancel()
return s.server.Shutdown(ctx)
}
func (s *APIServerHTTPS) GetName() string {
return "HTTPS REST"
}
func (s *APIServerHTTPS) Version() string {
return config.OrchestratorAPIVersion
}
type tlsAuthHandler struct {
handler http.Handler
}
func (h *tlsAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Service requests from Trident nodes with a valid client certificate
if len(r.TLS.PeerCertificates) > 0 && r.TLS.PeerCertificates[0].Subject.CommonName == config.ClientCertName {
log.WithField("peerCert", config.ClientCertName).Debug("Authenticated by HTTPS REST frontend.")
h.handler.ServeHTTP(w, r)
} else {
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", config.OrchestratorName))
w.WriteHeader(http.StatusUnauthorized)
}
}