This page covers how to write policies for the content of the requests that are passed to OPA by Envoy’s External Authorization filter.

Writing Policies

Let’s start with an example policy that restricts access to an endpoint based on a user’s role and permissions.

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

The first line package envoy.authz declaration gives the (hierarchical) name envoy.authz to the rules in the remainder of the policy. If the OPA-Envoy configuration does not specify the path field, envoy/authz/allow will be considered as the default policy decision path. data.envoy.authz.allow will be the name of the policy decision to query in the default case.

The above policy uses the io.jwt.decode_verify builtin function to parse and verify the JWT containing information about the user making the request. It uses other builtins like glob.match, lower, base64url.decode etc. OPA has 150+ builtins detailed at openpolicyagent.org/docs/policy-reference.

The dot notation seen in multiple places in the policy for ex. input.parsed_body.firstname simply descends through the hierarchy to access the requested value. The dot (.) operator never throws any errors; if the path does not exist the value of the expression is undefined.

  1. data.envoy.authz.allow

Sample input received by OPA is shown below:

  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. false

Example Policy with Additional Controls

The allow variable in the above policy returns a boolean decision to indicate whether a request should be allowed or not. If you want, you can also control the HTTP status sent to the upstream or downstream client, along with the response body, and the response headers. To do that, you can write rules like the ones below to fill in values for variables with the following types:

  • headers is an object whose keys are strings and values are strings. In case the request is denied, the object represents the HTTP response headers to be sent to the downstream client. If the request is allowed, the object represents additional request headers to be sent to the upstream.
  • response_headers_to_add is an object whose keys are strings and values are strings. It defines the HTTP response headers to be sent to the downstream client when a request is allowed.
  • request_headers_to_remove is an array of strings which describes the HTTP headers to remove from the original request before dispatching it to the upstream when a request is allowed.
  • body is a string which represents the response body data sent to the downstream client when a request is denied.
  • status_code is a number which represents the HTTP response status code sent to the downstream client when a request is denied.
  1. package envoy.authz
  2. import input.attributes.request.http
  3. default allow := false
  4. allow {
  5. is_token_valid
  6. action_allowed
  7. }
  8. headers["x-ext-auth-allow"] := "yes"
  9. headers["x-validated-by"] := "security-checkpoint"
  10. request_headers_to_remove := ["one-auth-header", "another-auth-header"]
  11. response_headers_to_add["x-foo"] := "bar"
  12. status_code := 200 {
  13. allow
  14. } else = 401 {
  15. not is_token_valid
  16. } else = 403 {
  17. true
  18. }
  19. body := "Authentication Failed" { status_code == 401 }
  20. body := "Unauthorized Request" { status_code == 403 }
  21. is_token_valid {
  22. token.valid
  23. now := time.now_ns() / 1000000000
  24. token.payload.nbf <= now
  25. now < token.payload.exp
  26. }
  27. action_allowed {
  28. http.method == "GET"
  29. token.payload.role == "guest"
  30. glob.match("/people/*", ["/"], http.path)
  31. }
  32. action_allowed {
  33. http.method == "GET"
  34. token.payload.role == "admin"
  35. glob.match("/people/*", ["/"], http.path)
  36. }
  37. action_allowed {
  38. http.method == "POST"
  39. token.payload.role == "admin"
  40. glob.match("/people", ["/"], http.path)
  41. lower(input.parsed_body.firstname) != base64url.decode(token.payload.sub)
  42. }
  43. token := {"valid": valid, "payload": payload} {
  44. [_, encoded] := split(http.headers.authorization, " ")
  45. [valid, _, payload] := io.jwt.decode_verify(encoded, {"secret": "secret"})
  46. }
  1. data.envoy.authz

Sample input received by OPA is shown below:

  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 value of all the variables in the package are:

  1. {
  2. "allow": false,
  3. "body": "Authentication Failed",
  4. "headers": {
  5. "x-ext-auth-allow": "yes",
  6. "x-validated-by": "security-checkpoint"
  7. },
  8. "request_headers_to_remove": [
  9. "one-auth-header",
  10. "another-auth-header"
  11. ],
  12. "response_headers_to_add": {
  13. "x-foo": "bar"
  14. },
  15. "status_code": 401,
  16. "token": {
  17. "payload": {},
  18. "valid": false
  19. }
  20. }

Output Document

When Envoy receives a policy decision, it expects a JSON object with the following fields:

  • allowed (required): a boolean deciding whether or not the request is allowed
  • headers (optional): an object mapping a string header name to a string header value (e.g. key “x-ext-auth-allow” has value “yes”)
  • response_headers_to_add (optional): an object mapping a string header name to a string header value
  • request_headers_to_remove (optional): is an array of string header names
  • http_status (optional): a number representing the HTTP status code
  • body (optional): the response body

