opa

    The type indicates that the request type. (e.g. http or stream) The reqesut is used when the request type is http, it contains the basic information of the request. (e.g. url, header) The var contains basic information about this requested connection. (e.g. IP, port, request timestamp) The route, service, and consumer will be sent only after the opa plugin has enabled the relevant features, and their contents are same as those stored by APISIX in etcd.

    In the response, result is automatically added by OPA. The allow is indispensable and will indicate whether the request is allowed to be forwarded through the APISIX. The reason, headers, and status_code are optional and are only returned when you need to use a custom response, as you’ll see in the next section with the actual use case for it.

    1. {
    2. "result": {
    3. "allow": true,
    4. "reason": "test",
    5. "headers": {
    6. "an": "header"
    7. },
    8. "status_code": 401
    9. }
    10. }

    First, you need to launch the Open Policy Agent environment.

    1. $ docker run -d --name opa -p 8181:8181 openpolicyagent/opa:0.35.0 run -s

    After that, you can create a route and turn on the opa plugin.

    1. -H 'X-API-KEY: <api-key>' \
    2. -H 'Content-Type: application/json' \
    3. -d '{
    4. "uri": "/*",
    5. "opa": {
    6. "host": "http://127.0.0.1:8181",
    7. "policy": "example1"
    8. }
    9. },
    10. "upstream": {
    11. "nodes": {
    12. "httpbin.org:80": 1
    13. },
    14. "type": "roundrobin"
    15. }
    16. }'

    Try it out.

    1. # Successful request
    2. $ curl -i -X GET 127.0.0.1:9080/get
    3. HTTP/1.1 200 OK
    4. # Failed request
    5. $ curl -i -X POST 127.0.0.1:9080/post
    6. HTTP/1.1 403 FORBIDDEN

    Next, let’s think about some more complex scenarios.

    Update the route and set opa plugin’s policy parameter to example2. Then, let’s try it.

    1. # Successful request
    2. $ curl -i -X GET 127.0.0.1:9080/get
    3. $ curl -i -X POST 127.0.0.1:9080/post
    4. HTTP/1.1 302 FOUND
    5. Location: http://example.com/auth
    6. test

    Let’s think about another scenario, when your decision needs to use some APISIX data, such as route, consumer, etc., how should we do it?

    Create a simple policy echo, which will return the data sent by APISIX to the OPA service as is, so we can simply see them.

    1. $ curl -X PUT '127.0.0.1:8181/v1/policies/echo' \
    2. -H 'Content-Type: text/plain' \
    3. -d 'package echo
    4. allow = false
    5. reason = input'

    Try it. As you can see, we output this data with the help of the custom response body function described above, along with the data from the route.

    1. $ curl -X GET 127.0.0.1:9080/get
    2. {
    3. "type": "http",
    4. "request": {
    5. xxx
    6. },
    7. "var": {
    8. xxx
    9. },
    10. "route": {
    11. xxx