Mail-DKIM2

 view release on metacpan or  search on metacpan

t/milter-script.t  view on Meta::CPAN

        $v =~ s/\r?\n/$EOL/g;
        if ($m->{op} eq 'insert') {
            splice @h, $m->{idx}, 0, [$m->{name}, "$m->{name}: $v$EOL"];
        } elsif ($m->{op} eq 'add') {
            push @h, [$m->{name}, "$m->{name}: $v$EOL"];
        } elsif ($m->{op} eq 'change') {
            my ($n, $pos) = (0);
            for my $i (0 .. $#h) {
                next unless lc $h[$i][0] eq lc $m->{name};
                if (++$n == $m->{idx}) { $pos = $i; last }
            }
            next unless defined $pos;
            if ($v eq '') { splice @h, $pos, 1 }
            else          { $h[$pos] = [$h[$pos][0], "$h[$pos][0]: $v$EOL"] }
        } elsif ($m->{op} eq 'body') {
            $new_body .= $m->{value};
        }
    }
    return join('', map { $_->[1] } @h) . $EOL . ($new_body // $body);
}

sub verify {
    my ($raw) = @_;
    my $v = Mail::DKIM2::Verifier->new;
    $v->set_pubkey_callback(DKIM2TestKeys::pubkey_callback());
    $v->PRINT($raw); $v->CLOSE;
    return $v;
}

sub inserted { my ($mods, $name) = @_; grep { $_->{op} eq 'insert' && lc($_->{name}) eq lc($name) } @$mods }
sub reply_of { my ($mods) = @_; my ($r) = grep { $_->{op} eq 'reply' } @$mods; $r ? $r->{value} : '' }

# --- Fixtures ---

# An originator's message, as it arrives from test1.dkim2.com: Message-Instance
# m=1 and DKIM2-Signature i=1. Signed now, because the milter's verifier
# applies the real timestamp window.
my $PLAIN = join($EOL,
    'MIME-Version: 1.0',
    'Message-Id: <post@test1.dkim2.com>',
    'Date: Thu, 10 Sep 2026 15:47:11 +1000',
    'From: Author <author@test1.dkim2.com>',
    'To: list@test2.dkim2.com',
    'Subject: a post',
    'Content-Type: text/plain',
    '',
    "Here's a test user!",
    '');

# The same post from an author at the list's own domain: a message the
# outbound milter signs as i=1 must have a From in its domain (-09 section
# 11), and an unsigned post keeps its From in the m=1 stamped on arrival.
my $LOCAL = $PLAIN =~ s/<author\@test1\.dkim2\.com>/<author\@test2.dkim2.com>/r;

sub originator_signed {
    my $plain = shift // $PLAIN;
    my $mi  = Mail::DKIM2::MessageInstance->calculate(Email::MIME->new($plain));
    my $msg = "Message-Instance: " . $mi->as_string . $EOL . $plain;
    my $signer = Mail::DKIM2::Signer->new(
        Domain => 'test1.dkim2.com', Selector => 'sel1',
        Key => DKIM2TestKeys::private_key('test1.dkim2.com', 'sel1'),
        MailFrom => 'author@test1.dkim2.com', RcptTo => ['list@test2.dkim2.com'],
        Timestamp => time());
    $signer->PRINT($msg); $signer->CLOSE;
    return $signer->as_string . $EOL . $msg;
}

# What a list manager (Mailman, Sympa) does before handing the message to the
# outbound MTA: tag the subject, add List-* fields, append a footer, and record
# the change as Message-Instance m=2 with a Recipe back to m=1. The m=2 is
# UNSIGNED at this point -- signing it is the milter's job.
sub list_modified {
    my ($signed) = @_;
    my $mod = $signed;
    $mod =~ s/^Subject: /Subject: [list] /m;
    $mod =~ s/^(Content-Type: text\/plain$EOL)/List-Id: <list.test2.dkim2.com>$EOL$1/m;
    $mod .= "--$EOL" . "list footer$EOL";
    my $mi = Mail::DKIM2::MessageInstance->calculate(
        Email::MIME->new($mod), Email::MIME->new($signed));
    return "Message-Instance: " . $mi->as_string . $EOL . $mod;
}

