forked from Taytay/api-proxy-3scale-heroku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nginx.lua
349 lines (282 loc) · 8.89 KB
/
nginx.lua
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
-- -*- mode: lua; -*-
-- Version:
-- Error Messages per service
service_2555417686521 = {
error_auth_failed = 'Authentication failed',
error_auth_missing = 'Authentication parameters missing',
auth_failed_headers = 'text/plain; charset=us-ascii',
auth_missing_headers = 'text/plain; charset=us-ascii',
error_no_match = 'No rule matched',
no_match_headers = 'text/plain; charset=us-ascii',
no_match_status = 404,
auth_failed_status = 403,
auth_missing_status = 403,
}
-- Logging Helpers
function show_table(a)
for k,v in pairs(a) do
local msg = ""
msg = msg.. k
if type(v) == "string" then
msg = msg.. " => " .. v
end
ngx.log(0,msg)
end
end
function log_message(str)
ngx.log(0, str)
end
function log(content)
if type(content) == "table" then
show_table(content)
else
log_message(content)
end
newline()
end
function newline()
ngx.log(0," --- ")
end
-- End Logging Helpers
-- Error Codes
function error_no_credentials(service)
ngx.status = service.auth_missing_status
ngx.header.content_type = service.auth_missing_headers
ngx.print(service.error_auth_missing)
ngx.exit(ngx.HTTP_OK)
end
function error_authorization_failed(service)
ngx.status = service.auth_failed_status
ngx.header.content_type = service.auth_failed_headers
ngx.print(service.error_auth_failed)
ngx.exit(ngx.HTTP_OK)
end
function error_no_match(service)
ngx.status = service.no_match_status
ngx.header.content_type = service.no_match_headers
ngx.print(service.error_no_match)
ngx.exit(ngx.HTTP_OK)
end
-- End Error Codes
--[[
Aux function to split a string
]]--
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
function first_values(a)
r = {}
for k,v in pairs(a) do
if type(v) == "table" then
r[k] = v[1]
else
r[k] = v
end
end
return r
end
function set_or_inc(t, name, delta)
return (t[name] or 0) + delta
end
function build_querystring(query)
local qstr = ""
for i,v in pairs(query) do
qstr = qstr .. 'usage[' .. i .. ']' .. '=' .. v .. '&'
end
return string.sub(qstr, 0, #qstr-1)
end
---
-- Builds a query string from a table.
--
-- This is the inverse of <code>parse_query</code>.
-- @param query A dictionary table where <code>table['name']</code> =
-- <code>value</code>.
-- @return A query string (like <code>"name=value2&name=value2"</code>).
-----------------------------------------------------------------------------
function build_query(query)
local qstr = ""
for i,v in pairs(query) do
qstr = qstr .. i .. '=' .. v .. '&'
end
return string.sub(qstr, 0, #qstr-1)
end
--[[
Mapping between url path to 3scale methods. In here you must output the usage string encoded as a query_string param.
Here there is an example of 2 resources (word, and sentence) and 3 methods. The complexity of this function depends
on the level of control you want to apply. If you only want to report hits for any of your methods it would be as simple
as this:
function extract_usage(request)
return "usage[hits]=1&"
end
In addition. You do not have to do this on LUA, you can do it straight from the nginx conf via the location. For instance:
location ~ ^/v1/word {
set $provider_key null;
set $app_id null;
set $app_key null;
set $usage "usage[hits]=1&";
access_by_lua_file /Users/solso/3scale/proxy/nginx_sentiment.lua;
proxy_pass http://sentiment_backend;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
}
This is totally up to you. We prefer to keep the nginx conf as clean as possible. But you might already have declared
the resources there, in this case, it's better to declare the $usage explicitly
]]--
matched_rules2 = ""
function extract_usage_2555417686521(params, request)
local t = string.split(request," ")
local method = t[1]
local path = t[2]
local found = false
local usage_t = {}
local m = ""
local matched_rules = {}
local args = get_auth_params(nil, method)
local m = ngx.re.match(path,[=[^/api/([\w_\.-]+)/contacts\.json]=])
if (m and method == "GET") then
-- rule: /api/{username}/contacts.json --
params.username = m[1]
table.insert(matched_rules, "/api/{username}/contacts.json")
usage_t["get_contacts"] = set_or_inc(usage_t, "get_contacts", 1)
found = true
end
-- if there was no match, usage is set to nil and it will respond a 404, this behavior can be changed
if found then
matched_rules2 = table.concat(matched_rules, ", ")
return build_querystring(usage_t)
else
return nil
end
end
--[[
Authorization logic
]]--
function get_auth_params(where, method)
local params = {}
if where == "headers" then
params = ngx.req.get_headers()
elseif method == "GET" then
params = ngx.req.get_uri_args()
else
ngx.req.read_body()
params = ngx.req.get_post_args()
end
return first_values(params)
end
function get_credentials_app_id_app_key(params, service)
if params["app_id"] == nil or params["app_key"] == nil then
error_no_credentials(service)
end
end
function get_credentials_access_token(params, service)
if params["access_token"] == nil then -- TODO: check where the params come
error_no_credentials(service)
end
end
function get_credentials_user_key(params, service)
if params["user_key"] == nil then
error_no_credentials(service)
end
end
function get_debug_value()
local h = ngx.req.get_headers()
if h["X-3scale-debug"] == os.getenv("THREESCALE_PROVIDER_KEY") then
return true
else
return false
end
end
function authorize(auth_strat, params, service)
if auth_strat == 'oauth' then
oauth(params, service)
else
authrep(params, service)
end
end
function oauth(params, service)
if ngx.var.usage ~= nil then
ngx.var.usage = add_trans(ngx.var.usage)
end
ngx.var.cached_key = ngx.var.cached_key .. ":" .. ngx.var.usage
local access_tokens = ngx.shared.api_keys
local is_known = access_tokens:get(ngx.var.cached_key)
if is_known ~= 200 then
local res = ngx.location.capture("/_threescale/toauth_authorize?access_token="..ngx.var.access_token..
"&user_id="..params.username,
{ share_all_vars = true })
if res.status ~= 200 then
access_tokens:delete(ngx.var.cached_key)
ngx.status = res.status
ngx.header.content_type = "application/json"
error_authorization_failed(service)
else
access_tokens:set(ngx.var.cached_key,200)
end
ngx.var.cached_key = nil
end
end
function authrep(params, service)
ngx.var.cached_key = ngx.var.cached_key .. ":" .. ngx.var.usage
local api_keys = ngx.shared.api_keys
local is_known = api_keys:get(ngx.var.cached_key)
if is_known ~= 200 then
local res = ngx.location.capture("/threescale_authrep", { share_all_vars = true })
-- IN HERE YOU DEFINE THE ERROR IF CREDENTIALS ARE PASSED, BUT THEY ARE NOT VALID
if res.status ~= 200 then
-- remove the key, if it's not 200 let's go the slow route, to 3scale's backend
api_keys:delete(ngx.var.cached_key)
ngx.status = res.status
ngx.header.content_type = "application/json"
error_authorization_failed(service)
else
api_keys:set(ngx.var.cached_key,200)
end
ngx.var.cached_key = nil
end
end
function add_trans(usage)
local us = usage:split("&")
local ret = ""
for i,v in ipairs(us) do
ret = ret .. "transactions[0][usage]" .. string.sub(v, 6) .. "&"
end
return string.sub(ret, 1, -2)
end
local params = {}
local host = ngx.req.get_headers()["Host"]
local auth_strat = ""
local service = {}
if ngx.var.service_id == '2555417686521' then
local parameters = get_auth_params("not_headers", string.split(ngx.var.request, " ")[1] )
service = service_2555417686521 --
params.access_token = parameters.access_token
get_credentials_access_token(params , service_2555417686521)
ngx.var.cached_key = "2555417686521" .. ":" .. ngx.var.access_token
auth_strat = "oauth"
ngx.var.service_id = "2555417686521"
ngx.var.proxy_pass = "https://backend_address-book-app.herokuapp.com"
ngx.var.usage = extract_usage_2555417686521(params, ngx.var.request)
ngx.var.access_token = parameters.access_token..":"..params.username
end
ngx.var.credentials = build_query(params)
-- WHAT TO DO IF NO USAGE CAN BE DERIVED FROM THE REQUEST.
if ngx.var.usage == nil then
ngx.header["X-3scale-matched-rules"] = ''
error_no_match(service)
end
if get_debug_value() then
ngx.header["X-3scale-matched-rules"] = matched_rules2
ngx.header["X-3scale-credentials"] = ngx.var.credentials
ngx.header["X-3scale-usage"] = ngx.var.usage
end
authorize(auth_strat, params, service)
-- END OF SCRIPT