To construct that output object using the policies demonstrated in the last section, you can use the following Rego snippet. Notice that we are using partial object rules so that any variables with undefined values simply have no key in the result object.

  1. result["allowed"] := allow
  2. result["headers"] := headers
  3. result["response_headers_to_add"] := response_headers_to_add
  4. result["request_headers_to_remove"] := request_headers_to_remove
  5. result["body"] := body
  6. result["http_status"] := status_code

For a single user, including this snippet in your normal policy is fine, but when you have multiple teams writing policies, you will typically pull this bit of boilerplate into a wrapper package, so your teams can focus on writing the policies shown in the previous sections.

Input Document

In OPA, input is a reserved, global variable whose value is the request sent by the Envoy External Authorization filter to OPA. The OPA-Envoy plugin supports both v2 and v3 versions of the CheckRequest which is used to pass the request to OPA.

For v3 requests, the specified JSON mapping for protobuf is used for making the incoming envoy.service.auth.v3.CheckRequest available in input. It differs from the encoding used for v2 requests. In v3, all keys are lower camelcase. Also, needless nesting of oneof values is removed.

For example, source address data that looks like this in v2,

  1. "source": {
  2. "address": {
  3. "Address": {
  4. "SocketAddress": {
  5. "PortSpecifier": {
  6. "PortValue": 59052
  7. },
  8. "address": "127.0.0.1"
  9. }
  10. }
  11. }
  12. }

becomes, in v3,

  1. "source": {
  2. "address": {
  3. "socketAddress": {
  4. "address": "127.0.0.1",
  5. "portValue": 59052
  6. }
  7. }
  8. }

The following table shows the rego code for common data, in v2 and v3:

informationrego v2rego v3
source addressinput.attributes.source.address.Address.SocketAddress.addressinput.attributes.source.address.socketAddress.address
source portinput.attributes.source.address.Address.SocketAddress.PortSpecifier.PortValueinput.attributes.source.address.socketAddress.portValue
destination addressinput.attributes.destination.address.Address.SocketAddress.addressinput.attributes.destination.address.socketAddress.address
destination portinput.attributes.destination.address.Address.SocketAddress.PortSpecifier.PortValueinput.attributes.destination.address.socketAddress.portValue
dynamic metadatainput.attributes.metadata_context.filter_metadatainput.attributes.metadataContext.filterMetadata

Due to those differences, it’s important to know which version is used when writing policies. Thus, this information is passed into the OPA evaluation under input.version, where you’ll either find, for v2,

  1. input.version == { "ext_authz": "v2", "encoding": "encoding/json" }

or, for v3,

  1. input.version == { "ext_authz": "v3", "encoding": "protojson" }

To have Envoy use the v3 version of the service, the http_filters entry in the Envoy configuration should look like below (minimal version):

  1. http_filters:
  2. - name: envoy.ext_authz
  3. typed_config:
  4. '@type': type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
  5. transport_api_version: V3
  6. grpc_service:
  7. google_grpc: # or envoy_grpc
  8. target_uri: "127.0.0.1:9191"

Example Input

