server.go 8.21 KB
Newer Older
ale's avatar
ale committed
1
2
3
package server

import (
4
	"crypto/tls"
ale's avatar
ale committed
5
	"encoding/json"
ale's avatar
ale committed
6
	"errors"
7
	"fmt"
ale's avatar
ale committed
8
9
	"log"
	"net/http"
10
11
	"net/http/httputil"
	"net/url"
12
	"reflect"
13
	"strings"
ale's avatar
ale committed
14

15
	"git.autistici.org/ai3/go-common/clientutil"
ale's avatar
ale committed
16
	"git.autistici.org/ai3/go-common/serverutil"
17
	"github.com/prometheus/client_golang/prometheus"
ale's avatar
ale committed
18

ale's avatar
ale committed
19
	as "git.autistici.org/ai3/accountserver"
ale's avatar
ale committed
20
21
)

22
23
24
25
26
27
28
29
30
31
32
33
var (
	requestCounter = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "accountserver_requests_total",
		Help: "Total number of requests, by type",
	},
		[]string{"method", "status"})
)

func init() {
	prometheus.MustRegister(requestCounter)
}

34
type actionRegistry struct {
35
	service  *as.AccountService
36
	handlers map[string]reflect.Type
ale's avatar
ale committed
37
38
}

39
func newActionRegistry(service *as.AccountService) *actionRegistry {
40
	return &actionRegistry{
41
		service:  service,
42
		handlers: make(map[string]reflect.Type),
43
	}
ale's avatar
ale committed
44
45
}

46
47
func (r *actionRegistry) Register(path string, rtype as.Request) {
	r.handlers[path] = reflect.ValueOf(rtype).Elem().Type()
ale's avatar
ale committed
48
49
}

50
51
52
// Create a new instance of a Request type, along with the type name
// (used for monitoring).
func (r *actionRegistry) newRequest(path string) (as.Request, string, bool) {
53
54
	h, ok := r.handlers[path]
	if !ok {
55
		return nil, "", false
56
	}
57
58
59
	return reflect.New(h).Interface().(as.Request),
		strings.TrimSuffix(h.Name(), "Request"),
		true
60
61
}

