Add support for OPA: add resource opa_cli and opa_api

Signed-off-by: Vasu1105 <vasundhara.jagdale@chef.io>
This commit is contained in:
Vasu1105 2021-07-07 14:54:55 +05:30
parent 16de66df74
commit 9b691b32ac
4 changed files with 107 additions and 0 deletions

View file

@ -83,6 +83,8 @@ require "inspec/resources/nginx_conf"
require "inspec/resources/npm"
require "inspec/resources/ntp_conf"
require "inspec/resources/oneget"
require "inspec/resources/opa_cli"
require "inspec/resources/opa_api"
require "inspec/resources/oracledb_session"
require "inspec/resources/os"
require "inspec/resources/os_env"

View file

@ -0,0 +1,22 @@
require "inspec/resources/json"
module Inspec::Resources
class Opa < JsonConfig
name "opa"
supports platform: "unix"
supports platform: "windows"
def initialize(content)
@content = content
super({content: @content})
end
private
def parse(content)
@content = YAML.load(content)
rescue => e
raise Inspec::Exceptions::ResourceFailed, "Unable to parse OPA query output: #{e.message}"
end
end
end

View file

@ -0,0 +1,41 @@
require "inspec/resources/opa"
module Inspec::Resources
class OpaApi < Opa
name "opa_api"
supports platform: "unix"
supports platform: "windows"
attr_reader :allow
def initialize(opts={})
@url = opts[:url]
@data = opts[:data]
fail_resource "policy and data are the mandatory for executing OPA." if @url.nil? && @data.nil?
@content = load_result
super(@content)
end
def allow
@content["result"]
end
def to_s
"OPA api"
end
private
def load_result
raise Inspec::Exceptions::ResourceFailed, "#{resource_exception_message}" if resource_failed?
result = inspec.command("curl -X POST #{@url} -d @#{@data} -H 'Content-Type: application/json'")
if result.exit_status == 0
result.stdout.gsub("\n", "")
else
error = result.stdout + "\n" + result.stderr
raise Inspec::Exceptions::ResourceFailed, "Error while executing OPA query: #{error}"
end
end
end
end

View file

@ -0,0 +1,42 @@
require "inspec/resources/opa"
module Inspec::Resources
class OpaCli < Opa
name "opa_cli"
supports platform: "unix"
supports platform: "windows"
attr_reader :allow
def initialize(opts = {})
@policy = opts[:policy] || nil
@data = opts[:data] || nil
@query = opts[:query] || nil
fail_resource "policy and data are the mandatory for executing OPA." if @policy.nil? && @data.nil?
@content = load_result
super(@content)
end
def allow
@content["result"][0]["expressions"][0]["value"] if @content["result"][0]["expressions"][0]["text"].include?("allow")
end
def to_s
"OPA cli"
end
private
def load_result
raise Inspec::Exceptions::ResourceFailed, "#{resource_exception_message}" if resource_failed?
result = inspec.command("opa eval -i '#{@data}' -d '#{@policy}' '#{@query}'")
if result.exit_status == 0
result.stdout.gsub("\n", "")
else
error = result.stdout + "\n" + result.stderr
raise Inspec::Exceptions::ResourceFailed, "Error while executing OPA query: #{error}"
end
end
end
end