Example v3 Input

  1. {
  2. "attributes": {
  3. "source": {
  4. "address": {
  5. "socketAddress": {
  6. "address": "172.17.0.1",
  7. "portValue": 61402
  8. }
  9. }
  10. },
  11. "destination": {
  12. "address": {
  13. "socketAddress": {
  14. "address": "172.17.06",
  15. "portValue": 8000
  16. }
  17. }
  18. },
  19. "request": {
  20. "time": "2020-11-20T09:47:47.722473Z",
  21. "http": {
  22. "id":"13519049518330544501",
  23. "method": "POST",
  24. "headers": {
  25. ":authority":"192.168.99.206:30164",
  26. ":method":"POST",
  27. ":path":"/people?lang=en",
  28. "accept": "*/*",
  29. "authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJzdWIiOiJZbTlpIiwibmJmIjoxNTE0ODUxMTM5LCJleHAiOjE2NDEwODE1Mzl9.WCxNAveAVAdRCmkpIObOTaSd0AJRECY2Ch2Qdic3kU8",
  30. "content-length":"41",
  31. "content-type":"application/json",
  32. "user-agent":"curl/7.54.0",
  33. "x-forwarded-proto":"http",
  34. "x-request-id":"7bca5c86-bf55-432c-b212-8c0f1dc999ec"
  35. },
  36. "host":"192.168.99.206:30164",
  37. "path":"/people?lang=en",
  38. "protocol":"HTTP/1.1",
  39. "body":"{\"firstname\":\"Charlie\", \"lastname\":\"Opa\"}",
  40. "size":41
  41. }
  42. },
  43. "metadataContext": {}
  44. },
  45. "parsed_body":{"firstname": "Charlie", "lastname": "Opa"},
  46. "parsed_path":["people"],
  47. "parsed_query": {"lang": ["en"]},
  48. "truncated_body": false,
  49. "version": {
  50. "encoding":"protojson",
  51. "ext_authz":"v3"
  52. }
  53. }
  54. ``` Example v2 Input

{ “attributes”:{ “source”:{ “address”:{ “Address”:{ “SocketAddress”:{ “PortSpecifier”:{ “PortValue”:61402 }, “address”:”172.17.0.1” } } } }, “destination”:{ “address”:{ “Address”:{ “SocketAddress”:{ “PortSpecifier”:{ “PortValue”:8000 }, “address”:”172.17.0.6” } } } }, “request”:{ “http”:{ “id”:”13519049518330544501”, “method”:”POST”, “headers”:{ “:authority”:”192.168.99.206:30164”, “:method”:”POST”, “:path”:”/people?lang=en”, “accept”:”/“, “authorization”:”Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJzdWIiOiJZbTlpIiwibmJmIjoxNTE0ODUxMTM5LCJleHAiOjE2NDEwODE1Mzl9.WCxNAveAVAdRCmkpIObOTaSd0AJRECY2Ch2Qdic3kU8”, “content-length”:”41”, “content-type”:”application/json”, “user-agent”:”curl/7.54.0”, “x-forwarded-proto”:”http”, “x-request-id”:”7bca5c86-bf55-432c-b212-8c0f1dc999ec” }, “host”:”192.168.99.206:30164”, “path”:”/people?lang=en”, “protocol”:”HTTP/1.1”, “body”:”{\”firstname\”:\”Charlie\”, \”lastname\”:\”Opa\”}”, “size”:41 } } }, “parsed_body”:{“firstname”: “Charlie”, “lastname”: “Opa”}, “parsed_path”:[“people”], “parsed_query”: {“lang”: [“en”]}, “truncated_body”: false, “version”: { “encoding”:”encoding/json”, “ext_authz”:”v2” } }

  1. The `parsed_path` field in the input is generated from the `path` field in the HTTP request which is included in the Envoy External Authorization `CheckRequest` message type. This field provides the request path as a string array which can help policy authors perform pattern matching on the HTTP request path. The below sample policy allows anyone to access the path `/people`.

package envoy.authz

default allow = false

allow { input.parsed_path == [“people”] }

  1. The `parsed_query` field in the input is also generated from the `path` field in the HTTP request. This field provides the HTTP URL query as a map of string array. The below sample policy allows anyone to access the path `/people?lang=en&id=1&id=2`.

package envoy.authz

default allow := false

allow { input.parsed_path == [“people”] input.parsed_query.lang == [“en”] input.parsed_query.id == [“1”, “2”] }

  1. The `parsed_body` field in the input is generated from the `body` field in the HTTP request which is included in the Envoy External Authorization `CheckRequest` message type. This field contains the deserialized JSON request body which can then be used in a policy as shown below.

package envoy.authz

default allow := false

allow { input.parsed_body.firstname == “Charlie” input.parsed_body.lastname == “Opa” }

  1. The `truncated_body` field in the input represents if the HTTP request body is truncated. The body is considered to be truncated, if the value of the `Content-Length` header exceeds the size of the request body.
  2. ## Example with JWT payload passed from Envoy
  3. Envoy can be configured to pass validated JWT payload data into the `ext_authz` filter with `metadata_context_namespaces` and `payload_in_metadata`.
  4. ### Example Envoy Configuration

http_filters:

  • name: envoy.filters.http.jwt_authn typed_config: “@type”: type.googleapis.com/envoy.config.filter.http.jwt_authn.v2alpha.JwtAuthentication providers: example:
    1. payload_in_metadata: verified_jwt
    2. <...>
  • name: envoy.ext_authz config: metadata_context_namespaces:
    • envoy.filters.http.jwt_authn <…> ```

Example OPA Input

This will result in something like the following dictionary being added to input.attributes (some common fields have been excluded for brevity):

  1. "metadata_context": {
  2. "filter_metadata": {
  3. "envoy.filters.http.jwt_authn": {
  4. "verified_jwt": {
  5. "email": "alice@example.com",
  6. "exp": 1569026124,
  7. "name": "Alice"
  8. }
  9. }
  10. }
  11. }