├── .busted ├── .editorconfig ├── .gitignore ├── .luacheckrc ├── .pongo └── pongorc ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── kong-plugin-serverless-functions-2.1.0-0.rockspec ├── kong └── plugins │ ├── post-function │ ├── handler.lua │ └── schema.lua │ └── pre-function │ ├── _handler.lua │ ├── _schema.lua │ ├── handler.lua │ └── schema.lua └── spec ├── 01-schema_spec.lua ├── 02-access_spec.lua ├── 03-dbless_spec.lua └── 04-phases_spec.lua /.busted: -------------------------------------------------------------------------------- 1 | return { 2 | default = { 3 | verbose = true, 4 | coverage = false, 5 | output = "gtest", 6 | }, 7 | } 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | [*.lua] 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [kong/templates/nginx*] 14 | indent_style = space 15 | indent_size = 4 16 | 17 | [*.template] 18 | indent_style = space 19 | indent_size = 4 20 | 21 | [Makefile] 22 | indent_style = tab 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vagrant/ 3 | .buildpath 4 | .project 5 | .idea 6 | *.tar.gz 7 | *.rock 8 | package.sh 9 | servroot 10 | 11 | -------------------------------------------------------------------------------- /.luacheckrc: -------------------------------------------------------------------------------- 1 | -- Configuration file for LuaCheck 2 | -- see: https://luacheck.readthedocs.io/en/stable/ 3 | -- 4 | -- To run do: `luacheck .` from the repo 5 | 6 | std = "ngx_lua" 7 | unused_args = false 8 | redefined = false 9 | max_line_length = false 10 | 11 | 12 | globals = { 13 | "_KONG", 14 | "kong", 15 | "ngx.IS_CLI", 16 | } 17 | 18 | 19 | not_globals = { 20 | "string.len", 21 | "table.getn", 22 | } 23 | 24 | 25 | ignore = { 26 | "6.", -- ignore whitespace warnings 27 | } 28 | 29 | 30 | exclude_files = { 31 | --"spec/fixtures/invalid-module.lua", 32 | --"spec-old-api/fixtures/invalid-module.lua", 33 | } 34 | 35 | 36 | files["spec/**/*.lua"] = { 37 | std = "ngx_lua+busted", 38 | } 39 | -------------------------------------------------------------------------------- /.pongo/pongorc: -------------------------------------------------------------------------------- 1 | --postgres 2 | --no-cassandra 3 | 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: bionic 2 | 3 | jobs: 4 | include: 5 | - name: Kong CE 2.4.x 6 | env: KONG_VERSION=2.4.x 7 | - name: Kong CE Master 8 | env: KONG_VERSION=nightly 9 | - name: Kong EE 2.4.1.x 10 | env: KONG_VERSION=2.4.1.x 11 | - name: Kong Enterprise nightly 12 | env: KONG_VERSION=nightly-ee 13 | 14 | install: 15 | - git clone --single-branch https://github.com/Kong/kong-pongo ../kong-pongo 16 | - "../kong-pongo/pongo.sh up" 17 | - "../kong-pongo/pongo.sh build" 18 | 19 | script: 20 | - "../kong-pongo/pongo.sh lint" 21 | - "../kong-pongo/pongo.sh run" 22 | 23 | notifications: 24 | slack: 25 | if: branch = master AND type != pull_request 26 | on_success: change 27 | on_failure: always 28 | rooms: 29 | secure: jeyfYnQslOOjT+kVHSNWeKPKEjDxwYDpygd3SuAbnchmlrog90wgBcjmPxIRTP0R5cEXDmIw45LjFM4srdZT4vf5Whykznz6IkQ7NeHs5cpk8aDK9Ya3dv+NNbbq3TPyKa6G7B/DnVoRl5cLI6Fyw6ympRalyg/7f1Hwv90FKUH7MW1LJGnSFKY7+ghlNP1dRGfesoxIC0JS9n2Nh6y6MvcqRFHQmE3Nn2Qi1aN1+8gVCxLVpe7vHdtEh7vQvsBQ12E/zdQRG6ZJDzuwiu1buETzcHmG2/pweF9U2j9Hdm2f/J/9foEkvjGvCA3Xt5nKsrQPfzym1MgE4S8rVUQBo8wviQOINz90Z98pdYb5z8EnS2cQMRzJYS9mOitReRiyskiYxZJf5pKyaO4kXSE+YSG5gFsTZc3H42l0gDpVwvGQAU9b/by389NudIYqHkxvtEgdbBLmKO/p6zstyrAftGNCf2CTyrQvngM9prbf7RvPX+BJhHirTEr0Te6sIIGnlUUpS3Kv65lJqPnAIJ1GUUAO4mwZeAf8gVDXAsaPrXLYxpgb0tlWfhr2uBAUQ/0fEOX0ehrrvrDZ9RSYqsVwdUYJdBTGQjm1N9EWmJECn9hJLVGdS0ID0hi7AnSTldxQ4x3z4PxMnvXIIU7ksU9Uq4QRol3GCQ2X15VwkFOteyI= 30 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog; Kong Serverless Functions Plugin 2 | 3 | ## 2.1.0 2010-01-08 4 | 5 | - Use Kong sandboxing module 6 | 7 | ## 2.0.0 2020-12-22 8 | 9 | - Change: Only allow kong PDK, nginx and plain Lua 10 | 11 | ## 1.0.0 released 7-Apr-2020 12 | 13 | - Change: adds the ability to run functions in each phase 14 | - Fix: bug when upvalues are used, combined with an early exit 15 | 16 | ## 0.3.1 17 | 18 | - Do not execute functions when validating ([Kong/kong#5110](https://github.com/Kong/kong/issues/5110)) 19 | 20 | ## 0.3.0 21 | 22 | - Functions can now have upvalues 23 | - Plugins are no longer required to inherit from the `BasePlugin` module 24 | 25 | ## 0.2.0 26 | 27 | - Updated schemas to new format 28 | - Updated specs to test Services & Routes instead of plugins, and adapted to new schemas 29 | 30 | ## 0.1.0 Initial release 31 | 32 | - `pre-function` and `post-function` plugins added 33 | -------------------------------------------------------------------------------- /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 2018 Kong Inc. 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 | # Kong Serverless Functions Plugin 2 | 3 | ## :warning: This plugin is now maintained as part of [Kong](https://github.com/Kong/kong). Please open Issues and PRs in that repository 4 | 5 | ## :open_book: For documentation, please visit https://docs.konghq.com/hub/kong-inc/serverless-functions 6 | -------------------------------------------------------------------------------- /kong-plugin-serverless-functions-2.1.0-0.rockspec: -------------------------------------------------------------------------------- 1 | package = "kong-plugin-serverless-functions" 2 | version = "2.1.0-0" 3 | source = { 4 | url = "git://github.com/kong/kong-plugin-serverless-functions", 5 | tag = "2.1.0" 6 | } 7 | description = { 8 | summary = "Dynamically run Lua code from Kong during plugin phases.", 9 | license = "Apache 2.0" 10 | } 11 | dependencies = { 12 | "lua >= 5.1" 13 | } 14 | build = { 15 | type = "builtin", 16 | modules = { 17 | ["kong.plugins.pre-function._handler"] = "kong/plugins/pre-function/_handler.lua", 18 | ["kong.plugins.pre-function._schema"] = "kong/plugins/pre-function/_schema.lua", 19 | 20 | ["kong.plugins.pre-function.handler"] = "kong/plugins/pre-function/handler.lua", 21 | ["kong.plugins.pre-function.schema"] = "kong/plugins/pre-function/schema.lua", 22 | 23 | ["kong.plugins.post-function.handler"] = "kong/plugins/post-function/handler.lua", 24 | ["kong.plugins.post-function.schema"] = "kong/plugins/post-function/schema.lua", 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /kong/plugins/post-function/handler.lua: -------------------------------------------------------------------------------- 1 | return require("kong.plugins.pre-function._handler")(-1000) 2 | -------------------------------------------------------------------------------- /kong/plugins/post-function/schema.lua: -------------------------------------------------------------------------------- 1 | return require("kong.plugins.pre-function._schema")("post-function") 2 | -------------------------------------------------------------------------------- /kong/plugins/pre-function/_handler.lua: -------------------------------------------------------------------------------- 1 | local sandbox = require "kong.tools.sandbox" 2 | 3 | -- handler file for both the pre-function and post-function plugin 4 | 5 | 6 | local config_cache do 7 | 8 | local no_op = function() end 9 | 10 | local sandbox_opts = { env = { kong = kong, ngx = ngx } } 11 | 12 | -- compiles the array for a phase into a single function 13 | local function compile_phase_array(phase_funcs) 14 | if not phase_funcs or #phase_funcs == 0 then 15 | -- nothing to do for this phase 16 | return no_op 17 | else 18 | -- compile the functions we got 19 | local compiled = {} 20 | for i, func_string in ipairs(phase_funcs) do 21 | local func = assert(sandbox.sandbox(func_string, sandbox_opts)) 22 | 23 | local first_run_complete = false 24 | compiled[i] = function() 25 | -- this is a temporary closure, that will replace itself 26 | if not first_run_complete then 27 | first_run_complete = true 28 | local result = func() --> this might call ngx.exit() 29 | 30 | -- if we ever get here, then there was NO early exit from a 0.1.0 31 | -- type config 32 | if type(result) == "function" then 33 | -- this is a new function (0.2.0+), with upvalues 34 | -- the first call to func above only initialized it, so run again 35 | func = result 36 | compiled[i] = func 37 | func() --> this again, may do an early exit 38 | end 39 | 40 | -- if we ever get here, then there was no early exit from either 41 | -- 0.1.0 or 0.2.0+ code 42 | -- Replace the entry of this closure in the array with the actual 43 | -- function, since the closure is no longer needed. 44 | compiled[i] = func 45 | 46 | else 47 | -- first run is marked as complete, but we (this temporary closure) 48 | -- are being called again. So we are here only if the initial 49 | -- function call did an early exit. 50 | -- So replace this closure now; 51 | compiled[i] = func 52 | -- And call it again, for this 2nd run; 53 | func() 54 | end 55 | -- unreachable 56 | end 57 | end 58 | 59 | -- now return a function that executes the entire array 60 | return function() 61 | for _, f in ipairs(compiled) do f() end 62 | end 63 | end 64 | end 65 | 66 | 67 | local phases = { "certificate", "rewrite", "access", 68 | "header_filter", "body_filter", "log", 69 | "functions" } -- <-- this one being legacy 70 | 71 | 72 | config_cache = setmetatable({}, { 73 | __mode = "k", 74 | __index = function(self, config) 75 | -- config was not found yet, so go and compile our config functions 76 | local runtime_funcs = {} 77 | for _, phase in ipairs(phases) do 78 | local func = compile_phase_array(config[phase]) 79 | 80 | if phase == "functions" then 81 | if func == no_op then 82 | func = nil -- do not set a "functions" key, since we won't run it anyway 83 | else 84 | -- functions, which is legacy is specified, so inject as "access". The 85 | -- schema already prevents "access" and "functions" to co-exist, so 86 | -- this should be safe. 87 | phase = "access" 88 | end 89 | end 90 | 91 | runtime_funcs[phase] = func 92 | end 93 | -- store compiled results in cache, and return them 94 | self[config] = runtime_funcs 95 | return runtime_funcs 96 | end 97 | }) 98 | end 99 | 100 | 101 | 102 | return function(priority) 103 | 104 | local ServerlessFunction = { 105 | PRIORITY = priority, 106 | VERSION = "2.1.0", 107 | } 108 | 109 | function ServerlessFunction:certificate(config) 110 | config_cache[config].certificate() 111 | end 112 | 113 | function ServerlessFunction:rewrite(config) 114 | config_cache[config].rewrite() 115 | end 116 | 117 | function ServerlessFunction:access(config) 118 | config_cache[config].access() 119 | end 120 | 121 | function ServerlessFunction:header_filter(config) 122 | config_cache[config].header_filter() 123 | end 124 | 125 | function ServerlessFunction:body_filter(config) 126 | config_cache[config].body_filter() 127 | end 128 | 129 | function ServerlessFunction:log(config) 130 | config_cache[config].log() 131 | end 132 | 133 | 134 | return ServerlessFunction 135 | end 136 | -------------------------------------------------------------------------------- /kong/plugins/pre-function/_schema.lua: -------------------------------------------------------------------------------- 1 | -- schema file for both the pre-function and post-function plugin 2 | return function(plugin_name) 3 | 4 | local Schema = require "kong.db.schema" 5 | local typedefs = require "kong.db.schema.typedefs" 6 | 7 | local loadstring = loadstring 8 | 9 | local functions_deprecated = "[%s] 'config.functions' will be deprecated in favour of 'config.access'" 10 | 11 | 12 | local function validate_function(fun) 13 | local _, err = loadstring(fun) 14 | if err then 15 | return false, "error parsing " .. plugin_name .. ": " .. err 16 | end 17 | 18 | return true 19 | end 20 | 21 | 22 | local phase_functions = Schema.define { 23 | required = true, 24 | default = {}, 25 | type = "array", 26 | elements = { 27 | type = "string", 28 | required = false, 29 | custom_validator = validate_function, 30 | } 31 | } 32 | 33 | return { 34 | name = plugin_name, 35 | fields = { 36 | { consumer = typedefs.no_consumer }, 37 | { 38 | config = { 39 | type = "record", 40 | fields = { 41 | -- old interface. functions are always on access phase 42 | { functions = phase_functions { 43 | custom_validator = function(v) 44 | if #v > 0 then 45 | kong.log.warn(functions_deprecated:format(plugin_name)) 46 | end 47 | 48 | return true 49 | end, 50 | } }, 51 | -- new interface 52 | { certificate = phase_functions }, 53 | { rewrite = phase_functions }, 54 | { access = phase_functions }, 55 | { header_filter = phase_functions }, 56 | { body_filter = phase_functions }, 57 | { log = phase_functions }, 58 | }, 59 | }, 60 | }, 61 | }, 62 | entity_checks = { 63 | { mutually_exclusive_sets = { 64 | set1 = { "config.functions" }, 65 | set2 = { "config.access" }, 66 | } }, 67 | { at_least_one_of = { 68 | "config.functions", 69 | "config.certificate", 70 | "config.rewrite", 71 | "config.access", 72 | "config.header_filter", 73 | "config.body_filter", 74 | "config.log", 75 | } }, 76 | }, 77 | } 78 | end 79 | -------------------------------------------------------------------------------- /kong/plugins/pre-function/handler.lua: -------------------------------------------------------------------------------- 1 | return require("kong.plugins.pre-function._handler")(math.huge) 2 | -------------------------------------------------------------------------------- /kong/plugins/pre-function/schema.lua: -------------------------------------------------------------------------------- 1 | return require("kong.plugins.pre-function._schema")("pre-function") 2 | -------------------------------------------------------------------------------- /spec/01-schema_spec.lua: -------------------------------------------------------------------------------- 1 | local v = require("spec.helpers").validate_plugin_config_schema 2 | 3 | local mock_fn_one = '("hello world!"):find("world")' 4 | local mock_fn_two = 'local x = 1' 5 | local mock_fn_three = 'local x = 1 return function() x = x + 1 end' 6 | local mock_fn_invalid = 'print(' 7 | local mock_fn_invalid_return = 'return "hello-world"' 8 | 9 | 10 | for _, plugin_name in ipairs({ "pre-function", "post-function" }) do 11 | 12 | for _, method in ipairs({ "functions", "phase=functions"}) do 13 | local function get_conf(functions) 14 | if method == "functions" then 15 | return { functions = functions } 16 | elseif method == "phase=functions" then 17 | return { access = functions } 18 | end 19 | end 20 | 21 | local function get_functions_from_error(err) 22 | if method == "functions" then 23 | return err.config.functions 24 | elseif method == "phase=functions" then 25 | return err.config.access 26 | end 27 | end 28 | 29 | 30 | describe("Plugin: " .. plugin_name .. string.format(" (by %s)", method) .. " schema", function() 31 | local schema 32 | 33 | setup(function() 34 | schema = require("kong.plugins." .. plugin_name .. ".schema") 35 | 36 | spy.on(kong.log, "warn") 37 | end) 38 | 39 | teardown(function() 40 | kong.log.warn:revert() 41 | end) 42 | 43 | it("validates single function", function() 44 | local ok, err = v(get_conf { mock_fn_one }, schema) 45 | 46 | assert.truthy(ok) 47 | assert.falsy(err) 48 | end) 49 | 50 | it("error in function is not triggered during validation", function() 51 | local ok, err = v(get_conf { 52 | [[error("should never happen")]], 53 | }, schema) 54 | 55 | assert.truthy(ok) 56 | assert.falsy(err) 57 | end) 58 | 59 | it("validates single function with upvalues", function() 60 | local ok, err = v(get_conf{ mock_fn_three }, schema) 61 | 62 | assert.truthy(ok) 63 | assert.falsy(err) 64 | end) 65 | 66 | it("validates multiple functions", function() 67 | local ok, err = v(get_conf { mock_fn_one, mock_fn_two }, schema) 68 | 69 | assert.truthy(ok) 70 | assert.falsy(err) 71 | end) 72 | 73 | it("a valid chunk with an invalid return type", function() 74 | local ok, err = v(get_conf { mock_fn_invalid_return }, schema) 75 | 76 | assert.truthy(ok) 77 | assert.falsy(err) 78 | end) 79 | 80 | 81 | if method == "functions" then 82 | it("throws a log warning when being used", function() 83 | v(get_conf { mock_fn_one, mock_fn_two }, schema) 84 | assert.spy(kong.log.warn).was_called.with(string.format("[%s] 'config.functions' will be deprecated in favour of 'config.access'", plugin_name)) 85 | end) 86 | end 87 | 88 | describe("errors", function() 89 | it("with an invalid function", function() 90 | local ok, err = v(get_conf { mock_fn_invalid }, schema) 91 | 92 | assert.falsy(ok) 93 | assert.equals("error parsing " .. plugin_name .. ": [string \"print(\"]:1: unexpected symbol near ''", get_functions_from_error(err)[1]) 94 | end) 95 | 96 | it("with a valid and invalid function", function() 97 | local ok, err = v(get_conf { mock_fn_one, mock_fn_invalid }, schema) 98 | 99 | assert.falsy(ok) 100 | assert.equals("error parsing " .. plugin_name .. ": [string \"print(\"]:1: unexpected symbol near ''", get_functions_from_error(err)[2]) 101 | end) 102 | end) 103 | end) 104 | end 105 | end 106 | -------------------------------------------------------------------------------- /spec/02-access_spec.lua: -------------------------------------------------------------------------------- 1 | local helpers = require "spec.helpers" 2 | local cjson = require "cjson" 3 | 4 | local mock_fn_one = [[ 5 | ngx.status = 503 6 | ngx.exit(ngx.status) 7 | ]] 8 | 9 | local mock_fn_two = [[ 10 | ngx.status = 404 11 | ngx.say("Not Found") 12 | ngx.exit(ngx.status) 13 | ]] 14 | 15 | local mock_fn_three = [[ 16 | return kong.response.exit(406, { message = "Invalid" }) 17 | ]] 18 | 19 | local mock_fn_four = [[ 20 | ngx.status = 400 21 | ]] 22 | 23 | local mock_fn_five = [[ 24 | ngx.exit(ngx.status) 25 | ]] 26 | 27 | local mock_fn_six = [[ 28 | local count = 0 29 | ngx.log(ngx.ERR, "mock_fn_six: initialization ran") 30 | return function() 31 | ngx.log(ngx.ERR, "mock_fn_six: function ran") 32 | count = count + 1 33 | ngx.status = 200 34 | ngx.say(ngx.worker.pid() * 1000 + count) 35 | ngx.exit(ngx.status) 36 | end 37 | ]] 38 | 39 | local mock_fn_seven = [[ 40 | ngx.req.read_body() 41 | 42 | local count = tonumber(ngx.req.get_body_data()) 43 | count = count + 1 44 | 45 | ngx.status = 200 46 | ngx.say(count) 47 | ngx.exit(ngx.status) 48 | ]] 49 | 50 | -- same as 7, but with upvalue format 51 | local mock_fn_eight = "return function() \n" .. mock_fn_seven .. "\n end" 52 | 53 | local mock_fn_nine = [[ 54 | error("this should stop the request with a 500") 55 | ]] 56 | 57 | 58 | describe("Plugin: serverless-functions", function() 59 | it("priority of plugins", function() 60 | local pre = require "kong.plugins.pre-function.handler" 61 | local post = require "kong.plugins.post-function.handler" 62 | assert(pre.PRIORITY > post.PRIORITY, "expected the priority of PRE (" .. 63 | tostring(pre.PRIORITY) .. ") to be higher than POST (" .. 64 | tostring(post.PRIORITY)..")") 65 | end) 66 | end) 67 | 68 | 69 | 70 | for _, plugin_name in ipairs({ "pre-function", "post-function" }) do 71 | 72 | for _, method in ipairs({ "functions", "phase=functions"}) do 73 | local function get_conf(functions) 74 | if method == "functions" then 75 | return { functions = functions } 76 | elseif method == "phase=functions" then 77 | return { access = functions } 78 | end 79 | end 80 | 81 | describe("Plugin: " .. plugin_name .. string.format(" (by %s)", method) .. " access", function() 82 | local client, admin_client 83 | 84 | setup(function() 85 | local bp, db = helpers.get_db_utils() 86 | 87 | assert(db:truncate()) 88 | 89 | local service = bp.services:insert { 90 | name = "service-1", 91 | host = helpers.mock_upstream_host, 92 | port = helpers.mock_upstream_port, 93 | } 94 | 95 | local route1 = bp.routes:insert { 96 | service = { id = service.id }, 97 | hosts = { "one." .. plugin_name .. ".com" }, 98 | } 99 | 100 | local route2 = bp.routes:insert { 101 | service = { id = service.id }, 102 | hosts = { "two." .. plugin_name .. ".com" }, 103 | } 104 | 105 | local route3 = bp.routes:insert { 106 | service = { id = service.id }, 107 | hosts = { "three." .. plugin_name .. ".com" }, 108 | } 109 | 110 | local route4 = bp.routes:insert { 111 | service = { id = service.id }, 112 | hosts = { "four." .. plugin_name .. ".com" }, 113 | } 114 | 115 | local route6 = bp.routes:insert { 116 | service = { id = service.id }, 117 | hosts = { "six." .. plugin_name .. ".com" }, 118 | } 119 | 120 | local route7 = bp.routes:insert { 121 | service = { id = service.id }, 122 | hosts = { "seven." .. plugin_name .. ".com" }, 123 | } 124 | 125 | local route8 = bp.routes:insert { 126 | service = { id = service.id }, 127 | hosts = { "eight." .. plugin_name .. ".com" }, 128 | } 129 | 130 | local route9 = bp.routes:insert { 131 | service = { id = service.id }, 132 | hosts = { "nine." .. plugin_name .. ".com" }, 133 | } 134 | 135 | bp.plugins:insert { 136 | name = plugin_name, 137 | route = { id = route1.id }, 138 | config = get_conf { mock_fn_one }, 139 | } 140 | 141 | bp.plugins:insert { 142 | name = plugin_name, 143 | route = { id = route2.id }, 144 | config = get_conf { mock_fn_two }, 145 | } 146 | 147 | bp.plugins:insert { 148 | name = plugin_name, 149 | route = { id = route3.id }, 150 | config = get_conf { mock_fn_three }, 151 | } 152 | 153 | bp.plugins:insert { 154 | name = plugin_name, 155 | route = { id = route4.id }, 156 | config = get_conf { mock_fn_four, mock_fn_five }, 157 | } 158 | 159 | bp.plugins:insert { 160 | name = plugin_name, 161 | route = { id = route6.id }, 162 | config = get_conf { mock_fn_six }, 163 | } 164 | 165 | bp.plugins:insert { 166 | name = plugin_name, 167 | route = { id = route7.id }, 168 | config = get_conf { mock_fn_seven }, 169 | } 170 | 171 | bp.plugins:insert { 172 | name = plugin_name, 173 | route = { id = route8.id }, 174 | config = get_conf { mock_fn_eight }, 175 | } 176 | 177 | bp.plugins:insert { 178 | name = plugin_name, 179 | route = { id = route9.id }, 180 | config = get_conf { mock_fn_nine }, 181 | } 182 | 183 | assert(helpers.start_kong({ 184 | nginx_conf = "spec/fixtures/custom_nginx.template", 185 | })) 186 | end) 187 | 188 | teardown(function() 189 | helpers.stop_kong() 190 | end) 191 | 192 | before_each(function() 193 | client = helpers.proxy_client() 194 | admin_client = helpers.admin_client() 195 | end) 196 | 197 | after_each(function() 198 | if client and admin_client then 199 | client:close() 200 | admin_client:close() 201 | end 202 | end) 203 | 204 | 205 | describe("request termination", function() 206 | it("using ngx.exit()", function() 207 | local res = assert(client:send { 208 | method = "GET", 209 | path = "/status/200", 210 | headers = { 211 | ["Host"] = "one." .. plugin_name .. ".com" 212 | } 213 | }) 214 | 215 | assert.res_status(503, res) 216 | end) 217 | 218 | it("with upvalues", function() 219 | local results = {} 220 | for i = 1, 50 do 221 | local res = assert(client:send { 222 | method = "GET", 223 | path = "/status/200", 224 | headers = { 225 | ["Host"] = "six." .. plugin_name .. ".com" 226 | } 227 | }) 228 | 229 | local body = assert.res_status(200, res) 230 | assert.is_string(body) 231 | --print(i, ": ", body) 232 | assert.is_nil(results[body]) 233 | results[body] = true 234 | end 235 | end) 236 | 237 | it("using ngx.status and exit", function() 238 | local res = assert(client:send { 239 | method = "GET", 240 | path = "/status/200", 241 | headers = { 242 | ["Host"] = "two." .. plugin_name .. ".com" 243 | } 244 | }) 245 | local body = assert.res_status(404, res) 246 | assert.same("Not Found", body) 247 | end) 248 | 249 | it("import response utility and send message", function() 250 | local res = assert(client:send { 251 | method = "GET", 252 | path = "/status/200", 253 | headers = { 254 | ["Host"] = "three." .. plugin_name .. ".com" 255 | } 256 | }) 257 | local body = assert.res_status(406, res) 258 | local json = cjson.decode(body) 259 | assert.same({ message = "Invalid" }, json) 260 | end) 261 | 262 | it("cascading functions for a 400 and exit", function() 263 | local res = assert(client:send { 264 | method = "GET", 265 | path = "/status/200", 266 | headers = { 267 | ["Host"] = "four." .. plugin_name .. ".com" 268 | } 269 | }) 270 | local body = assert.res_status(400, res) 271 | assert.same("Bad request", body) 272 | end) 273 | 274 | it("runtime error aborts with a 500", function() 275 | local res = assert(client:send { 276 | method = "GET", 277 | path = "/status/200", 278 | headers = { 279 | ["Host"] = "nine." .. plugin_name .. ".com" 280 | } 281 | }) 282 | local body = assert.res_status(500, res) 283 | assert.same('{"message":"An unexpected error occurred"}', body) 284 | end) 285 | end) 286 | 287 | describe("invocation count", function() 288 | it("once on initialization", function() 289 | local count = 0 290 | local res = assert(client:send { 291 | method = "POST", 292 | path = "/status/200", 293 | headers = { 294 | ["Host"] = "seven." .. plugin_name .. ".com", 295 | ["Content-Length"] = #tostring(count), 296 | }, 297 | body = count, 298 | }) 299 | assert.equal(1, tonumber(res:read_body())) 300 | end) 301 | 302 | it("on repeated calls", function() 303 | local count = 0 304 | 305 | for i = 1, 10 do 306 | local res = assert(client:send { 307 | method = "POST", 308 | path = "/status/200", 309 | headers = { 310 | ["Host"] = "seven." .. plugin_name .. ".com", 311 | ["Content-Length"] = #tostring(count), 312 | }, 313 | body = count, 314 | }) 315 | count = tonumber(res:read_body()) 316 | end 317 | 318 | assert.equal(10, count) 319 | end) 320 | 321 | it("once on initialization, with upvalues", function() 322 | local count = 0 323 | local res = assert(client:send { 324 | method = "POST", 325 | path = "/status/200", 326 | headers = { 327 | ["Host"] = "eight." .. plugin_name .. ".com", 328 | ["Content-Length"] = #tostring(count), 329 | }, 330 | body = count, 331 | }) 332 | assert.equal(1, tonumber(res:read_body())) 333 | end) 334 | 335 | it("on repeated calls, with upvalues", function() 336 | local count = 0 337 | for i = 1, 10 do 338 | local res = assert(client:send { 339 | method = "POST", 340 | path = "/status/200", 341 | headers = { 342 | ["Host"] = "eight." .. plugin_name .. ".com", 343 | ["Content-Length"] = #tostring(count), 344 | }, 345 | body = count, 346 | }) 347 | count = tonumber(res:read_body()) 348 | end 349 | 350 | assert.equal(10, count) 351 | end) 352 | 353 | 354 | end) 355 | end) 356 | end 357 | end 358 | -------------------------------------------------------------------------------- /spec/03-dbless_spec.lua: -------------------------------------------------------------------------------- 1 | local helpers = require "spec.helpers" 2 | 3 | local strategies = require("kong.db.strategies").STRATEGIES 4 | 5 | -- set tests as pending for kongs without strategy 'off' 6 | local describe = describe 7 | if not strategies.off then 8 | describe = pending 9 | end 10 | 11 | for _, plugin_name in ipairs({ "pre-function", "post-function" }) do 12 | 13 | describe("Plugin: " .. plugin_name .. " (dbless)", function() 14 | local admin_client 15 | 16 | setup(function() 17 | assert(helpers.start_kong({ 18 | nginx_conf = "spec/fixtures/custom_nginx.template", 19 | database = "off", 20 | })) 21 | end) 22 | 23 | teardown(function() 24 | helpers.stop_kong() 25 | end) 26 | 27 | before_each(function() 28 | admin_client = helpers.admin_client() 29 | end) 30 | 31 | after_each(function() 32 | if admin_client then 33 | admin_client:close() 34 | end 35 | end) 36 | 37 | 38 | describe("loading functions from declarative config", function() 39 | it("does not execute the function ( https://github.com/kong/kong/issues/5110 )", function() 40 | local res = assert(admin_client:send { 41 | method = "POST", 42 | path = "/config", 43 | body = { 44 | config = [[ 45 | "_format_version": "1.1" 46 | plugins: 47 | - name: "pre-function" 48 | config: 49 | functions: 50 | - | 51 | kong.log.err("foo") 52 | kong.response.exit(418) 53 | ]] 54 | }, 55 | headers = { 56 | ["Content-type"] = "application/json" 57 | } 58 | }) 59 | assert.res_status(201, res) 60 | end) 61 | end) 62 | end) 63 | 64 | end 65 | -------------------------------------------------------------------------------- /spec/04-phases_spec.lua: -------------------------------------------------------------------------------- 1 | local helpers = require "spec.helpers" 2 | 3 | local mock_one_fn = [[ 4 | local plugin_name = "%s" 5 | local filename = "/tmp/" .. plugin_name .. "_output" 6 | local text = "phase: '%s', index: '%s', plugin: '" .. plugin_name .. "'\n" 7 | local readfile = require("pl.utils").readfile 8 | local writefile = require("pl.utils").writefile 9 | 10 | return function() 11 | local file_content, err = readfile(filename) or "" 12 | file_content = file_content .. text 13 | assert(writefile(filename, file_content)) 14 | end 15 | ]] 16 | 17 | 18 | for _, plugin_name in ipairs({ "pre-function", "post-function" }) do 19 | 20 | -- This whole test is marked as pending because it relies on a side-effect (writing to a file) 21 | -- which is no longer a possibility after sandboxing 22 | pending("Plugin: " .. plugin_name, function() 23 | 24 | setup(function() 25 | local bp, db = helpers.get_db_utils() 26 | 27 | assert(db:truncate()) 28 | 29 | local service = bp.services:insert { 30 | name = "service-1", 31 | host = helpers.mock_upstream_host, 32 | port = helpers.mock_upstream_port, 33 | } 34 | 35 | bp.routes:insert { 36 | service = { id = service.id }, 37 | hosts = { "one." .. plugin_name .. ".com" }, 38 | } 39 | 40 | local config = {} 41 | for _, phase in ipairs({ "certificate", "rewrite", "access", 42 | "header_filter", "body_filter", "log"}) do 43 | config[phase] = {} 44 | for i, index in ipairs({"first", "second", "third"}) do 45 | config[phase][i] = mock_one_fn:format(plugin_name, phase, index) 46 | end 47 | end 48 | 49 | bp.plugins:insert { 50 | name = plugin_name, 51 | config = config, 52 | } 53 | 54 | assert(helpers.start_kong({ 55 | nginx_conf = "spec/fixtures/custom_nginx.template", 56 | })) 57 | end) 58 | 59 | teardown(function() 60 | helpers.stop_kong() 61 | end) 62 | 63 | 64 | it("hits all phases, with 3 functions, on 3 requests", function() 65 | local filename = "/tmp/" .. plugin_name .. "_output" 66 | os.remove(filename) 67 | 68 | for i = 1,3 do 69 | local client = helpers.proxy_ssl_client() 70 | 71 | local res = assert(client:send { 72 | method = "GET", 73 | path = "/status/200", 74 | headers = { 75 | ["Host"] = "one." .. plugin_name .. ".com" 76 | } 77 | }) 78 | assert.response(res).has.status(200) 79 | 80 | client:close() 81 | ngx.sleep(0.1) -- wait for log-phase handler to execute 82 | end 83 | 84 | local content = require("pl.utils").readfile(filename) 85 | assert.equal(([[ 86 | phase: 'certificate', index: 'first', plugin: 'pre-function' 87 | phase: 'certificate', index: 'second', plugin: 'pre-function' 88 | phase: 'certificate', index: 'third', plugin: 'pre-function' 89 | phase: 'rewrite', index: 'first', plugin: 'pre-function' 90 | phase: 'rewrite', index: 'second', plugin: 'pre-function' 91 | phase: 'rewrite', index: 'third', plugin: 'pre-function' 92 | phase: 'access', index: 'first', plugin: 'pre-function' 93 | phase: 'access', index: 'second', plugin: 'pre-function' 94 | phase: 'access', index: 'third', plugin: 'pre-function' 95 | phase: 'header_filter', index: 'first', plugin: 'pre-function' 96 | phase: 'header_filter', index: 'second', plugin: 'pre-function' 97 | phase: 'header_filter', index: 'third', plugin: 'pre-function' 98 | phase: 'body_filter', index: 'first', plugin: 'pre-function' 99 | phase: 'body_filter', index: 'second', plugin: 'pre-function' 100 | phase: 'body_filter', index: 'third', plugin: 'pre-function' 101 | phase: 'body_filter', index: 'first', plugin: 'pre-function' 102 | phase: 'body_filter', index: 'second', plugin: 'pre-function' 103 | phase: 'body_filter', index: 'third', plugin: 'pre-function' 104 | phase: 'log', index: 'first', plugin: 'pre-function' 105 | phase: 'log', index: 'second', plugin: 'pre-function' 106 | phase: 'log', index: 'third', plugin: 'pre-function' 107 | phase: 'certificate', index: 'first', plugin: 'pre-function' 108 | phase: 'certificate', index: 'second', plugin: 'pre-function' 109 | phase: 'certificate', index: 'third', plugin: 'pre-function' 110 | phase: 'rewrite', index: 'first', plugin: 'pre-function' 111 | phase: 'rewrite', index: 'second', plugin: 'pre-function' 112 | phase: 'rewrite', index: 'third', plugin: 'pre-function' 113 | phase: 'access', index: 'first', plugin: 'pre-function' 114 | phase: 'access', index: 'second', plugin: 'pre-function' 115 | phase: 'access', index: 'third', plugin: 'pre-function' 116 | phase: 'header_filter', index: 'first', plugin: 'pre-function' 117 | phase: 'header_filter', index: 'second', plugin: 'pre-function' 118 | phase: 'header_filter', index: 'third', plugin: 'pre-function' 119 | phase: 'body_filter', index: 'first', plugin: 'pre-function' 120 | phase: 'body_filter', index: 'second', plugin: 'pre-function' 121 | phase: 'body_filter', index: 'third', plugin: 'pre-function' 122 | phase: 'body_filter', index: 'first', plugin: 'pre-function' 123 | phase: 'body_filter', index: 'second', plugin: 'pre-function' 124 | phase: 'body_filter', index: 'third', plugin: 'pre-function' 125 | phase: 'log', index: 'first', plugin: 'pre-function' 126 | phase: 'log', index: 'second', plugin: 'pre-function' 127 | phase: 'log', index: 'third', plugin: 'pre-function' 128 | phase: 'certificate', index: 'first', plugin: 'pre-function' 129 | phase: 'certificate', index: 'second', plugin: 'pre-function' 130 | phase: 'certificate', index: 'third', plugin: 'pre-function' 131 | phase: 'rewrite', index: 'first', plugin: 'pre-function' 132 | phase: 'rewrite', index: 'second', plugin: 'pre-function' 133 | phase: 'rewrite', index: 'third', plugin: 'pre-function' 134 | phase: 'access', index: 'first', plugin: 'pre-function' 135 | phase: 'access', index: 'second', plugin: 'pre-function' 136 | phase: 'access', index: 'third', plugin: 'pre-function' 137 | phase: 'header_filter', index: 'first', plugin: 'pre-function' 138 | phase: 'header_filter', index: 'second', plugin: 'pre-function' 139 | phase: 'header_filter', index: 'third', plugin: 'pre-function' 140 | phase: 'body_filter', index: 'first', plugin: 'pre-function' 141 | phase: 'body_filter', index: 'second', plugin: 'pre-function' 142 | phase: 'body_filter', index: 'third', plugin: 'pre-function' 143 | phase: 'body_filter', index: 'first', plugin: 'pre-function' 144 | phase: 'body_filter', index: 'second', plugin: 'pre-function' 145 | phase: 'body_filter', index: 'third', plugin: 'pre-function' 146 | phase: 'log', index: 'first', plugin: 'pre-function' 147 | phase: 'log', index: 'second', plugin: 'pre-function' 148 | phase: 'log', index: 'third', plugin: 'pre-function' 149 | ]]):gsub("pre%-function", plugin_name),content) 150 | end) 151 | end) 152 | end 153 | --------------------------------------------------------------------------------