forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_goplugin.go
214 lines (176 loc) · 5.38 KB
/
test_goplugin.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
package main
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"io/ioutil"
"net/http"
"github.com/buger/jsonparser"
"github.com/TykTechnologies/tyk-pump/analytics"
"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/user"
)
// MyPluginPre checks if session is NOT present, adds custom header
// with initial URI path and will be used as "pre" custom MW
func MyPluginPre(rw http.ResponseWriter, r *http.Request) {
session := ctx.GetSession(r)
if session != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.Header().Add(header.XInitialURI, r.URL.RequestURI())
}
// MyPluginAuthCheck does custom auth and will be used as
// "auth_check" custom MW
func MyPluginAuthCheck(rw http.ResponseWriter, r *http.Request) {
// perform auth (only one token "abc" is allowed)
token := r.Header.Get(header.Authorization)
if token != "abc" {
rw.Header().Add(header.XAuthResult, "failed")
rw.WriteHeader(http.StatusForbidden)
_, _ = rw.Write([]byte("auth failed"))
return
}
// create session
session := &user.SessionState{
OrgID: "default",
Alias: "abc-session",
KeyID: token,
}
ctx.SetSession(r, session, true, true)
rw.Header().Add(header.XAuthResult, "OK")
}
// MyPluginPostKeyAuth checks if session is present, adds custom header with session-alias
// and will be used as "post_key_auth" custom MW
func MyPluginPostKeyAuth(rw http.ResponseWriter, r *http.Request) {
session := ctx.GetSession(r)
if session == nil {
rw.Header().Add(header.XSessionAlias, "not found")
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.Header().Add(header.XSessionAlias, session.Alias)
}
// MyPluginPost prepares and sends reply, will be used as "post" custom MW
func MyPluginPost(rw http.ResponseWriter, r *http.Request) {
replyData := map[string]interface{}{
"message": "post message",
}
jsonData, err := json.Marshal(replyData)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
apiDefinition := ctx.GetDefinition(r)
if apiDefinition == nil {
rw.Header().Add("X-Plugin-Data", "null")
} else {
pluginConfig, ok := apiDefinition.ConfigData["my-context-data"].(string)
if !ok || pluginConfig == "" {
rw.Header().Add("X-Plugin-Data", "null")
} else {
rw.Header().Add("X-Plugin-Data", pluginConfig)
}
}
rw.Header().Set(header.ContentType, header.ApplicationJSON)
rw.WriteHeader(http.StatusOK)
rw.Write(jsonData)
}
// MyPluginResponse intercepts response from upstream which we can then manipulate
func MyPluginResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) {
res.Header.Add("X-Response-Added", "resp-added")
var buf bytes.Buffer
buf.Write([]byte(`{"message":"response injected message"}`))
res.Body = ioutil.NopCloser(&buf)
apiDefinition := ctx.GetDefinition(req)
if apiDefinition == nil {
res.Header.Add("X-Plugin-Data", "null")
return
}
pluginConfig, ok := apiDefinition.ConfigData["my-context-data"].(string)
if !ok || pluginConfig == "" {
res.Header.Add("X-Plugin-Data", "null")
return
}
res.Header.Add("X-Plugin-Data", pluginConfig)
}
func MyPluginPerPathFoo(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add("X-foo", "foo")
}
func MyPluginPerPathBar(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add("X-bar", "bar")
}
func MyPluginPerPathResp(rw http.ResponseWriter, r *http.Request) {
// prepare data to send
replyData := map[string]string{
"current_time": "now",
}
jsonData, err := json.Marshal(replyData)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
// send HTTP response from Golang plugin
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
rw.Write(jsonData)
}
func MyAnalyticsPluginDeleteHeader(record *analytics.AnalyticsRecord) {
str, err := base64.StdEncoding.DecodeString(record.RawResponse)
if err != nil {
return
}
var b = &bytes.Buffer{}
b.Write(str)
r := bufio.NewReader(b)
var resp *http.Response
resp, err = http.ReadResponse(r, nil)
if err != nil {
return
}
resp.Header.Del("Server")
var bNew bytes.Buffer
_ = resp.Write(&bNew)
record.RawResponse = base64.StdEncoding.EncodeToString(bNew.Bytes())
}
func MyAnalyticsPluginMaskJSONLoginBody(record *analytics.AnalyticsRecord) {
if record.ContentLength < 1 {
return
}
d, err := base64.StdEncoding.DecodeString(record.RawRequest)
if err != nil {
return
}
var mask = []byte("\"****\"")
const endOfHeaders = "\r\n\r\n"
paths := [][]string{
{"email"},
{"password"},
{"data", "email"},
{"data", "password"},
}
if i := bytes.Index(d, []byte(endOfHeaders)); i > 0 || (i+4) < len(d) {
body := d[i+4:]
jsonparser.EachKey(body, func(idx int, _ []byte, _ jsonparser.ValueType, _ error) {
body, _ = jsonparser.Set(body, mask, paths[idx]...)
}, paths...)
record.RawRequest = base64.StdEncoding.EncodeToString(append(d[:i+4], body...))
}
}
func MyPluginAccessingOASAPI(rw http.ResponseWriter, r *http.Request) {
oas := ctx.GetOASDefinition(r)
rw.Header().Add("X-OAS-Doc-Title", oas.Info.Title)
}
func MyPluginReturningError(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusTeapot)
rw.Write([]byte(http.StatusText(http.StatusTeapot)))
}
func MyPluginApplyingPolicy(rw http.ResponseWriter, r *http.Request) {
session := &user.SessionState{
KeyID: "my-key",
ApplyPolicies: []string{"my-pol"},
}
ctx.SetSession(r, session, true)
}