Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(plugin/remote-auth): plugin to auth requests via remote server #14041

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog/unreleased/kong/plugins-remote-auth.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
message: |
"**remote-auth**: Add a new plugin to authenticate requests via remote server
type: "feature"
scope: "Plugin"
4 changes: 4 additions & 0 deletions kong-3.10.0-0.rockspec
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,10 @@ build = {
["kong.plugins.redirect.handler"] = "kong/plugins/redirect/handler.lua",
["kong.plugins.redirect.schema"] = "kong/plugins/redirect/schema.lua",

["kong.plugins.remote-auth.access"] = "kong/plugins/remote-auth/access.lua",
["kong.plugins.remote-auth.handler"] = "kong/plugins/remote-auth/handler.lua",
["kong.plugins.remote-auth.schema"] = "kong/plugins/remote-auth/schema.lua",

["kong.vaults.env"] = "kong/vaults/env/init.lua",
["kong.vaults.env.schema"] = "kong/vaults/env/schema.lua",

Expand Down
3 changes: 2 additions & 1 deletion kong/constants.lua
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ local plugins = {
"ai-request-transformer",
"ai-response-transformer",
"standard-webhooks",
"redirect"
"redirect",
"remote-auth",
}

local plugin_map = {}
Expand Down
173 changes: 173 additions & 0 deletions kong/plugins/remote-auth/access.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
local http = require "resty.http"
local url = require "socket.url"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"


local kong = kong
local _M = {}
local fmt = string.format

local function unauthorized(message)
return { status = 401, message = message }
end

local function bad_gateway(message)
return { status = 502, message = message }
end

local parsed_urls_cache = {}
local function parse_url(host_url)
local parsed_url = parsed_urls_cache[host_url]

if parsed_url then
return parsed_url
end

parsed_url = url.parse(host_url)
if not parsed_url.port then
if parsed_url.scheme == "http" then
parsed_url.port = 80
elseif parsed_url.scheme == "https" then
parsed_url.port = 443
end
end
if not parsed_url.path then
parsed_url.path = "/"
end

parsed_urls_cache[host_url] = parsed_url

return parsed_url
end

local function request_auth(conf, request_token)
local method = conf.auth_request_method
local timeout = conf.auth_request_timeout
local keepalive = conf.auth_request_keepalive
local parsed_url = parse_url(conf.auth_request_url)
local request_header = conf.auth_request_token_header
local response_token_header = conf.auth_response_token_header
local host = parsed_url.host
local port = tonumber(parsed_url.port)

local httpc = http.new()
httpc:set_timeout(timeout)

local headers = {
[request_header] = request_token
}

if conf.auth_request_headers then
for h, v in pairs(conf.headers) do
headers[h] = headers[h] or v
end
end

local auth_server_url = fmt("%s://%s:%d%s", parsed_url.scheme, host, port, parsed_url.path)
local res, err = httpc:request_uri(auth_server_url, {
method = method,
headers = headers,
keepalive_timeout = keepalive,
})
if not res then
return nil, "failed request to " .. host .. ":" .. tostring(port) .. ": " .. err
end

if res.status >= 300 then
return nil, "authentication failed with status: " .. res.status
end

local token = res.headers[response_token_header]
return token, nil
end

local function validate_token(token, public_key, max_expiration)
if not token then
return false, nil
end

local jwt, err = jwt_decoder:new(token)
if err then
return false, unauthorized("JWT - Bad token; " .. tostring(err))
end

-- Verify JWT signature
if not jwt:verify_signature(public_key) then
return false, unauthorized("JWT - Invalid signature")
end

-- Verify the JWT expiration
if max_expiration ~= nil and max_expiration > 0 then
local _, errs = jwt:verify_registered_claims({ "exp" })
if errs then
return false, unauthorized("JWT - Token Expired")
end
_, errs = jwt:check_maximum_expiration(max_expiration)
if errs then
return false, unauthorized("JWT - Token Expiry Exceeds Maximum - " .. tostring(errs))
end
end

return true, nil
end

local function authenticate(conf)
local request_header = conf.consumer_auth_header
local request_token = kong.request.get_header(request_header)

-- If the header is missing, then reject the request
if not request_token then
return unauthorized("Missing Token, Unauthorized")
end

-- Make remote request to check credentials
local auth_token, err = request_auth(conf, request_token)
if err then
return unauthorized("Unauthorized: " .. err)
end

-- set header in forwarded request
if auth_token then
_, err = validate_token(auth_token, conf.jwt_public_key, conf.jwt_max_expiration)
if err then
return bad_gateway(err.message)
end

local service_auth_header = conf.service_auth_header
local service_token_prefix = conf.service_auth_header_value_prefix
local header_value = auth_token
if service_token_prefix then
header_value = service_token_prefix .. auth_token
end
kong.service.request.set_header(service_auth_header, header_value)
kong.response.set_header(conf.auth_response_token_header, auth_token)
else
return bad_gateway("Upsteam Authentication server returned an empty response")
end
end


function _M.authenticate(conf)
-- Check if the request has a valid JWT
local authenticated, err = validate_token(
kong.request.get_header(conf.request_authentication_header),
conf.jwt_public_key,
conf.jwt_max_expiration
)
if err then
kong.response.error(err.status, err.message, err.headers)
return
end
-- If the request is authenticated, then we don't need to re-authenticate
if authenticated then
return
end

-- Unauthenticated request needs to be authenticated.
err = authenticate(conf)
if err then
kong.response.error(err.status, err.message, err.headers)
end
end

return _M
12 changes: 12 additions & 0 deletions kong/plugins/remote-auth/handler.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
local access = require "kong.plugins.remote-auth.access"

local plugin = {
PRIORITY = 1100,
VERSION = "0.1.0",
}

function plugin:access(plugin_conf)
access.authenticate(plugin_conf)
end

return plugin
132 changes: 132 additions & 0 deletions kong/plugins/remote-auth/schema.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
local typedefs = require "kong.db.schema.typedefs"

local PLUGIN_NAME = "remote-auth"


local schema = {
name = PLUGIN_NAME,
fields = {
{ consumer = typedefs.no_consumer }, -- this plugin cannot be configured on a consumer (typical for auth plugins)
{ protocols = typedefs.protocols_http }, -- http protocols only
{
config = {
type = "record",
fields = {
{
auth_request_url = typedefs.url {
required = true,
}
},
{
consumer_auth_header = typedefs.header_name {
required = true,
default = "Authorization",
}
},
{
auth_request_method = typedefs.http_method {
required = true,
default = "POST",
}
},
{
auth_request_timeout = typedefs.timeout {
required = true,
default = 10000,
}
},
{
auth_request_keepalive = {
type = "number",
default = 60000,
required = true,
description =
"A value in milliseconds that defines how long an idle connection will live before being closed.",
}
},
{
auth_request_token_header = typedefs.header_name {
required = true,
default = "Authorization",
}
},
{
auth_response_token_header = typedefs.header_name {
required = true,
default = "X-Token"
}
},
{
auth_request_headers = {
description =
"An optional table of headers included in the HTTP message to the upstream server. Values are indexed by header name, and each header name accepts a single string.",
type = "map",
required = false,
keys = typedefs.header_name {
match_none = {
{
pattern = "^[Hh][Oo][Ss][Tt]$",
err = "cannot contain 'Host' header",
},
{
pattern = "^[Cc][Oo][Nn][Tt][Ee][Nn][Tt]%-[Ll][Ee][nn][Gg][Tt][Hh]$",
err = "cannot contain 'Content-Length' header",
},
{
pattern = "^[Cc][Oo][Nn][Tt][Ee][Nn][Tt]%-[Tt][Yy][Pp][Ee]$",
err = "cannot contain 'Content-Type' header",
},
},
},
values = {
type = "string",
referenceable = true,
},
}
},
{
service_auth_header = typedefs.header_name {
required = true,
default = "Authorization",
}
},
{
service_auth_header_value_prefix = {
type = "string",
default = "bearer ",
required = true,
description = "A header value prefix for the upstream service request header value.",
}
},
{
request_authentication_header = typedefs.header_name {
required = true,
default = "X-Token",
}
},
{
jwt_public_key = {
type = "string",
required = true,
description = "The public key used to verify the siguration of issued JWT tokens",
}
},
{
jwt_max_expiration = {
description =
"A value between 0 and 31536000 (365 days) limiting the lifetime of the JWT to maximum_expiration seconds in the future.",
type = "number",
between = { 0, 31536000 },
required = false,
default = 0,
}
},

},
entity_checks = {},
},
},
},
}

return schema
Loading
Loading