Mail-DKIM2

 view release on metacpan or  search on metacpan

t/milter.t  view on Meta::CPAN

            push @header_lines, $current if $current ne '';
            $current = $line;
        }
    }
    push @header_lines, $current if $current ne '';

    # Run callbacks, with the envelope the top signature names, as the MTA
    # the message was sent to would see it (-09 section 14.4 checks it).
    my ($top) = sort { $b->sequence <=> $a->sequence }
                map  { Mail::DKIM2::Signature->parse((split /:/, $_, 2)[1]) }
                grep { /^DKIM2-Signature\s*:/i } @header_lines;
    $envelope //= $top ? [ $top->mail_from // '<>', $top->rcpt_to || [] ]
                       : [ '<sender@test1.dkim2.com>', [] ];
    $handler->envfrom_callback($envelope->[0]);
    $handler->envrcpt_callback($_) for @{ $envelope->[1] };

    for my $hline (@header_lines) {
        my ($name, $value) = $hline =~ /^([^\s:]+)\s*:\s*(.*)/s;
        $handler->header_callback($name, $value, $hline);
    }

    $handler->eoh_callback();

    # Now set up the pubkey callback on the verifier object
    my $verifier = $handler->get_object('dkim2_verifier');
    if ($verifier) {
        $verifier->set_pubkey_callback(DKIM2TestKeys::pubkey_callback());
        $verifier->skip_timestamp_check(1);
    }

    # Feed body in chunks
    if (defined $body) {
        my @chunks = ($body =~ /(.{1,256})/gs);
        for my $chunk (@chunks) {
            $handler->body_callback($chunk);
        }
    }

    $handler->eom_callback();

    return $handler;
}

# === Tests ===

diag("=== DKIM2Verify milter tests ===");

# Test 1: Verify a signed message through milter callbacks
{
    # Generate a signed message inline
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    $raw =~ s/\r//gs;
    $raw =~ s/\n/\r\n/gs;
    my $msg = Email::MIME->new($raw);
    my $mi = Mail::DKIM2::MessageInstance->calculate($msg);
    my $mi_str = "Message-Instance: " . $mi->as_string() . "\r\n";
    my $with_mi = $mi_str . $raw;
    my $signer = Mail::DKIM2::Signer->new(
        Domain   => 'test1.dkim2.com',
        Selector => 'rsa1024',
        Key      => DKIM2TestKeys::private_key('test1.dkim2.com', 'rsa1024'),
        MailFrom => 'sender@test1.dkim2.com',
        RcptTo   => ['recipient@test2.dkim2.com'],
    );
    $signer->PRINT($with_mi);
    $signer->CLOSE();
    my $signed_msg = $signer->as_string() . "\r\n" . $with_mi;

    my $handler = run_verify($signed_msg);
    my @auth = @{$handler->{_auth_headers}};
    ok(@auth > 0, "verify signed: auth header added");
    is($auth[0]->{value}, 'pass', "verify signed: result is pass");
}

