Skip to content

Instantly share code, notes, and snippets.

@hemalvarambhia
Last active August 29, 2015 14:09
Show Gist options
  • Save hemalvarambhia/ef43b5eddcd1f8e4e928 to your computer and use it in GitHub Desktop.
Save hemalvarambhia/ef43b5eddcd1f8e4e928 to your computer and use it in GitHub Desktop.
A ChefSpec nginx matcher that checks requests from a list of IP addresses have been whitelisted
if defined?(ChefSpec)
module ChefSpec::Matchers
class NginxPrivilegeMatcher
def initialize(runner, ip_addresses, permission="allow")
@runner = runner
@ip_addresses = ip_addresses
@permission = permission
end
def matches?(resource)
@resource = resource
@path = @resource.name
is_created? and @ip_addresses.all? { |ip_address| correctly_restricted?(ip_address) }
end
def to_url(url)
@url = url
self
end
def failure_message_for_should
missing_ip_addresses = @ip_addresses.select{ |ip_address| !correctly_restricted?(ip_address) }
message = %Q{expected Chef run to render "#{@path}"}
if @permission == "allow"
message << " that whitelists requests to #{@url} from #{missing_ip_addresses.join(", ")}"
else
message << " that blacklists requests to #{@url} from #{missing_ip_addresses.join(", ")}"
end
message
end
private
def correctly_restricted?(ip_address)
escaped_url = Regexp.escape @url
escaped_ip_address = Regexp.escape ip_address
actual_content = ChefSpec::Renderer.new(@runner, @resource).content
actual_content=~/location #{escaped_url} \{[^}]+#{@permission} #{escaped_ip_address};/m
end
def is_created?
[:create, :create_if_missing].any? { |action| @resource.performed_action?(action) }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment