How do I tell WWW::Mechanize to ignore a secure cookie?

Viewed 186

I need to work with a legacy CGI program and I am writing tests for it. I use Test::WWW::Mechanize::CGI for that. The application runs on https in production, and the home-made session handling simply throws out a cookie, which has the secure option set.

my $cookie = $q->cookie(
    -name     => 'session',
    -value    => 'foobar',
    -expires  => '+24h',
    -secure   => 1,           # this is the culprit
    -httponly => 1,
    -samesite => 'Strict',
;

While this makes sense under the https URL in production, it breaks my tests because I don't have SSL support there.

The obvious solution would be to put in a switch that only enables this option on the cookie if there is SSL available, but I don't want to do that at this point. Instead, I want to find out how to disable this thing from the testing end.

Here's an example that illustrates what I'm talking about. It uses things in CGI.pm that I would usually discourage people from using. Please bear with me to understand the issue.

use strict;
use warnings;
use CGI;
use Test::WWW::Mechanize::CGI;
use Test::More;

my $mech = Test::WWW::Mechanize::CGI->new;
$mech->cgi(
    sub {
        my $q = CGI->new;

        if ( $q->param('behind_login') ) {
            # check if we've got the session cookie
            if ( $q->cookie('session') ) {
                print $q->header, $q->start_html('Logged in'), $q->h1('Welcome back'), $q->end_html;
            }
            else {
                print $q->header( 'text/plain', '403 Unauthorized' );
            }
        }
        else {
            # this is where the user gets logged in
            my $cookie = $q->cookie(
                -name     => 'session',
                -value    => 'foobar',
                -expires  => '+24h',
                -secure   => 1,           # this is the culprit
                -httponly => 1,
                -samesite => 'Strict'
            );

            print $q->header( -cookie => $cookie ),
                $q->start_html('Hello World'),
                $q->h1('Hello World'),
                $q->end_html;
        }
    }
);

$mech->get_ok('http://localhost/');
$mech->get_ok('http://localhost/?behind_login=1');

done_testing;

If this program is run, the first test will pass, and the second one will fail. If the marked line with the -secure option is commented out, the second test will pass, too.

I've rummaged around in LWP::UserAgent a bit, but haven't found where this could be disabled. I'm aware that this is the default behavior and that it's good that it behaves like this.

There might be an option to turn this off that I have failed to see when I was studying the docs, but it's likely there is not. I am fine with monkey-patching this thing away once I understand where to do that.

1 Answers
Related