summaryrefslogtreecommitdiffstats
path: root/ipatests/test_ipaclient/test_csrgen.py
blob: 556f8e096976387d24057084c06d53bcb9998a69 (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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#
# Copyright (C) 2016  FreeIPA Contributors see COPYING for license
#

import os
import pytest

from ipaclient import csrgen
from ipalib import errors

BASE_DIR = os.path.dirname(__file__)
CSR_DATA_DIR = os.path.join(BASE_DIR, 'data', 'test_csrgen')


@pytest.fixture
def formatter():
    return csrgen.Formatter(csr_data_dir=CSR_DATA_DIR)


@pytest.fixture
def rule_provider():
    return csrgen.FileRuleProvider(csr_data_dir=CSR_DATA_DIR)


@pytest.fixture
def generator():
    return csrgen.CSRGenerator(csrgen.FileRuleProvider())


class StubRuleProvider(csrgen.RuleProvider):
    def __init__(self):
        self.syntax_rule = csrgen.Rule(
            'syntax', '{{datarules|join(",")}}', {})
        self.data_rule = csrgen.Rule('data', 'data_template', {})
        self.field_mapping = csrgen.FieldMapping(
            'example', self.syntax_rule, [self.data_rule])
        self.rules = [self.field_mapping]

    def rules_for_profile(self, profile_id, helper):
        return self.rules


class IdentityFormatter(csrgen.Formatter):
    base_template_name = 'identity_base.tmpl'

    def __init__(self):
        super(IdentityFormatter, self).__init__(csr_data_dir=CSR_DATA_DIR)

    def _get_template_params(self, syntax_rules):
        return {'options': syntax_rules}


class IdentityCSRGenerator(csrgen.CSRGenerator):
    FORMATTERS = {'identity': IdentityFormatter}


class test_Formatter(object):
    def test_prepare_data_rule_with_data_source(self, formatter):
        data_rule = csrgen.Rule('uid', '{{subject.uid.0}}',
                                {'data_source': 'subject.uid.0'})
        prepared = formatter._prepare_data_rule(data_rule)
        assert prepared == '{% if subject.uid.0 %}{{subject.uid.0}}{% endif %}'

    def test_prepare_data_rule_no_data_source(self, formatter):
        """Not a normal case, but we should handle it anyway"""
        data_rule = csrgen.Rule('uid', 'static_text', {})
        prepared = formatter._prepare_data_rule(data_rule)
        assert prepared == 'static_text'

    def test_prepare_syntax_rule_with_data_sources(self, formatter):
        syntax_rule = csrgen.Rule(
            'example', '{{datarules|join(",")}}', {})
        data_rules = ['{{subject.field1}}', '{{subject.field2}}']
        data_sources = ['subject.field1', 'subject.field2']
        prepared = formatter._prepare_syntax_rule(
            syntax_rule, data_rules, 'example', data_sources)

        assert prepared == (
            '{% if subject.field1 or subject.field2 %}{{subject.field1}},'
            '{{subject.field2}}{% endif %}')

    def test_prepare_syntax_rule_with_combinator(self, formatter):
        syntax_rule = csrgen.Rule('example', '{{datarules|join(",")}}',
                                  {'data_source_combinator': 'and'})
        data_rules = ['{{subject.field1}}', '{{subject.field2}}']
        data_sources = ['subject.field1', 'subject.field2']
        prepared = formatter._prepare_syntax_rule(
            syntax_rule, data_rules, 'example', data_sources)

        assert prepared == (
            '{% if subject.field1 and subject.field2 %}{{subject.field1}},'
            '{{subject.field2}}{% endif %}')

    def test_prepare_syntax_rule_required(self, formatter):
        syntax_rule = csrgen.Rule('example', '{{datarules|join(",")}}',
                                  {'required': True})
        data_rules = ['{{subject.field1}}']
        data_sources = ['subject.field1']
        prepared = formatter._prepare_syntax_rule(
            syntax_rule, data_rules, 'example', data_sources)

        assert prepared == (
            '{% filter required("example") %}{% if subject.field1 %}'
            '{{subject.field1}}{% endif %}{% endfilter %}')

    def test_prepare_syntax_rule_passthrough(self, formatter):
        """
        Calls to macros defined as passthrough are still call tags in the final
        template.
        """
        formatter._define_passthrough('example.macro')

        syntax_rule = csrgen.Rule(
            'example',
            '{% call example.macro() %}{{datarules|join(",")}}{% endcall %}',
            {})
        data_rules = ['{{subject.field1}}']
        data_sources = ['subject.field1']
        prepared = formatter._prepare_syntax_rule(
            syntax_rule, data_rules, 'example', data_sources)

        assert prepared == (
            '{% if subject.field1 %}{% call example.macro() %}'
            '{{subject.field1}}{% endcall %}{% endif %}')

    def test_prepare_syntax_rule_no_data_sources(self, formatter):
        """Not a normal case, but we should handle it anyway"""
        syntax_rule = csrgen.Rule(
            'example', '{{datarules|join(",")}}', {})
        data_rules = ['rule1', 'rule2']
        data_sources = []
        prepared = formatter._prepare_syntax_rule(
            syntax_rule, data_rules, 'example', data_sources)

        assert prepared == 'rule1,rule2'


class test_FileRuleProvider(object):
    def test_rule_basic(self, rule_provider):
        rule_name = 'basic'

        rule1 = rule_provider._rule(rule_name, 'openssl')
        rule2 = rule_provider._rule(rule_name, 'certutil')

        assert rule1.template == 'openssl_rule'
        assert rule2.template == 'certutil_rule'

    def test_rule_global_options(self, rule_provider):
        rule_name = 'options'

        rule1 = rule_provider._rule(rule_name, 'openssl')
        rule2 = rule_provider._rule(rule_name, 'certutil')

        assert rule1.options['global_option'] is True
        assert rule2.options['global_option'] is True

    def test_rule_helper_options(self, rule_provider):
        rule_name = 'options'

        rule1 = rule_provider._rule(rule_name, 'openssl')
        rule2 = rule_provider._rule(rule_name, 'certutil')

        assert rule1.options['helper_option'] is True
        assert 'helper_option' not in rule2.options

    def test_rule_nosuchrule(self, rule_provider):
        with pytest.raises(errors.NotFound):
            rule_provider._rule('nosuchrule', 'openssl')

    def test_rule_nosuchhelper(self, rule_provider):
        with pytest.raises(errors.EmptyResult):
            rule_provider._rule('basic', 'nosuchhelper')

    def test_rules_for_profile_success(self, rule_provider):
        rules = rule_provider.rules_for_profile('profile', 'certutil')

        assert len(rules) == 1
        field_mapping = rules[0]
        assert field_mapping.syntax_rule.name == 'basic'
        assert len(field_mapping.data_rules) == 1
        assert field_mapping.data_rules[0].name == 'options'

    def test_rules_for_profile_nosuchprofile(self, rule_provider):
        with pytest.raises(errors.NotFound):
            rule_provider.rules_for_profile('nosuchprofile', 'certutil')


class test_CSRGenerator(object):
    def test_userCert_OpenSSL(self, generator):
        principal = {
            'uid': ['testuser'],
            'mail': ['testuser@example.com'],
        }
        config = {
            'ipacertificatesubjectbase': [
                'O=DOMAIN.EXAMPLE.COM'
            ],
        }

        script = generator.csr_script(principal, config, 'userCert', 'openssl')
        with open(os.path.join(
                CSR_DATA_DIR, 'scripts', 'userCert_openssl.sh')) as f:
            expected_script = f.read()
        assert script == expected_script

    def test_userCert_Certutil(self, generator):
        principal = {
            'uid': ['testuser'],
            'mail': ['testuser@example.com'],
        }
        config = {
            'ipacertificatesubjectbase': [
                'O=DOMAIN.EXAMPLE.COM'
            ],
        }

        script = generator.csr_script(
            principal, config, 'userCert', 'certutil')

        with open(os.path.join(
                CSR_DATA_DIR, 'scripts', 'userCert_certutil.sh')) as f:
            expected_script = f.read()
        assert script == expected_script

    def test_caIPAserviceCert_OpenSSL(self, generator):
        principal = {
            'krbprincipalname': [
                'HTTP/machine.example.com@DOMAIN.EXAMPLE.COM'
            ],
        }
        config = {
            'ipacertificatesubjectbase': [
                'O=DOMAIN.EXAMPLE.COM'
            ],
        }

        script = generator.csr_script(
            principal, config, 'caIPAserviceCert', 'openssl')
        with open(os.path.join(
                CSR_DATA_DIR, 'scripts', 'caIPAserviceCert_openssl.sh')) as f:
            expected_script = f.read()
        assert script == expected_script

    def test_caIPAserviceCert_Certutil(self, generator):
        principal = {
            'krbprincipalname': [
                'HTTP/machine.example.com@DOMAIN.EXAMPLE.COM'
            ],
        }
        config = {
            'ipacertificatesubjectbase': [
                'O=DOMAIN.EXAMPLE.COM'
            ],
        }

        script = generator.csr_script(
            principal, config, 'caIPAserviceCert', 'certutil')
        with open(os.path.join(
                CSR_DATA_DIR, 'scripts', 'caIPAserviceCert_certutil.sh')) as f:
            expected_script = f.read()
        assert script == expected_script


class test_rule_handling(object):
    def test_optionalAttributeMissing(self, generator):
        principal = {'uid': 'testuser'}
        rule_provider = StubRuleProvider()
        rule_provider.data_rule.template = '{{subject.mail}}'
        rule_provider.data_rule.options = {'data_source': 'subject.mail'}
        generator = IdentityCSRGenerator(rule_provider)

        script = generator.csr_script(
            principal, {}, 'example', 'identity')
        assert script == '\n'

    def test_twoDataRulesOneMissing(self, generator):
        principal = {'uid': 'testuser'}
        rule_provider = StubRuleProvider()
        rule_provider.data_rule.template = '{{subject.mail}}'
        rule_provider.data_rule.options = {'data_source': 'subject.mail'}
        rule_provider.field_mapping.data_rules.append(csrgen.Rule(
            'data2', '{{subject.uid}}', {'data_source': 'subject.uid'}))
        generator = IdentityCSRGenerator(rule_provider)

        script = generator.csr_script(principal, {}, 'example', 'identity')
        assert script == ',testuser\n'

    def test_requiredAttributeMissing(self):
        principal = {'uid': 'testuser'}
        rule_provider = StubRuleProvider()
        rule_provider.data_rule.template = '{{subject.mail}}'
        rule_provider.data_rule.options = {'data_source': 'subject.mail'}
        rule_provider.syntax_rule.options = {'required': True}
        generator = IdentityCSRGenerator(rule_provider)

        with pytest.raises(errors.CSRTemplateError):
            _script = generator.csr_script(
                principal, {}, 'example', 'identity')