-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.lua
More file actions
342 lines (300 loc) · 10 KB
/
Copy pathhandler.lua
File metadata and controls
342 lines (300 loc) · 10 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
-- Copyright 2020 Patrick Huck
local resty_session = require("resty.session")
local constants = require("kong.constants")
local BasePlugin = require("kong.plugins.base_plugin")
local acl_groups = require("kong.plugins.acl.groups")
local jwt_decoder = require("kong.plugins.jwt.jwt_parser")
local resty_cookie = require("resty.cookie")
-- local pl_pretty = require "pl.pretty"
-- local openssl = require('openssl')
local cjson = require("cjson")
local ngx = ngx
local kong = kong
local tostring = tostring
local CustomHandler = BasePlugin:extend()
CustomHandler.VERSION = "0.0-0"
CustomHandler.PRIORITY = 1004
function CustomHandler:new()
CustomHandler.super.new(self, "grant-proxy-oauth")
end
function CustomHandler:access(config)
CustomHandler.super.access(self)
local consumer = kong.client.get_consumer()
local credential = kong.client.get_credential()
-- check if already authenticated through global session plugin
if config.anonymous and consumer and credential then
local consumer_groups, err = acl_groups.get_consumer_groups(consumer.id)
if err then
return kong.response.exit(500, "failed to retrieve groups for " .. consumer.username)
end
set_consumer(consumer, credential, consumer_groups)
kong.log.notice(consumer.username .. " - session authenticated")
return
end
-- set up session and init with grant cookie
local opts = { name = config.cookie_name, storage = "redis", secret = config.secret }
opts.redis = { host = config.redis }
local session = resty_session.new(opts)
local cookie = resty_session.get_cookie(session)
if not cookie then
kong.log.info("anonymous - grant cookie missing")
return do_authentication(session, nil, config.anonymous)
end
-- URL-unescape cookie and check prefix
cookie = ngx.unescape_uri(cookie)
local prefix = string.sub(cookie, 1, 2)
if prefix ~= "s:" then
return kong.response.exit(500, "wrong cookie prefix")
end
-- get session ID
local sep_idx = string.find(cookie, ".", 3, true)
local session_id = string.sub(cookie, 3, sep_idx - 1)
-- TODO check signature
-- local signed, err = sign(session_id, config.secret)
-- if err then
-- return kong.response.exit(500, err)
-- end
-- if session_id ~= signed then
-- return kong.response.exit(500, "invalid signature")
-- end
-- retrieve session data
local data, err = session.storage:open(session_id)
if err or not data then
local msg = "anonymous - failed to retrieve grant session data: "
local rsn = tostring(err) and err or "empty"
kong.log.notice(msg .. rsn)
return do_authentication(session, nil, config.anonymous)
end
-- serialize session data
data, err = session.serializer.deserialize(data)
if err then
kong.log.notice("anonymous - failed to deserialize grant session data: " .. tostring(err))
return do_authentication(session, nil, config.anonymous)
end
-- ensure grant data exists before accessing it
if not data or not data.grant then
kong.log.notice("anonymous - no grant data found in session")
return do_authentication(session, nil, config.anonymous)
end
-- DEBUG: Log the full response structure
kong.log.err("DEBUG - Grant Response: ", cjson.encode(data.grant.response))
if data.grant.response and data.grant.response.id_token then
-- Wrap in pcall to prevent decoder crashes on bad tokens
local ok, jwt_debug = pcall(jwt_decoder.new, jwt_decoder, data.grant.response.id_token)
if ok and jwt_debug then
kong.log.err("DEBUG - ID Token Claims: ", cjson.encode(jwt_debug.claims))
end
end
-- check if oauth cycle completed
local response = data.grant.response
if type(response) ~= "table" then
kong.log.notice("anonymous - grant oauth cycle not completed yet")
return do_authentication(session, nil, config.anonymous)
end
-- check for error in token request by grant
if response.error then
kong.log.err(response.error)
destroy_grant_session(session, session_id)
return kong.response.exit(500, response.error)
end
-- extract email from provider response
local email = nil
local provider = data.grant.provider
if not provider then
local msg = "Session missing 'provider' field."
kong.log.err(msg)
destroy_grant_session(session, session_id)
return kong.response.exit(500, msg)
end
-- Try to get email from Profile
if response.profile then
-- Standard object style (e.g., most OIDC providers)
if type(response.profile.email) == "string" then
email = response.profile.email
end
-- Handle array-style profiles (e.g. Google) if direct access failed
if type(email) ~= "string" and type(response.profile) == "table" then
for _, prof in ipairs(response.profile) do
if prof.primary then
email = prof.email
break
end
end
end
end
-- If Profile failed, try ID Token
if (type(email) ~= "string" or email == "") and response.id_token then
local jwt, err = jwt_decoder:new(response.id_token)
if not err and jwt and jwt.claims then
if jwt.claims.email then
email = jwt.claims.email
kong.log.notice("Extracted email from ID Token: " .. tostring(email))
else
kong.log.err("ID Token found but contains no 'email' claim")
end
else
kong.log.err("Failed to decode ID token: " .. tostring(err))
end
end
-- catch bad email just in case
if type(email) ~= "string" then
local msg = "could not extract valid email from " .. provider .. " token response"
kong.log.err(msg)
destroy_grant_session(session, session_id)
return kong.response.exit(500, msg)
end
-- authenticate user with username <provider>:<email>
-- different accounts for different providers to avoid potential hijacking
local username = provider .. ":" .. email
kong.log.notice("Attempting authentication for: " .. username)
do_authentication(session, username, config.anonymous)
-- destroy grant session
if kong.client.get_credential() then
destroy_grant_session(session, session_id)
end
end
-- see https://github.com/tj/node-cookie-signature/blob/master/index.js
-- function sign(val, secret)
-- local digest, err = openssl.hmac.digest('sha256', val, secret)
-- if err then
-- return nil, err
-- end
-- local encoded, err = openssl.base64(digest)
-- if err then
-- return nil, err
-- end
-- local signature = encoded -- TODO .replace(/\=+$/, '')
-- return val .. "." .. signature
-- end
function destroy_grant_session(session, session_id)
-- destroy grant session
local ok, err = session.storage:destroy(session_id)
if err or not ok then
local msg = "failed to destroy " .. session_id
if err then
msg = msg .. " - " .. err
end
return kong.response.exit(500, msg)
end
end
function do_authentication(session, consumerid_or_username, anonymous)
-- load consumer
local consumer = nil
if consumerid_or_username then
consumer = kong.client.load_consumer(consumerid_or_username, true)
if not consumer then
-- consumer not created by grant server yet
kong.log.notice("anonymous - user not created yet: " .. consumerid_or_username)
end
end
-- destroy resty_session
session.data = {}
session.present = nil
session.opened = nil
session.started = nil
session.closed = true
session.destroyed = true
-- load and authenticate anonymous consumer if needed
if not consumer then
consumer = kong.client.load_consumer(anonymous, true)
if not consumer then
-- anonymous consumer not created
local msg = "anonymous user not created: " .. anonymous
return kong.response.exit(500, msg)
end
local consumer_groups, err = acl_groups.get_consumer_groups(consumer.id)
if err then
return nil, err
end
return set_consumer(consumer, nil, consumer_groups)
end
-- authenticate user (incl. credential and groups)
local ok, err = authenticate(consumer)
if err then
return kong.response.exit(500, err)
end
if not ok then
return kong.response.exit(500, "failed to authenticate " .. consumer.username)
end
kong.log.notice(consumerid_or_username .. " authenticated")
end
function authenticate(consumer)
local cache_key = kong.db.keyauth_credentials:cache_key(consumer.id)
local credential, err = kong.cache:get(cache_key, nil, load_credential, { id = consumer.id })
if err then
return nil, err
end
local consumer_groups, err = acl_groups.get_consumer_groups(consumer.id)
if err then
return nil, err
end
return set_consumer(consumer, credential, consumer_groups)
end
function load_credential(consumer_pk)
for row, err in kong.db.keyauth_credentials:each_for_consumer(consumer_pk) do
if err then
return nil, err
end
return row
end
end
function set_cookie(key, value)
local cookie, err = resty_cookie:new()
if not cookie then
kong.log.err(err)
return
end
local ok, err = cookie:set({
key = key,
value = value,
path = "/",
domain = os.getenv("COOKIE_DOMAIN"),
secure = false,
samesite = "Strict",
})
if not ok then
kong.log.err(err)
return
end
end
function set_consumer(consumer, credential, groups)
local set_header = kong.service.request.set_header
local clear_header = kong.service.request.clear_header
if consumer.id then
set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
else
clear_header(constants.HEADERS.CONSUMER_ID)
end
if consumer.custom_id then
set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
else
clear_header(constants.HEADERS.CONSUMER_CUSTOM_ID)
end
if consumer.username then
set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
else
clear_header(constants.HEADERS.CONSUMER_USERNAME)
end
if groups then
set_header(constants.HEADERS.AUTHENTICATED_GROUPS, table.concat(groups, ", "))
ngx.ctx.authenticated_groups = groups
else
clear_header(constants.HEADERS.AUTHENTICATED_GROUPS)
end
if credential then
set_cookie("_csrf_token", "authenticated")
clear_header(constants.HEADERS.ANONYMOUS)
if constants.HEADERS.CREDENTIAL_IDENTIFIER then
set_header(constants.HEADERS.CREDENTIAL_IDENTIFIER, credential.id)
end
else
set_cookie("_csrf_token", "anonymous")
set_header(constants.HEADERS.ANONYMOUS, true)
if constants.HEADERS.CREDENTIAL_IDENTIFIER then
clear_header(constants.HEADERS.CREDENTIAL_IDENTIFIER)
end
end
kong.client.authenticate(consumer, credential)
return true
end
return CustomHandler