Envoy

Envoy is a L7 proxy and communication bus designed for large modern service oriented architectures. Envoy (v1.7.0+) supports an External Authorization filter which calls an authorization service to check if the incoming request is authorized or not.

This feature makes it possible to delegate authorization decisions to an external service and also makes the request context available to the service which can then be used to make an informed decision about the fate of the incoming request received by Envoy.

Goals

The tutorial shows how Envoy’s External authorization filter can be used with OPA as an authorization service to enforce security policies over API requests received by Envoy. The tutorial also covers examples of authoring custom policies over the HTTP request body.

Prerequisites

This tutorial requires Kubernetes 1.14 or later. To run the tutorial locally, we recommend using minikube in version v1.0+ with Kubernetes 1.14 (which is the default).

Steps

1. Start Minikube

  1. minikube start

2. Create ConfigMap containing configuration for Envoy

The Envoy configuration below defines an external authorization filter envoy.ext_authz for a gRPC authorization server.

Save the configuration as envoy.yaml:

  1. static_resources:
  2. listeners:
  3. - address:
  4. socket_address:
  5. address: 0.0.0.0
  6. port_value: 8000
  7. filter_chains:
  8. - filters:
  9. - name: envoy.http_connection_manager
  10. typed_config:
  11. "@type": type.googleapis.com/envoy.config.filter.network.http_connection_manager.v2.HttpConnectionManager
  12. codec_type: auto
  13. stat_prefix: ingress_http
  14. route_config:
  15. name: local_route
  16. virtual_hosts:
  17. - name: backend
  18. domains:
  19. - "*"
  20. routes:
  21. - match:
  22. prefix: "/"
  23. route:
  24. cluster: service
  25. http_filters:
  26. - name: envoy.ext_authz
  27. config:
  28. with_request_body:
  29. max_request_bytes: 8192
  30. allow_partial_message: true
  31. failure_mode_allow: false
  32. grpc_service:
  33. google_grpc:
  34. target_uri: 127.0.0.1:9191
  35. stat_prefix: ext_authz
  36. timeout: 0.5s
  37. - name: envoy.router
  38. typed_config: {}
  39. clusters:
  40. - name: service
  41. connect_timeout: 0.25s
  42. type: strict_dns
  43. lb_policy: round_robin
  44. load_assignment:
  45. cluster_name: service
  46. endpoints:
  47. - lb_endpoints:
  48. - endpoint:
  49. address:
  50. socket_address:
  51. address: 127.0.0.1
  52. port_value: 8080
  53. admin:
  54. access_log_path: "/dev/null"
  55. address:
  56. socket_address:
  57. address: 0.0.0.0
  58. port_value: 8001

Create the ConfigMap:

  1. kubectl create configmap proxy-config --from-file envoy.yaml

3. Define a OPA policy

The following OPA policy restricts access to the /people endpoint exposed by our sample app:

  • Alice is granted a guest role and can perform a GET request to /people.
  • Bob is granted an admin role and can perform a GET and POST request to /people.

The policy also restricts an admin user, in this case bob from creating an employee with the same firstname as himself.

policy.rego

  1. package envoy.authz
  2. import input.attributes.request.http as http_request
  3. default allow = false
  4. token = {"valid": valid, "payload": payload} {
  5. [_, encoded] := split(http_request.headers.authorization, " ")
  6. [valid, _, payload] := io.jwt.decode_verify(encoded, {"secret": "secret"})
  7. }
  8. allow {
  9. is_token_valid
  10. action_allowed
  11. }
  12. is_token_valid {
  13. token.valid
  14. token.payload.nbf <= time.now_ns() < token.payload.exp
  15. }
  16. action_allowed {
  17. http_request.method == "GET"
  18. token.payload.role == "guest"
  19. glob.match("/people*", [], http_request.path)
  20. }
  21. action_allowed {
  22. http_request.method == "GET"
  23. token.payload.role == "admin"
  24. glob.match("/people*", [], http_request.path)
  25. }
  26. action_allowed {
  27. http_request.method == "POST"
  28. token.payload.role == "admin"
  29. glob.match("/people", [], http_request.path)
  30. lower(input.parsed_body.firstname) != base64url.decode(token.payload.sub)
  31. }

Store the policy in Kubernetes as a Secret.

  1. kubectl create secret generic opa-policy --from-file policy.rego

In the next step, OPA is configured to query for the data.envoy.authz.allow decision. If the response is true the operation is allowed, otherwise the operation is denied. Sample input received by OPA is shown below:

  1. data.envoy.authz.allow
  1. {
  2. "attributes": {
  3. "request": {
  4. "http": {
  5. "method": "GET",
  6. "path": "/people",
  7. "headers": {
  8. "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiZ3Vlc3QiLCJzdWIiOiJZV3hwWTJVPSIsIm5iZiI6MTUxNDg1MTEzOSwiZXhwIjoxNjQxMDgxNTM5fQ.K5DnnbbIOspRbpCr2IKXE9cPVatGOCBrBQobQmBmaeU"
  9. }
  10. }
  11. }
  12. }
  13. }

With the input value above, the answer is:

  1. true

An example of the complete input received by OPA can be seen here.

In typical deployments the policy would either be built into the OPA container image or it would fetched dynamically via the Bundle API. ConfigMaps are used in this tutorial for test purposes.

4. Create App Deployment with OPA and Envoy sidecars

Our deployment contains a sample Go app which provides information about employees in a company. It exposes a /people endpoint to get and create employees. More information can on the app be found here.

