# frozen_string_literal: true require_relative "helper" require_relative "../lib/tynn/ssl" class SSLTest < Minitest::Test def setup @app = Class.new(Tynn) end def test_redirect_to_https @app.plugin(Tynn::SSL) @app.define {} ts = Tynn::Test.new(@app) ts.get("/") assert_equal 301, ts.res.status assert_equal "https://example.org/", ts.res.location end def test_redirect_port_80 @app.plugin(Tynn::SSL) @app.define {} ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTP_HOST" => "example.org:80") assert_equal 301, ts.res.status assert_equal "https://example.org/", ts.res.location end def test_redirect_port_443 @app.plugin(Tynn::SSL) @app.define {} ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTP_HOST" => "example.org:443") assert_equal 301, ts.res.status assert_equal "https://example.org/", ts.res.location end def test_redirect_to_non_default_port @app.plugin(Tynn::SSL) @app.define {} ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTP_HOST" => "example.org:4567") assert_equal 301, ts.res.status assert_equal "https://example.org:4567/", ts.res.location end def test_accept_safe_request @app.plugin(Tynn::SSL) @app.define { res.write("secure") } ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTPS" => "on") assert_equal 200, ts.res.status assert_equal "secure", ts.res.body end def test_set_hsts_header_with_defaults @app.plugin(Tynn::SSL) @app.define {} ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTPS" => "on") header = ts.res.headers["Strict-Transport-Security"] assert_equal "max-age=15552000; includeSubdomains", header end def test_set_hsts_header_with_options @app.plugin(Tynn::SSL, hsts: { expires: 1, subdomains: false, preload: true }) @app.define {} ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTPS" => "on") header = ts.res.headers["Strict-Transport-Security"] assert_equal "max-age=1; preload", header end def test_disable_hsts @app.plugin(Tynn::SSL, hsts: false) @app.define {} ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTPS" => "on") header = ts.res.headers["Strict-Transport-Security"] assert_equal "max-age=0; includeSubdomains", header end def test_set_secure_flag @app.plugin(Tynn::SSL, hsts: false) @app.define do get do res.set_cookie("first", "cookie", secure: false) res.set_cookie("other", "cookie", http_only: true) res.set_cookie("secure", "cookie", secure: true) end end ts = Tynn::Test.new(@app) ts.get("/", {}, "HTTPS" => "on") first, other, secure = ts.res.headers["Set-Cookie"].split("\n") assert_equal "first=cookie; secure", first assert_equal "other=cookie; HttpOnly; secure", other assert_equal "secure=cookie; secure", secure end end