forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
191 lines (163 loc) · 4.6 KB
/
api.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
package keystore
import (
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"github.com/rs/cors"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/health"
"github.com/stellar/go/support/render/httpjson"
"github.com/stellar/go/support/render/problem"
)
func init() {
// register errors
problem.RegisterError(httpjson.ErrBadRequest, probInvalidRequest)
problem.RegisterError(sql.ErrNoRows, problem.NotFound)
// register service host as an empty string
problem.RegisterHost("")
}
func (s *Service) wrapMiddleware(handler http.Handler) http.Handler {
handler = authHandler(handler, s.authenticator)
handler = recoverHandler(handler)
handler = corsHandler(handler)
return handler
}
func ServeMux(s *Service) http.Handler {
mux := http.NewServeMux()
mux.Handle("/keys", s.wrapMiddleware(s.keysHTTPMethodHandler()))
mux.Handle("/health", s.wrapMiddleware(health.PassHandler{}))
return mux
}
func (s *Service) keysHTTPMethodHandler() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
jsonHandler(s.getKeys).ServeHTTP(rw, req)
case http.MethodPut:
jsonHandler(s.putKeys).ServeHTTP(rw, req)
case http.MethodDelete:
jsonHandler(s.deleteKeys).ServeHTTP(rw, req)
default:
problem.Render(req.Context(), rw, probMethodNotAllowed)
}
})
}
type authResponse struct {
UserID string `json:"userID"`
}
var forwardHeaders = map[string]struct{}{
"authorization": {},
"cookie": {},
}
func authHandler(next http.Handler, authenticator *Authenticator) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if authenticator == nil {
// to facilitate API testing
next.ServeHTTP(rw, req.WithContext(withUserID(req.Context(), "test-user")))
return
}
var (
proxyReq *http.Request
err error
clientIP string
)
ctx := req.Context()
// set a 5-second timeout
client := http.Client{Timeout: time.Duration(5 * time.Second)}
switch authenticator.APIType {
case REST:
proxyReq, err = http.NewRequest("GET", authenticator.URL, nil)
if err != nil {
problem.Render(ctx, rw, errors.Wrap(err, "creating the auth proxy request"))
return
}
case GraphQL:
// to be implemented later
default:
problem.Render(ctx, rw, probNotAuthorized)
return
}
proxyReq.Header = make(http.Header)
for k, v := range req.Header {
// http headers are case-insensitive
// https://www.ietf.org/rfc/rfc2616.txt
if _, ok := forwardHeaders[strings.ToLower(k)]; ok {
proxyReq.Header[k] = v
}
}
if clientIP, _, err = net.SplitHostPort(req.RemoteAddr); err == nil {
proxyReq.Header.Set("X-Forwarded-For", clientIP)
}
proxyReq.Header.Set("Accept-Encoding", "identity")
resp, err := client.Do(proxyReq)
if err != nil {
problem.Render(ctx, rw, errors.Wrap(err, "sending the auth proxy request"))
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
problem.Render(ctx, rw, probNotAuthorized)
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
problem.Render(ctx, rw, errors.Wrap(err, "reading the auth response"))
return
}
var authResp authResponse
err = json.Unmarshal(body, &authResp)
if err != nil {
log.Ctx(ctx).Infof("Response body as a plain string: %s\n. Response body as a hex dump string: %s\n", string(body), hex.Dump(body))
problem.Render(ctx, rw, errors.Wrap(err, "unmarshaling the auth response"))
return
}
if authResp.UserID == "" {
problem.Render(ctx, rw, probNotAuthorized)
return
}
next.ServeHTTP(rw, req.WithContext(withUserID(ctx, authResp.UserID)))
})
}
func jsonHandler(f interface{}) http.Handler {
h, err := httpjson.ReqBodyHandler(f, httpjson.JSON)
if err != nil {
panic(err)
}
return h
}
func recoverHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
defer func() {
r := recover()
if r == nil {
return
}
err, ok := r.(error)
if !ok {
err = fmt.Errorf("panic: %v", r)
}
if errors.Cause(err) == http.ErrAbortHandler {
panic(err)
}
ctx := req.Context()
log.Ctx(ctx).WithStack(err).Error(err)
problem.Render(ctx, rw, err)
}()
next.ServeHTTP(rw, req)
})
}
func corsHandler(next http.Handler) http.Handler {
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"},
})
return cors.Handler(next)
}