inspec/lib/resources/postgres_session.rb

56 lines
1.3 KiB
Ruby
Raw Normal View History

# encoding: utf-8
2015-07-15 13:15:18 +00:00
# copyright: 2015, Vulcano Security GmbH
# license: All rights reserved
class Lines
2015-09-03 18:43:58 +00:00
def initialize(raw, desc)
@raw = raw
@desc = desc
end
def output
@raw
end
def lines
@raw.split("\n")
end
def to_s
@desc
end
end
class PostgresSession
2015-09-03 18:43:58 +00:00
def initialize(user, pass)
@user = user || 'postgres'
@pass = pass
end
def describe(query, db = [], &block)
2015-09-05 14:07:54 +00:00
dbs = db.map { |x| "-d #{x}" }.join(' ')
# TODO: simple escape, must be handled by a library
# that does this securely
2015-09-05 14:07:54 +00:00
escaped_query = query.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$')
# run the query
cmd = vulcano.run_command("PGPASSWORD='#{@pass}' psql -U #{@user} #{dbs} -c \"#{escaped_query}\"")
out = cmd.stdout + "\n" + cmd.stderr
if out =~ /could not connect to .*/ or
out.downcase =~ /^error/
# skip this test if the server can't run the query
2015-09-05 14:07:54 +00:00
RSpec.describe(cmd) do
2015-09-03 21:18:28 +00:00
it 'is skipped', skip: out do
end
end
else
lines = cmd.stdout.
2015-09-05 14:07:54 +00:00
# remove the whole header (i.e. up to the first ^-----+------+------$)
sub(/(.*\n)+([-]+[+])*[-]+\n/, '').
# remove the tail
sub(/\n[^\n]*\n\n$/, '')
l = Lines.new(lines.strip, "PostgreSQL query: #{query}")
2015-09-05 14:07:54 +00:00
RSpec.__send__('describe', l, &block)
end
end
end