OPA is started with a configuration that sets the listening address of Envoy External Authorization gRPC server and specifies the name of the policy decision to query. More information on the configuration options can be found here.

Save the deployment as deployment.yaml:

  1. kind: Deployment
  2. apiVersion: apps/v1
  3. metadata:
  4. name: example-app
  5. labels:
  6. app: example-app
  7. spec:
  8. replicas: 1
  9. selector:
  10. matchLabels:
  11. app: example-app
  12. template:
  13. metadata:
  14. labels:
  15. app: example-app
  16. spec:
  17. initContainers:
  18. - name: proxy-init
  19. image: openpolicyagent/proxy_init:v2
  20. args: ["-p", "8000", "-u", "1111"]
  21. securityContext:
  22. capabilities:
  23. add:
  24. - NET_ADMIN
  25. runAsNonRoot: false
  26. runAsUser: 0
  27. containers:
  28. - name: app
  29. image: openpolicyagent/demo-test-server:v1
  30. ports:
  31. - containerPort: 8080
  32. - name: envoy
  33. image: envoyproxy/envoy:v1.10.0
  34. securityContext:
  35. runAsUser: 1111
  36. volumeMounts:
  37. - readOnly: true
  38. mountPath: /config
  39. name: proxy-config
  40. args:
  41. - "envoy"
  42. - "--config-path"
  43. - "/config/envoy.yaml"
  44. - name: opa
  45. # Note: openpolicyagent/opa:latest-istio is created by retagging
  46. # the latest released image of OPA-Istio.
  47. image: openpolicyagent/opa:0.14.2-istio
  48. securityContext:
  49. runAsUser: 1111
  50. volumeMounts:
  51. - readOnly: true
  52. mountPath: /policy
  53. name: opa-policy
  54. args:
  55. - "--plugin-dir=/app"
  56. - "run"
  57. - "--server"
  58. - "--set=plugins.envoy_ext_authz_grpc.addr=:9191"
  59. - "--set=plugins.envoy_ext_authz_grpc.query=data.envoy.authz.allow"
  60. - "--set=decision_logs.console=true"
  61. - "--ignore=.*"
  62. - "/policy/policy.rego"
  63. volumes:
  64. - name: proxy-config
  65. configMap:
  66. name: proxy-config
  67. - name: opa-policy
  68. secret:
  69. secretName: opa-policy
  1. kubectl apply -f deployment.yaml

The proxy-init container installs iptables rules to redirect all container traffic through the Envoy proxy sidecar. More information can be found here.

5. Create a Service to expose HTTP server

  1. kubectl expose deployment example-app --type=NodePort --name=example-app-service --port=8080

Set the SERVICE_URL environment variable to the service’s IP/port.

minikube:

  1. export SERVICE_PORT=$(kubectl get service example-app-service -o jsonpath='{.spec.ports[?(@.port==8080)].nodePort}')
  2. export SERVICE_HOST=$(minikube ip)
  3. export SERVICE_URL=$SERVICE_HOST:$SERVICE_PORT
  4. echo $SERVICE_URL

minikube (example):

  1. 192.168.99.113:31056

6. Exercise the OPA policy

For convenience, we’ll want to store Alice’s and Bob’s tokens in environment variables.

  1. export ALICE_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiZ3Vlc3QiLCJzdWIiOiJZV3hwWTJVPSIsIm5iZiI6MTUxNDg1MTEzOSwiZXhwIjoxNjQxMDgxNTM5fQ.K5DnnbbIOspRbpCr2IKXE9cPVatGOCBrBQobQmBmaeU"
  2. export BOB_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJzdWIiOiJZbTlpIiwibmJmIjoxNTE0ODUxMTM5LCJleHAiOjE2NDEwODE1Mzl9.WCxNAveAVAdRCmkpIObOTaSd0AJRECY2Ch2Qdic3kU8"

Check that Alice can get employees but cannot create one.

  1. curl -i -H "Authorization: Bearer "$ALICE_TOKEN"" http://$SERVICE_URL/people
  2. curl -i -H "Authorization: Bearer "$ALICE_TOKEN"" -d '{"firstname":"Charlie", "lastname":"OPA"}' -H "Content-Type: application/json" -X POST http://$SERVICE_URL/people

Check that Bob can get employees and also create one.

  1. curl -i -H "Authorization: Bearer "$BOB_TOKEN"" http://$SERVICE_URL/people
  2. curl -i -H "Authorization: Bearer "$BOB_TOKEN"" -d '{"firstname":"Charlie", "lastname":"Opa"}' -H "Content-Type: application/json" -X POST http://$SERVICE_URL/people

Check that Bob cannot create an employee with the same firstname as himself.

  1. curl -i -H "Authorization: Bearer "$BOB_TOKEN"" -d '{"firstname":"Bob", "lastname":"Rego"}' -H "Content-Type: application/json" -X POST http://$SERVICE_URL/people

Wrap Up

Congratulations for finishing the tutorial !

This tutorial showed how to use OPA as an External authorization service to enforce custom policies by leveraging Envoy’s External authorization filter.

This tutorial also showed a sample OPA policy that returns a boolean decision to indicate whether a request should be allowed or not.

Envoy’s external authorization filter allows optional response headers and body to be sent to the downstream client or upstream. An example of a rule that returns an object that not only indicates if a request is allowed or not but also provides optional response headers, body and HTTP status that can be sent to the downstream client or upstream can be seen here.