open-policy-agentconftest

Using contains in conftest rules


I have following XML (it is a dotnet project file:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <None Remove="appsettings.json" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="LoadA1Test" />
  </ItemGroup>
</Project>

And following rules:

package main

project_reference = input.Project.ItemGroup[i].ProjectReference

deny[msg] {

    not project_reference[i]["-Include"] = "XYZ"
    msg = sprintf("in %s works \n", [project_reference[i]])
}

deny[msg] {
    
    not contains(project_reference[i]["-Include"],"XYZ")
    msg = sprintf("in %s doesn't work \n", [project_reference[i]])
}

When I try to validate with conftest the first rule fails as expected, but the second one passes. I tried a few options, but I don't know what I'm doing wrong.


Solution

  • A few things looks a bit odd:

    And I don't think you'd need to reuse the i iterator since you're looking up a map key in the project reference. Something like this might do:

    package main
    
    deny[msg] {
        project_reference := input.Project.ItemGroup[_].ProjectReference
        project_reference["-Include"] != "XYZ"
        msg = sprintf("-Include (%v) != XYZ", [project_reference["-Include"]])
    }
    
    deny[msg] {
        project_reference := input.Project.ItemGroup[_].ProjectReference
        not contains(project_reference["-Include"], "XYZ")
        msg = sprintf("-Include: (%v) does not contain XYZ", [project_reference["-Include"]])
    }
    

    Though I'm not sure about the logic, since you'll always have the first rule fail if the -Include value isn't exactly XYZ, so there wouldn't be much point in adding another one to deny also if -Include did not contain that value.