require 'test_helper'
require 'mechanize'

class SecurityTest < Minitest::Test
  include WebserverHelper
  include SSLHelper

  def domain
    "ssl.evolix.net".freeze
  end

  def test_certificate_level
    level = "intermediate"
    command = analyze_cmd(domain: domain, level: level)
    output = `#{command}`

    assert_match %r|has intermediate ssl/tls\nand complies with the '#{level}' level|, output, "Expected to comply with #{level} level :\n#{output.inspect}"
    refute_match %r|consider enabling OCSP Stapling|, output, 'Expected to have OCSP stapling enabled'
  end

  def test_certificate
    options = {
      domain: "ssl.evolix.net",
      issuer: %Q("Let's Encrypt Authority X3"),
      cn: "ssl.evolix.net",
    }
    command = check_ssl_cert_cmd(options)
    output = `#{command}`

    assert_match(/\ASSL_CERT OK/, output, output)
  end

  def test_accepts_tls_v1
    command = openssl_verify_cmd(domain, "-tls1")
    output = `#{command}`

    assert_match(/Verify return code: 0 \(ok\)/, output, "Expected to accept TLSv1")
  end

  def test_refuse_ssl_v3
    command = openssl_verify_cmd(domain, "-ssl3")
    output = `#{command}`

    assert_match(/sslv3 alert handshake failure/, output, "Expected to refuse SSLv3")
  end

  def test_hsts_header
    agent = Mechanize.new { |a|
      a.follow_redirect = true
    }
    url = "https://#{domain}/"
    page = agent.get(url)
    context = "for #{url}"

    assert_status_ok page, context
    assert_has_hsts page, context
    assert_hsts_max_age "315360000", page, context
    refute_hsts_include_subdomains page, context
  end

end
