Oracle fix when invoking query using os user and db role

Signed-off-by: Nikita Mathur <nikita.mathur@chef.io>
This commit is contained in:
Nikita Mathur 2021-10-19 14:43:49 +05:30
parent 648afbb6fa
commit e5f2ede389
2 changed files with 29 additions and 4 deletions

View file

@ -42,6 +42,7 @@ module Inspec::Resources
end
def query(sql)
raise Inspec::Exceptions::ResourceSkipped, "#{resource_exception_message}" if resource_skipped?
raise Inspec::Exceptions::ResourceFailed, "#{resource_exception_message}" if resource_failed?
if @sqlcl_bin && inspec.command(@sqlcl_bin).exist?
@ -78,7 +79,14 @@ module Inspec::Resources
# using a db_role
# su, using a db_role
def command_builder(format_options, query)
verified_query = verify_query(query)
if @db_role.nil? || @su_user.nil?
verified_query = verify_query(query)
else
escaped_query = query.gsub(/\\/, "\\\\").gsub(/"/, '\\"')
escaped_query = escaped_query.gsub("$", '\\$')
verified_query = verify_query(escaped_query)
end
sql_prefix, sql_postfix = "", ""
if inspec.os.windows?
sql_prefix = %{@'\n#{format_options}\n#{verified_query}\nEXIT\n'@ | }
@ -87,11 +95,11 @@ module Inspec::Resources
end
if @db_role.nil?
"#{sql_prefix}#{bin} #{user}/#{password}@#{host}:#{port}/#{@service}#{sql_postfix}"
%{#{sql_prefix}#{bin} #{user}/#{password}@#{host}:#{port}/#{@service}#{sql_postfix}}
elsif @su_user.nil?
"#{sql_prefix}#{bin} #{user}/#{password}@#{host}:#{port}/#{@service} as #{@db_role}#{sql_postfix}"
%{#{sql_prefix}#{bin} #{user}/#{password}@#{host}:#{port}/#{@service} as #{@db_role}#{sql_postfix}}
else
"su - #{@su_user} -c env ORACLE_SID=#{@service} #{@bin} / as #{@db_role}#{sql_postfix}"
%{su - #{@su_user} -c "env ORACLE_SID=#{@service} #{@bin} / as #{@db_role}#{sql_postfix}"}
end
end

View file

@ -20,6 +20,23 @@ describe "Inspec::Resources::OracledbSession" do
_(query.row(0).column("value").value).must_equal "ORCL"
end
it "sqlplus Linux with os user and db role" do
resource = quick_resource(:oracledb_session, :linux, as_os_user: "OSUSER", as_db_role: "DBA", host: "localhost", service: "ORCL", port: 1527, sqlplus_bin: "/bin/sqlplus") do |cmd|
cmd.strip!
case cmd
when "su - OSUSER -c \"env ORACLE_SID=ORCL /bin/sqlplus -S / as DBA <<'EOC'\nSET PAGESIZE 32000\nSET FEEDBACK OFF\nSET UNDERLINE OFF\nSELECT NAME AS VALUE FROM v\\$database;\nEXIT\nEOC\"" then
stdout_file "test/fixtures/cmd/oracle-result"
else
raise cmd.inspect
end
end
_(resource.resource_skipped?).must_equal false
query = resource.query("SELECT NAME AS VALUE FROM v$database;")
_(query.size).must_equal 1
_(query.row(0).column("value").value).must_equal "ORCL"
end
it "sqlplus Windows" do
resource = quick_resource(:oracledb_session, :windows, user: "USER", password: "password", host: "localhost", service: "ORCL", port: 1527, sqlplus_bin: "C:/sqlplus.exe") do |cmd|
cmd.strip!