├── .azure-pipelines └── pipeline.yml ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── commitlint.yml │ └── publish.yml ├── .gitignore ├── .standard-version ├── makefile-updater.js ├── package-updater.js └── rockspec-updater.js ├── .versionrc.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yml ├── rockspec.template └── url-rewrite ├── .luacov ├── handler.lua ├── schema.lua └── spec └── handler_spec.lua /.azure-pipelines/pipeline.yml: -------------------------------------------------------------------------------- 1 | pr: 2 | - main 3 | - develop 4 | 5 | trigger: 6 | - main 7 | - develop 8 | 9 | pool: 10 | vmImage: 'ubuntu-latest' 11 | 12 | variables: 13 | plugin: 'url-rewrite' 14 | 15 | stages: 16 | - stage: Build 17 | jobs: 18 | - job: Build 19 | steps: 20 | - bash: | 21 | sudo apt install -y lua5.1 22 | sudo apt install -y liblua5.1-dev 23 | 24 | wget https://luarocks.org/releases/luarocks-3.3.1.tar.gz 25 | tar zxpf luarocks-3.3.1.tar.gz 26 | cd luarocks-3.3.1 && ./configure --with-lua-include=/usr/include/lua5.1 \ 27 | && make && sudo make install 28 | cd .. && rm -rf luarocks-3.3.1 && rm luarocks-3.3.1.tar.gz 29 | displayName: Install Lua and Luarocks 30 | 31 | - bash: | 32 | sudo apt install -y libssl-dev 33 | wget https://download.konghq.com/gateway-3.x-ubuntu-bionic/pool/all/k/kong/kong_3.0.0_amd64.deb 34 | sudo apt install -y ./kong_3.0.0_amd64.deb 35 | rm kong_3.0.0_amd64.deb 36 | displayName: Install kong 37 | 38 | - task: Bash@3 39 | displayName: 'Prepare' 40 | inputs: 41 | targetType: 'inline' 42 | script: | 43 | sudo make setup 44 | make check 45 | sudo make install 46 | sudo make package 47 | 48 | - task: UniversalPackages@0 49 | displayName: 'Download correct luacov-cobertura version' 50 | inputs: 51 | command: 'download' 52 | downloadDirectory: '$(System.DefaultWorkingDirectory)' 53 | feedsToUse: 'internal' 54 | vstsFeed: 'd8a23181-28c7-4e59-9cea-25e643da3675' 55 | vstsFeedPackage: '6162cb93-aff3-4686-8f03-fade4ecabccb' 56 | vstsPackageVersion: '2.0.0' 57 | 58 | - task: Bash@3 59 | displayName: 'Install luacov-cobertura correct version' 60 | inputs: 61 | targetType: 'inline' 62 | script: | 63 | sudo luarocks install $(System.DefaultWorkingDirectory)/luacov-cobertura-2.0-0.all.rock 64 | rm $(System.DefaultWorkingDirectory)/luacov-cobertura-2.0-0.all.rock 65 | 66 | - task: Bash@3 67 | displayName: 'Run tests and code coverage' 68 | inputs: 69 | targetType: 'inline' 70 | script: | 71 | make coverage 72 | 73 | - task: PublishCodeCoverageResults@1 74 | displayName: 'Publish code coverage' 75 | inputs: 76 | codeCoverageTool: Cobertura 77 | summaryFileLocation: '$(System.DefaultWorkingDirectory)/$(plugin)/cobertura.xml' 78 | 79 | - task: Bash@3 80 | displayName: 'Set Artifact Name and Version' 81 | inputs: 82 | targetType: 'inline' 83 | script: | 84 | export ARTIFACT_NAME=$(ls $(plugin)/*.rock) 85 | echo "##vso[task.setvariable variable=ArtifactName]$(echo $ARTIFACT_NAME)" 86 | 87 | - task: PublishBuildArtifacts@1 88 | displayName: 'Publish Artifact: drop' 89 | inputs: 90 | PathtoPublish: '$(ArtifactName)' 91 | 92 | - stage: Publish 93 | condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/main')) 94 | jobs: 95 | - job: Publish 96 | steps: 97 | - task: DownloadBuildArtifacts@0 98 | displayName: 'Download build artifacts' 99 | inputs: 100 | buildType: 'current' 101 | downloadType: 'single' 102 | artifactName: drop 103 | downloadPath: '$(System.ArtifactsDirectory)' 104 | 105 | - task: Bash@3 106 | displayName: 'Set Artifact Name and Version' 107 | inputs: 108 | targetType: 'inline' 109 | script: | 110 | export ARTIFACT_NAME=$(ls $(System.ArtifactsDirectory)/drop/*.rock) 111 | echo "##vso[task.setvariable variable=ArtifactName]$(echo $ARTIFACT_NAME)" 112 | export ARTIFACT_VERSION=$(echo $ARTIFACT_NAME | grep -Eo '[0-9]+.[0-9]+.[0-9]+?') 113 | echo "##vso[task.setvariable variable=ArtifactVersion]$(echo $ARTIFACT_VERSION)" 114 | 115 | - task: UniversalPackages@0 116 | displayName: 'Publish package to feed' 117 | inputs: 118 | command: 'publish' 119 | publishDirectory: '$(System.ArtifactsDirectory)/drop' 120 | feedsToUsePublish: 'internal' 121 | vstsFeedPackagePublish: 'kong-plugin-url-rewrite' 122 | packagePublishDescription: 'kong-plugin-url-rewrite' 123 | vstsFeedPublish: 'd8a23181-28c7-4e59-9cea-25e643da3675' 124 | versionOption: 'custom' 125 | versionPublish: $(ArtifactVersion) -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @ALTbruno @andreals @andremacdowell @asamedeiros @caiocanallipagarme @guih50 @henrique1996n1 @jonathanlazaro1 @leoferlopes @lucaslima-7 @Wuerike -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Issue Description 2 | 3 | ### Expected Behavior 4 | 5 | ### Checklist 6 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | ## How Has This Been Tested? 4 | 5 | ## Checklist -------------------------------------------------------------------------------- /.github/workflows/commitlint.yml: -------------------------------------------------------------------------------- 1 | name: Commitlint 2 | on: [pull_request] 3 | 4 | jobs: 5 | lint: 6 | runs-on: ubuntu-latest 7 | env: 8 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 9 | steps: 10 | - uses: actions/checkout@v2 11 | with: 12 | fetch-depth: 0 13 | - uses: wagoid/commitlint-github-action@v1 14 | with: 15 | configFile: .commitlintrc.json 16 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: PublishPlugin 2 | 3 | on: 4 | push: 5 | branches: [main, legacy/v0] 6 | 7 | workflow_dispatch: 8 | 9 | env: 10 | LUA: "lua=5.1" 11 | GCP_PROJECT_ID: "si26ef9dii9zscrxrecql6kl8eguw2" 12 | 13 | jobs: 14 | publish: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 19 | - uses: actions/checkout@v2 20 | 21 | - name: 'Create PR: Merge main into develop branch' 22 | id: create-develop-pull-request 23 | uses: thomaseizinger/create-pull-request@1.2.1 24 | env: 25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | with: 27 | head: main 28 | base: develop 29 | labels: develop 30 | title: Merge main into develop branch 31 | body: | 32 | This PR merges the main branch back into develop. 33 | This happens to ensure that the updates that happend on the release branch, i.e. CHANGELOG and manifest updates are also present on the develop branch. 34 | 35 | - name: before install 36 | run: | 37 | sudo apt-get update 38 | sudo apt-get install -y libssl-dev luarocks 39 | sudo pip install hererocks 40 | sudo hererocks lua_install -r^ --${{ env.LUA }} 41 | export PATH=$PATH:$PWD/lua_install/bin 42 | 43 | - name: install 44 | run: | 45 | git config --global url.https://github.com/.insteadOf git://github.com/ 46 | sudo make setup 47 | sudo make install 48 | 49 | - name: test 50 | run: | 51 | sudo make test 52 | 53 | - name: GCP Auth 54 | id: auth 55 | uses: google-github-actions/auth@v0.4.0 56 | with: 57 | credentials_json: ${{ secrets.GCP_CREDENTIALS }} 58 | 59 | - name: Get Luarocks API Key 60 | id: luarocks-key 61 | uses: google-github-actions/get-secretmanager-secrets@v0.2.2 62 | with: 63 | secrets: |- 64 | LUAROCKS_API_KEY:${{ env.GCP_PROJECT_ID }}/LUAROCKS_APIKEY 65 | 66 | - name: deploy 67 | run: | 68 | luarocks upload kong-plugin-url-rewrite-*.rockspec --api-key=${{ steps.luarocks-key.outputs.LUAROCKS_API_KEY }} 69 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Lua sources 2 | luac.out 3 | 4 | # luarocks build files 5 | *.src.rock 6 | *.zip 7 | *.tar.gz 8 | *.all.rock 9 | *.rockspec 10 | 11 | # Object files 12 | *.o 13 | *.os 14 | *.ko 15 | *.obj 16 | *.elf 17 | 18 | # Precompiled Headers 19 | *.gch 20 | *.pch 21 | 22 | # Libraries 23 | *.lib 24 | *.a 25 | *.la 26 | *.lo 27 | *.def 28 | *.exp 29 | 30 | # Shared objects (inc. Windows DLLs) 31 | *.dll 32 | *.so 33 | *.so.* 34 | *.dylib 35 | 36 | # Executables 37 | *.exe 38 | *.out 39 | *.app 40 | *.i*86 41 | *.x86_64 42 | *.hex 43 | 44 | # Cobertura 45 | cobertura.xml -------------------------------------------------------------------------------- /.standard-version/makefile-updater.js: -------------------------------------------------------------------------------- 1 | const capturingRegex = /VERSION = "(?[\d.]*)-0"/; 2 | 3 | module.exports.readVersion = function (contents) { 4 | const { version } = contents.match(capturingRegex).groups; 5 | return version; 6 | }; 7 | 8 | module.exports.writeVersion = function (contents, version) { 9 | const replacer = () => `VERSION = "${version}-0"`; 10 | 11 | return contents.replace(capturingRegex, replacer); 12 | }; 13 | -------------------------------------------------------------------------------- /.standard-version/package-updater.js: -------------------------------------------------------------------------------- 1 | const capturingRegex = /VERSION = "(?[\d.]*)"/; 2 | 3 | module.exports.readVersion = function (contents) { 4 | const { version } = contents.match(capturingRegex).groups; 5 | return version; 6 | }; 7 | 8 | module.exports.writeVersion = function (contents, version) { 9 | const replacer = () => `VERSION = "${version}"`; 10 | 11 | return contents.replace(capturingRegex, replacer); 12 | }; 13 | -------------------------------------------------------------------------------- /.standard-version/rockspec-updater.js: -------------------------------------------------------------------------------- 1 | const capturingRegex = /version = "(?[\d.]*)-0"/; 2 | 3 | module.exports.readVersion = function (contents) { 4 | const { version } = contents.match(capturingRegex).groups; 5 | return version; 6 | }; 7 | 8 | module.exports.writeVersion = function (contents, version) { 9 | const replacer = () => `version = "${version}-0"`; 10 | 11 | return contents.replace(capturingRegex, replacer); 12 | }; 13 | -------------------------------------------------------------------------------- /.versionrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "header": "# Changelog\n\nAll changes made on any release of this project should be commented on high level of this document.\n\nDocument model based on [Semantic Versioning](http://semver.org/).\nExamples of how to use this _markdown_ cand be found here [Keep a CHANGELOG](http://keepachangelog.com/).\n", 3 | "bumpFiles": [ 4 | { 5 | "filename": "rockspec.template", 6 | "updater": ".standard-version/rockspec-updater.js" 7 | }, 8 | { 9 | "filename": "Makefile", 10 | "updater": ".standard-version/makefile-updater.js" 11 | }, 12 | { 13 | "filename": "url-rewrite/handler.lua", 14 | "updater": ".standard-version/package-updater.js" 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All changes made on any release of this project should be commented on high level of this document. 4 | 5 | Document model based on [Semantic Versioning](http://semver.org/). 6 | Examples of how to use this _markdown_ cand be found here [Keep a CHANGELOG](http://keepachangelog.com/). 7 | 8 | ## [1.3.0](https://github.com/stone-payments/kong-plugin-url-rewrite/compare/v1.2.0...v1.3.0) (2023-06-01) 9 | 10 | 11 | ### Features 12 | 13 | * Makes rockspec file generation a separate entry in Makefile ([97d4983](https://github.com/stone-payments/kong-plugin-url-rewrite/commit/97d4983d35ac718616455f3347327b330d3b8843)) 14 | 15 | ## [1.2.0](https://github.com/stone-payments/kong-plugin-url-rewrite/compare/v1.1.1...v1.2.0) (2022-10-04) 16 | 17 | 18 | ### Features 19 | 20 | * Ensures compatibility with kong 3.0 ([06aa948](https://github.com/stone-payments/kong-plugin-url-rewrite/commit/06aa9485701724b122ba571f11546d84192e4cbb)) 21 | 22 | ### [1.1.1](https://github.com/stone-payments/kong-plugin-url-rewrite/compare/v1.1.0...v1.1.1) (2022-03-17) 23 | 24 | 25 | ### Bug Fixes 26 | 27 | * Fixes luarocks package download during publish ([ae086cd](https://github.com/stone-payments/kong-plugin-url-rewrite/commit/ae086cd2015bc0b2037251f1be3953a808eb3d3f)) 28 | 29 | ## [1.1.0](https://github.com/stone-payments/kong-plugin-url-rewrite/compare/v1.0.0...v1.1.0) (2022-03-16) 30 | 31 | 32 | ### Features 33 | 34 | * Adds service path to upstream URL when it is present ([cafa270](https://github.com/stone-payments/kong-plugin-url-rewrite/commit/cafa270ebab5f585705234d4491a0206ffd811f5)) 35 | 36 | ## [1.0.0](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v1.0.0) - 2021-12-21 37 | ### Feature 38 | - Upgrades plugin to be kong >= 2.6.0 compatible. 39 | 40 | ## [0.5.1](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v0.5.1) - 2020-04-01 41 | ### Fixed 42 | - [resolveUrlParams function with special character in url](https://dev.azure.com/stonepagamentos/frt-portal/_workitems/edit/132078) 43 | 44 | ## [0.5.0](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v0.5.0) - 2020-03-05 45 | ### Added 46 | - Support to querystring field. 47 | 48 | ## [0.4.0](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v0.4.0) - 2018-12-26 49 | ### Added 50 | - Support to parameter replacing when rewriting URL. 51 | 52 | ## [0.3.0](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v0.3.0) - 2018-10-30 53 | ### Added 54 | - Travis CI and deploy stage. 55 | 56 | ## [0.2.0](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v0.2.0) - 2018-05-23 57 | ### Changed 58 | - Package name in rockspec. 59 | 60 | ## [0.1.0](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/v0.1.0) - 2018-04-24 61 | ### Added 62 | - First version of the url rewrite plugin. 63 | - VSTS support. 64 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributor Guidelines 2 | 3 | :honeybee: Please read this document before beginning any implementation, we use a set of guidelines that should be followed.:honeybee: 4 | 5 | ## DOs and DON'Ts 6 | 7 | - **DO** follow our git branching styleguide 8 | - **DO** give priority to the current style of the project or file you're changing even if it diverges from the general guidelines 9 | - **DO** include tests when adding new features. When fixing bugs, start with adding a test that highlights how the current behavior is broken 10 | - **DO** keep the discussions focused. When a new or related topic comes up it's often better to create a new issue than to side track the discussion 11 | - **DO NOT** make PRs for style changes 12 | - **DO NOT** surprise us with big pull requests. Instead, file an issue and start a discussion so we can agree on a direction before you invest a large amount of time working on it 13 | - **DO NOT** add API additions without filing an issue and discussing with us first 14 | 15 | ## Testing 16 | 17 | We're using [busted](http://olivinelabs.com/busted) to run our tests. Every test file should live in a `spec` folder and end with `_spec.lua`. 18 | 19 | ### Running the tests 20 | 21 | `make test` or `busted spec/` in the plugin folder should do the job. 22 | 23 | remember to run it as super user if your current environment needs it. 24 | 25 | ### Test Coverage 26 | 27 | If you're using our Makefile, just run `make coverage`. 28 | 29 | With Busted, a `-c` flag will do the job. 30 | It will generate a `luacov.stats.out` that you can use to generate coverage reports. 31 | You can run `luacov` and it will generate a `luacov.report.out` containing a comprehensive coverage report. 32 | 33 | ## Lint 34 | 35 | `make lint` or `luacheck -q .` in the plugin folder should run the linter. 36 | 37 | ### Adding External Library Dependencies 38 | 39 | - Add new dependencies to the project ONLY IF STRICTLY NECESSARY, we know that adding new dependencies is easier, but by doing so it increases the build time of the framework. 40 | 41 | ### Workflow 42 | 43 | - We use GitFlow, you can find more about this workfow [here](http://nvie.com/posts/a-successful-git-branching-model/). 44 | 45 | ### Branching 46 | 47 | - **New Features** `feature/` from `develop`. 48 | - **Bugfix** `bugfix/` from `develop`. 49 | - **Improvements** `improvement/` from `develop`. 50 | - **Hotfix** `hotfix/` from `main`. 51 | 52 | ### Tests and coverage 53 | 54 | - Don't forget to write tests!! 55 | - We'd like to keep our project with a minimum of 60%, but 90% is the desirable target. 56 | 57 | ### Commit messages 58 | 59 | - Use emoji at the beginning of each message. It help us to identify what's the purpose for each commit. 60 | 61 | | Code. | Emoji | Description | 62 | |-----------------------|---------------------|-------------------------------------------------| 63 | | `:rocket:` | :rocket: | when deploying a new version | 64 | | `:airplane:` | :airplane: | when releasing a new beta version | 65 | | `:art:` | :art: | when improving the format/structure of the code | 66 | | `:racehorse:` | :racehorse: | when improving performance | 67 | | `:memo:` | :memo: | when writing docs | 68 | | `:bug:` | :bug: | when fixing a bug | 69 | | `:fire:` | :fire: | when removing code or files | 70 | | `:green_heart:` | :green_heart: | when work with CI | 71 | | `:white_check_mark:` | :white_check_mark: | when work with tests | 72 | | `:lock:` | :lock: | when dealing with security | 73 | | `:arrow_up:` | :arrow_up: | when upgrading dependencies | 74 | | `:arrow_down:` | :arrow_down: | when downgrading dependencies | 75 | | `:shirt:` | :shirt: | when removing linter warnings | 76 | | `:bulb:` | :bulb: | new idea | 77 | | `:construction:` | :construction: | work in progress | 78 | | `:heavy_plus_sign:` | :heavy_plus_sign: | when adding feature | 79 | | `:heavy_minus_sign:` | :heavy_minus_sign: | when removing feature | 80 | | `:facepunch:` | :facepunch: | when resolving conflicts | 81 | | `:hammer:` | :hammer: | when changing configuration files | 82 | 83 | - If possible, link the commit to the corresponding task in our JIRA. 84 | 85 | Commit example: 86 | 87 | ```bash 88 | git commit -m ":arrow_up: (APIDC-001) Updates rockspec" 89 | ``` 90 | 91 | ### Pull Requests 92 | 93 | - **DO** give PRs short-but-descriptive names (e.g. "Improves code coverage for System.Console by 10%", not "Fix #1234"). 94 | - **DO NOT** submit "work in progress" PRs. A PR should only be submitted when it is considered ready for review and subsequent merging by the contributor. 95 | - **DO** tag any users that should know about and/or review the change. 96 | - **DO** submit all code changes via pull requests (PRs) rather than through a direct commit. PRs will be reviewed and potentially merged by the repo maintainers after a peer review that includes at least one maintainer. 97 | - **DO** ensure each commit successfully builds. The entire PR must pass all tests in the Continuous Integration (CI) system before it'll be merged. 98 | - **DO NOT** mix independent, unrelated changes in one PR. Separate real product/test code changes from larger code formatting/dead code removal changes. Separate unrelated fixes into separate PRs, especially if they are in different assemblies. 99 | - **DO** address PR feedback in an additional commit(s) rather than amending the existing commits, and only rebase/squash them when necessary. This makes it easier for reviewers to track changes. If necessary, squashing should be handled by the merger using the "squash and merge" feature, and should only be done by the contributor upon request. 100 | - **DO** all the PRs to `develop` branch unless it is a `hotfix`. For this one you should do for both `develop` and `main` branches. 101 | 102 | ### Guiding Principles 103 | 104 | - We allow anyone to participate in our projects. Tasks can be carried out by anyone that demonstrates the capability to complete them. 105 | - Always be respectful of one another. Assume the best in others and act with empathy at all times. 106 | - Collaborate closely with individuals maintaining the project or experienced users. Getting ideas out in the open and seeing a proposal before it's a pull request helps reduce redundancy and ensures we're all connected to the decision making process. 107 | - Don't be a jerk. 108 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:22.04 2 | 3 | RUN apt-get update -y 4 | 5 | RUN apt update -y && apt install -y lua5.1 liblua5.1-dev build-essential wget git zip unzip 6 | RUN git config --global url.https://github.com/.insteadOf git://github.com/ 7 | RUN wget https://download.konghq.com/gateway-3.x-ubuntu-bionic/pool/all/k/kong/kong_3.0.0_amd64.deb &&\ 8 | apt install -y ./kong_3.0.0_amd64.deb 9 | 10 | WORKDIR /home/plugin 11 | 12 | COPY Makefile . 13 | COPY rockspec.template . 14 | RUN make setup 15 | 16 | RUN chmod -R a+rw /home/plugin 17 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | DEV_ROCKS = "https://raw.githubusercontent.com/openresty/lua-cjson/2.1.0.8/lua-cjson-2.1.0.6-1.rockspec" "kong 3.0.0" "luacov 0.12.0" "busted 2.0.rc12" "luacov-cobertura 0.2-1" "luacheck 0.20.0" 2 | PROJECT_FOLDER = url-rewrite 3 | LUA_PROJECT = kong-plugin-url-rewrite 4 | VERSION = "1.3.0-0" 5 | 6 | rockspec: 7 | cp rockspec.template kong-plugin-url-rewrite-$(VERSION).rockspec 8 | 9 | setup: rockspec 10 | @for rock in $(DEV_ROCKS) ; do \ 11 | if luarocks list --porcelain $$rock | grep -q "installed" ; then \ 12 | echo $$rock already installed, skipping ; \ 13 | else \ 14 | echo $$rock not found, installing via luarocks... ; \ 15 | luarocks install $$rock; \ 16 | fi \ 17 | done; 18 | 19 | check: 20 | @for rock in $(DEV_ROCKS) ; do \ 21 | if luarocks list --porcelain $$rock | grep -q "installed" ; then \ 22 | echo $$rock is installed ; \ 23 | else \ 24 | echo $$rock is not installed ; \ 25 | fi \ 26 | done; 27 | 28 | install: 29 | -@luarocks remove $(LUA_PROJECT) 30 | luarocks make 31 | 32 | docker-build: 33 | docker build . -t $(LUA_PROJECT) 34 | 35 | docker-run: 36 | docker run -it -v $(shell pwd):/home/plugin $(LUA_PROJECT) /bin/bash 37 | 38 | test: 39 | cd $(PROJECT_FOLDER) && busted spec/ ${ARGS} 40 | 41 | coverage: 42 | cd $(PROJECT_FOLDER) && busted spec/ -c && luacov && luacov-cobertura -o cobertura.xml 43 | 44 | package: 45 | luarocks make --pack-binary-rock 46 | 47 | lint: 48 | cd $(PROJECT_FOLDER) && luacheck -q . 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/stone-payments/kong-plugin-url-rewrite.svg?branch=master)](https://travis-ci.org/stone-payments/kong-plugin-url-rewrite) 2 | 3 | # Kong-plugin-url-rewrite 4 | 5 | Kong API Gateway plugin for url-rewrite purposes. This plugin has been tested to work along with kong >= 2.6.x, for a legacy version of this plugin, please check [this link](https://github.com/stone-payments/kong-plugin-url-rewrite/tree/legacy/v0). 6 | 7 | ## The Problem 8 | 9 | When using Kong, you can create routes that proxy to an upstream. The problem lies when the upstream has an url that is not very friendly to your clients, or restful, or even pretty. When you [add a Route in Kong](https://docs.konghq.com/0.14.x/admin-api/#add-route), you have a [somewhat limited](https://docs.konghq.com/0.14.x/proxy/#routes-and-matching-capabilities) url rewrite capability. This plugin simply throws away the url set in Kong route and uses the url set in it's configuration to proxy to the upstream. This gives you full freedom as to how to write your url's in Kong and inner services as well. 10 | 11 | ## Project Structure 12 | 13 | The plugin folder should contain at least a `schema.lua` and a `handler.lua`, alongside with a `spec` folder and a `.rockspec` file specifying the current version of the package. 14 | 15 | ## Rockspec Format 16 | 17 | The `.rockspec` file should follow [LuaRocks' conventions](https://github.com/luarocks/luarocks/wiki/Rockspec-format) 18 | 19 | ## Configuration 20 | 21 | ### Enabling the plugin on a Route 22 | 23 | Configure this plugin on a Route with: 24 | 25 | ```bash 26 | curl -X POST http://kong:8001/routes/{route_id}/plugins \ 27 | --data "name=kong-plugin-url-rewrite" \ 28 | --data "config.url=http://new-url.com" 29 | ``` 30 | 31 | - route_id: the id of the Route that this plugin configuration will target. 32 | - config.url: the url where you want kong to execute the request. 33 | 34 | ## Developing 35 | 36 | ### In docker 37 | 38 | ```bash 39 | docker build . -t kong-plugin-url-rewrite-dev 40 | docker run -it -v ${PWD}/url-rewrite:/url-rewrite kong-plugin-url-rewrite-dev bash 41 | ``` 42 | 43 | ## Credits 44 | 45 | made with :heart: by Stone Payments 46 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | services: 4 | 5 | kong: 6 | build: 7 | context: . 8 | dockerfile: Dockerfile 9 | stdin_open: true 10 | volumes: 11 | - ./${PROJECT_FOLDER}:/home/plugin 12 | ports: 13 | - "8001:8001" 14 | - "8000:8000" 15 | entrypoint: /bin/bash 16 | -------------------------------------------------------------------------------- /rockspec.template: -------------------------------------------------------------------------------- 1 | package = "kong-plugin-url-rewrite" 2 | version = "1.3.0-0" 3 | source = { 4 | url = "git://github.com/stone-payments/kong-plugin-url-rewrite", 5 | branch = "main", 6 | tag = "v1.1.1", 7 | } 8 | description = { 9 | summary = "KongAPI Gateway middleware plugin for url-rewrite purposes.", 10 | license = "Apache License 2.0" 11 | } 12 | dependencies = { 13 | "lua >= 5.1" 14 | } 15 | build = { 16 | type = "builtin", 17 | modules = { 18 | ["kong.plugins.kong-plugin-url-rewrite.handler"] = "url-rewrite/handler.lua", 19 | ["kong.plugins.kong-plugin-url-rewrite.schema"] = "url-rewrite/schema.lua" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /url-rewrite/.luacov: -------------------------------------------------------------------------------- 1 | exclude = { 'spec.*', 'usr.local.*', 'usr.share.*'} -------------------------------------------------------------------------------- /url-rewrite/handler.lua: -------------------------------------------------------------------------------- 1 | local URLRewriter = { 2 | PRIORITY = 700, 3 | VERSION = "1.3.0" 4 | } 5 | 6 | function split(s, delimiter) 7 | local result = {} 8 | for match in (s..delimiter):gmatch("(.-)"..delimiter) do 9 | table.insert(result, match) 10 | end 11 | return result 12 | end 13 | 14 | function resolveUrlParams(requestParams, url) 15 | for paramValue in requestParams do 16 | local requestParamValue = ngx.ctx.router_matches.uri_captures[paramValue] 17 | if type(requestParamValue) == 'string' then 18 | requestParamValue = requestParamValue:gsub("%%", "%%%%") 19 | end 20 | url = url:gsub("<" .. paramValue .. ">", requestParamValue) 21 | end 22 | return url 23 | end 24 | 25 | function getRequestUrlParams(url) 26 | return string.gmatch(url, "<(.-)>") 27 | end 28 | 29 | function URLRewriter:access(config) 30 | if config.query_string ~= nil then 31 | local args = ngx.req.get_uri_args() 32 | for k, queryString in ipairs(config.query_string) do 33 | local splitted = split(queryString, '=') 34 | local key, value = splitted[1], splitted[2] 35 | local queryParams = getRequestUrlParams(value) 36 | local resolvedParams = resolveUrlParams(queryParams, value) 37 | args[key] = resolvedParams 38 | end 39 | ngx.req.set_uri_args(args) 40 | end 41 | 42 | local requestParams = getRequestUrlParams(config.url) 43 | local url = resolveUrlParams(requestParams, config.url) 44 | 45 | local service_path = ngx.ctx.service.path or "" 46 | if service_path ~= "" then 47 | url = service_path..url 48 | end 49 | 50 | ngx.var.upstream_uri = url 51 | end 52 | 53 | return URLRewriter 54 | -------------------------------------------------------------------------------- /url-rewrite/schema.lua: -------------------------------------------------------------------------------- 1 | local typedefs = require 'kong.db.schema.typedefs' 2 | 3 | return { 4 | name = "kong-plugin-url-rewrite", 5 | fields = { 6 | { consumer = typedefs.no_consumer, }, 7 | { 8 | config = { 9 | type = "record", 10 | fields = { 11 | { url = { required = true, type = "string" }, }, 12 | { query_string = { required = false, type = "array", elements = { type = "string" } } }, 13 | } 14 | } 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /url-rewrite/spec/handler_spec.lua: -------------------------------------------------------------------------------- 1 | -- Mock ngx 2 | local ngx = { 3 | log = spy.new(function() end), 4 | var = { 5 | upstream_uri = "mock" 6 | }, 7 | ctx = { 8 | router_matches = { 9 | uri_captures = {} 10 | }, 11 | service = {} 12 | }, 13 | req = { 14 | get_uri_args = spy.new(function() return {} end), 15 | set_uri_args = spy.new(function() end) 16 | } 17 | } 18 | 19 | _G.ngx = ngx 20 | 21 | local URLRewriter = require('../handler') 22 | 23 | describe("TestHandler", function() 24 | 25 | it("should test rewrite of upstream_uri", function() 26 | assert.equal('mock', ngx.var.upstream_uri) 27 | config = { 28 | url = "new_url" 29 | } 30 | URLRewriter:access(config) 31 | assert.equal('new_url', ngx.var.upstream_uri) 32 | end) 33 | 34 | it("should add service path to upstream_uri when it is present", function() 35 | ngx.ctx.service['path'] = "path/to/" 36 | config = { 37 | url = "new_url" 38 | } 39 | URLRewriter:access(config) 40 | assert.equal('path/to/new_url', ngx.var.upstream_uri) 41 | ngx.ctx.service['path'] = nil 42 | end) 43 | 44 | it("should test rewrite of upstream_uri with params", function() 45 | ngx.ctx.router_matches.uri_captures["code_parameter"] = "123456" 46 | config = { 47 | url = "new_url/" 48 | } 49 | URLRewriter:access(config) 50 | assert.equal('new_url/123456', ngx.var.upstream_uri) 51 | end) 52 | 53 | it("should replace url params", function() 54 | local mockUrl = "url//" 55 | local iter = getRequestUrlParams(mockUrl) 56 | ngx.ctx.router_matches.uri_captures["param1"] = 123456 57 | ngx.ctx.router_matches.uri_captures["param2"] = "test" 58 | 59 | local result = resolveUrlParams(iter, mockUrl) 60 | 61 | assert.equal("url/123456/test", result) 62 | end) 63 | 64 | it("should replace url params with special character", function() 65 | local mockUrl = "url//" 66 | local iter = getRequestUrlParams(mockUrl) 67 | ngx.ctx.router_matches.uri_captures["param1"] = "test%23special%2fcharacter" 68 | ngx.ctx.router_matches.uri_captures["param2"] = "test%2bspecial%3fcharacter" 69 | 70 | local result = resolveUrlParams(iter, mockUrl) 71 | 72 | assert.equal("url/test%23special%2fcharacter/test%2bspecial%3fcharacter", result) 73 | end) 74 | 75 | it("should add querystring params when schema has query_string field", function() 76 | ngx.ctx.router_matches.uri_captures["code_parameter"] = "123456" 77 | config = { 78 | url = "new_url", 79 | query_string = { 80 | "code_parameter=", 81 | "parameter2=abcdef", 82 | } 83 | } 84 | URLRewriter:access(config) 85 | local expected = { 86 | code_parameter = "123456", 87 | parameter2 = "abcdef", 88 | } 89 | assert.spy(ngx.req.set_uri_args).was_called_with(expected) 90 | end) 91 | end) 92 | --------------------------------------------------------------------------------