Search code examples
open-policy-agent

Test attribute of the json response returned by open policy agent with opa test


Is there a way to test value of a key/attribute inside the json response of the decision returned by OPA.(Response returned is not yes/no but a json with key allow which dictates the decision) For example:

test_get_user_allowed_for_admin {
        decision["allow"] with input as {"path": ["users", "kate"], "method": "GET", "user_id": "bob"}
}

Let’s say the policy evaluated is of the form:

get_user_info = decision{
    decision := {
      "allow": input.user_id == "bob", "user_id": input.user_id,
  }
}

currently I get a var decision is unsafe error because decision is not defined in the test_get_user_allowed_for_admin but that is just a filler


Solution

  • Your test can check the value generated by the rule get_user_info just like any other value (e.g., input, a local variable, etc.)

    For example:

    test_get_user_allowed_for_admin {
      in := {
        "path": ["users", "kate"],
        "method": "GET",
        "user_id": "bob"
      }
    
      result := get_user_info with input as in
      result.allow == true
      result.user_id == "bob"
    }
    
    # OR
    
    test_get_user_allowed_for_admin_alt {
      in := {
        "path": ["users", "kate"],
        "method": "GET",
        "user_id": "bob"
      }
      result := get_user_info with input as in
      result == {"allow": true, "user_id": "bob"}
    }
    

    Technically you don't have to assign the value generated by get_user_info a variable:

    test_get_user_allowed_for_admin_oneline {
      in := {
        "path": ["users", "kate"],
        "method": "GET",
        "user_id": "bob"
      }
      get_user_info.allow with input as in
    }