require 'json'

test_name "CVE 2013-1652 Improper query parameter validation" do
  confine :except, :platform => 'windows'
  confine :except, :platform => /osx/ # see PUP-4820
  confine :except, :platform => /aix/

  tag 'audit:high',        # risk low, high (security) impact
      'audit:integration',
      'server'

  with_puppet_running_on master, {} do
    # Ensure each agent has a signed cert
    on agents, puppet('agent', "-t")

    agents.each do |agent|
      next if agent['roles'].include?( 'master' )

      certname = on(agent, puppet('agent', "--configprint certname")).stdout.chomp

      payload = "https://#{master}:8140/puppet/v3/catalog/#{certname}" +
                "?environment=production&use_node=" +
                "---%20!ruby/object:Puppet::Node%0A%20%20" +
                "name:%20#{master}%0A%20%20classes:%20\[\]%0A%20%20" +
                "parameters:%20%7B%7D%0A%20%20facts:%20%7B%7D"

      cert_path = on(agent, puppet('agent', "--configprint hostcert")).stdout.chomp
      key_path = on(agent, puppet('agent', "--configprint hostprivkey")).stdout.chomp
      curl_base = "curl --tlsv1 -g --cert \"#{cert_path}\" --key \"#{key_path}\" -k -H 'Accept: application/json'"

      curl_call =  "#{curl_base} '#{payload}'"

      step "Attempt to retrieve another nodes catalog" do
        on agent, curl_call do |test|
          begin
            res = JSON.parse( test.stdout )
            fail_test( "Retrieved catalog for #{master} from #{agent}" ) if
              res['data'] && res['data']['name'] == master.name
          rescue JSON::ParserError
            # good, continue
          end
        end
      end
    end
  end
end
