mirror of
https://github.com/inspec/inspec
synced 2024-11-10 23:24:18 +00:00
d029f7f58c
When using the `query` method in the `postgres_session` resource, if the query fails, the `query` method attempts to call `skip_resource` with an error message. Not only does the `skip_resource` not properly work, but it also returns a `String` object back to the test which is probably going to try and call the `output` method on it to run the test. This results in an error like this: ``` Can't read ∅ undefined method `output' for "output":String ``` This change returns the full psql output as a Lines object to the user, including stderr, so they can at least get the error in their test output and avoids undefined method errors. Signed-off-by: Adam Leff <adam@leff.co>
72 lines
1.8 KiB
Ruby
72 lines
1.8 KiB
Ruby
# encoding: utf-8
|
|
# copyright: 2015, Vulcano Security GmbH
|
|
# author: Dominik Richter
|
|
# author: Christoph Hartmann
|
|
# author: Aaron Lippold
|
|
|
|
require 'shellwords'
|
|
|
|
module Inspec::Resources
|
|
class Lines
|
|
attr_reader :output
|
|
|
|
def initialize(raw, desc)
|
|
@output = raw
|
|
@desc = desc
|
|
end
|
|
|
|
def lines
|
|
output.split("\n")
|
|
end
|
|
|
|
def to_s
|
|
@desc
|
|
end
|
|
end
|
|
|
|
class PostgresSession < Inspec.resource(1)
|
|
name 'postgres_session'
|
|
desc 'Use the postgres_session InSpec audit resource to test SQL commands run against a PostgreSQL database.'
|
|
example "
|
|
sql = postgres_session('username', 'password', 'host')
|
|
query('sql_query', ['database_name'])` contains the query and (optional) database to execute
|
|
|
|
# default values:
|
|
# username: 'postgres'
|
|
# host: 'localhost'
|
|
# db: databse == db_user running the sql query
|
|
|
|
describe sql.query('SELECT * FROM pg_shadow WHERE passwd IS NULL;') do
|
|
its('output') { should eq '' }
|
|
end
|
|
"
|
|
|
|
def initialize(user, pass, host = nil)
|
|
@user = user || 'postgres'
|
|
@pass = pass
|
|
@host = host || 'localhost'
|
|
end
|
|
|
|
def query(query, db = [])
|
|
psql_cmd = create_psql_cmd(query, db)
|
|
cmd = inspec.command(psql_cmd)
|
|
out = cmd.stdout + "\n" + cmd.stderr
|
|
if cmd.exit_status != 0 || out =~ /could not connect to .*/ || out.downcase =~ /^error:.*/
|
|
Lines.new(out, "PostgreSQL query with errors: #{query}")
|
|
else
|
|
Lines.new(cmd.stdout.strip, "PostgreSQL query: #{query}")
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def escaped_query(query)
|
|
Shellwords.escape(query)
|
|
end
|
|
|
|
def create_psql_cmd(query, db = [])
|
|
dbs = db.map { |x| "-d #{x}" }.join(' ')
|
|
"PGPASSWORD='#{@pass}' psql -U #{@user} #{dbs} -h #{@host} -A -t -c #{escaped_query(query)}"
|
|
end
|
|
end
|
|
end
|