├── .env
├── .github
└── ISSUE_TEMPLATE.md
├── .gitignore
├── .luacov
├── .travis.yml
├── LICENSE
├── README.md
├── bin
├── build-env.sh
├── run-unit-tests.sh
└── teardown-env.sh
├── ci
├── root.sh
├── run.sh
└── setup.sh
├── docs
└── kong_oidc_flow.png
├── kong-oidc-1.1.0-0.rockspec
├── kong
└── plugins
│ └── oidc
│ ├── filter.lua
│ ├── handler.lua
│ ├── schema.lua
│ ├── session.lua
│ └── utils.lua
├── spec
└── plugins
│ └── oidc
│ └── access_spec.lua
└── test
├── docker
├── integration
│ ├── Dockerfile
│ ├── _network_functions
│ ├── docker-compose.yml
│ └── setup.py
└── unit
│ └── Dockerfile
└── unit
├── base_case.lua
├── mockable_case.lua
├── run.sh
├── test_filter.lua
├── test_filters_advanced.lua
├── test_handler_mocking_openidc.lua
├── test_introspect.lua
├── test_utils.lua
└── test_utils_bearer_access_token.lua
/.env:
--------------------------------------------------------------------------------
1 | BUILD_IMG_NAME=nokia/kong-oidc
2 | INTEGRATION_PATH=test/docker/integration
3 | UNIT_PATH=test/docker/unit
4 |
5 | KONG_BASE_TAG=:1.0-centos
6 | KONG_TAG=
7 | KONG_DB_TAG=:10.1
8 | KONG_DB_PORT=5432
9 | KONG_DB_USER=kong
10 | KONG_DB_PW=kong
11 | KONG_DB_NAME=kong
12 | KONG_HTTP_PROXY_PORT=8000
13 | KONG_HTTP_ADMIN_PORT=8001
14 |
15 | KEYCLOAK_TAG=:4.8.3.Final
16 | KEYCLOAK_PORT=8080
17 | KEYCLOAK_USER=admin
18 | KEYCLOAK_PW=password
--------------------------------------------------------------------------------
/.github/ ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | 1. Used Kong OIDC plugin version:
2 |
3 | 2. Used Kong version:
4 |
5 | 3. Kong OIDC plugin configuration:
6 |
7 | 4. Used OIDC provider:
8 |
9 | 5. Issue description:
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # emacs
2 | *~
3 | \#*\#
4 | .\#*
5 | lua_install
6 | luacov.stats.out
--------------------------------------------------------------------------------
/.luacov:
--------------------------------------------------------------------------------
1 | return {
2 | ["include"] = {
3 | 'kong/plugins/oidc'
4 | },
5 | }
6 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # .travis.yaml
2 |
3 | language: python
4 |
5 | sudo: true
6 |
7 | env:
8 | - LUA_VERSION="5.1" KONG_VERSION="0.13.0-0" LUA_RESTY_OPENIDC_VERSION="1.6.1-1"
9 | - LUA_VERSION="5.1" KONG_VERSION="0.12.3-0" LUA_RESTY_OPENIDC_VERSION="1.6.1-1"
10 | - LUA_VERSION="5.1" KONG_VERSION="0.11.2-0" LUA_RESTY_OPENIDC_VERSION="1.6.1-1"
11 | - LUA_VERSION="5.1" KONG_VERSION="1.0.2-0" LUA_RESTY_OPENIDC_VERSION="1.6.1-1"
12 |
13 | script:
14 | - sudo -E bash ci/root.sh
15 | - . ci/setup.sh
16 | - . ci/run.sh
17 |
18 | after_success:
19 | - luarocks install luacov-coveralls
20 | - luacov-coveralls
21 |
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # What is Kong OIDC plugin
2 |
3 | [](https://gitter.im/nokia/kong-oidc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4 |
5 | **Continuous Integration:** [](https://travis-ci.org/nokia/kong-oidc)
6 | [](https://coveralls.io/github/nokia/kong-oidc?branch=master)
7 |
8 | **kong-oidc** is a plugin for [Kong](https://github.com/Mashape/kong) implementing the
9 | [OpenID Connect](http://openid.net/specs/openid-connect-core-1_0.html) Relying Party (RP) functionality.
10 |
11 | It authenticates users against an OpenID Connect Provider using
12 | [OpenID Connect Discovery](http://openid.net/specs/openid-connect-discovery-1_0.html)
13 | and the Basic Client Profile (i.e. the Authorization Code flow).
14 |
15 | It maintains sessions for authenticated users by leveraging `lua-resty-openidc` thus offering
16 | a configurable choice between storing the session state in a client-side browser cookie or use
17 | in of the server-side storage mechanisms `shared-memory|memcache|redis`.
18 |
19 | It supports server-wide caching of resolved Discovery documents and validated Access Tokens.
20 |
21 | It can be used as a reverse proxy terminating OAuth/OpenID Connect in front of an origin server so that
22 | the origin server/services can be protected with the relevant standards without implementing those on
23 | the server itself.
24 |
25 | Introspection functionality add capability for already authenticated users and/or applications that
26 | already posses acces token to go through kong. The actual token verification is then done by Resource Server.
27 |
28 | ## How does it work
29 |
30 | The diagram below shows the message exchange between the involved parties.
31 |
32 | 
33 |
34 | The `X-Userinfo` header contains the payload from the Userinfo Endpoint
35 |
36 | ```
37 | X-Userinfo: {"preferred_username":"alice","id":"60f65308-3510-40ca-83f0-e9c0151cc680","sub":"60f65308-3510-40ca-83f0-e9c0151cc680"}
38 | ```
39 |
40 | The plugin also sets the `ngx.ctx.authenticated_consumer` variable, which can be using in other Kong plugins:
41 | ```
42 | ngx.ctx.authenticated_consumer = {
43 | id = "60f65308-3510-40ca-83f0-e9c0151cc680", -- sub field from Userinfo
44 | username = "alice" -- preferred_username from Userinfo
45 | }
46 | ```
47 |
48 |
49 | ## Dependencies
50 |
51 | **kong-oidc** depends on the following package:
52 |
53 | - [`lua-resty-openidc`](https://github.com/pingidentity/lua-resty-openidc/)
54 |
55 |
56 | ## Installation
57 |
58 | If you're using `luarocks` execute the following:
59 |
60 | luarocks install kong-oidc
61 |
62 | You also need to set the `KONG_PLUGINS` environment variable
63 |
64 | export KONG_PLUGINS=oidc
65 |
66 | ## Usage
67 |
68 | ### Parameters
69 |
70 | | Parameter | Default | Required | description |
71 | | --- | --- | --- | --- |
72 | | `name` || true | plugin name, has to be `oidc` |
73 | | `config.client_id` || true | OIDC Client ID |
74 | | `config.client_secret` || true | OIDC Client secret |
75 | | `config.discovery` | https://.well-known/openid-configuration | false | OIDC Discovery Endpoint (`/.well-known/openid-configuration`) |
76 | | `config.scope` | openid | false| OAuth2 Token scope. To use OIDC it has to contains the `openid` scope |
77 | | `config.ssl_verify` | false | false | Enable SSL verification to OIDC Provider |
78 | | `config.session_secret` | | false | Additional parameter, which is used to encrypt the session cookie. Needs to be random |
79 | | `config.introspection_endpoint` | | false | Token introspection endpoint |
80 | | `config.timeout` | | false | OIDC endpoint calls timeout |
81 | | `config.introspection_endpoint_auth_method` | client_secret_basic | false | Token introspection auth method. resty-openidc supports `client_secret_(basic|post)` |
82 | | `config.bearer_only` | no | false | Only introspect tokens without redirecting |
83 | | `config.realm` | kong | false | Realm used in WWW-Authenticate response header |
84 | | `config.logout_path` | /logout | false | Absolute path used to logout from the OIDC RP |
85 |
86 | ### Enabling
87 |
88 | To enable the plugin only for one API:
89 |
90 | ```
91 | POST /apis//plugins/ HTTP/1.1
92 | Host: localhost:8001
93 | Content-Type: application/x-www-form-urlencoded
94 | Cache-Control: no-cache
95 |
96 | name=oidc&config.client_id=kong-oidc&config.client_secret=29d98bf7-168c-4874-b8e9-9ba5e7382fa0&config.discovery=https%3A%2F%2F%2F.well-known%2Fopenid-configuration
97 | ```
98 |
99 | To enable the plugin globally:
100 | ```
101 | POST /plugins HTTP/1.1
102 | Host: localhost:8001
103 | Content-Type: application/x-www-form-urlencoded
104 | Cache-Control: no-cache
105 |
106 | name=oidc&config.client_id=kong-oidc&config.client_secret=29d98bf7-168c-4874-b8e9-9ba5e7382fa0&config.discovery=https%3A%2F%2F%2F.well-known%2Fopenid-configuration
107 | ```
108 |
109 | A successful response:
110 | ```
111 | HTTP/1.1 201 Created
112 | Date: Tue, 24 Oct 2017 19:37:38 GMT
113 | Content-Type: application/json; charset=utf-8
114 | Transfer-Encoding: chunked
115 | Connection: keep-alive
116 | Access-Control-Allow-Origin: *
117 | Server: kong/0.11.0
118 |
119 | {
120 | "created_at": 1508871239797,
121 | "config": {
122 | "response_type": "code",
123 | "client_id": "kong-oidc",
124 | "discovery": "https:///.well-known/openid-configuration",
125 | "scope": "openid",
126 | "ssl_verify": "no",
127 | "client_secret": "29d98bf7-168c-4874-b8e9-9ba5e7382fa0",
128 | "token_endpoint_auth_method": "client_secret_post"
129 | },
130 | "id": "58cc119b-e5d0-4908-8929-7d6ed73cb7de",
131 | "enabled": true,
132 | "name": "oidc",
133 | "api_id": "32625081-c712-4c46-b16a-5d6d9081f85f"
134 | }
135 | ```
136 |
137 | ### Upstream API request
138 |
139 | The plugin adds a additional `X-Userinfo`, `X-Access-Token` and `X-Id-Token` headers to the upstream request, which can be consumer by upstream server. All of them are base64 encoded:
140 |
141 | ```
142 | GET / HTTP/1.1
143 | Host: netcat:9000
144 | Connection: keep-alive
145 | X-Forwarded-For: 172.19.0.1
146 | X-Forwarded-Proto: http
147 | X-Forwarded-Host: localhost
148 | X-Forwarded-Port: 8000
149 | X-Real-IP: 172.19.0.1
150 | Cache-Control: max-age=0
151 | User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
152 | Upgrade-Insecure-Requests: 1
153 | Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
154 | Accept-Encoding: gzip, deflate
155 | Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
156 | Cookie: session=KOn1am4mhQLKazlCA.....
157 | X-Userinfo: eyJnaXZlbl9uYW1lIjoixITEmMWaw5PFgcW7xbnEhiIsInN1YiI6ImM4NThiYzAxLTBiM2ItNDQzNy1hMGVlLWE1ZTY0ODkwMDE5ZCIsInByZWZlcnJlZF91c2VybmFtZSI6ImFkbWluIiwibmFtZSI6IsSExJjFmsOTxYHFu8W5xIYiLCJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOiJjODU4YmMwMS0wYjNiLTQ0MzctYTBlZS1hNWU2NDg5MDAxOWQifQ==
158 | X-Access-Token: eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJGenFSY0N1Ry13dzlrQUJBVng1ZG9sT2ZwTFhBNWZiRGFlVDRiemtnSzZRIn0.eyJqdGkiOiIxYjhmYzlkMC1jMjlmLTQwY2ItYWM4OC1kNzMyY2FkODcxY2IiLCJleHAiOjE1NDg1MTA4MjksIm5iZiI6MCwiaWF0IjoxNTQ4NTEwNzY5LCJpc3MiOiJodHRwOi8vMTkyLjE2OC4wLjk6ODA4MC9hdXRoL3JlYWxtcy9tYXN0ZXIiLCJhdWQiOlsibWFzdGVyLXJlYWxtIiwiYWNjb3VudCJdLCJzdWIiOiJhNmE3OGQ5MS01NDk0LTRjZTMtOTU1NS04NzhhMTg1Y2E0YjkiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJrb25nIiwibm9uY2UiOiJmNGRkNDU2YzBjZTY4ZmFmYWJmNGY4ZDA3YjQ0YWE4NiIsImF1dGhfdGltZSI6…IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGVtYWlsIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJhZG1pbiJ9.GWuguFjSEDGxw_vbD04UMKxtai15BE2lwBO0YkSzp-NKZ2SxAzl0nyhZxpP0VTzk712nQ8f_If5-mQBf_rqEVnOraDmX5NOXP0B8AoaS1jsdq4EomrhZGqlWmuaV71Cnqrw66iaouBR_6Q0s8bgc1FpCPyACM4VWs57CBdTrAZ2iv8dau5ODkbEvSgIgoLgBbUvjRKz1H0KyeBcXlVSgHJ_2zB9q2HvidBsQEIwTP8sWc6er-5AltLbV8ceBg5OaZ4xHoramMoz2xW-ttjIujS382QQn3iekNByb62O2cssTP3UYC747ehXReCrNZmDA6ecdnv8vOfIem3xNEnEmQw
159 | X-Id-Token: eyJuYmYiOjAsImF6cCI6ImtvbmciLCJpYXQiOjE1NDg1MTA3NjksImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMC45OjgwODBcL2F1dGhcL3JlYWxtc1wvbWFzdGVyIiwiYXVkIjoia29uZyIsIm5vbmNlIjoiZjRkZDQ1NmMwY2U2OGZhZmFiZjRmOGQwN2I0NGFhODYiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJhZG1pbiIsImF1dGhfdGltZSI6MTU0ODUxMDY5NywiYWNyIjoiMSIsInNlc3Npb25fc3RhdGUiOiJiNDZmODU2Ny0zODA3LTQ0YmMtYmU1Mi1iMTNiNWQzODI5MTQiLCJleHAiOjE1NDg1MTA4MjksImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwianRpIjoiMjI1ZDRhNDItM2Y3ZC00Y2I2LTkxMmMtOGNkYzM0Y2JiNTk2Iiwic3ViIjoiYTZhNzhkOTEtNTQ5NC00Y2UzLTk1NTUtODc4YTE4NWNhNGI5IiwidHlwIjoiSUQifQ==
160 | ```
161 |
162 |
163 | ## Development
164 |
165 | ### Running Unit Tests
166 |
167 | To run unit tests, run the following command:
168 |
169 | ```
170 | ./bin/run-unit-tests.sh
171 | ```
172 |
173 | This may take a while for the first run, as the docker image will need to be built, but subsequent runs will be quick.
174 |
175 | ### Building the Integration Test Environment
176 |
177 | To build the integration environment (Kong with the oidc plugin enabled, and Keycloak as the OIDC Provider), you will first need to find your computer's IP, and assign that to the environment variable `IP`. Finally, you will run the `./bin/build-env.sh` command. Here's an example:
178 |
179 | ```
180 | export IP=192.168.0.1
181 | ./bin/build-env.sh
182 | ```
183 |
184 | To tear the environment down:
185 |
186 | ```
187 | ./bin/teardown-env.sh
188 | ```
189 |
--------------------------------------------------------------------------------
/bin/build-env.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | . .env
3 | . ${INTEGRATION_PATH}/_network_functions
4 |
5 | (set -e
6 | if [[ -z "$IP" ]]; then
7 | echo "Please set the IP var to your local IP address. Example: export IP=192.168.0.1"
8 | exit 1
9 | fi
10 |
11 | (set -x
12 | # Tear down environment if it is running
13 | docker-compose -f ${INTEGRATION_PATH}/docker-compose.yml down
14 | docker build --build-arg KONG_BASE_TAG=${KONG_BASE_TAG} -t nokia/kong-oidc -f ${INTEGRATION_PATH}/Dockerfile .
15 | docker-compose -f ${INTEGRATION_PATH}/docker-compose.yml up -d kong-db
16 | )
17 |
18 | _wait_for_listener localhost:${KONG_DB_PORT}
19 |
20 | (set -x
21 | docker-compose -f ${INTEGRATION_PATH}/docker-compose.yml run --rm kong kong migrations bootstrap
22 | docker-compose -f ${INTEGRATION_PATH}/docker-compose.yml up -d
23 | )
24 |
25 | _wait_for_endpoint http://localhost:${KONG_HTTP_ADMIN_PORT}
26 | _wait_for_endpoint http://localhost:${KEYCLOAK_PORT}
27 |
28 | (set -x
29 | python3 ${INTEGRATION_PATH}/setup.py
30 | )
31 | )
--------------------------------------------------------------------------------
/bin/run-unit-tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | . .env
3 |
4 | (set -ex
5 | docker build \
6 | --build-arg KONG_BASE_TAG=${KONG_BASE_TAG} \
7 | -t ${BUILD_IMG_NAME} \
8 | -f ${UNIT_PATH}/Dockerfile .
9 | docker run -it --rm ${BUILD_IMG_NAME} /bin/bash test/unit/run.sh
10 | )
11 |
12 | echo "Done"
--------------------------------------------------------------------------------
/bin/teardown-env.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | . .env
3 |
4 | docker-compose -f ${INTEGRATION_PATH}/docker-compose.yml down
--------------------------------------------------------------------------------
/ci/root.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | apt-get update
5 | apt-get install -y curl unzip libssl-dev python python-pip git
6 |
7 |
--------------------------------------------------------------------------------
/ci/run.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | lua -lluacov test/unit/test_filter.lua -o TAP --failure
5 | lua -lluacov test/unit/test_filters_advanced.lua -o TAP --failure
6 | lua -lluacov test/unit/test_utils.lua -o TAP --failure
7 | lua -lluacov test/unit/test_handler_mocking_openidc.lua -o TAP --failure
8 | lua -lluacov test/unit/test_introspect.lua -o TAP --failure
9 | lua -lluacov test/unit/test_utils_bearer_access_token.lua -o TAP --failure
10 |
11 |
--------------------------------------------------------------------------------
/ci/setup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | export LUA_VERSION=${LUA_VERSION:-5.1}
5 | export KONG_VERSION=${KONG_VERSION:-0.13.1-0}
6 | export LUA_RESTY_OPENIDC_VERSION=${LUA_RESTY_OPENIDC_VERSION:-1.6.1-1}
7 |
8 | pip install hererocks
9 | hererocks lua_install -r^ --lua=${LUA_VERSION}
10 | export PATH=${PATH}:${PWD}/lua_install/bin
11 |
12 | luarocks install kong ${KONG_VERSION}
13 | luarocks install lua-resty-openidc ${LUA_RESTY_OPENIDC_VERSION}
14 | luarocks install lua-cjson
15 | luarocks install luaunit
16 | luarocks install luacov
17 |
18 |
--------------------------------------------------------------------------------
/docs/kong_oidc_flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nokia/kong-oidc/25104595cfedb341bda00003d792e5824943615c/docs/kong_oidc_flow.png
--------------------------------------------------------------------------------
/kong-oidc-1.1.0-0.rockspec:
--------------------------------------------------------------------------------
1 | package = "kong-oidc"
2 | version = "1.1.0-0"
3 | source = {
4 | url = "git://github.com/nokia/kong-oidc",
5 | tag = "v1.1.0",
6 | dir = "kong-oidc"
7 | }
8 | description = {
9 | summary = "A Kong plugin for implementing the OpenID Connect Relying Party (RP) functionality",
10 | detailed = [[
11 | kong-oidc is a Kong plugin for implementing the OpenID Connect Relying Party.
12 |
13 | When used as an OpenID Connect Relying Party it authenticates users against an OpenID Connect Provider using OpenID Connect Discovery and the Basic Client Profile (i.e. the Authorization Code flow).
14 |
15 | It maintains sessions for authenticated users by leveraging lua-resty-session thus offering a configurable choice between storing the session state in a client-side browser cookie or use in of the server-side storage mechanisms shared-memory|memcache|redis.
16 |
17 | It supports server-wide caching of resolved Discovery documents and validated Access Tokens.
18 |
19 | It can be used as a reverse proxy terminating OAuth/OpenID Connect in front of an origin server so that the origin server/services can be protected with the relevant standards without implementing those on the server itself.
20 | ]],
21 | homepage = "https://github.com/nokia/kong-oidc",
22 | license = "Apache 2.0"
23 | }
24 | dependencies = {
25 | "lua-resty-openidc ~> 1.6.1-1"
26 | }
27 | build = {
28 | type = "builtin",
29 | modules = {
30 | ["kong.plugins.oidc.filter"] = "kong/plugins/oidc/filter.lua",
31 | ["kong.plugins.oidc.handler"] = "kong/plugins/oidc/handler.lua",
32 | ["kong.plugins.oidc.schema"] = "kong/plugins/oidc/schema.lua",
33 | ["kong.plugins.oidc.session"] = "kong/plugins/oidc/session.lua",
34 | ["kong.plugins.oidc.utils"] = "kong/plugins/oidc/utils.lua"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/kong/plugins/oidc/filter.lua:
--------------------------------------------------------------------------------
1 | local M = {}
2 |
3 | local function shouldIgnoreRequest(patterns)
4 | if (patterns) then
5 | for _, pattern in ipairs(patterns) do
6 | local isMatching = not (string.find(ngx.var.uri, pattern) == nil)
7 | if (isMatching) then return true end
8 | end
9 | end
10 | return false
11 | end
12 |
13 | function M.shouldProcessRequest(config)
14 | return not shouldIgnoreRequest(config.filters)
15 | end
16 |
17 | return M
18 |
--------------------------------------------------------------------------------
/kong/plugins/oidc/handler.lua:
--------------------------------------------------------------------------------
1 | local BasePlugin = require "kong.plugins.base_plugin"
2 | local OidcHandler = BasePlugin:extend()
3 | local utils = require("kong.plugins.oidc.utils")
4 | local filter = require("kong.plugins.oidc.filter")
5 | local session = require("kong.plugins.oidc.session")
6 |
7 | OidcHandler.PRIORITY = 1000
8 |
9 |
10 | function OidcHandler:new()
11 | OidcHandler.super.new(self, "oidc")
12 | end
13 |
14 | function OidcHandler:access(config)
15 | OidcHandler.super.access(self)
16 | local oidcConfig = utils.get_options(config, ngx)
17 |
18 | if filter.shouldProcessRequest(oidcConfig) then
19 | session.configure(config)
20 | handle(oidcConfig)
21 | else
22 | ngx.log(ngx.DEBUG, "OidcHandler ignoring request, path: " .. ngx.var.request_uri)
23 | end
24 |
25 | ngx.log(ngx.DEBUG, "OidcHandler done")
26 | end
27 |
28 | function handle(oidcConfig)
29 | local response
30 | if oidcConfig.introspection_endpoint then
31 | response = introspect(oidcConfig)
32 | if response then
33 | utils.injectUser(response)
34 | end
35 | end
36 |
37 | if response == nil then
38 | response = make_oidc(oidcConfig)
39 | if response then
40 | if (response.user) then
41 | utils.injectUser(response.user)
42 | end
43 | if (response.access_token) then
44 | utils.injectAccessToken(response.access_token)
45 | end
46 | if (response.id_token) then
47 | utils.injectIDToken(response.id_token)
48 | end
49 | end
50 | end
51 | end
52 |
53 | function make_oidc(oidcConfig)
54 | ngx.log(ngx.DEBUG, "OidcHandler calling authenticate, requested path: " .. ngx.var.request_uri)
55 | local res, err = require("resty.openidc").authenticate(oidcConfig)
56 | if err then
57 | if oidcConfig.recovery_page_path then
58 | ngx.log(ngx.DEBUG, "Entering recovery page: " .. oidcConfig.recovery_page_path)
59 | ngx.redirect(oidcConfig.recovery_page_path)
60 | end
61 | utils.exit(500, err, ngx.HTTP_INTERNAL_SERVER_ERROR)
62 | end
63 | return res
64 | end
65 |
66 | function introspect(oidcConfig)
67 | if utils.has_bearer_access_token() or oidcConfig.bearer_only == "yes" then
68 | local res, err = require("resty.openidc").introspect(oidcConfig)
69 | if err then
70 | if oidcConfig.bearer_only == "yes" then
71 | ngx.header["WWW-Authenticate"] = 'Bearer realm="' .. oidcConfig.realm .. '",error="' .. err .. '"'
72 | utils.exit(ngx.HTTP_UNAUTHORIZED, err, ngx.HTTP_UNAUTHORIZED)
73 | end
74 | return nil
75 | end
76 | ngx.log(ngx.DEBUG, "OidcHandler introspect succeeded, requested path: " .. ngx.var.request_uri)
77 | return res
78 | end
79 | return nil
80 | end
81 |
82 |
83 | return OidcHandler
84 |
--------------------------------------------------------------------------------
/kong/plugins/oidc/schema.lua:
--------------------------------------------------------------------------------
1 | return {
2 | no_consumer = true,
3 | fields = {
4 | client_id = { type = "string", required = true },
5 | client_secret = { type = "string", required = true },
6 | discovery = { type = "string", required = true, default = "https://.well-known/openid-configuration" },
7 | introspection_endpoint = { type = "string", required = false },
8 | timeout = { type = "number", required = false },
9 | introspection_endpoint_auth_method = { type = "string", required = false },
10 | bearer_only = { type = "string", required = true, default = "no" },
11 | realm = { type = "string", required = true, default = "kong" },
12 | redirect_uri_path = { type = "string" },
13 | scope = { type = "string", required = true, default = "openid" },
14 | response_type = { type = "string", required = true, default = "code" },
15 | ssl_verify = { type = "string", required = true, default = "no" },
16 | token_endpoint_auth_method = { type = "string", required = true, default = "client_secret_post" },
17 | session_secret = { type = "string", required = false },
18 | recovery_page_path = { type = "string" },
19 | logout_path = { type = "string", required = false, default = '/logout' },
20 | redirect_after_logout_uri = { type = "string", required = false, default = '/' },
21 | filters = { type = "string" }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/kong/plugins/oidc/session.lua:
--------------------------------------------------------------------------------
1 | local utils = require("kong.plugins.oidc.utils")
2 |
3 | local M = {}
4 |
5 | function M.configure(config)
6 | if config.session_secret then
7 | local decoded_session_secret = ngx.decode_base64(config.session_secret)
8 | if not decoded_session_secret then
9 | utils.exit(500, "invalid OIDC plugin configuration, session secret could not be decoded", ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR))
10 | end
11 | ngx.var.session_secret = decoded_session_secret
12 | end
13 | end
14 |
15 | return M
16 |
--------------------------------------------------------------------------------
/kong/plugins/oidc/utils.lua:
--------------------------------------------------------------------------------
1 | local cjson = require("cjson")
2 |
3 | local M = {}
4 |
5 | local function parseFilters(csvFilters)
6 | local filters = {}
7 | if (not (csvFilters == nil)) then
8 | for pattern in string.gmatch(csvFilters, "[^,]+") do
9 | table.insert(filters, pattern)
10 | end
11 | end
12 | return filters
13 | end
14 |
15 | function M.get_redirect_uri_path(ngx)
16 | local function drop_query()
17 | local uri = ngx.var.request_uri
18 | local x = uri:find("?")
19 | if x then
20 | return uri:sub(1, x - 1)
21 | else
22 | return uri
23 | end
24 | end
25 |
26 | local function tackle_slash(path)
27 | local args = ngx.req.get_uri_args()
28 | if args and args.code then
29 | return path
30 | elseif path == "/" then
31 | return "/cb"
32 | elseif path:sub(-1) == "/" then
33 | return path:sub(1, -2)
34 | else
35 | return path .. "/"
36 | end
37 | end
38 |
39 | return tackle_slash(drop_query())
40 | end
41 |
42 | function M.get_options(config, ngx)
43 | return {
44 | client_id = config.client_id,
45 | client_secret = config.client_secret,
46 | discovery = config.discovery,
47 | introspection_endpoint = config.introspection_endpoint,
48 | timeout = config.timeout,
49 | introspection_endpoint_auth_method = config.introspection_endpoint_auth_method,
50 | bearer_only = config.bearer_only,
51 | realm = config.realm,
52 | redirect_uri_path = config.redirect_uri_path or M.get_redirect_uri_path(ngx),
53 | scope = config.scope,
54 | response_type = config.response_type,
55 | ssl_verify = config.ssl_verify,
56 | token_endpoint_auth_method = config.token_endpoint_auth_method,
57 | recovery_page_path = config.recovery_page_path,
58 | filters = parseFilters(config.filters),
59 | logout_path = config.logout_path,
60 | redirect_after_logout_uri = config.redirect_after_logout_uri,
61 | }
62 | end
63 |
64 | function M.exit(httpStatusCode, message, ngxCode)
65 | ngx.status = httpStatusCode
66 | ngx.say(message)
67 | ngx.exit(ngxCode)
68 | end
69 |
70 | function M.injectAccessToken(accessToken)
71 | ngx.req.set_header("X-Access-Token", accessToken)
72 | end
73 |
74 | function M.injectIDToken(idToken)
75 | local tokenStr = cjson.encode(idToken)
76 | ngx.req.set_header("X-ID-Token", ngx.encode_base64(tokenStr))
77 | end
78 |
79 | function M.injectUser(user)
80 | local tmp_user = user
81 | tmp_user.id = user.sub
82 | tmp_user.username = user.preferred_username
83 | ngx.ctx.authenticated_credential = tmp_user
84 | local userinfo = cjson.encode(user)
85 | ngx.req.set_header("X-Userinfo", ngx.encode_base64(userinfo))
86 | end
87 |
88 | function M.has_bearer_access_token()
89 | local header = ngx.req.get_headers()['Authorization']
90 | if header and header:find(" ") then
91 | local divider = header:find(' ')
92 | if string.lower(header:sub(0, divider-1)) == string.lower("Bearer") then
93 | return true
94 | end
95 | end
96 | return false
97 | end
98 |
99 | return M
100 |
--------------------------------------------------------------------------------
/spec/plugins/oidc/access_spec.lua:
--------------------------------------------------------------------------------
1 | local helpers = require "spec.helpers"
2 |
3 |
4 | describe("oidc plugin", function()
5 | local proxy_client
6 | local admin_client
7 | local timeout = 6000
8 |
9 | setup(function()
10 | local api1 = assert(helpers.dao.apis:insert {
11 | name = "mock",
12 | upstream_url = "http://mockbin.com",
13 | uris = { "/mock" }
14 | })
15 | print("Api created:")
16 | for k, v in pairs(api1) do
17 | print(k, ": ", v)
18 | end
19 | assert(helpers.dao.plugins:insert {
20 | name = "oidc",
21 | config = {
22 | client_id = "afcc3a0a-aaa4-4bac-b86a-a7bd77259dd3",
23 | client_secret = "81de73f0-3a0e-451a-88ee-e540811a049c",
24 | discovery = "http://mockbin.org/bin/bd08be64-1820-4e1a-aca2-b4a38cd07961/"
25 | }
26 | })
27 |
28 | -- start Kong with your testing Kong configuration (defined in "spec.helpers")
29 | assert(helpers.start_kong())
30 | print("Kong started")
31 |
32 | admin_client = helpers.admin_client(timeout)
33 | end)
34 |
35 | teardown(function()
36 | if admin_client then
37 | admin_client:close()
38 | end
39 |
40 | helpers.stop_kong()
41 | print("Kong stopped")
42 | end)
43 |
44 | before_each(function()
45 | proxy_client = helpers.proxy_client(timeout)
46 | end)
47 |
48 | after_each(function()
49 | if proxy_client then
50 | proxy_client:close()
51 | end
52 | end)
53 |
54 | describe("being an OpenID Connect Relaying Party component", function()
55 | it("should redirect the authentication request (which is an OAuth 2.0 authorization request) to OP", function()
56 | local res = assert(proxy_client:send {
57 | method = "GET",
58 | path = "/mock",
59 | })
60 | local body = assert.res_status(302, res)
61 | local redirect_uri = res.headers["Location"]
62 | assert.is_truthy(string.find(redirect_uri, "response_type=code"))
63 | assert.is_truthy(string.find(redirect_uri, "scope=openid"))
64 | assert.is_truthy(string.find(redirect_uri, "client_id="))
65 | assert.is_truthy(string.find(redirect_uri, "state="))
66 | assert.is_truthy(string.find(redirect_uri, "redirect_uri="))
67 | end)
68 |
69 | it("should after successful login contact token and userinfo endpoints", function()
70 | -- Mimic authentication response
71 | local res = assert(proxy_client:send {
72 | method = "GET",
73 | path = "/mock/?state=123456&code=123456",
74 | })
75 | -- This will fail in openidc.lua because session created in first phase is loat
76 | -- and several things could mismatch (state, nonce, original_url, ...)
77 | local body = assert.res_status(500, res)
78 | end)
79 | end)
80 | end)
81 |
82 |
--------------------------------------------------------------------------------
/test/docker/integration/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG KONG_BASE_TAG
2 | FROM kong${KONG_BASE_TAG}
3 |
4 | ENV LUA_PATH /usr/local/share/lua/5.1/?.lua;/usr/local/kong-oidc/?.lua;;
5 | # For lua-cjson
6 | ENV LUA_CPATH /usr/local/lib/lua/5.1/?.so;;
7 |
8 | # Install unzip for luarocks, gcc for lua-cjson
9 | RUN yum install -y unzip gcc
10 | RUN luarocks install luacov
11 | RUN luarocks install luaunit
12 | RUN luarocks install lua-cjson
13 |
14 | # Change openidc version when version in rockspec changes
15 | RUN luarocks install lua-resty-openidc 1.6.0
16 |
17 | COPY . /usr/local/kong-oidc
--------------------------------------------------------------------------------
/test/docker/integration/_network_functions:
--------------------------------------------------------------------------------
1 | # Determine if a listener is active (useful for non-http endpoints)
2 | function _listener_ready() {
3 | local endpoint=$1
4 | if ! shift 1; then echo "ERROR: ${FUNCNAME[0]}() Missing argument"; return 1; fi
5 | curl -sf --max-time 1 "gopher://${endpoint}"
6 |
7 | # '28 Operation timeout' means that curl WAS able to connect
8 | [[ $? == 28 ]]
9 | }
10 |
11 | # Sleep until listener becomes active
12 | function _wait_for_listener() {
13 | local endpoint=$1
14 | if ! shift 1; then echo "ERROR: ${FUNCNAME[0]}() Missing argument"; return 1; fi
15 |
16 | echo -n "Waiting for ${endpoint} "
17 | local -i sec=0
18 | while ! _listener_ready ${endpoint}; do
19 | echo -n "."
20 | sleep 1
21 | sec+=1
22 | done
23 | echo "(${sec}s)"
24 | }
25 |
26 | function _endpoint_ready() {
27 | local url=$1
28 | if ! shift 1; then echo "ERROR: ${FUNCNAME[0]}() Missing argument"; return 1; fi
29 |
30 | curl -sf --max-time 1 "${url}" > /dev/null 2>&1
31 | }
32 |
33 | # Sleep until listener becomes active
34 | # Usage: _wait_for_endpoint []
35 | function _wait_for_endpoint() {
36 | local url=$1
37 | if ! shift 1; then echo "ERROR: ${FUNCNAME[0]}() Missing argument"; return 1; fi
38 | local -i timeout=$2
39 |
40 | local -i sec=0
41 | echo -n "Waiting for ${url} "
42 | while ! _endpoint_ready ${url}; do
43 | echo -n "."
44 | sleep 1
45 | sec+=1
46 | done
47 | echo "(${sec}s)"
48 | }
--------------------------------------------------------------------------------
/test/docker/integration/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.4'
2 |
3 | services:
4 | kong-db:
5 | image: postgres${KONG_DB_TAG}
6 | ports:
7 | - ${KONG_DB_PORT}:5432
8 | environment:
9 | POSTGRES_USER: ${KONG_DB_USER}
10 | POSTGRES_PASSWORD: ${KONG_DB_PW}
11 | POSTGRES_DB: ${KONG_DB_NAME}
12 |
13 | keycloak:
14 | image: jboss/keycloak${KEYCLOAK_TAG}
15 | ports:
16 | - ${KEYCLOAK_PORT}:8080
17 | environment:
18 | KEYCLOAK_USER: ${KEYCLOAK_USER}
19 | KEYCLOAK_PASSWORD: ${KEYCLOAK_PW}
20 |
21 | kong:
22 | image: nokia/kong-oidc${KONG_TAG}
23 | ports:
24 | - 8000:8000
25 | - 8443:8443
26 | - 8001:8001
27 | - 8444:8444
28 | environment:
29 | KONG_DATABASE: postgres
30 | KONG_PG_HOST: kong-db
31 | KONG_PG_DATABASE: ${KONG_DB_NAME}
32 | KONG_PG_USER: ${KONG_DB_USER}
33 | KONG_PG_PASSWORD: ${KONG_DB_PW}
34 | KONG_ADMIN_LISTEN: 0.0.0.0:${KONG_HTTP_ADMIN_PORT}
35 | KONG_PROXY_LISTEN: 0.0.0.0:${KONG_HTTP_PROXY_PORT}
36 | KONG_PROXY_ACCESS_LOG: /dev/stdout
37 | KONG_ADMIN_ACCESS_LOG: /dev/stdout
38 | KONG_PROXY_ERROR_LOG: /dev/stderr
39 | KONG_ADMIN_ERROR_LOG: /dev/stderr
40 | KONG_PLUGINS: oidc
41 | depends_on:
42 | - kong-db
--------------------------------------------------------------------------------
/test/docker/integration/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import os
4 | import requests
5 |
6 | from collections import namedtuple
7 |
8 | local_ip = os.getenv("IP", default="")
9 | host = "localhost"
10 | env_file_path = ".env"
11 |
12 | Config = namedtuple("Config", [
13 | "keycloak_endpoint",
14 | "keycloak_admin",
15 | "keycloak_password",
16 | "client_id",
17 | "client_secret",
18 | "discovery",
19 | "kong_endpoint"
20 | ])
21 |
22 | def validate_ip_set():
23 | if local_ip == "":
24 | raise Exception("IP environment variable not set. See README.md for further instructions.")
25 |
26 | """
27 | Attempt to pull in environment variables from .env file
28 | Returns {"KONG_TAG": "", "KONG_DB_TAG": ":10.1" ...}
29 | """
30 | def get_env_vars():
31 | with open(env_file_path) as f:
32 | lines = [l.rstrip().split("=", maxsplit=1)
33 | for l in f
34 | # Skip blank lines and comments
35 | if l.strip() != "" and not l.startswith("#")]
36 |
37 | return {l[0]: l[1] for l in lines}
38 |
39 | def get_config(env):
40 | keycloak_url = "http://{}:{}".format(host, env["KEYCLOAK_PORT"])
41 | discovery_path = "/auth/realms/master/.well-known/openid-configuration"
42 |
43 | return Config(
44 | keycloak_endpoint = keycloak_url,
45 | keycloak_admin = env["KEYCLOAK_USER"],
46 | keycloak_password = env["KEYCLOAK_PW"],
47 | client_id = "kong",
48 | client_secret = "secret",
49 | # Set host to local IP address so requests from Kong to Keycloak can make it
50 | # out of the container
51 | discovery = "http://{}:{}{}".format(local_ip, env["KEYCLOAK_PORT"], discovery_path),
52 | kong_endpoint = "http://{}:{}".format(host, env["KONG_HTTP_ADMIN_PORT"])
53 | )
54 |
55 |
56 | class KeycloakClient:
57 | def __init__(self, url, username, password):
58 | self._endpoint = url
59 | self._session = requests.session()
60 | self._username = username
61 | self._password = password
62 |
63 | def create_client(self, name, secret):
64 | url = "{}/auth/admin/realms/master/clients".format(self._endpoint)
65 | payload = {
66 | "clientId": name,
67 | "secret": secret,
68 | "redirectUris": ["*"],
69 | }
70 |
71 | headers = self.get_auth_header()
72 | res = self._session.post(url, json=payload, headers=headers)
73 |
74 | if res.status_code not in [201, 409]:
75 | raise Exception("Cannot Keycloak create client")
76 |
77 | def get_auth_header(self):
78 | return {
79 | "Authorization": "Bearer {}".format(self.get_admin_token())
80 | }
81 |
82 | def get_admin_token(self):
83 | url = "{}/auth/realms/master/protocol/openid-connect/token".format(self._endpoint)
84 |
85 | payload = "client_id=admin-cli&grant_type=password" + \
86 | "&username={}&password={}".format(self._username, self._password)
87 |
88 | headers = {
89 | "Content-Type": "application/x-www-form-urlencoded"
90 | }
91 |
92 | res = self._session.post(url, data=payload, headers=headers)
93 | res.raise_for_status()
94 |
95 | return res.json()["access_token"]
96 |
97 |
98 | class KongClient:
99 | def __init__(self, url):
100 | self._endpoint = url
101 | self._session = requests.session()
102 |
103 | def create_service(self, name, upstream_url):
104 | url = "{}/services".format(self._endpoint)
105 | payload = {
106 | "name": name,
107 | "url": upstream_url,
108 | }
109 | res = self._session.post(url, json=payload)
110 | res.raise_for_status()
111 | return res.json()
112 |
113 | def create_route(self, service_name, paths):
114 | url = "{}/services/{}/routes".format(self._endpoint, service_name)
115 | payload = {
116 | "paths": paths,
117 | }
118 | res = self._session.post(url, json=payload)
119 | res.raise_for_status()
120 | return res.json()
121 |
122 | def create_plugin(self, plugin_name, service_name, config):
123 | url = "{}/services/{}/plugins".format(self._endpoint, service_name)
124 | payload = {
125 | "name": plugin_name,
126 | "config": config,
127 | }
128 | res = self._session.post(url, json=payload)
129 | try:
130 | res.raise_for_status()
131 | except Exception as e:
132 | print(res.text)
133 | raise e
134 | return res.json()
135 |
136 | def delete_service(self, name):
137 | try:
138 | routes = self.get_routes(name)
139 | for route in routes:
140 | self.delete_route(route)
141 | except requests.exceptions.HTTPError:
142 | pass
143 | url = "{}/services/{}".format(self._endpoint, name)
144 | self._session.delete(url).raise_for_status()
145 |
146 | def delete_route(self, route_id):
147 | url = "{}/routes/{}".format(self._endpoint, route_id)
148 | self._session.delete(url).raise_for_status()
149 |
150 | def get_routes(self, service_name):
151 | url = "{}/services/{}/routes".format(self._endpoint, service_name)
152 | res = self._session.get(url)
153 | res.raise_for_status()
154 | return map(lambda x: x['id'], res.json()['data'])
155 |
156 | if __name__ == '__main__':
157 | validate_ip_set()
158 |
159 | print("Reading environment vars from {}".format(env_file_path))
160 | env = get_env_vars()
161 | config = get_config(env)
162 |
163 | print("Creating Keycloak HTTP Client at {}".format(config.keycloak_endpoint))
164 | kc_client = KeycloakClient(config.keycloak_endpoint,
165 | config.keycloak_admin,
166 | config.keycloak_password)
167 |
168 | print("Creating Keycloak client: {}".format(config.client_id))
169 | kc_client.create_client(config.client_id, config.client_secret)
170 |
171 | print("Creating Kong HTTP Admin Client at {}".format(config.kong_endpoint))
172 | kong_client = KongClient(config.kong_endpoint)
173 |
174 | print("Configuring Kong services, routes, and plugins for testing")
175 | kong_client.delete_service("httpbin")
176 | kong_client.create_service("httpbin", "http://httpbin.org")
177 | kong_client.create_route("httpbin", ["/httpbin"])
178 | kong_client.create_plugin("oidc", "httpbin", {
179 | "client_id": config.client_id,
180 | "client_secret": config.client_secret,
181 | "discovery": config.discovery,
182 | "logout_path": "/httpbin/logout",
183 | })
184 |
185 | print("Environment setup complete")
--------------------------------------------------------------------------------
/test/docker/unit/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG KONG_BASE_TAG
2 | FROM kong${KONG_BASE_TAG}
3 |
4 | ENV LUA_PATH /usr/local/share/lua/5.1/?.lua;/usr/local/kong-oidc/?.lua
5 | # For lua-cjson
6 | ENV LUA_CPATH /usr/local/lib/lua/5.1/?.so
7 |
8 | # Install unzip for luarocks, gcc for lua-cjson
9 | RUN yum install -y unzip gcc
10 | RUN luarocks install luacov
11 | RUN luarocks install luaunit
12 | RUN luarocks install lua-cjson
13 |
14 | # Change openidc version when version in rockspec changes
15 | RUN luarocks install lua-resty-openidc 1.6.1-1
16 |
17 | WORKDIR /usr/local/kong-oidc
18 |
19 | COPY . .
--------------------------------------------------------------------------------
/test/unit/base_case.lua:
--------------------------------------------------------------------------------
1 | package.path = package.path .. ";test/lib/?.lua;;" -- kong & co
2 |
3 | local Object = require "kong.vendor.classic"
4 | local BaseCase = Object:extend()
5 |
6 |
7 | function BaseCase:setUp()
8 | end
9 |
10 | function BaseCase:tearDown()
11 | end
12 |
13 |
14 | return BaseCase
15 |
--------------------------------------------------------------------------------
/test/unit/mockable_case.lua:
--------------------------------------------------------------------------------
1 | local BaseCase = require("test.unit.base_case")
2 | local MockableCase = BaseCase:extend()
3 |
4 |
5 | function MockableCase:setUp()
6 | MockableCase.super:setUp()
7 | self.logs = {}
8 | self.mocked_ngx = {
9 | DEBUG = "debug",
10 | ERR = "error",
11 | HTTP_UNAUTHORIZED = 401,
12 | ctx = {},
13 | header = {},
14 | var = {request_uri = "/"},
15 | req = {
16 | get_uri_args = function(...) end,
17 | set_header = function(...) end,
18 | get_headers = function(...) end
19 | },
20 | log = function(...)
21 | self.logs[#self.logs+1] = table.concat({...}, " ")
22 | print("ngx.log: ", self.logs[#self.logs])
23 | end,
24 | say = function(...) end,
25 | exit = function(...) end,
26 | redirect = function(...) end,
27 | config = {
28 | subsystem = "http"
29 | }
30 | }
31 | self.ngx = _G.ngx
32 | _G.ngx = self.mocked_ngx
33 |
34 | self.resty = package.loaded.resty
35 | package.loaded["resty.http"] = nil
36 | package.preload["resty.http"] = function()
37 | return {encode = function(...) return "encoded" end}
38 | end
39 |
40 | self.cjson = package.loaded.cjson
41 | package.loaded.cjson = nil
42 | package.preload["cjson"] = function()
43 | return {
44 | encode = function(...) return "encoded" end,
45 | decode = function(...) return {sub = "sub"} end
46 | }
47 | end
48 | end
49 |
50 | function MockableCase:tearDown()
51 | MockableCase.super:tearDown()
52 | _G.ngx = self.ngx
53 | package.loaded.resty = self.resty
54 | package.loaded.cjson = self.cjson
55 | end
56 |
57 | function MockableCase:log_contains(str)
58 | return table.concat(self.logs, "//"):find(str) and true or false
59 | end
60 |
61 | function MockableCase:__tostring()
62 | return "MockableCase"
63 | end
64 |
65 |
66 | return MockableCase
67 |
--------------------------------------------------------------------------------
/test/unit/run.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | # Run all test_*.lua files in test/unit
5 | for f in test/unit/test_*.lua; do
6 | (set -x
7 | lua -lluacov ${f} -o TAP --failure
8 | )
9 | done
--------------------------------------------------------------------------------
/test/unit/test_filter.lua:
--------------------------------------------------------------------------------
1 | local filter = require("kong.plugins.oidc.filter")
2 | local lu = require("luaunit")
3 |
4 | TestFilter = require("test.unit.base_case"):extend()
5 |
6 | function TestFilter:setUp()
7 | TestFilter.super:setUp()
8 | _G.ngx = {
9 | var = {
10 | uri = ""
11 | }
12 | }
13 | end
14 |
15 | function TestFilter:tearDown()
16 | TestFilter.super:tearDown()
17 | end
18 |
19 | local config = {
20 | filters = { "^/pattern1$","^/pattern2$"}
21 | }
22 |
23 | function TestFilter:testIgnoreRequestWhenMatchingPattern1()
24 | ngx.var.uri = "/pattern1"
25 | lu.assertFalse(filter.shouldProcessRequest(config))
26 | end
27 |
28 | function TestFilter:testIgnoreRequestWhenMatchingPattern2()
29 | ngx.var.uri = "/pattern2"
30 | lu.assertFalse(filter.shouldProcessRequest(config))
31 | end
32 |
33 | function TestFilter:testProcesseRequestWhenNoMatch()
34 | ngx.var.uri = "/not_matching"
35 | lu.assertTrue(filter.shouldProcessRequest(config))
36 | end
37 |
38 | function TestFilter:testProcessRequestWhenTheyAreNoFiltersNil()
39 | ngx.var.uri = "/pattern1"
40 | config.filters= nil
41 | lu.assertTrue(filter.shouldProcessRequest(config))
42 | end
43 |
44 | function TestFilter:testProcessRequestWhenTheyAreNoFiltersEmpty()
45 | ngx.var.uri = "/pattern1"
46 | config.filters= {}
47 | lu.assertTrue(filter.shouldProcessRequest(config))
48 | end
49 |
50 |
51 | lu.run()
52 |
--------------------------------------------------------------------------------
/test/unit/test_filters_advanced.lua:
--------------------------------------------------------------------------------
1 | local filter = require("kong.plugins.oidc.filter")
2 | local lu = require("luaunit")
3 |
4 | TestFilter = require("test.unit.mockable_case"):extend()
5 |
6 | function TestFilter:setUp()
7 | TestFilter.super:setUp()
8 | _G.ngx = {
9 | var = {
10 | uri = ""
11 | }
12 | }
13 | end
14 |
15 | function TestFilter:tearDown()
16 | TestFilter.super:tearDown()
17 | end
18 |
19 |
20 | local config = {
21 | filters = { "^/auth$","^/auth[^%w_%-%.~]","^/arc$","^/arc[^%w_%-%.~]","^/projects/%d+/zeppelin[^%w_%-%.~]","^/projects/%d+/zeppelin$"}
22 | }
23 |
24 | function TestFilter:testIgnoreRequestWhenUriIsAuth()
25 | ngx.var.uri = "/auth"
26 | lu.assertFalse(filter.shouldProcessRequest(config))
27 |
28 | ngx.var.uri = "/auth/"
29 | lu.assertFalse(filter.shouldProcessRequest(config))
30 | end
31 |
32 | function TestFilter:testIgnoreRequestWhenUriIsArc()
33 | ngx.var.uri = "/arc"
34 | lu.assertFalse(filter.shouldProcessRequest(config))
35 |
36 | ngx.var.uri = "/arc/"
37 | lu.assertFalse(filter.shouldProcessRequest(config))
38 | end
39 |
40 | function TestFilter:testProcessRequestWhichAreAllowed()
41 | ngx.var.uri = "/not_auth"
42 | assert(filter.shouldProcessRequest(config) == true)
43 | end
44 |
45 | function TestFilter:testIgnoreRequestBeingIdenticalToFilter()
46 | ngx.var.uri = "/arc"
47 | lu.assertFalse(filter.shouldProcessRequest(config) )
48 | end
49 |
50 | function TestFilter:testIgnoreRequestStartingWithFilterFollowedBySlash()
51 | ngx.var.uri = "/arc/"
52 | lu.assertFalse(filter.shouldProcessRequest(config) )
53 | end
54 |
55 | function TestFilter:testIgnoreRequestStartingWithFilterFollowedByPaths()
56 | ngx.var.uri = "/arc/de/triomphe"
57 | lu.assertFalse(filter.shouldProcessRequest(config) )
58 |
59 | end
60 |
61 | function TestFilter:testIgnoreRequestStartingWithFilterFollowedByQuestionmark()
62 | ngx.var.uri = "/arc?"
63 | lu.assertFalse(filter.shouldProcessRequest(config) )
64 |
65 | ngx.var.uri = "/arc?de=triomphe"
66 | lu.assertFalse(filter.shouldProcessRequest(config) )
67 |
68 | end
69 |
70 | function TestFilter:testIgnoreRequestStartingWithFilterFollowedByQuestionmark()
71 | ngx.var.uri = "/arc?"
72 | lu.assertFalse(filter.shouldProcessRequest(config) )
73 |
74 | ngx.var.uri = "/arc?de=triomphe"
75 | lu.assertFalse(filter.shouldProcessRequest(config) )
76 |
77 | end
78 |
79 | function TestFilter:testPrefixNotAtTheStart()
80 | ngx.var.uri = "/process_this/arc"
81 | lu.assertTrue(filter.shouldProcessRequest(config) )
82 |
83 | ngx.var.uri = "/process_this/arc/de/triomphe"
84 | lu.assertTrue(filter.shouldProcessRequest(config) )
85 |
86 | ngx.var.uri = "/process_this/architecture"
87 | lu.assertTrue(filter.shouldProcessRequest(config) )
88 |
89 | end
90 |
91 | function TestFilter:testLowercaseLetterAfterPrefix()
92 | ngx.var.uri = "/architecture"
93 | lu.assertTrue(filter.shouldProcessRequest(config) )
94 | end
95 |
96 | function TestFilter:testUppercaseLetterLetterAfterPrefix()
97 | ngx.var.uri = "/archITACTURE"
98 | lu.assertTrue(filter.shouldProcessRequest(config) )
99 | end
100 |
101 | function TestFilter:testDigitAfterPrefix()
102 | ngx.var.uri = "/arc123"
103 | lu.assertTrue(filter.shouldProcessRequest(config) )
104 | end
105 |
106 | function TestFilter:testHyphenAfterPrefix()
107 | ngx.var.uri = "/arc-123"
108 | lu.assertTrue(filter.shouldProcessRequest(config) )
109 | end
110 |
111 | function TestFilter:testPeriodAfterPrefix()
112 | ngx.var.uri = "/arc.123"
113 | lu.assertTrue(filter.shouldProcessRequest(config) )
114 | end
115 |
116 | function TestFilter:testUnderscoreAfterPrefix()
117 | ngx.var.uri = "/arc_123"
118 | lu.assertTrue(filter.shouldProcessRequest(config) )
119 | end
120 |
121 | function TestFilter:testTildeAfterPrefix()
122 | ngx.var.uri = "/arc~123"
123 | lu.assertTrue(filter.shouldProcessRequest(config) )
124 | end
125 |
126 | lu.run()
127 |
--------------------------------------------------------------------------------
/test/unit/test_handler_mocking_openidc.lua:
--------------------------------------------------------------------------------
1 | local lu = require("luaunit")
2 | TestHandler = require("test.unit.mockable_case"):extend()
3 |
4 |
5 | function TestHandler:setUp()
6 | TestHandler.super:setUp()
7 |
8 | package.loaded["resty.openidc"] = nil
9 | self.module_resty = {openidc = {
10 | authenticate = function(...) return {}, nil end }
11 | }
12 | package.preload["resty.openidc"] = function()
13 | return self.module_resty.openidc
14 | end
15 |
16 | self.handler = require("kong.plugins.oidc.handler")()
17 | end
18 |
19 | function TestHandler:tearDown()
20 | TestHandler.super:tearDown()
21 | end
22 |
23 | function TestHandler:test_authenticate_ok_no_userinfo()
24 | self.module_resty.openidc.authenticate = function(opts)
25 | return {}, false
26 | end
27 |
28 | self.handler:access({})
29 | lu.assertTrue(self:log_contains("calling authenticate"))
30 | end
31 |
32 | function TestHandler:test_authenticate_ok_with_userinfo()
33 | self.module_resty.openidc.authenticate = function(opts)
34 | return {user = {sub = "sub"}}, false
35 | end
36 | ngx.encode_base64 = function(x)
37 | return "eyJzdWIiOiJzdWIifQ=="
38 | end
39 |
40 | local headers = {}
41 | ngx.req.set_header = function(h, v)
42 | headers[h] = v
43 | end
44 |
45 | self.handler:access({})
46 | lu.assertTrue(self:log_contains("calling authenticate"))
47 | lu.assertEquals(ngx.ctx.authenticated_credential.id, "sub")
48 | lu.assertEquals(headers['X-Userinfo'], "eyJzdWIiOiJzdWIifQ==")
49 | end
50 |
51 | function TestHandler:test_authenticate_ok_with_no_accesstoken()
52 | self.module_resty.openidc.authenticate = function(opts)
53 | return {}, true
54 | end
55 |
56 | local headers = {}
57 | ngx.req.set_header = function(h, v)
58 | headers[h] = v
59 | end
60 |
61 | self.handler:access({})
62 | lu.assertTrue(self:log_contains("calling authenticate"))
63 | lu.assertNil(headers['X-Access-Token'])
64 | end
65 |
66 | function TestHandler:test_authenticate_ok_with_accesstoken()
67 | self.module_resty.openidc.authenticate = function(opts)
68 | return {access_token = "ACCESS_TOKEN"}, true
69 | end
70 |
71 | local headers = {}
72 | ngx.req.set_header = function(h, v)
73 | headers[h] = v
74 | end
75 |
76 | self.handler:access({})
77 | lu.assertTrue(self:log_contains("calling authenticate"))
78 | lu.assertEquals(headers['X-Access-Token'], "ACCESS_TOKEN")
79 | end
80 |
81 | function TestHandler:test_authenticate_ok_with_no_idtoken()
82 | self.module_resty.openidc.authenticate = function(opts)
83 | return {}, true
84 | end
85 |
86 | local headers = {}
87 | ngx.req.set_header = function(h, v)
88 | headers[h] = v
89 | end
90 |
91 | self.handler:access({})
92 | lu.assertTrue(self:log_contains("calling authenticate"))
93 | lu.assertNil(headers['X-ID-Token'])
94 | end
95 |
96 | function TestHandler:test_authenticate_ok_with_idtoken()
97 | self.module_resty.openidc.authenticate = function(opts)
98 | return {id_token = {sub = "sub"}}, true
99 | end
100 |
101 | ngx.encode_base64 = function(x)
102 | return "eyJzdWIiOiJzdWIifQ=="
103 | end
104 |
105 | local headers = {}
106 | ngx.req.set_header = function(h, v)
107 | headers[h] = v
108 | end
109 |
110 | self.handler:access({})
111 | lu.assertTrue(self:log_contains("calling authenticate"))
112 | lu.assertEquals(headers['X-ID-Token'], "eyJzdWIiOiJzdWIifQ==")
113 | end
114 |
115 | function TestHandler:test_authenticate_nok_no_recovery()
116 | self.module_resty.openidc.authenticate = function(opts)
117 | return {}, true
118 | end
119 |
120 | self.handler:access({})
121 | lu.assertTrue(self:log_contains("calling authenticate"))
122 | end
123 |
124 | function TestHandler:test_authenticate_nok_with_recovery()
125 | self.module_resty.openidc.authenticate = function(opts)
126 | return {}, true
127 | end
128 |
129 | self.handler:access({recovery_page_path = "x"})
130 | lu.assertTrue(self:log_contains("recovery page"))
131 | end
132 |
133 | function TestHandler:test_introspect_ok_no_userinfo()
134 | self.module_resty.openidc.introspect = function(opts)
135 | return false, false
136 | end
137 | ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
138 |
139 | self.handler:access({introspection_endpoint = "x"})
140 | lu.assertTrue(self:log_contains("introspect succeeded"))
141 | end
142 |
143 | function TestHandler:test_introspect_ok_with_userinfo()
144 | self.module_resty.openidc.introspect = function(opts)
145 | return {}, false
146 | end
147 | ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
148 |
149 | ngx.encode_base64 = function(x)
150 | return "eyJzdWIiOiJzdWIifQ=="
151 | end
152 |
153 | local headers = {}
154 | ngx.req.set_header = function(h, v)
155 | headers[h] = v
156 | end
157 |
158 | self.handler:access({introspection_endpoint = "x"})
159 | lu.assertTrue(self:log_contains("introspect succeeded"))
160 | lu.assertEquals(headers['X-Userinfo'], "eyJzdWIiOiJzdWIifQ==")
161 | end
162 |
163 | function TestHandler:test_bearer_only_with_good_token()
164 | self.module_resty.openidc.introspect = function(opts)
165 | return {sub = "sub"}, false
166 | end
167 | ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
168 |
169 | ngx.encode_base64 = function(x)
170 | return "eyJzdWIiOiJzdWIifQ=="
171 | end
172 |
173 | local headers = {}
174 | ngx.req.set_header = function(h, v)
175 | headers[h] = v
176 | end
177 |
178 | self.handler:access({introspection_endpoint = "x", bearer_only = "yes", realm = "kong"})
179 | lu.assertTrue(self:log_contains("introspect succeeded"))
180 | lu.assertEquals(headers['X-Userinfo'], "eyJzdWIiOiJzdWIifQ==")
181 | end
182 |
183 | function TestHandler:test_bearer_only_with_bad_token()
184 | self.module_resty.openidc.introspect = function(opts)
185 | return {}, "validation failed"
186 | end
187 | ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
188 |
189 | self.handler:access({introspection_endpoint = "x", bearer_only = "yes", realm = "kong"})
190 |
191 | lu.assertEquals(ngx.header["WWW-Authenticate"], 'Bearer realm="kong",error="validation failed"')
192 | lu.assertEquals(ngx.status, ngx.HTTP_UNAUTHORIZED)
193 | lu.assertFalse(self:log_contains("introspect succeeded"))
194 | end
195 |
196 | lu.run()
197 |
198 |
199 |
--------------------------------------------------------------------------------
/test/unit/test_introspect.lua:
--------------------------------------------------------------------------------
1 | local lu = require("luaunit")
2 |
3 | TestIntrospect = require("test.unit.mockable_case"):extend()
4 |
5 |
6 | function TestIntrospect:setUp()
7 | TestIntrospect.super:setUp()
8 | self.handler = require("kong.plugins.oidc.handler")()
9 | end
10 |
11 | function TestIntrospect:tearDown()
12 | TestIntrospect.super:tearDown()
13 | end
14 |
15 | function TestIntrospect:test_access_token_exists()
16 | ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
17 | local dict = {}
18 | function dict:get(key) return key end
19 | _G.ngx.shared = {introspection = dict }
20 |
21 | ngx.encode_base64 = function(x)
22 | return "eyJzdWIiOiJzdWIifQ=="
23 | end
24 |
25 | local headers = {}
26 | ngx.req.set_header = function(h, v)
27 | headers[h] = v
28 | end
29 |
30 | self.handler:access({introspection_endpoint = "x"})
31 | lu.assertTrue(self:log_contains("introspect succeeded"))
32 | lu.assertEquals(headers['X-Userinfo'], "eyJzdWIiOiJzdWIifQ==")
33 | end
34 |
35 | function TestIntrospect:test_no_authorization_header()
36 | package.loaded["resty.openidc"].authenticate = function(...) return {}, nil end
37 | ngx.req.get_headers = function() return {} end
38 |
39 | local headers = {}
40 | ngx.req.set_header = function(h, v)
41 | headers[h] = v
42 | end
43 |
44 | self.handler:access({introspection_endpoint = "x"})
45 | lu.assertFalse(self:log_contains(self.mocked_ngx.ERR))
46 | lu.assertEquals(headers['X-Userinfo'], nil)
47 | end
48 |
49 |
50 | lu.run()
51 |
--------------------------------------------------------------------------------
/test/unit/test_utils.lua:
--------------------------------------------------------------------------------
1 | local utils = require("kong.plugins.oidc.utils")
2 | local lu = require("luaunit")
3 |
4 | TestUtils = require("test.unit.base_case"):extend()
5 |
6 |
7 | function TestUtils:testRedirectUriPath()
8 | local ngx = {
9 | var = {
10 | scheme = "http",
11 | host = "1.2.3.4",
12 | request_uri = ""
13 | },
14 | req = {
15 | get_uri_args = function() return nil end
16 | }
17 | }
18 | ngx.var.request_uri = "/path?some=stuff"
19 | lu.assertEquals(utils.get_redirect_uri_path(ngx), "/path/")
20 |
21 | ngx.var.request_uri = "/long/path/"
22 | lu.assertEquals(utils.get_redirect_uri_path(ngx), "/long/path")
23 |
24 | ngx.req.get_uri_args = function() return {code = 1}end
25 | lu.assertEquals(utils.get_redirect_uri_path(ngx), "/long/path/")
26 | end
27 |
28 | function TestUtils:testOptions()
29 | local opts = utils.get_options({
30 | client_id = 1,
31 | client_secret = 2,
32 | discovery = "d",
33 | scope = "openid",
34 | response_type = "code",
35 | ssl_verify = "no",
36 | token_endpoint_auth_method = "client_secret_post",
37 | introspection_endpoint_auth_method = "client_secret_basic",
38 | filters = "pattern1,pattern2,pattern3",
39 | logout_path = "/logout",
40 | redirect_after_logout_uri = "/login"
41 | }, {var = {request_uri = "/path"},
42 | req = {get_uri_args = function() return nil end}})
43 |
44 | lu.assertEquals(opts.client_id, 1)
45 | lu.assertEquals(opts.client_secret, 2)
46 | lu.assertEquals(opts.discovery, "d")
47 | lu.assertEquals(opts.scope, "openid")
48 | lu.assertEquals(opts.response_type, "code")
49 | lu.assertEquals(opts.ssl_verify, "no")
50 | lu.assertEquals(opts.token_endpoint_auth_method, "client_secret_post")
51 | lu.assertEquals(opts.introspection_endpoint_auth_method, "client_secret_basic")
52 | lu.assertEquals(opts.redirect_uri_path, "/path/")
53 | lu.assertEquals(opts.logout_path, "/logout")
54 | lu.assertEquals(opts.redirect_after_logout_uri, "/login")
55 |
56 | local expectedFilters = {
57 | "pattern1",
58 | "pattern2",
59 | "pattern3"
60 | }
61 |
62 | lu.assertItemsEquals(expectedFilters, opts.filters)
63 |
64 | end
65 |
66 |
67 | lu.run()
68 |
--------------------------------------------------------------------------------
/test/unit/test_utils_bearer_access_token.lua:
--------------------------------------------------------------------------------
1 | local utils = require("kong.plugins.oidc.utils")
2 | local lu = require("luaunit")
3 |
4 | TestToken = require("test.unit.mockable_case"):extend()
5 |
6 | function TestToken:setUp()
7 | TestToken.super:setUp()
8 | end
9 |
10 | function TestToken:tearDown()
11 | TestToken.super:tearDown()
12 | end
13 |
14 | function TestToken:test_access_token_authorization_missing()
15 | _G.ngx = {req = {
16 | get_headers = function() return {} end }
17 | }
18 | lu.assertFalse(utils.has_bearer_access_token())
19 | end
20 |
21 | function TestToken:test_access_token_bearer_missing()
22 | _G.ngx = {req = {
23 | get_headers = function() return {"Authorization"} end }
24 | }
25 | lu.assertFalse(utils.has_bearer_access_token())
26 | end
27 |
28 | function TestToken:test_access_token_bearer_exists()
29 | _G.ngx = {req = {
30 | get_headers = function() return {Authorization = "Bearer xxx"} end }
31 | }
32 | lu.assertTrue(utils.has_bearer_access_token())
33 | end
34 |
35 |
36 | lu.run()
37 |
--------------------------------------------------------------------------------