# Test 2: options left out of the config take their documented defaults.
# The authentication_milter framework never merges default_config() into
# the running config, so the handler applies its own: add_message_instance
# is on unless set to 0.
{
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    $raw =~ s/\r//gs;
    $raw =~ s/\n/\r\n/gs;
    my $signer = Mail::DKIM2::Signer->new(
        Domain   => 'test1.dkim2.com',
        Selector => 'rsa1024',
        Key      => DKIM2TestKeys::private_key('test1.dkim2.com', 'rsa1024'),
        MailFrom => 'sender@test1.dkim2.com',
        RcptTo   => ['recipient@test2.dkim2.com'],
    );
    my $with_mi = "Message-Instance: "
        . Mail::DKIM2::MessageInstance->calculate(Email::MIME->new($raw))->as_string() . "\r\n" . $raw;
    $signer->PRINT($with_mi);
    $signer->CLOSE();
    my $signed_msg = $signer->as_string() . "\r\n" . $with_mi;

    my $snap = tempdir(CLEANUP => 1);
    my $handler = run_verify($signed_msg, _bare => 1, snapshot_directory => $snap);
    is($handler->{_auth_headers}[0]{value}, 'pass', 'defaults: verify passes');
    my $files_in = sub { my @f; File::Find::find(sub { push @f, $File::Find::name if -f }, $_[0]); @f };
    my @stored = $files_in->($snap);
    ok(@stored, 'defaults: add_message_instance defaults on (snapshot stored)');

    # Without a snapshot_directory there is nothing to store, so the handler
    # must not run MessageInstance->verify just to pick a key.
    {
        my $calls = 0;
        no warnings 'redefine';
        my $orig = \&Mail::DKIM2::MessageInstance::verify;
        local *Mail::DKIM2::MessageInstance::verify = sub { $calls++; goto &$orig };
        run_verify($signed_msg, _bare => 1);
        my $without = $calls;
        $calls = 0;
        run_verify($signed_msg, _bare => 1, snapshot_directory => tempdir(CLEANUP => 1));
        is($calls - $without, 1, 'no snapshot_directory: the snapshot-key verify is skipped');
    }

    my $snap0 = tempdir(CLEANUP => 1);
    run_verify($signed_msg, _bare => 1, snapshot_directory => $snap0, add_message_instance => 0);
    my @none = $files_in->($snap0);
    is(scalar @none, 0, 'defaults: an explicit add_message_instance => 0 still wins');

    # The verifier hashes the body as it arrives; the handler keeps a copy
    # only when it has something to build from it: a snapshot to store, or
    # a first Message-Instance to compute.
    my $kept = sub {
        my $h = shift;
        my $v = $h->get_object('dkim2_verifier');
        return (length(join '', @{ $h->{body} || [] }), length($v->{_buf} // ''));
    };
    my ($copy, $buf) = $kept->(run_verify($signed_msg, add_message_instance => 0));
    is($copy, 0, 'add_message_instance off: the handler keeps no body');
    is($buf,  0, 'add_message_instance off: the verifier keeps no body');
    ($copy) = $kept->(run_verify($signed_msg, _bare => 1));
    is($copy, 0, 'an instance present and no snapshot_directory: no body kept');
    ($copy) = $kept->(run_verify($signed_msg, _bare => 1, snapshot_directory => tempdir(CLEANUP => 1)));
    ok($copy > 0, 'a snapshot to store: the body is kept for it');
}

# Test 3: Message with no DKIM2-Signature
{
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    my $handler = run_verify($raw);
    my @auth = @{$handler->{_auth_headers}};
    ok(@auth > 0, "no-sig: auth header added");
    is($auth[0]->{value}, 'none', "no-sig: result is none");
}

diag("=== DKIM2Sign milter tests ===");

# Test 5: Sign a message through milter callbacks
{
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    my ($handler, $mock) = run_sign($raw,
        domains => {
            'test1.dkim2.com' => {
                selector => 'rsa1024',
                key => DKIM2TestKeys::private_key_pem('test1.dkim2.com', 'rsa1024'),
            },
        },
    );

    my @pre = @{$mock->{pre_headers}};
    my @dk2 = grep { $_->{field} eq 'DKIM2-Signature' } @pre;
    ok(@dk2 > 0, "sign: DKIM2-Signature header added");

    # Check the signature has expected structure
    my $sig_value = $dk2[0]->{value};
    like($sig_value, qr/i=1/, "sign: signature has i=1");
    like($sig_value, qr/d=test1\.dkim2\.com/, "sign: signature has correct domain");
    like($sig_value, qr/s=/, "sign: signature has s= tag");

    # Check MI was also added
    my @mi = grep { $_->{field} eq 'Message-Instance' } @pre;
    ok(@mi > 0, "sign: Message-Instance header added");
}

# Test 6: Sign should not fire for unauthenticated senders
{
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    my ($handler, $mock) = run_sign($raw,
        _authenticated => 0,
        _local => 0,
        domains => {
            'test1.dkim2.com' => {
                selector => 'rsa1024',
                key => DKIM2TestKeys::private_key_pem('test1.dkim2.com', 'rsa1024'),
            },
        },
    );

    my @pre = @{$mock->{pre_headers}};
    my @dk2 = grep { $_->{field} eq 'DKIM2-Signature' } @pre;
    is(scalar @dk2, 0, "unauth: no signature added");
}

# Test 7: Sign should not fire when domain has no config
{
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    my ($handler, $mock) = run_sign($raw,
        domains => {},  # no domains configured
    );

    my @pre = @{$mock->{pre_headers}};
    my @dk2 = grep { $_->{field} eq 'DKIM2-Signature' } @pre;
    is(scalar @dk2, 0, "no-config: no signature added");
}

# Test 8: Round-trip: sign then verify
{
    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    my ($sign_handler, $mock) = run_sign($raw,
        domains => {
            'test1.dkim2.com' => {
                selector => 'rsa1024',
                key => DKIM2TestKeys::private_key_pem('test1.dkim2.com', 'rsa1024'),
            },
        },
    );

    # Build the signed message from pre_headers + original
    my @pre = @{$mock->{pre_headers}};
    my $EOL = "\r\n";
    my $signed_msg = '';
    for my $h (reverse @pre) {
        $signed_msg .= "$h->{field}: $h->{value}$EOL";
    }
    $raw =~ s/\r//gs;
    $raw =~ s/\n/\r\n/gs;
    $signed_msg .= $raw;

    # Now verify it
    my $verify_handler = run_verify($signed_msg);
    my @auth = @{$verify_handler->{_auth_headers}};
    ok(@auth > 0, "round-trip: auth header added");
    is($auth[0]->{value}, 'pass', "round-trip: verify passes after sign");
}

# Bounce signing: a Postfix-style null-sender DSN gets origin-signed.
{
    my $raw = join("\r\n",
        'From: Mail Delivery System <MAILER-DAEMON@test1.dkim2.com>',
        'To: sender@origin.example',
        'Subject: Undelivered Mail Returned to Sender',
        'Content-Type: multipart/report; report-type=delivery-status; boundary="B"',
        'MIME-Version: 1.0',
        '',
        '--B',
        'Content-Type: text/plain',
        '',
        'This is the mail system. Delivery permanently failed.',
        '--B',
        'Content-Type: message/delivery-status',
        '',
        'Reporting-MTA: dns; mail.test1.dkim2.com',
        'Action: failed',
        'Status: 5.1.1',
        '--B',
        'Content-Type: message/rfc822',
        '',
        'From: orig@elsewhere.example',
        'Subject: greetings',
        '',
        'hello',
        '--B--',
        '');

    my ($handler, $mock) = run_sign($raw,
        env_from => '<>',
        env_rcpt => '<sender@origin.example>',
        domains  => {
            'test1.dkim2.com' => {
                selector => 'rsa1024',
                key => DKIM2TestKeys::private_key_pem('test1.dkim2.com', 'rsa1024'),
            },
        },
    );

    my @pre = @{$mock->{pre_headers}};
    my @dk2 = grep { $_->{field} eq 'DKIM2-Signature' } @pre;
    ok(@dk2 > 0, "bounce: DKIM2-Signature added for null sender");
    my $sig = $dk2[0]->{value};
    like($sig, qr/i=1/,                  "bounce: i=1");
    like($sig, qr/d=test1\.dkim2\.com/,  "bounce: d= from From: header");
    like($sig, qr/mf=PD4=/,              "bounce: mf=<> (base64 PD4=)");
    my @mi = grep { $_->{field} eq 'Message-Instance' } @pre;
    ok(@mi > 0, "bounce: Message-Instance m=1 added");
    like($mi[0]->{value}, qr/m=1/, "bounce: MI is m=1");
}

# Negative: null sender whose From: domain has no key is left unsigned.
{
    my $raw = join("\r\n",
        'From: Mail Delivery System <MAILER-DAEMON@unknown.example>',
        'To: sender@origin.example',
        'Subject: bounce',
        '', 'x', '');
    my ($handler, $mock) = run_sign($raw,
        env_from => '<>',
        env_rcpt => '<sender@origin.example>',
        domains  => {
            'test1.dkim2.com' => {
                selector => 'rsa1024',
                key => DKIM2TestKeys::private_key_pem('test1.dkim2.com', 'rsa1024'),
            },
        },
    );
    my @dk2 = grep { $_->{field} eq 'DKIM2-Signature' } @{$mock->{pre_headers}};
    is(scalar @dk2, 0, "bounce: unknown From: domain not signed");
}

diag("=== Forwarding flow tests ===");

# These tests simulate a complete inbound→processing→outbound flow through
# a forwarding MTA that uses DKIM2Verify on inbound and DKIM2Sign on outbound.
#
# INBOUND (DKIM2Verify):
#   1. Message arrives with DKIM2-Signature i=1 + Message-Instance v=1
#   2. Verify checks signatures and MI — passes
#   3. Since MI v=1 already matches content, no new MI is added
#   4. The message is stored as a snapshot, keyed by the MI v=1 value
#
# LOCAL PROCESSING:
#   The MTA may modify the message (add headers, rewrite body, etc.)
#   It may or may not add its own Message-Instance header.
#
# OUTBOUND (DKIM2Sign):
#   1. Sign reconstructs the message from headers+body seen in callbacks
#   2. If add_message_instance is on, checks if topmost MI matches content
#   3. If MI matches → no new MI needed (Case 1 and 3)
#      If MI doesn't match → looks up snapshot for any MI, computes diff
#      MI v=2 with Recipes (Case 2)
#   4. Creates DKIM2-Signature i=2

# Helper: create a signed originator message for forwarding tests
sub make_originator_message {
    use Mail::DKIM2::Signer;
    use Mail::DKIM2::MessageInstance;

    my $raw = path("tests/emails/brong-orig.eml")->slurp;
    $raw =~ s/\r//gs;
    $raw =~ s/\n/\r\n/gs;

    # Calculate MI v=1
    my $msg = Email::MIME->new($raw);
    my $mi = Mail::DKIM2::MessageInstance->calculate($msg);
    my $mi_str = "Message-Instance: " . $mi->as_string() . "\r\n";

    # Prepend MI to message, then sign
    my $with_mi = $mi_str . $raw;
    my $signer = Mail::DKIM2::Signer->new(
        Domain    => 'test1.dkim2.com',
        Selector  => 'rsa1024',
        Key       => DKIM2TestKeys::private_key('test1.dkim2.com', 'rsa1024'),
        MailFrom  => 'sender@test1.dkim2.com',
        RcptTo    => ['foo@test2.dkim2.com'],
        Timestamp => 1740000000,
    );
    $signer->PRINT($with_mi);
    $signer->CLOSE();

    my $result = $signer->as_string() . "\r\n" . $with_mi;

    # Write the originator message for interop testing
    path("tests/expected")->child("milter-originator.eml")->spew($result);

    return $result;
}

# Helper: run the full inbound verify with snapshot storage
sub run_inbound_verify {
    my ($raw, $snapshot_dir) = @_;
    return run_verify($raw,
        add_message_instance => 1,
        snapshot_directory   => $snapshot_dir,
    );
}

# Helper: run the full outbound sign with snapshot lookup
sub run_outbound_sign {
    my ($raw, $snapshot_dir, %extra) = @_;
    my ($handler, $mock) = run_sign($raw,
        domains => {
            'test2.dkim2.com' => {
                selector => 'rsa1024',
                key => DKIM2TestKeys::private_key_pem('test2.dkim2.com', 'rsa1024'),
            },
        },
        add_message_instance => 1,
        snapshot_directory   => $snapshot_dir,
        _authenticated       => 0,
        _local               => 1,
        %extra,
    );
    # Override env_from for the forwarding domain
    $handler->{'env_from'} = '<forwarder@test2.dkim2.com>';
    # Re-run addheader with corrected env_from
    $mock = { pre_headers => [], add_headers => [] };
    $handler->{_changed_headers} = [];
    $handler->addheader_callback($mock);
    # Header changes go through the framework's change_header(), not the
    # mock handler object.
    $mock->{changed_headers} = $handler->{_changed_headers};
    return ($handler, $mock);
}

# The X-DKIM2-Snapshot token DKIM2Verify put on a message, and the message
# with it on top (as the MTA would hand it to the signing instance).
sub snapshot_token {
    my ($verify_handler) = @_;
    my ($t) = map { $_->{value} } grep { $_->{field} eq 'X-DKIM2-Snapshot' }
              @{$verify_handler->{_prepended}};
    return $t;
}
sub with_token {
    my ($raw, $verify_handler) = @_;
    my $t = snapshot_token($verify_handler) // die 'no X-DKIM2-Snapshot token';
    $raw =~ s/\r//gs;
    $raw =~ s/\n/\r\n/gs;
    return "X-DKIM2-Snapshot: $t\r\n" . $raw;
}

# Helper: assemble the final outbound message from sign mock output.
# pre_headers are prepended (in reverse, as milters do) to the message
# that was fed to the signer.
sub assemble_outbound {
    my ($input_msg, $mock) = @_;
    my $EOL = "\r\n";
    my $result = '';
    for my $h (reverse @{$mock->{pre_headers}}) {
        my $val = $h->{value};
        $val =~ s/\r?\n/\r\n/gs;
        $result .= "$h->{field}: $val$EOL";
    }
    $input_msg =~ s/\r//gs;
    $input_msg =~ s/\n/\r\n/gs;
    # Apply the header changes the handler asked the framework for (e.g.
    # deleting stripped broken MI headers), in order, as the MTA does: an
    # empty value deletes the index'th field of that name (1-based).
    for my $c (@{$mock->{changed_headers} // []}) {
        my ($hdr, $body) = split /\r\n\r\n/, $input_msg, 2;
        my @fields;
        for my $line (split /\r\n/, $hdr) {
            if ($line =~ /^[ \t]/ && @fields) { $fields[-1] .= "\r\n$line" }
            else                               { push @fields, $line }
        }



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