# --- 1. Baseline: no upstream chain at all -> originate m=1 / i=1 ---
{
    my ($verdict, $mods) = run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => $LOCAL);
    is($verdict, 'c', 'plain: milter continues');
    my @sig = inserted($mods, 'DKIM2-Signature');
    is(scalar @sig, 1, 'plain: one DKIM2-Signature inserted');
    like($sig[0]{value}, qr/\bi=1;/, 'plain: signature is i=1');
    is(scalar(inserted($mods, 'Message-Instance')), 1, 'plain: Message-Instance m=1 added');
    # draft-gondwana-dkim2-debug-header-01: every tag ends in ";", and the
    # instance action is mi-m=<N>.
    # Unfold, then drop the whitespace a consumer is told to ignore next to
    # ";" and ",".
    my @info = map { $_->{value} =~ s/\n[ \t]/ /gr =~ s/([;,])[ \t]+/$1 /gr =~ s/,[ \t]+/,/gr } inserted($mods, 'X-DKIM2-Info');
    is(scalar @info, 2, 'plain: one X-DKIM2-Info per action (mi-m=1, sign)');
    like($_, qr/^draft=\S+; repo=\S+; date=\d{4}-\d\d-\d\d; sw=dkim2-milter; action=/, 'plain: provenance tags lead') for @info;
    like($_, qr/;\z/, 'plain: the last tag is followed by ";"') for @info;
    like("@info", qr/action=mi-m=1; hc=\d+; hn=\S+;/, 'plain: action=mi-m=1 with hc= and hn=');
    like("@info", qr/action=sign d=test2\.dkim2\.com a=rsa-sha256;/, 'plain: action=sign names d= and a=');
    my $v = verify(assemble($LOCAL, $mods));
    is($v->result, 'pass', 'plain: signed output verifies') or diag($v->result_detail);
}

# --- 1a. No upstream chain, From in another domain: not ours to originate ---
# (-09 section 11): the message goes on unsigned, with no instance of ours.
{
    my ($verdict, $mods) = run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => $PLAIN);
    is($verdict, 'c', 'foreign From: milter continues');
    is(scalar(inserted($mods, 'DKIM2-Signature')), 0, 'foreign From: not signed');
    is(scalar(inserted($mods, 'Message-Instance')), 0, 'foreign From: no Message-Instance');
    like(milter_log(), qr/From header field is not Authentic for d=test2\.dkim2\.com/,
        'foreign From: the refusal is logged');
    like(milter_log(), qr/From domain test1\.dkim2\.com is not d=test2\.dkim2\.com or below it/,
        'foreign From: the log names the From domain and d= (final review I3)');
}

t/milter-script.t  view on Meta::CPAN

    chmod 0700, "$dir/keys/unreadable.test2.dkim2.com";
}

# --- 5. A list's unsigned m=2 with a null body Recipe ---
#
# Built like the case in 2, but the list rewrote the body and said so ("b":
# null). That null is this hop's own, so it is signed (0.29, -09 contract
# E2): the message PERMERRORs downstream, but the header changes are signed.
# The header history below the null is still checked.
sub null_list_post {
    my (%o) = @_;
    my $signed = originator_signed();
    my $mod = $signed;
    $mod =~ s/^Subject: /Subject: [list] /m;
    $mod =~ s/^To: .*$/To: tampered\@example.net/m if $o{forge};
    $mod .= "--$EOL" . "rewritten$EOL";
    my $mi = Mail::DKIM2::MessageInstance->calculate(
        Email::MIME->new($mod), Email::MIME->new($signed));
    $mi->set_null_body_recipe;
    if ($o{forge}) {
        # hide the To change from the header Recipe
        my $rh = $mi->{bits}{rh};
        delete $rh->{$_} for grep { lc($_) eq 'to' } keys %$rh;
    }
    return "Message-Instance: " . $mi->as_string . $EOL . $mod;
}

sub info_values {
    my ($mods) = @_;
    return map { $_->{value} } inserted($mods, 'X-DKIM2-Info');
}

{
    my ($verdict, $mods) = run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => null_list_post());
    is($verdict, 'c', 'own null body: milter continues');
    is(scalar(inserted($mods, 'DKIM2-Signature')), 1, 'own null body: signed') or diag(milter_log());
    like(join("\n", info_values($mods)), qr/action=null-body-recipe/,
        'own null body: X-DKIM2-Info records null-body-recipe');
    is(verify(assemble(null_list_post(), $mods))->result_detail,
       'permerror (PERMERROR: Message-Instance m=2 has a null recipe)',
       'own null body: a receiver gets the -09 PERMERROR');

    # The list also changed To, and its header Recipe hides that: refused
    # by the header-history walk.
    ($verdict, $mods) = run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => null_list_post(forge => 1));
    is(scalar(inserted($mods, 'DKIM2-Signature')), 0, 'forged header history not signed');
}

# --- 5b. The same null m=2, but the list domain signed it (i=2, m=2) ---
# A forwarder (test3) relays the list post unchanged. The null is upstream's
# and fails verification (-09: "has a null recipe"), so the milter refuses:
# 550, since the message carries a DKIM2-Signature.
{
    my $post = null_list_post();
    my $s = Mail::DKIM2::Signer->new(
        Domain => 'test2.dkim2.com', Selector => 'sel1',
        Key => DKIM2TestKeys::private_key('test2.dkim2.com', 'sel1'),
        MailFrom => 'list-bounces@test2.dkim2.com', RcptTo => ['subscriber@test3.dkim2.com'],
        Timestamp => time());
    $s->PRINT($post); $s->CLOSE;
    my $signed_post = $s->as_string . $EOL . $post;

    my ($verdict, $mods) = run_milter(
        from => 'fwd@test3.dkim2.com', rcpt => ['user@example.org'],
        message => $signed_post);
    is($verdict, 'y', 'signed null top: rejected');
    is(scalar(inserted($mods, 'DKIM2-Signature')), 0, 'signed null top: not signed');
    like(reply_of($mods), qr/^550 5\.7\.1 not signing: .*has a null recipe/,
        'signed null top: the reply says why');
}

