Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
carnei-ro authored and leandro-carneiro-ifood committed Jun 1, 2020
0 parents commit 91e0b64
Show file tree
Hide file tree
Showing 12 changed files with 895 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.rockspec
dist/*
opa/opa
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 TravelNest

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
110 changes: 110 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
VERSION := $(shell sed -n "s/.*VERSION.*= \{1,\}\(.*\)/\1/p;" opa/handler.lua)
NAME := $(shell basename $${PWD})
UID := $(shell id -u)
GID := $(shell id -g)
SUMMARY := $(shell sed -n '/^summary: /s/^summary: //p' README.md)
export UID GID NAME VERSION

build: rockspec validate
@find . -type f -iname "*lua~" -exec rm -f {} \;
@docker run --rm \
-v ${PWD}:/plugin \
kong /bin/sh -c "apk add --no-cache zip > /dev/null 2>&1 ; cd /plugin ; luarocks make > /dev/null 2>&1 ; luarocks pack ${NAME} 2> /dev/null ; chown ${UID}:${GID} *.rock"
@mkdir -p dist
@mv *.rock dist/
@printf '\n\n Check "dist" folder \n\n'

validate:
@if [ -z "$${VERSION}" ]; then \
printf "\n\nNo VERSION found in handler.lua;\nPlease set it in your object that extends the base_plugin.\nEx: plugin.VERSION = \"0.1.0-1\"\n\n"; \
exit 1 ;\
else \
echo ${VERSION} | egrep '(\w.+)-([0-9]+)$$' > /dev/null 2>&1 ; \
if [ $${?} -ne 0 ]; then \
printf "\n\nVERSION must follow the pattern [%%w.]+-[%%d]+\nWhich means: 0.0-0 or 0.0.0-0 or ...\nReceived: $${VERSION} \n\n"; \
exit 2 ; \
fi ; \
fi
@if [ -z "${SUMMARY}" ]; then \
printf "\n\nNo SUMMARY found.\nPlease, create a 'README.md' file and place your summary there.\nFollow the pattern '^summary: '\nDo not use double quotes"; \
printf "\nExample:\nsummary: this is my summary\n\n\n" ;\
exit 4 ;\
fi
@if [ ! -f ${NAME}-${VERSION}.rockspec ]; then \
make rockspec; \
fi

copy-docker-compose:
@[ ! -f docker-compose.yaml ] && cp ../docker-compose.yaml . || printf ''

rockspec:
@printf 'package = "%s"\nversion = "%s"\n\nsource = {\n url = "[email protected]:carnei-ro/${NAME}.git",\n branch = "master"\n}\n\ndescription = {\n summary = "%s",\n}\n\ndependencies = {\n "lua ~> 5.1"\n}\n\nbuild = {\n type = "builtin",\n modules = {\n' "${NAME}" "${VERSION}" "${SUMMARY}" > ${NAME}-${VERSION}.rockspec
@find opa -type f -iname "*.lua" -exec bash -c 'printf " [\"kong.plugins.%s.%s\"] = \"%s\",\n" "${NAME}" "$$(basename $${1/\.lua})" "{}"' _ {} \; >> ${NAME}-${VERSION}.rockspec
@printf " }\n}" >> ${NAME}-${VERSION}.rockspec

clean: copy-docker-compose
@rm -rf *.rock *.rockspec dist shm opa/opa
@find . -type f -iname "*lua~" -exec rm -f {} \;
@docker-compose down -v

clear: clean

start: validate copy-docker-compose
@docker-compose up -d

stop: copy-docker-compose
@docker-compose down

logs: kong-logs
kong-logs:
@docker logs -f $$(docker ps -qf name=${NAME}_kong_1) 2>&1 || true

shell: kong-bash
kong-bash:
@docker exec -it $$(docker ps -qf name=${NAME}_kong_1) bash || true

reload: kong-reload
kong-reload:
@docker exec -it $$(docker ps -qf name=${NAME}_kong_1) bash -c "/usr/local/bin/kong reload"

restart:
@docker rm -vf $$(docker ps -qf name=${NAME}_kong_1)
@docker-compose up -d

reconfigure: clean start kong-logs

config-aux:
@[ ! -f aux.lua ] && echo -e 'ngx.say("hello from aux - edit aux.lua and run make patch-aux")\nngx.exit(200)' > aux.lua || printf ''
@curl -s -X POST http://localhost:8001/services/ -d 'name=aux' -d url=http://localhost
@curl -s -X POST http://localhost:8001/services/aux/routes -d 'paths[]=/aux'
@curl -i -X POST http://localhost:8001/services/aux/plugins -F "name=pre-function" -F "[email protected]"

patch-aux:
@curl -i -X PATCH http://localhost:8001/plugins/$$(curl -s http://localhost:8001/plugins/ | jq -r ".data[] | select (.name|test(\"pre-function\")) .id") -F "name=pre-function" -F "[email protected]"
@echo " "

req-aux:
@curl -s http://localhost:8000/aux

populate-opa-server:
@curl -iX PUT http://localhost:8181/v1/policies/carneiro --data-binary @opa_files/policy1.rego
@curl -iX PUT localhost:8181/v1/data -d @opa_files/data.json -H content-type:application/json

config:
@curl -s -X POST http://localhost:8001/services/ -d 'name=httpbin' -d url=http://httpbin.org/anything
@curl -s -X POST http://localhost:8001/services/httpbin/routes -d 'paths[]=/' -d 'name=some_route_name_here'
@curl -i -X POST http://localhost:8001/routes/some_route_name_here/plugins -d "name=${NAME}" -d "config.opa_host=opa_server" -d "config.opa_port=8181" -d "config.policy_uri=/v1/data/carneiro/policy1" -d "config.opa_result_boolean_key=deny" -d "config.opa_result_boolean_value=false"

config-plugin-remove:
@curl -i -X DELETE http://localhost:8001/plugins/$$(curl -s http://localhost:8001/plugins/ | jq -r ".data[] | select (.name|test(\"${NAME}\")) .id")

config-plugin-enable-debug:
@curl -i -X PATCH http://localhost:8001/plugins/$$(curl -s http://localhost:8001/plugins/ | jq -r ".data[] | select (.name|test(\"${NAME}\")) .id") -F "name=${NAME}" -F "config.debug=true"
@echo " "

config-plugin-disable-debug:
@curl -i -X PATCH http://localhost:8001/plugins/$$(curl -s http://localhost:8001/plugins/ | jq -r ".data[] | select (.name|test(\"${NAME}\")) .id") -F "name=${NAME}" -F "config.debug=false"
@echo " "

remove-all:
@for i in plugins consumers routes services upstreams; do for j in $$(curl -s --url http://127.0.0.1:8001/$${i} | jq -r ".data[].id"); do curl -s -i -X DELETE --url http://127.0.0.1:8001/$${i}/$${j}; done; done
85 changes: 85 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# OPA Kong Plugin
summary: Custom Kong plugin to allow for fine grained Authorization through Open Policy Agent

_Created to work with Kong 2.0.x

Inspired by https://github.com/TravelNest/kong-authorization-opa
Connection based on https://github.com/Kong/kong-plugin-aws-lambda

Custom Kong plugin to allow for fine grained Authorization through [Open Policy Agent](https://www.openpolicyagent.org/).

Plugin will continue the request to the upstream target if OPA responds with `true`, else the plugin will return a `403 Forbidden`.

Requests will add the header `X-Kong-Authz-Latency` to requests which have been impacted by the plugin.

## Setup

### Config
|Parameter | Usage | Type | Default |
|-----------------------------|-------------------------------------------------------------------------------------------------------------|---------|---------|
|`opa_method` |request method to OPA endpoint |`string` | POST |
|`opa_scheme` |OPA scheme endpoint |`string` | http |
|`opa_host` |OPA hostname (FQDN) (e.g. `authz.example.com`) |`string` | |
|`opa_port` |OPA port to the endpoint |`number` | 80 |
|`policy_uri` |OPA target policy (e.g. `/v1/data/my_policy`) |`string` | |
|`opa_result_boolean_key` |OPA result boolean key to evaluate |`string` | allow |
|`opa_result_boolean_value` |OPA result boolean value expected to allow request |`boolean`| true |
|`timeout` |timeout in ms for request to OPA |`number` | 60000 |
|`keepalive` |keepalive in ms for request to OPA |`number` | 60000 |
|`forward_request_method` |flag to forward request method |`boolean`| true |
|`forward_request_headers` |flag to forward request headers |`boolean`| true |
|`forward_upstream_split_path`|flag to forward split upstream path (e.g. `/path/to/my/endpoint` becomes `["path", "to", "my", "endpoint"]`) |`boolean`| true |
|`forward_request_uri` |flag to forward request uri |`boolean`| true |
|`forward_request_body` |flag to forward request body |`boolean`| true |
|`forward_request_cookies` |flag to forward request cookies (will remove headers.cookie) |`boolean`| true |
|`debug` |flag to return the request/response to/from OPA - not the upstream target (used for testing purposes) |`boolean`| false |
|`config.proxy_url` |An optional value that defines whether the plugin should connect through the given proxy server URL. This value is required if `proxy_scheme` is defined. | `string` | |
|`config.proxy_scheme` |An optional value that defines which HTTP protocol scheme to use in order to connect through the proxy server. The schemes supported are: `http` and `https`. This value is required if `proxy_url` is defined. | `string` | |

#### Example

```
$ curl -i -X POST \
--url http://localhost:8001/services/my-service/plugins \
--data 'name=kong-authorization-opa' \
--data 'config.opa_host=authz.example.com' \
--data 'config.policy_uri=/v1/data/my_policy'
```

#### Request example

`curl -X POST -s http://localhost:8000/foo/bar/baz?foo=bar -H content-type:application/json -d '{"a": "baaa"}' --cookie "jwt=eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.JlX3gXGyClTBFciHhknWrjo7SKqyJ5iBO0n-3S2_I7cIgfaZAeRDJ3SQEbaPxVC7X8aqGCOM-pQOjZPKUJN8DMFrlHTOdqMs0TwQ2PRBmVAxXTSOZOoEhD4ZNCHohYoyfoDhJDP4Qye_FCqu6POJzg0Jcun4d3KW04QTiGxv2PkYqmB7nHxYuJdnqE3704hIS56pc_8q6AW0WIT0W-nIvwzaSbtBU9RgaC7ZpBD2LiNE265UBIFraMDF8IAFw9itZSUCTKg1Q-q27NwwBZNGYStMdIBDor2Bsq5ge51EkWajzZ7ALisVp-bskzUsqUf77ejqX_CBAqkNdH1Zebn93A"`

```json
{
"request_body_args": {
"a": "baaa"
},
"query": {
"foo": "bar"
},
"path": "/foo/bar/baz",
"cookies": {
"jwt": "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.JlX3gXGyClTBFciHhknWrjo7SKqyJ5iBO0n-3S2_I7cIgfaZAeRDJ3SQEbaPxVC7X8aqGCOM-pQOjZPKUJN8DMFrlHTOdqMs0TwQ2PRBmVAxXTSOZOoEhD4ZNCHohYoyfoDhJDP4Qye_FCqu6POJzg0Jcun4d3KW04QTiGxv2PkYqmB7nHxYuJdnqE3704hIS56pc_8q6AW0WIT0W-nIvwzaSbtBU9RgaC7ZpBD2LiNE265UBIFraMDF8IAFw9itZSUCTKg1Q-q27NwwBZNGYStMdIBDor2Bsq5ge51EkWajzZ7ALisVp-bskzUsqUf77ejqX_CBAqkNdH1Zebn93A"
},
"method": "POST",
"headers": {
"host": "localhost:8000",
"user-agent": "curl/7.59.0",
"accept": "*/*",
"content-length": "13",
"content-type": "application/json"
},
"request_body": "{\"a\": \"baaa\"}",
"path_split": [
"foo",
"bar",
"baz"
]
}
```

## Roadmap

- Recreate the connection part based on the AWS Lambda plugin (OK)
- Implement toggle to use cache
91 changes: 91 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
version: '3'

services:

dockerhost:
image: qoomon/docker-host
cap_add: [ 'NET_ADMIN', 'NET_RAW' ]
restart: on-failure

kong-database:
image: postgres:9.5
environment:
- POSTGRES_USER=kong
- POSTGRES_DB=kong
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres"]
interval: 10s
timeout: 5s
retries: 5

kong-migration:
image: kong:2.0.3-centos
command: "sleep 10; kong migrations bootstrap ; kong migrations list ; kong migrations up"
restart: on-failure
environment:
KONG_PG_HOST: kong-database
links:
- kong-database
depends_on:
- kong-database

opa_server:
image: openpolicyagent/opa
restart: on-failure
ports:
- "8181:8181"
command:
run --server --log-level debug

kong:
image: kong:2.0.3-centos
depends_on:
- kong-database
environment:
- KONG_LUA_SSL_VERIFY_DEPTH=3
- KONG_LUA_SSL_TRUSTED_CERTIFICATE=/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt
- KONG_DATABASE=postgres
- KONG_PG_HOST=kong-database
- KONG_PROXY_ACCESS_LOG=/dev/stdout
- KONG_ADMIN_ACCESS_LOG=/dev/stdout
- KONG_PROXY_ERROR_LOG=/dev/stderr
- KONG_ADMIN_ERROR_LOG=/dev/stderr
- KONG_ADMIN_LISTEN=0.0.0.0:8001
- KONG_ADMIN_LISTEN_SSL=0.0.0.0:8444
- KONG_VITALS=off
- KONG_PORTAL=off
- KONG_LOG_LEVEL=debug
- KONG_PLUGINS=bundled,${NAME}
volumes:
- plugin-development:/plugin-development
user: "0:0"
command:
- /bin/bash
- -c
- |
sleep 12
mkdir -p /usr/local/lib/luarocks/rocks-5.1/${NAME}/${VERSION}/
ln -s /plugin-development/${NAME}-${VERSION}.rockspec /usr/local/lib/luarocks/rocks-5.1/${NAME}/${VERSION}/${NAME}-${VERSION}.rockspec
ln -s /plugin-development/opa /usr/local/share/lua/5.1/kong/plugins/${NAME}
kong migrations bootstrap
kong migrations list
kong migrations up
/usr/local/bin/kong start --run-migrations --vv
ports:
- "8000:8000"
- "8443:8443"
- "8001:8001"
- "8444:8444"
- "8002:8002"
- "8445:8445"
- "8003:8003"
- "8004:8004"

volumes:

plugin-development:
driver: local
driver_opts:
type: none
o: bind
device: ${PWD}/
Loading

0 comments on commit 91e0b64

Please sign in to comment.