Commit edbe9607 authored by Solano Morales's avatar Solano Morales
Browse files

Initial commit

parents
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<h1>Kong plugin jwt-keycloak</h1>
> **Attention**: This plugin was originally forked from https://github.com/gbbirkisson/kong-plugin-jwt-keycloak. It was modified to ensure if a jwt token was revoked or not. This can be the case when an admin banns a user and the token was deleted from Keycloaks database. The original plugin doesn't verify such cases and for this sake it was modified.
A plugin for the [Kong Microservice API Gateway](https://konghq.com/solutions/gateway/) to validate access tokens issued by [Keycloak](https://www.keycloak.org/). It uses the [Well-Known Uniform Resource Identifiers](https://tools.ietf.org/html/rfc5785) provided by [Keycloak](https://www.keycloak.org/) to load [JWK](https://tools.ietf.org/html/rfc7517) public keys from issuers that are specifically allowed for each endpoint.
The biggest advantages of this plugin are that it supports:
* Rotating public keys
* Authorization based on token claims:
* `scope`
* `realm_access`
* `resource_access`
* Matching Keycloak users/clients to Kong consumers
If you have any suggestion or comments, please feel free to open an issue on this GitHub page.
## Table of Contents
- [Table of Contents](#table-of-contents)
- [Tested and working for](#tested-and-working-for)
- [Installation](#installation)
- [Using luarocks](#using-luarocks)
- [From source](#from-source)
- [Packing the rock](#packing-the-rock)
- [Installing the rock](#installing-the-rock)
- [Enabling plugin](#enabling-plugin)
- [Changing plugin priority](#changing-plugin-priority)
- [Examples](#examples)
- [Usage](#usage)
- [Enabling on endpoints](#enabling-on-endpoints)
- [Service](#service)
- [Route](#route)
- [Globally](#globally)
- [Parameters](#parameters)
- [Example](#example)
- [Caveats](#caveats)
- [Testing](#testing)
- [Setup before tests](#setup-before-tests)
- [Running tests](#running-tests)
- [Useful debug commands](#useful-debug-commands)
## Tested and working for
| Kong Version | Tests passing |
| ------------ | :----------------: |
| 0.13.x | :x: |
| 0.14.x | :x: |
| 1.0.x | :white_check_mark: |
| 1.1.x | :white_check_mark: |
| 1.2.x | :white_check_mark: |
| 1.3.x | :white_check_mark: |
| 1.4.x | :white_check_mark: |
| 1.5.x | :white_check_mark: |
| 2.0.x | :white_check_mark: |
| 2.1.x | :white_check_mark: |
| 2.2.x | :white_check_mark: |
| 2.3.x | :white_check_mark: |
| Keycloak Version | Tests passing |
| ---------------- | :----------------: |
| 3.X.X | :white_check_mark: |
| 4.X.X | :white_check_mark: |
| 5.X.X | :white_check_mark: |
| 6.X.X | :white_check_mark: |
| 7.X.X | :white_check_mark: |
| 8.X.X | :white_check_mark: |
| 9.X.X | :white_check_mark: |
| 10.X.X | :white_check_mark: |
| 11.X.X | :white_check_mark: |
| 12.X.X | :white_check_mark: |
## Installation
### Using luarocks
```bash
luarocks install kong-plugin-jwt-keycloak
```
### From source
#### Packing the rock
```bash
export PLUGIN_VERSION=1.1.0-1
luarocks make
luarocks pack kong-plugin-jwt-keycloak ${PLUGIN_VERSION}
```
#### Installing the rock
```bash
export PLUGIN_VERSION=1.1.0-1
luarocks install jwt-keycloak-${PLUGIN_VERSION}.all.rock
```
### Enabling plugin
Set enabled kong enabled plugins, i.e. with environmental variable: `KONG_PLUGINS="bundled,jwt-keycloak"`
### Changing plugin priority
In some cases you might want to change the execution priority of the plugin. You can do that by setting an environmental variable: `JWT_KEYCLOAK_PRIORITY="900"`
### Examples
See [Dockerfile](./Dockerfile) or [luarocks Dockerfile](./luarocks.Dockerfile) for more concrete examples.
## Usage
### Enabling on endpoints
The same principle applies to this plugin as the [standard jwt plugin that comes with kong](https://docs.konghq.com/hub/kong-inc/jwt/). You can enable it on service, routes and globally.
#### Service
```bash
curl -X POST http://localhost:8001/services/{service}/plugins \
--data "name=jwt-keycloak" \
--data "config.allowed_iss=http://localhost:8280/auth/realms/master"
```
#### Route
```bash
curl -X POST http://localhost:8001/routes/{route_id}/plugins \
--data "name=jwt-keycloak" \
--data "config.allowed_iss=http://localhost:8280/auth/realms/master"
```
#### Globally
```bash
curl -X POST http://localhost:8001/plugins \
--data "name=jwt-keycloak" \
--data "config.allowed_iss=http://localhost:8280/auth/realms/master"
```
### Parameters
| Parameter | Requied | Default | Description |
| -------------------------------------- | ------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | yes | | The name of the plugin to use, in this case `keycloak-jwt`. |
| service_id | semi | | The id of the Service which this plugin will target. |
| route_id | semi | | The id of the Route which this plugin will target. |
| enabled | no | `true` | Whether this plugin will be applied. |
| config.uri_param_names | no | `jwt` | A list of querystring parameters that Kong will inspect to retrieve JWTs. |
| config.cookie_names | no | | A list of cookie names that Kong will inspect to retrieve JWTs. |
| config.claims_to_verify | no | `exp` | A list of registered claims (according to [RFC 7519](https://tools.ietf.org/html/rfc7519)) that Kong can verify as well. Accepted values: `exp`, `nbf`. |
| config.anonymous | no | | An optional string (consumer uuid) value to use as an “anonymous” consumer if authentication fails. If empty (default), the request will fail with an authentication failure `4xx`. Please note that this value must refer to the Consumer `id` attribute which is internal to Kong, and not its `custom_id`. |
| config.run_on_preflight | no | `true` | A boolean value that indicates whether the plugin should run (and try to authenticate) on `OPTIONS` preflight requests, if set to false then `OPTIONS` requests will always be allowed. |
| config.maximum_expiration | no | `0` | An integer limiting the lifetime of the JWT to `maximum_expiration` seconds in the future. Any JWT that has a longer lifetime will rejected (HTTP 403). If this value is specified, `exp` must be specified as well in the `claims_to_verify` property. The default value of `0` represents an indefinite period. Potential clock skew should be considered when configuring this value. |
| config.algorithm | no | `RS256` | The algorithm used to verify the token’s signature. Can be `HS256`, `HS384`, `HS512`, `RS256`, or `ES256`. |
| config.allowed_iss | yes | | A list of allowed issuers for this route/service/api. Can be specified as a `string` or as a [Pattern](http://lua-users.org/wiki/PatternsTutorial). |
| config.iss_key_grace_period | no | `10` | An integer that sets the number of seconds until public keys for an issuer can be updated after writing new keys to the cache. This is a guard so that the Kong cache will not invalidate every time a token signed with an invalid public key is sent to the plugin. |
| config.well_known_template | false | *see description* | A string template that the well known endpoint for keycloak is created from. String formatting is applied on the template and `%s` is replaced by the issuer of the token. Default value is `%s/.well-known/openid-configuration` |
| config.scope | no | | A list of scopes the token must have to access the api, i.e. `["email"]`. The token only has to have one of the listed scopes to be authorized. |
| config.roles | no | | A list of roles of current client the token must have to access the api, i.e. `["uma_protection"]`. The token only has to have one of the listed roles to be authorized. |
| config.realm_roles | no | | A list of realm roles (`realm_access`) the token must have to access the api, i.e. `["offline_access"]`. The token only has to have one of the listed roles to be authorized. |
| config.client_roles | no | | A list of roles of a different client (`resource_access`) the token must have to access the api, i.e. `["account:manage-account"]`. The format for each entry should be `<CLIENT_NAME>:<ROLE_NAME>`. The token only has to have one of the listed roles to be authorized. |
| config.consumer_match | no | `false` | A boolean value that indicates if the plugin should find a kong consumer with `id`/`custom_id` that equals the `consumer_match_claim` claim in the access token. |
| config.consumer_match_claim | no | `azp` | The claim name in the token that the plugin will try to match the kong `id`/`custom_id` against. |
| config.consumer_match_claim_custom_id | no | `false` | A boolean value that indicates if the plugin should match the `consumer_match_claim` claim against the consumers `id` or `custom_id`. By default it matches the consumer against the `id`. |
| config.consumer_match_ignore_not_found | no | `false` | A boolean value that indicates if the request should be let through regardless if the plugin is able to match the request to a kong consumer or not. |
### Example
Create service and add the plugin to it, and lastly create a route:
```bash
curl -X POST http://localhost:8001/services \
--data "name=mockbin-echo" \
--data "url=http://mockbin.org/echo"
curl -X POST http://localhost:8001/services/mockbin-echo/plugins \
--data "name=jwt-keycloak" \
--data "config.allowed_iss=http://localhost:8280/auth/realms/master"
curl -X POST http://localhost:8001/services/mockbin-echo/routes \
--data "paths=/"
```
Then you can call the API:
```bash
curl http://localhost:8000/
```
This should give you a 401 unauthorized. But if we call the API with a token:
```bash
export CLIENT_ID=<YOUR_CLIENT_ID>
export CLIENT_SECRET=<YOUR_CLIENT_SECRET>
export TOKENS=$(curl -s -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=${CLIENT_ID}" \
-d "client_secret=${CLIENT_SECRET}" \
http://localhost:8280/auth/realms/master/protocol/openid-connect/token)
export ACCESS_TOKEN=$(echo ${TOKENS} | jq -r ".access_token")
curl -H "Authorization: Bearer ${ACCESS_TOKEN}" http://localhost:8000/ \
--data "plugin=working"
```
This should give you the response: `plugin=working`
### Caveats
To verify token issuers, this plugin needs to be able to access the `<ISSUER_REALM_URL>/.well-known/openid-configuration` and `<ISSUER_REALM_URL>/protocol/openid-connect/certs` endpoints of keycloak. If you are getting the error `{ "message": "Unable to get public key for issuer" }` it is probably because for some reason the plugin is unable to access these endpoints.
## Testing
Requires:
* make
* docker
**Because testing uses docker host networking it does not work on MacOS**
### Setup before tests
```bash
make keycloak-start
```
### Running tests
```bash
make test-unit # Unit tests
make test-integration # Integration tests with postgres
make test-integration KONG_DATABASE=cassandra # Integration tests with cassandra
make test # All test with postgres
make test KONG_DATABASE=cassandra # All test with cassandra
make test-all # All test with cassandra and postgres and multiple versions of kong
```
### Useful debug commands
```bash
make kong-log # For proxy logs
make kong-err-proxy # For proxy error logs
make kong-err-admin # For admin error logs
```
package = "kong-plugin-catskillet-jwt-keycloak"
version = "1.0.0-1"
-- The version '1.0.0' is the source code version, the trailing '1' is the version of this rockspec.
-- whenever the source version changes, the rockspec should be reset to 1. The rockspec version is only
-- updated (incremented) when this file changes, but the source remains the same.
local pluginName = package:match("^kong%-plugin%-(.+)$") -- "catskillet-jwt-keycloak"
supported_platforms = {"linux", "macosx"}
source = {
url = "git@git.catskillet.com:public-plugins/plugins/kong-plugin-catskillet-jwt-keycloak",
tag = "v1.0.0",
}
description = {
summary = "A Kong plugin that will validate tokens issued by keycloak",
homepage = "https://git.catskillet.com/public-plugins/plugins/kong-plugin-catskillet-jwt-keycloak",
license = "Apache 2.0"
}
dependencies = {
"lua ~> 5"
}
build = {
type = "builtin",
modules = {
["kong.plugins.jwt-keycloak.validators.issuers"] = "src/validators/issuers.lua",
["kong.plugins.jwt-keycloak.validators.roles"] = "src/validators/roles.lua",
["kong.plugins.jwt-keycloak.validators.scope"] = "src/validators/scope.lua",
["kong.plugins.jwt-keycloak.handler"] = "src/handler.lua",
["kong.plugins.jwt-keycloak.key_conversion"] = "src/key_conversion.lua",
["kong.plugins.jwt-keycloak.keycloak_keys"] = "src/keycloak_keys.lua",
["kong.plugins.jwt-keycloak.schema"] = "src/schema.lua",
}
}
\ No newline at end of file
local url = require "socket.url"
local BasePlugin = require "kong.plugins.base_plugin"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local socket = require "socket"
local keycloak_keys = require("kong.plugins.jwt-keycloak.keycloak_keys")
local validate_issuer = require("kong.plugins.jwt-keycloak.validators.issuers").validate_issuer
local validate_scope = require("kong.plugins.jwt-keycloak.validators.scope").validate_scope
local validate_roles = require("kong.plugins.jwt-keycloak.validators.roles").validate_roles
local validate_realm_roles = require("kong.plugins.jwt-keycloak.validators.roles").validate_realm_roles
local validate_client_roles = require("kong.plugins.jwt-keycloak.validators.roles").validate_client_roles
local re_gmatch = ngx.re.gmatch
local JwtKeycloakHandler = BasePlugin:extend()
local priority_env_var = "JWT_KEYCLOAK_PRIORITY"
local priority
if os.getenv(priority_env_var) then
priority = tonumber(os.getenv(priority_env_var))
else
priority = 1005
end
kong.log.debug('JWT_KEYCLOAK_PRIORITY: ' .. priority)
JwtKeycloakHandler.PRIORITY = priority
JwtKeycloakHandler.VERSION = "1.1.0"
local function warn(conf, p, ...)
if not conf.user_token.cache.debug_print then return end
if args ~= nil then
kong.log.warn(p, unpack(arg))
return
else
kong.log.warn(p)
end
end
local function inspect(conf, p, ...)
if not conf.user_token.cache.debug_print then return end
if args ~= nil then
kong.log.inspect(p, unpack(arg))
return
else
kong.log.inspect(p)
end
end
local function request_token_validation(conf, token, jwt)
warn(conf, 'validate token with authorization server...')
local well_known_endpoint = keycloak_keys.get_wellknown_endpoint(conf.well_known_template, jwt.claims.iss)
local req = url.parse(well_known_endpoint)
local res, err = keycloak_keys.get_request(well_known_endpoint, req.scheme, req.port)
if err then
return nil, err
end
local res, err = keycloak_keys.get_request(
res['userinfo_endpoint'],
req.scheme,
req.port,
{
Authorization = "Bearer "..token,
Host = req.authority
}
)
local debug = {
req = req,
res = res,
err = err
}
inspect(conf, '5 >>>>>>>>>>>>> ', debug)
if err then
warn(conf, '... token is not valid')
return nil
end
warn(conf, '... token is valid')
return res
end
local function validate_token(conf, token, jwt)
warn(conf, '[start] token validation')
local token_cache_key = "token_key_" .. token;
-- kong.log.warn('>>>>>>>>>>>>> token key: '..token_cache_key)
-- kong.log.inspect('>>>>>>>>>>>>> cache: ', conf.user_token)
-- kong.cache:invalidate_local(token_cache_key)
local res, err
-- if conf.use_cache_for_user_token then
if conf.user_token.cache.enabled then
warn(conf, '-------------------')
warn(conf, 'USE CACHE')
warn(conf, '-------------------')
res, err = kong.cache:get(
token_cache_key,
{
-- ttl=conf.ttl_for_user_token_cache
ttl=conf.user_token.cache.ttl
},
request_token_validation,
conf,
token,
jwt
)
else
warn(conf, '-------------------')
warn(conf, 'DONT USE CACHE')
warn(conf, '-------------------')
res, err = request_token_validation(conf, token, jwt)
end
if not res or err then
warn(conf, '[end] token is not valid')
kong.cache:invalidate(token_cache_key)
return nil, err
end
warn(conf, '[end] token is valid')
return res, nil
end
function table_to_string(tbl)
local result = ""
for k, v in pairs(tbl) do
-- Check the key type (ignore any numerical keys - assume its an array)
if type(k) == "string" then
result = result.."[\""..k.."\"]".."="
end
-- Check the value type
if type(v) == "table" then
result = result..table_to_string(v)
elseif type(v) == "boolean" then