summaryrefslogtreecommitdiff
path: root/src/mailman/rules/tests/test_dmarc.py
blob: 640dd5cdae0254774f565647c1efee82193afdd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# Copyright (C) 2016 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman.  If not, see <http://www.gnu.org/licenses/>.

"""Provides support for mocking dnspython calls from dmarc rules and some
organizational domain tests."""

from contextlib import ExitStack
from dns.exception import DNSException
from dns.rdatatype import TXT
from dns.resolver import NXDOMAIN, NoAnswer
from mailman.app.lifecycle import create_list
from mailman.interfaces.mailinglist import DMARCMitigateAction
from mailman.rules import dmarc
from mailman.testing.helpers import (
    LogFileMark, specialized_message_from_string as mfs)
from mailman.testing.layers import ConfigLayer
from mailman.utilities.protocols import get as _get
from pkg_resources import resource_filename
from public import public
from unittest import TestCase
from unittest.mock import patch
from urllib.error import URLError


@public
def get_dns_resolver():
    """Create a dns.resolver.Resolver mock.

    This is used to return a predictable response to a _dmarc query.  It
    returns p=reject for the example.biz domain and raises an exception for
    other examples.

    It only implements those classes and attributes used by the dmarc rule.
    """
    class Name:
        # mock answer.name
        def __init__(self):
            pass

        def to_text(self):
            return '_dmarc.example.biz.'

    class Item:
        # mock answer.items
        def __init__(self):
            self.strings = [b'v=DMARC1; p=reject;']

    class Ans_e:
        # mock answer element
        def __init__(self):
            self.rdtype = TXT
            self.items = [Item()]
            self.name = Name()

    class Answer:
        # mock answer
        def __init__(self):
            self.answer = [Ans_e()]

    class Resolver:
        # mock dns.resolver.Resolver class.
        def __init__(self):
            pass

        def query(self, domain, data_type):
            if data_type != TXT:
                raise NoAnswer
            dparts = domain.split('.')
            if len(dparts) < 3:
                raise NXDOMAIN
            if len(dparts) > 3:
                raise NoAnswer
            if dparts[0] != '_dmarc':
                raise NoAnswer
            if dparts[2] == 'info':
                raise DNSException('no internet')
            if dparts[1] != 'example' or dparts[2] != 'biz':
                raise NXDOMAIN
            self.response = Answer()
            return self
    patcher = patch('dns.resolver.Resolver', Resolver)
    return patcher


@public
def get_org_data():
    """Create a mock to load the organizational domain data from our local
    test data.
    """
    def ourget(url):
        datapath = resource_filename(
            'mailman.rules.tests.data', 'org_domain.txt')
        org_data_url = 'file:///{}'.format(datapath)
        return _get(org_data_url)
    return patch('mailman.rules.dmarc.protocols.get', ourget)


class TestDMARCRules(TestCase):
    """Test organizational domain determination."""

    layer = ConfigLayer

    def setUp(self):
        self.resources = ExitStack()
        self.addCleanup(self.resources.close)
        # Make sure every test has a clean cache.
        self.cache = {}
        self.resources.enter_context(
            patch('mailman.rules.dmarc.s_dict', self.cache))

    def test_no_url(self):
        dmarc._get_suffixes(None)
        self.assertEqual(len(self.cache), 0)

    def test_no_data_for_domain(self):
        with get_org_data():
            self.assertEqual(
                dmarc._get_org_dom('sub.dom.example.nxtld'),
                'example.nxtld')

    def test_domain_with_wild_card(self):
        with get_org_data():
            self.assertEqual(
                dmarc._get_org_dom('ssub.sub.foo.kobe.jp'),
                'sub.foo.kobe.jp')

    def test_exception_to_wild_card(self):
        with get_org_data():
            self.assertEqual(
                dmarc._get_org_dom('ssub.sub.city.kobe.jp'),
                'city.kobe.jp')

    def test_no_publicsuffix_dot_org(self):
        mark = LogFileMark('mailman.error')
        with patch('mailman.rules.dmarc.protocols.get',
                   side_effect=URLError('no internet')):
            domain = dmarc._get_org_dom('ssub.sub.city.kobe.jp')
        line = mark.readline()
        self.assertEqual(
            line[-95:],
            'Unable to retrieve data from '
            'https://publicsuffix.org/list/public_suffix_list.dat: '
            'no internet\n')
        self.assertEqual(domain, 'kobe.jp')

    def test_no_at_sign_in_from_address(self):
        # If there's no @ sign in the From: address, the rule can't hit.
        mlist = create_list('ant@example.com')
        # Use action reject.  The rule only hits on reject and discard.
        mlist.dmarc_mitigate_action = DMARCMitigateAction.reject
        msg = mfs("""\
From: anne
To: ant@example.com

""")
        rule = dmarc.DMARCMitigation()
        with get_dns_resolver():
            self.assertFalse(rule.check(mlist, msg, {}))

    def test_dmarc_dns_exception(self):
        mlist = create_list('ant@example.com')
        # Use action reject.  The rule only hits on reject and discard.
        mlist.dmarc_mitigate_action = DMARCMitigateAction.reject
        msg = mfs("""\
From: anne@example.info
To: ant@example.com

""")
        mark = LogFileMark('mailman.error')
        rule = dmarc.DMARCMitigation()
        with get_dns_resolver(), get_org_data():
            self.assertFalse(rule.check(mlist, msg, {}))
        line = mark.readline()
        self.assertEqual(
            line[-144:],
            'DNSException: Unable to query DMARC policy for '
            'anne@example.info (_dmarc.example.info). '
            'Abstract base class shared by all dnspython exceptions.\n')