{
    my ($pid2, $sock2) = spawn_milter(extra => ['--allow-null-body-recipe']);
    ok(-S $sock2, 'deprecated --allow-null-body-recipe: the milter still starts')
        or BAIL_OUT("milter never came up");
    my ($verdict, $mods) = run_milter(sock => $sock2,
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => null_list_post());
    is(scalar(inserted($mods, 'DKIM2-Signature')), 1, 'deprecated option: signed as without it');
    like(milter_log(), qr/--allow-null-body-recipe is deprecated and does nothing/,
        'deprecated option: warned about at startup');
}

# --- 5. nd= bridge: sign when the top nd= names our d=, refuse otherwise ---
{
    my $nd_signed = sub {
        my ($nd) = @_;
        my $mi  = Mail::DKIM2::MessageInstance->calculate(Email::MIME->new($PLAIN));
        my $msg = "Message-Instance: " . $mi->as_string . $EOL . $PLAIN;
        my $signer = Mail::DKIM2::Signer->new(
            Domain => 'test1.dkim2.com', Selector => 'sel1',
            Key => DKIM2TestKeys::private_key('test1.dkim2.com', 'sel1'),
            NextDomain => $nd, Timestamp => time());
        $signer->PRINT($msg); $signer->CLOSE;
        return $signer->as_string . $EOL . $msg;
    };
    my ($verdict, $mods) = run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => $nd_signed->('test2.dkim2.com'));
    my @sig = inserted($mods, 'DKIM2-Signature');
    is(scalar @sig, 1, 'nd=us: signed') or diag(milter_log());
    like($sig[0]{value}, qr/\bi=2;/, 'nd=us: signature is i=2') if @sig;

    ($verdict, $mods) = run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => $nd_signed->('test3.dkim2.com'));
    is(scalar(inserted($mods, 'DKIM2-Signature')), 0, 'nd=other: not signed');
    like(milter_log(), qr/not signing .*top signature nd=test3\.dkim2\.com names another domain/,
        'nd=other: refusal is logged');
}

# --- 6. Malformed Content-Type: parsed quietly, same decision ---
{
    for my $ct ('text/plain; charset=Windows-1252;', 'text/plain; Windows-1252') {
        (my $m = $LOCAL) =~ s/^Content-Type: text\/plain(?=\r)/Content-Type: $ct/m;
        my $before = length milter_log();
        my ($verdict, $mods) = run_milter(
            from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
            message => $m);
        is(scalar(inserted($mods, 'DKIM2-Signature')), 1, "Content-Type '$ct': signed");
        my $new = substr(milter_log(), $before);
        unlike($new, qr/Extra semicolon|Illegal parameter/, "Content-Type '$ct': no Email::MIME warning in log");
    }
}

# --- 7. An out-of-range i= upstream: refused, and the milter survives ---
# i=99999999999999999999 used to kill the Verifier ("Range iterator outside
# integer range") inside cb_eom, and with it the callback. Every i= and m= is
# bounded by MAX_CHAIN_LENGTH now, so it is an ordinary PERMERROR refusal.
{
    my $msg = "DKIM2-Signature: i=99999999999999999999; m=1; d=evil.example$EOL"
            . originator_signed();
    my ($verdict, $mods) = eval { run_milter(
        from => 'list-bounces@test2.dkim2.com', rcpt => ['subscriber@example.org'],
        message => $msg) };
    is($@, '', 'huge i=: the milter answers');
    is($verdict, 'y', 'huge i=: rejected');
    is(scalar(inserted($mods || [], 'DKIM2-Signature')), 0, 'huge i=: not signed');
    like(milter_log(), qr/not signing <post\@test1\.dkim2\.com>: .*exceeds the maximum chain number of 99/,
        'huge i=: refusal is logged with the reason');
}

# --- 8. An exception in the gate or the verifier fails closed ---
# A die inside the verify/sign path must not kill the callback: the milter
# logs a refusal and does not sign. Faults are injected with a -M module.
{
    path("$dir/inject")->mkpath;
    path("$dir/inject/DKIM2TestDieGate.pm")->spew(
        "package DKIM2TestDieGate; require Mail::DKIM2::Gate;\n"
      . "no warnings 'redefine';\n"
      . "*Mail::DKIM2::Gate::check = sub { die \"injected gate fault\\n\" };\n1;\n");
    path("$dir/inject/DKIM2TestDieVerifier.pm")->spew(



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