62
func (r *actionRegistry) ServeHTTP(w http.ResponseWriter, httpReq *http.Request) {
63
64
	// Create a new empty request object based on the request
	// path, then decode the HTTP request JSON body onto it.
65
	req, reqTypeName, ok := r.newRequest(httpReq.URL.Path)
66
	if !ok {
67
		http.NotFound(w, httpReq)
68
69
		return
	}
70
	if !serverutil.DecodeJSONRequest(w, httpReq, req) {
71
72
73
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
74

75
	resp, err := r.service.Handle(httpReq.Context(), req)
76
	if err != nil {
77
78
		// Handle structured errors, serve a JSON response.
		status := errToStatus(err)
79
80
		var verr *as.ValidationError
		if errors.As(err, &verr) {
81
82
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(status)
83
			w.Write(verr.JSON()) // nolint
84
85
86
		} else {
			http.Error(w, err.Error(), status)
		}
87
88
89
90
	} else {
		// Don't send nulls, send empty dicts instead.
		if resp == nil {
			resp = emptyResponse
91
		}
ale's avatar
ale committed
92
		serverutil.EncodeJSONResponse(w, resp)
93
	}
ale's avatar
ale committed
94

95
96
	// Now that all is done, we can log the request/response
	// (sanitization might modify the objects in place).
97
	reqData := marshalJSONSanitized(req)
98
	reqStatus := "error"
99
	if err != nil {
100
		log.Printf("request: %s %s -> ERROR: %v", httpReq.URL.Path, reqData, err)
101
102
	} else {
		respData := marshalJSONSanitized(resp)
103
		log.Printf("request: %s %s -> %s", httpReq.URL.Path, reqData, respData)
104
		reqStatus = "ok"
105
	}
106
107
108

	// Increment the request metric.
	requestCounter.WithLabelValues(reqTypeName, reqStatus).Inc()
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
}

// APIServer is the HTTP API interface to AccountService. It
// implements the http.Handler interface.
type APIServer struct {
	*http.ServeMux
}

type apiEndpoint struct {
	path    string
	handler as.Request
}

var (
	readOnlyEndpoints = []apiEndpoint{
		{"/api/user/get", &as.GetUserRequest{}},
		{"/api/user/search", &as.SearchUserRequest{}},
		{"/api/resource/get", &as.GetResourceRequest{}},
		{"/api/resource/search", &as.SearchResourceRequest{}},
		{"/api/resource/check_availability", &as.CheckResourceAvailabilityRequest{}},
	}
	writeEndpoints = []apiEndpoint{
		{"/api/user/create", &as.CreateUserRequest{}},
		{"/api/user/update", &as.UpdateUserRequest{}},
ale's avatar
ale committed
133
		{"/api/user/disable", &as.DisableUserRequest{}},
134
135
136
137
138
139
140
141
142
143
		{"/api/user/admin_update", &as.AdminUpdateUserRequest{}},
		{"/api/user/change_password", &as.ChangeUserPasswordRequest{}},
		{"/api/user/reset_password", &as.ResetPasswordRequest{}},
		{"/api/user/set_account_recovery_hint", &as.SetAccountRecoveryHintRequest{}},
		{"/api/user/enable_otp", &as.EnableOTPRequest{}},
		{"/api/user/disable_otp", &as.DisableOTPRequest{}},
		{"/api/user/create_app_specific_password", &as.CreateApplicationSpecificPasswordRequest{}},
		{"/api/user/delete_app_specific_password", &as.DeleteApplicationSpecificPasswordRequest{}},
		{"/api/resource/set_status", &as.SetResourceStatusRequest{}},
		{"/api/resource/create", &as.CreateResourcesRequest{}},
ale's avatar
ale committed
144
		{"/api/resource/update", &as.AdminUpdateResourceRequest{}},
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
		{"/api/resource/move", &as.MoveResourceRequest{}},
		{"/api/resource/reset_password", &as.ResetResourcePasswordRequest{}},
		{"/api/resource/email/add_alias", &as.AddEmailAliasRequest{}},
		{"/api/resource/email/delete_alias", &as.DeleteEmailAliasRequest{}},
		{"/api/recover_account", &as.AccountRecoveryRequest{}},
	}
)

// New creates a new APIServer. If leaderAddr is not the empty string,
// write requests will be forwarded to that address.
func New(service *as.AccountService, backend as.Backend, leaderAddr string, clientTLS *clientutil.TLSClientConfig) (*APIServer, error) {
	registry := newActionRegistry(service)
	mux := http.NewServeMux()

	for _, ep := range readOnlyEndpoints {
		registry.Register(ep.path, ep.handler)
	}

	var fs *forwardServer
	if leaderAddr != "" {
		var err error
		fs, err = newForwardServer(leaderAddr, clientTLS)
		if err != nil {
			return nil, err
		}
	}
	for _, ep := range writeEndpoints {
		if leaderAddr == "" {
			registry.Register(ep.path, ep.handler)
		} else {
			mux.Handle(ep.path, fs)
		}
	}

	mux.Handle("/", registry)

	return &APIServer{ServeMux: mux}, nil
}

var emptyResponse struct{}

// A forwardServer is just a fancy httputil.ReverseProxy with loop
// detection (we don't want to receive proxied requests if we are not
// the leader).
type forwardServer struct {
	proxy *httputil.ReverseProxy
}

const (
	loopHdr      = "X-Accountserver-Forwarded"
	loopHdrValue = "true"
)

func newForwardServer(leaderURL string, tlsClientConf *clientutil.TLSClientConfig) (*forwardServer, error) {
	leader, err := url.Parse(strings.TrimRight(leaderURL, "/"))
	if err != nil {
		return nil, err
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243

	var tlsConf *tls.Config
	if tlsClientConf != nil {
		tlsConf, err = tlsClientConf.TLSConfig()
		if err != nil {
			return nil, err
		}
	}

	proxy := &httputil.ReverseProxy{
		Director: func(req *http.Request) {
			req.URL.Scheme = leader.Scheme
			req.URL.Host = leader.Host
			req.URL.Path = leader.Path + req.URL.Path

			// Loop protection.
			req.Header.Set(loopHdr, loopHdrValue)

			// Explicitly disable User-Agent so it's not set to default value.
			if _, ok := req.Header["User-Agent"]; !ok {
				req.Header.Set("User-Agent", "")
			}
		},
		Transport: &http.Transport{
			TLSClientConfig: tlsConf,
		},
		BufferPool: newBufferPool(8192, 64),
	}
	return &forwardServer{proxy: proxy}, nil
}

func (s *forwardServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Simple forwarding loop checker, using out-of-band data in
	// the form of a custom HTTP header.
	if req.Header.Get(loopHdr) == loopHdrValue {
		log.Printf("received leader request from %s, aborted", req.RemoteAddr)
		http.Error(w, "This node is not the leader", http.StatusInternalServerError)
		return
	}

	s.proxy.ServeHTTP(w, req)
ale's avatar
ale committed
244
}
ale's avatar
ale committed
245
246
247
248
249
250

func errToStatus(err error) int {
	switch {
	case err == as.ErrUserNotFound, err == as.ErrResourceNotFound:
		return http.StatusNotFound
	case as.IsAuthError(err):
ale's avatar
ale committed
251
		return http.StatusForbidden
ale's avatar
ale committed
252
253
	case as.IsRequestError(err):
		return http.StatusBadRequest
254
255
	case as.IsValidationError(err):
		return http.StatusBadRequest
ale's avatar
ale committed
256
257
258
259
260
	default:
		return http.StatusInternalServerError
	}
}

261
262
263
264
265
266
267
268
269
270
// Some requests contain private information that should not be
// logged: these objects should implement a Sanitize() method that
// modifies the object in-place by editing out the private fields.
type hasSanitize interface {
	Sanitize()
}

func marshalJSONSanitized(obj interface{}) string {
	if s, ok := obj.(hasSanitize); ok {
		s.Sanitize()
ale's avatar
ale committed
271
	}
272
	data, err := json.Marshal(obj)
ale's avatar
ale committed
273
	if err != nil {
274
		return fmt.Sprintf("SERIALIZATION ERROR: %v", err)
ale's avatar
ale committed
275
276
277
	}
	return string(data)
}
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310

// Simple buffer pool for httputil.ReverseProxy.
type bufferPool struct {
	ch      chan []byte
	bufSize int
}

func newBufferPool(bufSize, poolSize int) *bufferPool {
	pool := make(chan []byte, poolSize)
	for i := 0; i < poolSize; i++ {
		pool <- make([]byte, bufSize)
	}
	return &bufferPool{
		ch:      pool,
		bufSize: bufSize,
	}
}

func (p *bufferPool) Get() (b []byte) {
	select {
	case b = <-p.ch:
	default:
		b = make([]byte, p.bufSize)
	}
	return
}

func (p *bufferPool) Put(b []byte) {
	select {
	case p.ch <- b:
	default:
	}
}