Mail-DKIM2

 view release on metacpan or  search on metacpan

t/chain-length.t  view on Meta::CPAN

#!/usr/bin/perl
use strict;
use warnings;
use Test::More;
use FindBin;
use lib "$FindBin::Bin/../lib", "$FindBin::Bin/lib";
use Mail::DKIM2::Common qw(MAX_CHAIN_LENGTH);
use Mail::DKIM2::Signer;
use Mail::DKIM2::Verifier;
use Mail::DKIM2::MessageInstance;
use Email::MIME;
use DKIM2TestKeys;

# A chain of MAX_CHAIN_LENGTH hops verifies as usual. One more Message-Instance
# or DKIM2-Signature field is a PERMERROR found from the headers alone: no key
# is fetched, no signature checked, no recipe applied, and the body is not
# kept.

my $TIMESTAMP = 1740000000;
my $DOMAIN    = 'test1.dkim2.com';
my $SELECTOR  = 'sel1';
my $ADDRESS   = 'hop@test1.dkim2.com';

sub signer {
    return Mail::DKIM2::Signer->new(
        Domain    => $DOMAIN,
        Selector  => $SELECTOR,
        Key       => DKIM2TestKeys::private_key($DOMAIN, $SELECTOR),
        MailFrom  => $ADDRESS,
        RcptTo    => [$ADDRESS],
        Timestamp => $TIMESTAMP,
    );
}

sub sign_hop {
    my ($text) = @_;
    my $signer = signer();
    $signer->PRINT($text);
    $signer->CLOSE;
    (my $header = $signer->as_string) =~ s/\r?\n\z//;
    return "$header\r\n$text";
}

# $more is fed after the message, as a later chunk would be.
sub verify {
    my ($text, $more) = @_;
    my $lookups = 0;
    my $callback = DKIM2TestKeys::pubkey_callback();
    my $v = Mail::DKIM2::Verifier->new;
    $v->set_pubkey_callback(sub { $lookups++; $callback->(@_) });
    $v->skip_timestamp_check(1);
    $v->PRINT($text);
    $v->PRINT($more) if defined $more;
    $v->CLOSE;
    return ($v, $lookups);
}

# Every hop adds a body line, a Message-Instance recording how to undo it, and
# a signature.
sub build_chain {
    my ($hops) = @_;
    my $text = join("\r\n",
        'From: sender@test1.dkim2.com',
        'To: hop@test1.dkim2.com',
        'Subject: a long chain',
        '',
        'original body',
        '',
    );
    my $mi = Mail::DKIM2::MessageInstance->calculate($text);
    $text = sign_hop("Message-Instance: " . $mi->as_string . "\r\n$text");
    for my $hop (2 .. $hops) {
        my $previous = Email::MIME->new($text);
        my $current  = Email::MIME->new($text);
        $current->body_set($current->body_raw . "hop $hop\r\n");
        my $next = Mail::DKIM2::MessageInstance->calculate($current, $previous);
        $current->header_raw_prepend('Message-Instance', $next->as_string);
        $text = sign_hop($current->as_string);
    }
    return $text;
}

my $text = build_chain(MAX_CHAIN_LENGTH);

{
    my ($v) = verify($text);
    is($v->result, 'pass', MAX_CHAIN_LENGTH . ' hops verify')
        or diag($v->details);



( run in 0.985 second using v1.01-cache-2.11-cpan-8379b9b8ec2 )