-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
200 lines (163 loc) · 3.9 KB
/
proxy.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
package index
import (
"bytes"
"crypto/ecdsa"
"encoding/json"
"io"
"log/slog"
"net/http"
"strings"
"github.com/opensearch-project/opensearch-go/v2"
"github.com/ttab/elephantine"
)
type ActiveIndexGetter interface {
GetActiveIndex() (*opensearch.Client, string)
}
type ElasticProxy struct {
logger *slog.Logger
publicJWTKey *ecdsa.PublicKey
active ActiveIndexGetter
}
func NewElasticProxy(
logger *slog.Logger,
active ActiveIndexGetter,
publicJWTKey *ecdsa.PublicKey,
) *ElasticProxy {
return &ElasticProxy{
logger: logger,
active: active,
publicJWTKey: publicJWTKey,
}
}
func (ep *ElasticProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger := ep.logger.With(elephantine.LogKeyRoute, r.URL.Path)
parts := splitPath(r.URL.Path)
switch {
case len(parts) <= 2 && parts[len(parts)-1] == "_search":
ElasticHandler(logger, w, r,
ep.searchHandler)
default:
ElasticHandler(logger, w, r,
func(w http.ResponseWriter, r *http.Request) error {
return ElasticErrorf(ErrorTypeNotFound, "no such route")
})
}
}
func splitPath(path string) []string {
return strings.Split(strings.Trim(path, "/"), "/")
}
func (ep *ElasticProxy) searchHandler(
w http.ResponseWriter, r *http.Request,
) error {
ctx := r.Context()
authorization := r.Header.Get("Authorization")
if authorization == "" {
return ElasticErrorf(
ErrorTypeUnauthorized,
"no authorization header")
}
client, indexSet := ep.active.GetActiveIndex()
if client == nil {
return ElasticErrorf(
ErrorTypeClusterUnavailable,
"the active index is not set")
}
indexBase := "documents-" + indexSet + "-"
parts := splitPath(r.URL.Path)
indicesParam := "_all"
if len(parts) == 2 {
indicesParam = parts[0]
}
var indices []string
switch indicesParam {
case "", "*", "_all":
indices = []string{indexBase + "*"}
default:
indices = strings.Split(indicesParam, ",")
for i := range indices {
indices[i] = indexBase + indices[i]
}
}
auth, err := elephantine.AuthInfoFromHeader(
ep.publicJWTKey, authorization)
if err != nil {
return ElasticErrorf(
ErrorTypeUnauthorized,
"invalid token: %v", err)
}
if !auth.Claims.HasScope("search") {
return ElasticErrorf(
ErrorTypeAccessDenied,
"missing 'search' permission")
}
var rawQuery RawSearchRequest
dec := json.NewDecoder(r.Body)
err = dec.Decode(&rawQuery)
if err != nil {
return ElasticErrorf(
ErrorTypeBadRequest,
"failed to parse request body: %v", err)
}
var filter []ElasticQuery
filter = append(filter,
ElasticQuery{
Term: map[string]string{
"readers": auth.Claims.Subject,
},
},
)
for _, unit := range auth.Claims.Units {
filter = append(filter, ElasticQuery{
Term: map[string]string{
"readers": unit,
},
})
}
rootQuery := ElasticQuery{
Bool: &BooleanQuery{
Filter: []ElasticQuery{
{Bool: &BooleanQuery{
Should: filter,
}},
},
Must: []json.RawMessage{rawQuery.Query},
},
}
var searchBody bytes.Buffer
enc := json.NewEncoder(&searchBody)
err = enc.Encode(ElasticSearchRequest{
Query: rootQuery,
Fields: rawQuery.Fields,
Source: rawQuery.Source,
Sort: rawQuery.Sort,
From: rawQuery.From,
Size: rawQuery.Size,
})
if err != nil {
return ElasticErrorf(
ErrorTypeInternal,
"failed to marshal upstream search request: %v", err)
}
res, err := client.Search(
client.Search.WithIndex(indices...),
client.Search.WithContext(ctx),
client.Search.WithBody(&searchBody))
if err != nil {
return ElasticErrorf(
ErrorTypeInternal,
"failed to perform request: %v", err)
}
defer elephantine.SafeClose(ep.logger, "search response", res.Body)
header := w.Header()
for k, v := range res.Header {
header[k] = v
}
w.WriteHeader(res.StatusCode)
_, err = io.Copy(w, res.Body)
if err != nil {
ep.logger.ErrorContext(ctx,
"failed to proxy search response to client",
elephantine.LogKeyError, err)
}
return nil
}