-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsinglea-client.lua
More file actions
350 lines (293 loc) · 13.4 KB
/
singlea-client.lua
File metadata and controls
350 lines (293 loc) · 13.4 KB
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
350
--
-- SPDX-License-Identifier: BSD-3-Clause
--
-- Usage:
--
-- (1) Login if necessary, request user token and add it into an original request
-- with custom client parameters:
--
-- server {
-- location ~ ^/any$ {
-- rewrite_by_lua_block {
-- require("singlea-client").new {
-- client_id = "hard_coded_client_id",
-- request_timeout = 10,
-- token_header = "Custom-Authorization",
-- }
-- :login()
-- :token()
-- }
-- # ...
-- }
-- }
--
--
-- (2) Request user token if authenticated only and flush the token if required:
--
-- server {
-- location ~ ^/any$ {
-- rewrite_by_lua_block {
-- require("singlea-client").new()
-- :token(false)
-- }
--
-- # Some request processing, e.g. with FastCGI
-- # ...
--
-- header_filter_by_lua_block {
-- require("singlea-client").new()
-- :flush_token()
-- }
-- }
-- }
--
--
-- (3) Validate user session only:
--
-- server {
-- location ~ ^/any$ {
-- rewrite_by_lua_block {
-- require("singlea-client").new()
-- :validate()
-- }
-- # ...
-- }
-- }
--
local base64 = require "base64"
local http_util = require "http.util"
local resty_http = require "resty.http"
local pkey = require "openssl.pkey"
local digest = require "openssl.digest"
local DEFAULT_LOGIN_PATH = "/login"
local DEFAULT_LOGOUT_PATH = "/logout"
local DEFAULT_VALIDATE_PATH = "/validate"
local DEFAULT_TOKEN_PATH = "/token"
local DEFAULT_ENV_PREFIX = "SINGLEA_"
local DEFAULT_REALM_QUERY_PARAM = "realm"
local DEFAULT_CLIENT_ID_QUERY_PARAM = "client_id"
local DEFAULT_SECRET_QUERY_PARAM = "secret"
local DEFAULT_REDIRECT_URI_QUERY_PARAM = "redirect_uri"
local DEFAULT_SIGNATURE_QUERY_PARAM = "sg"
local DEFAULT_TIMESTAMP_QUERY_PARAM = "ts"
local DEFAULT_SIGNATURE_MD_ALGORITHM = "SHA256"
local DEFAULT_TICKET_COOKIE_NAME = "tkt"
local DEFAULT_TICKET_HEADER = "X-Ticket"
local DEFAULT_TOKEN_DICT = "tokens"
local DEFAULT_TOKEN_HEADER = "Authorization"
local DEFAULT_TOKEN_PREFIX = "Bearer "
local DEFAULT_TOKEN_FLUSH_HEADER = "X-Flush-Token"
local DEFAULT_REQUEST_TIMEOUT = 30
local base64_url_encoder = base64.makeencoder("-", "_")
local function add_signature(query_params, config)
query_params[config.timestamp_query_param] = tostring(os.time())
local param_names = {}
for param in pairs(query_params) do
table.insert(param_names, param)
end
table.sort(param_names)
local param_values = {}
for index, param in ipairs(param_names) do
table.insert(param_values, index, query_params[param])
end
local successful, error, data, signature
successful, error = pcall(function()
data = digest.new(config.signature_md_algorithm)
data:update(table.concat(param_values, "."))
end)
if not successful then
ngx.log(ngx.CRIT, "Cannot create message digest instance: " .. error)
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
successful, error = pcall(function()
signature = config.signature_key:sign(data)
end)
if not successful then
ngx.log(ngx.CRIT, "Signature failed: " .. error)
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
query_params[config.signature_query_param] = base64.encode(signature, base64_url_encoder)
end
local function do_request(config, uri)
local ticket = assert(ngx.var["cookie_" .. config.ticket_cookie_name], "Ticket cookie should be defined")
local query_params = {
[config.client_id_query_param] = config.client_id,
[config.secret_query_param] = config.secret,
[config.realm_query_param] = config.realm,
}
if config.signature_key then
add_signature(query_params, config)
end
local url = config.base_url .. uri .. "?" .. http_util.dict_to_query(query_params)
local httpc = resty_http.new()
local response, error = httpc:request_uri(url, {
method = "GET",
headers = {
[config.ticket_header] = ticket,
},
keepalive_timeout = config.request_timeout,
ssl_verify = config.ssl_verify,
})
if not response then
ngx.log(ngx.CRIT, "Failed to request (" .. url .. "): " .. error)
ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
end
return response
end
local function make_redirect(config, path, redirect_uri)
local query_params = {
[config.client_id_query_param] = config.client_id,
[config.secret_query_param] = config.secret,
[config.redirect_uri_query_param] = redirect_uri,
[config.realm_query_param] = config.realm,
}
if config.signature_key then
add_signature(query_params, config)
end
return ngx.redirect(config.base_url .. path .. "?" .. http_util.dict_to_query(query_params))
end
return {
new = function (params)
params = params or {}
local env_prefix = params.env_prefix or DEFAULT_ENV_PREFIX
local signature_key = params.signature_key or os.getenv(env_prefix .. "SIGNATURE_KEY")
if signature_key ~= nil then
local successful, error
successful, error = pcall(function ()
signature_key = pkey.new(signature_key)
end)
if not successful then
ngx.log(ngx.CRIT, "Cannot read signature private key: " .. error)
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
end
local config = {
base_url = assert(params.base_url or os.getenv(env_prefix .. "BASE_URL"), "SingleA base url should be specified"),
client_id = assert(params.client_id or os.getenv(env_prefix .. "CLIENT_ID"), "Client ID should be specified"),
secret = assert(params.secret or os.getenv(env_prefix .. "SECRET"), "Client secret should be specified"),
client_id_query_param = params.client_id_query_param or os.getenv(env_prefix .. "CLIENT_ID_QUERY_PARAM") or DEFAULT_CLIENT_ID_QUERY_PARAM,
secret_query_param = params.secret_query_param or os.getenv(env_prefix .. "SECRET_QUERY_PARAM") or DEFAULT_SECRET_QUERY_PARAM,
redirect_uri_query_param = params.redirect_uri_query_param or os.getenv(env_prefix .. "REDIRECT_URI_QUERY_PARAM") or DEFAULT_REDIRECT_URI_QUERY_PARAM,
realm_query_param = params.realm_query_param or os.getenv(env_prefix .. "REALM_QUERY_PARAM") or DEFAULT_REALM_QUERY_PARAM,
timestamp_query_param = params.timestamp_query_param or os.getenv(env_prefix .. "TIMESTAMP_QUERY_PARAM") or DEFAULT_TIMESTAMP_QUERY_PARAM,
signature_query_param = params.signature_query_param or os.getenv(env_prefix .. "SIGNATURE_QUERY_PARAM") or DEFAULT_SIGNATURE_QUERY_PARAM,
ticket_cookie_name = params.ticket_cookie_name or os.getenv(env_prefix .. "TICKET_COOKIE_NAME") or DEFAULT_TICKET_COOKIE_NAME,
ticket_header = params.ticket_header or os.getenv(env_prefix .. "TICKET_HEADER") or DEFAULT_TICKET_HEADER,
signature_md_algorithm = params.signature_md_algorithm or os.getenv(env_prefix .. "SIGNATURE_MD_ALGORITHM") or DEFAULT_SIGNATURE_MD_ALGORITHM,
token_dict = params.token_dict or os.getenv(env_prefix .. "TOKEN_DICT") or DEFAULT_TOKEN_DICT,
token_header = params.token_header or os.getenv(env_prefix .. "TOKEN_HEADER") or DEFAULT_TOKEN_HEADER,
token_prefix = params.token_prefix or os.getenv(env_prefix .. "TOKEN_PREFIX") or DEFAULT_TOKEN_PREFIX,
token_flush_header = params.token_flush_header or os.getenv(env_prefix .. "TOKEN_FLUSH_HEADER") or DEFAULT_TOKEN_FLUSH_HEADER,
request_timeout = tonumber(params.request_timeout or os.getenv(env_prefix .. "REQUEST_TIMEOUT") or DEFAULT_REQUEST_TIMEOUT),
ssl_verify = (params.ssl_not_verify or os.getenv(env_prefix .. "SSL_NOT_VERIFY") or '') == '',
client_base_url = params.client_base_url or os.getenv(env_prefix .. "CLIENT_BASE_URL") or ngx.var.scheme .. "://" .. ngx.var.http_host,
realm = params.realm or os.getenv(env_prefix .. "REALM"),
signature_key = signature_key
}
local login_path = params.login_path or os.getenv(env_prefix .. "LOGIN_PATH") or DEFAULT_LOGIN_PATH
local logout_path = params.logout_path or os.getenv(env_prefix .. "LOGOUT_PATH") or DEFAULT_LOGOUT_PATH
local validate_path = params.validate_path or os.getenv(env_prefix .. "VALIDATE_PATH") or DEFAULT_VALIDATE_PATH
local token_path = params.token_path or os.getenv(env_prefix .. "TOKEN_PATH") or DEFAULT_TOKEN_PATH
return {
login = function (self)
if ngx.var["cookie_" .. config.ticket_cookie_name] ~= nil then
local response = do_request(config, validate_path)
if response.status == ngx.HTTP_OK then
return self
end
end
if ngx.var.http_x_requested_with == "XMLHttpRequest" then
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
local redirect_uri = config.client_base_url .. ngx.var.request_uri
if (ngx.var.args or '') ~= '' then
redirect_uri = redirect_uri .. "?" .. ngx.var.args
end
return make_redirect(config, login_path, redirect_uri)
end,
logout = function ()
if ngx.var["cookie_" .. config.ticket_cookie_name] == nil then
return
end
local redirect_uri = config.client_base_url .. ngx.var.request_uri
if (ngx.var.args or '') ~= '' then
redirect_uri = redirect_uri .. "?" .. ngx.var.args
end
return make_redirect(config, logout_path, redirect_uri)
end,
validate = function (self)
if ngx.var["cookie_" .. config.ticket_cookie_name] ~= nil then
local response = do_request(config, validate_path)
if response.status == ngx.HTTP_OK then
return self
end
end
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end,
token = function (self, auth_required)
if (ngx.var["cookie_" .. config.ticket_cookie_name] == nil) then
if auth_required == false then
return
end
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
local dict, key = ngx.shared[config.token_dict], config.client_id .. ngx.var["cookie_" .. config.ticket_cookie_name]
if ngx.req.get_headers()[config.token_flush_header] ~= nil then
local _, delete_error = dict:delete(key)
if delete_error then
ngx.log(ngx.ERR, "Delete token from shared dictionary error: " .. delete_error)
end
end
local token, get_error = dict:get(key)
if token == nil and get_error then
ngx.log(ngx.ERR, "Get token from shared dictionary error: " .. get_error)
end
if token == nil then
local response = do_request(config, token_path)
if response.status ~= ngx.HTTP_OK then
if auth_required == false then
return
end
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
token = response.body
if token == nil then
ngx.log(ngx.ERR, "Response does not contain token (header is empty or does not exist)")
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
local exptime = 0
local cache_control = response.headers["cache-control"]
if cache_control ~= nil then
local max_age, ok = cache_control:gsub("max%-age=(%d+).*", "%1")
if ok then
exptime = tonumber(max_age)
end
end
local success, set_error, forcible = dict:set(key, token, exptime)
if not success and set_error then
ngx.log(ngx.ERR, "Set token into shared dictionary error: " .. set_error)
end
if forcible then
ngx.log(ngx.WARN, "Token was forced into shared memory")
end
end
ngx.req.set_header(config.token_header, config.token_prefix .. token)
return self
end,
flush_token = function (force)
if force ~= true and ngx.header[config.token_flush_header] == nil then
return
end
if (ngx.var["cookie_" .. config.ticket_cookie_name] == nil) then
ngx.log(ngx.WARN, "No ticket cookie, cannot drop token")
return
end
local dict, key = ngx.shared[config.token_dict], config.client_id .. ngx.var["cookie_" .. config.ticket_cookie_name]
local _, delete_error = dict:delete(key)
if delete_error then
ngx.log(ngx.ERR, "Delete token from shared dictionary error: " .. delete_error)
end
end,
}
end
}