sharmila
sharmila

Reputation: 85

rego_type_error: undefined function

I am new to OPA and rego files. I have created a rego file like this :

package sample.access
import data.myaccess

default allow = false
allow = true {
    myaccess.is_user_allowed(input.user)
}

And, I have created test rego file like this :

package sample.access

test_allow_positive{
    allow with input as {
        "user": "user1"
    } with data.myaccess as {
        {
            {"user": "user1"},
            {"user": "user2"}
        }
            
    }
}

When I run this test case, I am getting error like "rego_type_error: undefined function data.myaccess.is_user_allowed". Help me to fix this. Thanks

Upvotes: 3

Views: 4046

Answers (2)

NPE
NPE

Reputation: 502

I was facing a similar issue, probably the below solution might help.

I had a function make_err, in the file myutils.rego which I was using in myModule-test.rego file.

When I ran the command like this:

user@ubuntu:~/rules$./opa test myModule-test.rego

Got this error:

1 error occurred: myModule-test.rego:7: rego_type_error: undefined function data.myutils.make_err

When I gave the below command, it worked:

user@ubuntu:~/rules$ ./opa test myutils.rego myModule-test.rego
PASS: 11/11

It seems we need to load all the modules on which the current test depends.

Upvotes: 3

Will Beason
Will Beason

Reputation: 3551

I assume this is what you are trying to do:

Create a rule, allow, which returns true if input.user is from a set of users passed at the call time. To do this, you can use the rule:

package sample.access

allow {
    data.allowed[input.user]
}

The corresponding unit tests:

package sample.access

test_allow {
    allow with input as {
        "user": "user1"
    } with data.allowed as {"user1", "user2"}
}

test_deny {
    not allow with input as {
        "user": "user3"
    } with data.allowed as {"user1", "user2"}
}

Note that you do not need to explicitly import parameters which you will pass at runtime.

If your input data is required to be in the form of a list of {"user": "id"}, then instead you should use a set comprehension.

package sample.access

allow {
    is_user_allowed = {user | user = data.allowed[_].user}

    is_user_allowed[input.user]
}

Your unit tests would then need to be amended as such:

package sample.access

test_allow {
    allow with input as {
        "user": "user1"
    } with data.allowed as {
        {"user": "user1"},
        {"user": "user2"}
    }
}

test_deny {
    not allow with input as {
        "user": "user3"
    } with data.allowed as {
         {"user": "user1"},
         {"user": "user2"}
    }
}

Upvotes: 1

Related Questions