-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
226 lines (194 loc) · 5.52 KB
/
server.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package server
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/alauda/registry-auth/pkg/server/config"
"github.com/emicklei/go-restful"
"go.uber.org/zap"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
// Server conole data
type Server struct {
BasicConfig config.BasicConfig
ServerConfig config.ServerConfig
proxy *httputil.ReverseProxy
client kubernetes.Interface
processor *AuthProcessor
stop <-chan struct{}
container *restful.Container
Log *zap.Logger
}
var logger *zap.Logger
// New creates new instance
func New() *Server {
return &Server{
container: restful.NewContainer(),
}
}
func getStopSignal() <-chan struct{} {
shutdownHandler := make(chan os.Signal, 2)
ctx, cancel := context.WithCancel(context.Background())
signal.Notify(shutdownHandler, os.Interrupt, syscall.SIGTERM)
go func() {
<-shutdownHandler
cancel()
<-shutdownHandler
os.Exit(1) // second signal. Exit directly.
}()
return ctx.Done()
}
func newWebService() *restful.WebService {
ws := new(restful.WebService)
ws.Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON).
Param(restful.HeaderParameter("Authorization", "Given Bearer token will use this as authorization for the API"))
return ws
}
func (s *Server) L() *zap.Logger {
return s.Log
}
func (s *Server) Container() *restful.Container {
return s.container
}
// ApplyToServer apply to server
func (s *Server) ApplyToServer() error {
ws := newWebService()
logger = s.L().Named("registry-auth")
ws.Doc("Registry Auth")
ws.ApiVersion("v1")
ws.Route(
ws.GET("/auth/token").
To(s.HandleAuth).
Doc("Handle registry auth"),
)
s.container.Add(ws)
s.container.ServeMux.Handle("/v2/", http.HandlerFunc(s.HandleProxy))
ws = newWebService()
ws.Path("/health")
ws.Route(
ws.GET("").
To(func(req *restful.Request, res *restful.Response) {
res.Write([]byte("OK"))
}),
)
s.container.Add(ws)
var err error
s.stop = getStopSignal()
s.processor, err = NewAuthProcessor(s.BasicConfig.AuthPrivateKeyFile, s.BasicConfig.AuthPublicCertFile, s.BasicConfig.AuthIssuer, s.BasicConfig.AuthTokenDuration)
if err != nil {
return err
}
if s.BasicConfig.AuthConfigFile != "" {
if err := WatchConfigFile(s.BasicConfig.AuthConfigFile, s.stop, s.processor); err != nil {
return err
}
}
if s.BasicConfig.AuthConfigNamespace != "" {
kubeconfig, err := clientcmd.BuildConfigFromFlags("", s.BasicConfig.Kubeconfig)
if err != nil {
return err
}
s.client, err = kubernetes.NewForConfig(kubeconfig)
if err != nil {
return err
}
if err := WatchSecret(s.client, s.BasicConfig.AuthConfigNamespace, s.BasicConfig.AuthConfigLabelSelector, s.stop, s.processor); err != nil {
return err
}
}
if s.BasicConfig.AuthThirdpartyServer != "" {
if err := NewThirdpartyAuth(logger, s.BasicConfig.AuthThirdpartyServer, s.processor); err != nil {
return err
}
}
if s.BasicConfig.RegistryBackend != "" {
s.proxy = &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "http"
},
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext(ctx, "tcp", s.BasicConfig.RegistryBackend)
},
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
s.proxy.ModifyResponse = func(res *http.Response) error {
if location := res.Header.Get("Location"); location != "" {
if loc, err := url.Parse(location); err == nil {
loc.Host = ""
loc.Scheme = ""
location = loc.String()
res.Header.Set("Location", location)
}
}
return nil
}
}
return nil
}
func (s *Server) Start() error {
addr := fmt.Sprintf("%s:%d", s.ServerConfig.BindAddress, s.ServerConfig.Port)
handler := s.Container()
connState := func(conn net.Conn, state http.ConnState) {
if state == http.StateNew {
if tcpConn, ok := conn.(*net.TCPConn); ok {
err := tcpConn.SetKeepAlive(true)
if err != nil {
logger.Error(fmt.Sprintf("failed to set keepalive, err: %v", err), zap.String("func", "connState"))
return
}
err = tcpConn.SetKeepAlivePeriod(time.Second * 30)
if err != nil {
logger.Error(fmt.Sprintf("failed to set keepalive period, err: %v", err), zap.String("func", "connState"))
return
}
}
}
}
if s.ServerConfig.TLSCertFile != "" && s.ServerConfig.TLSKeyFile != "" {
cert, err := tls.LoadX509KeyPair(s.ServerConfig.TLSCertFile, s.ServerConfig.TLSKeyFile)
if err != nil {
return err
}
config := tls.Config{
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
},
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
}
listener, err := tls.Listen("tcp", addr, &config)
if err != nil {
return err
}
srv := http.Server{Handler: handler, ConnState: connState}
return srv.Serve(listener)
}
srv := http.Server{Addr: addr, Handler: handler, ConnState: connState}
return srv.ListenAndServe()
}