Debian Codegraph @

ansible_collections/community/postgresql/tests/unit/plugins/modules/test_postgresql_pg_hba.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 import copy
11 import sys
12 import pytest
13
14
15 if sys.version_info[0] == 3:
16 from plugins.modules.postgresql_pg_hba import tokenize, TokenizerException, handle_address_field, \
17 handle_netmask_field, handle_db_and_user_strings, PgHbaRuleValueError, PgHbaValueError, parse_auth_options, \
18 parse_hba_file, PgHbaRuleError, PgHbaRule, from_rule_list, PG_HBA_HDR_MAP, search_rule, update_rules, \
19 sort_rules, render_rule_list, rule_list_to_dict_list, rule_list_from_hba_file
20 elif sys.version_info[0] == 2:
21 from ansible_collections.community.postgresql.plugins.modules.postgresql_pg_hba import tokenize, \
22 TokenizerException, handle_address_field, handle_netmask_field, handle_db_and_user_strings, \
23 PgHbaRuleValueError, PgHbaValueError, parse_auth_options, parse_hba_file, PgHbaRuleError, PgHbaRule, \
24 from_rule_list, PG_HBA_HDR_MAP, search_rule, update_rules, sort_rules, render_rule_list, \
25 rule_list_to_dict_list, rule_list_from_hba_file
26
27 VALID_PG_HBA = \
28 r'''local all all trust
29 host all all 127.0.0.1/32 trust
30 host all all 127.0.0.1 255.255.255.255 trust
31 host all all ::1/128 trust
32 host all all fe80:: ffff:: md5
33 host all all localhost trust
34 host "/^db\d{2,4}$" all localhost trust
35 host postgres all 192.168.93.0/24 ident
36 host postgres all 192.168.12.10/32 scram-sha-256
37 host all mike .example.com md5
38 host all all .example.com scram-sha-256
39 host all all 192.168.54.1/32 reject
40 hostgssenc all all 0.0.0.0/0 gss
41 host all all 192.168.12.10/32 gss
42 host all all 192.168.0.0/16 ident map=omicron
43 local sameuser all md5
44 local all /^.*helpdesk$ md5
45 local all @admins md5
46 local all +support md5
47 local all @admins,+support md5
48 local db1,db2,@demodbs all md5
49 host all all 0.0.0.0/0 radius radiusservers="server1,server2" radiussecrets="""secret one"",""secret two"""
50 host all all 10.0.0.0 255.0.0.0 radius radiusservers="server1,server2" radiussecrets="""secret one"",""secret two"""'''
51
52 VALID_RULE_DICTS = [
53 {'contype': 'local', 'databases': 'all', 'users': 'all', 'method': 'trust'},
54 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'trust', 'address': '127.0.0.1/32'},
55 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'trust', 'address': '127.0.0.1/32'},
56 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'trust', 'address': '::1/128'},
57 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'md5', 'address': 'fe80::/16'},
58 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'trust', 'address': 'localhost'},
59 {'contype': 'host', 'databases': '"/^db\\d{2,4}$"', 'users': 'all', 'method': 'trust', 'address': 'localhost'},
60 {'contype': 'host', 'databases': 'postgres', 'users': 'all', 'method': 'ident', 'address': '192.168.93.0/24'},
61 {'contype': 'host', 'databases': 'postgres', 'users': 'all', 'method': 'scram-sha-256',
62 'address': '192.168.12.10/32'},
63 {'contype': 'host', 'databases': 'all', 'users': 'mike', 'method': 'md5', 'address': '.example.com'},
64 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'scram-sha-256', 'address': '.example.com'},
65 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'reject', 'address': '192.168.54.1/32'},
66 {'contype': 'hostgssenc', 'databases': 'all', 'users': 'all', 'method': 'gss', 'address': '0.0.0.0/0'},
67 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'gss', 'address': '192.168.12.10/32'},
68 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'ident', 'address': '192.168.0.0/16',
69 'options': 'map=omicron'},
70 {'contype': 'local', 'databases': 'sameuser', 'users': 'all', 'method': 'md5'},
71 {'contype': 'local', 'databases': 'all', 'users': '/^.*helpdesk$', 'method': 'md5'},
72 {'contype': 'local', 'databases': 'all', 'users': '@admins', 'method': 'md5'},
73 {'contype': 'local', 'databases': 'all', 'users': '+support', 'method': 'md5'},
74 {'contype': 'local', 'databases': 'all', 'users': '+support,@admins', 'method': 'md5'},
75 {'contype': 'local', 'databases': '@demodbs,db1,db2', 'users': 'all', 'method': 'md5'},
76 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'radius', 'address': '0.0.0.0/0',
77 'options': 'radiussecrets="""secret one"",""secret two""" radiusservers="server1,server2"'},
78 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'radius', 'address': '10.0.0.0/8',
79 'options': 'radiussecrets="""secret one"",""secret two""" radiusservers="server1,server2"'},
80 ]
81
82 PG_HBA_REQUIRED_FIELDS = ['contype', 'databases', 'users', 'method']
83
84
85 def test_tokenize():
86 assert tokenize('one two three') == ["one", "two", "three"]
87 assert tokenize(' one two three ') == ["one", "two", "three"]
88 assert tokenize(' "one two" "three" ') == ['"one two"', '"three"']
89 assert tokenize('"one" two three') == ['"one"', 'two', 'three']
90 assert tokenize('"one two" three') == ['"one two"', "three"]
91 assert tokenize('one="two three" four') == ['one="two three"', "four"]
92 assert tokenize('"one two"') == ['"one two"']
93 assert tokenize('"one"') == ['"one"']
94 assert tokenize('one two # three four') == ['one', 'two', '# three four']
95 assert tokenize('one\ttwo\t#\tthree\tfour') == ['one', 'two', '#\tthree\tfour']
96 assert tokenize('one two# three four') == ['one', 'two', '# three four']
97 assert tokenize('one two#three four') == ['one', 'two', '#three four']
98 assert tokenize('one "two # three" four # five six') == ['one', '"two # three"', 'four', "# five six"]
99 assert tokenize('# one two') == ['# one two']
100 assert tokenize(' # one two') == ['# one two']
101 assert tokenize('one # two "three four" five') == ['one', '# two "three four" five']
102 assert tokenize('one # two "three four" five # six seven') == ['one', '# two "three four" five # six seven']
103 assert tokenize('one ##two') == ['one', "##two"]
104 with pytest.raises(TokenizerException, match="Unterminated quote"):
105 tokenize('one="two three four')
106 with pytest.raises(TokenizerException, match="Unterminated quote"):
107 tokenize('one two"')
108
109
110 def test_rule_creation():
111 """Test creating rules from a string and from dicts"""
112 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
113 # if you still run 2.7, that is your problem
114 try:
115 import ipaddress
116 except ImportError:
117 return
118 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
119 rules_from_str = []
120 for rule in rule_list_from_hba_file(VALID_PG_HBA):
121 rules_from_str.append(rule)
122 rules_from_dict = from_rule_list(VALID_RULE_DICTS)
123 assert len(rules_from_dict) == len(rules_from_str)
124 for i in range(0, len(rules_from_dict)):
125 assert rules_from_str[i].is_identical(rules_from_dict[i])
126
127
128 def test_rule_validations_from_tokens():
129 """Test if rules are correctly validated when created from a list of tokens"""
130 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
131 # if you still run 2.7, that is your problem
132 try:
133 import ipaddress
134 except ImportError:
135 return
136 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
137 with pytest.raises(PgHbaRuleError, match="The rule has too few symbols"):
138 PgHbaRule(tokens=["only", "three", "tokens"])
139 with pytest.raises(PgHbaRuleValueError, match="Found an unknown connection-type notype"):
140 PgHbaRule(tokens=["notype", "two", "three", "four"])
141 with pytest.raises(PgHbaRuleError,
142 match="The rule either needs a hostname, full CIDR or an IP-address and a netmask"):
143 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89", "md5"])
144 with pytest.raises(PgHbaRuleError,
145 match="The rule either needs a hostname, full CIDR or an IP-address and a netmask"):
146 PgHbaRule(tokens=["host", "all", "all", "1234:ffff::", "md5"])
147 with pytest.raises(PgHbaRuleError,
148 match="The rule either needs a hostname, full CIDR or an IP-address and a netmask"):
149 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89", "255.255.255.255/32", "md5"])
150 with pytest.raises(PgHbaValueError, match=".* is neither a valid IP address, network, hostname or keyword"):
151 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89/64", "md5"])
152 with pytest.raises(PgHbaRuleError, match="The rule has too few symbols"):
153 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89", "255.255.255.255"])
154 with pytest.raises(PgHbaRuleError, match="The rule has too few symbols"):
155 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89/32"])
156 with pytest.raises(PgHbaRuleValueError, match="Found an unknown method: nomethod"):
157 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89/32", "nomethod"])
158 with pytest.raises(PgHbaRuleValueError,
159 match="Found invalid option 'someopt'. Options need to be in the format 'key=value'"):
160 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89/32", "md5", "someopt"])
161 with pytest.raises(PgHbaRuleValueError, match="The rule contains two options with the same key.*"):
162 PgHbaRule(tokens=["host", "all", "all", "123.45.67.89/32", "md5", "key=v", "key=w"])
163 with pytest.raises(PgHbaRuleError, match="Can't mix IPv4 and IPv6 netmasks and addresses"):
164 PgHbaRule(tokens=["host", "all", "all", "1.2.3.4", "ffff:ffff::", "md5"])
165 with pytest.raises(PgHbaRuleError, match="Can't mix IPv4 and IPv6 netmasks and addresses"):
166 PgHbaRule(tokens=["host", "all", "all", "1234:ffff:abcf::", "255.255.255.0", "md5"])
167 with pytest.raises(PgHbaRuleError,
168 match="The rule either needs a hostname, full CIDR or an IP-address and a netmask"):
169 PgHbaRule(tokens=["host", "all", "all", "1234:ffff::", "ffff::/100", "md5"])
170 with pytest.raises(PgHbaValueError, match=".* is neither a valid IP address, network, hostname or keyword"):
171 PgHbaRule(tokens=["host", "all", "all", "::/256", "md5"])
172
173
174 def test_rule_validation_from_dict():
175 """Test if rules are correctly validated when created from a dict"""
176 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
177 # if you still run 2.7, that is your problem
178 try:
179 import ipaddress
180 except ImportError:
181 return
182 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
183 base_dict = {'contype': 'local', 'databases': 'all', 'users': 'all', 'method': 'ident'}
184 for field in PG_HBA_REQUIRED_FIELDS:
185 d = copy.copy(base_dict)
186 del d[field]
187 with pytest.raises(PgHbaRuleError, match="All rules need to contain .*"):
188 PgHbaRule(rule_dict=d)
189 d = copy.copy(base_dict)
190 d['contype'] = 'notype'
191 with pytest.raises(PgHbaRuleValueError, match="Unknown type notype"):
192 PgHbaRule(rule_dict=d)
193 d = copy.copy(base_dict)
194 d['method'] = 'nomethod'
195 with pytest.raises(PgHbaRuleValueError, match="Unknown method nomethod"):
196 PgHbaRule(rule_dict=d)
197
198 d = copy.copy(base_dict)
199 d['address'] = '127.0.0.1/32'
200 assert not PgHbaRule(rule_dict=d).address
201
202 d = copy.copy(base_dict)
203 d['netmask'] = '255.255.255.255'
204 assert not PgHbaRule(rule_dict=d).netmask
205
206 d = copy.copy(base_dict)
207 d['address'] = '127.0.0.1/32'
208 d['address'] = '255.255.255.255'
209 rule = PgHbaRule(rule_dict=d)
210 assert (not rule.address) and (not rule.netmask)
211
212 base_dict['contype'] = 'host'
213 with pytest.raises(PgHbaRuleError, match="If the contype isn't 'local', the rule needs to contain an address"):
214 PgHbaRule(rule_dict=base_dict)
215 base_dict['address'] = "127.0.0.1/32"
216 base_dict['netmask'] = '255.255.255.255'
217 with pytest.raises(PgHbaRuleError, match="Rule can't contain a netmask if address is a full CIDR or hostname"):
218 PgHbaRule(rule_dict=base_dict)
219 base_dict['address'] = "db.example.com"
220 with pytest.raises(PgHbaRuleError, match="Rule can't contain a netmask if address is a full CIDR or hostname"):
221 PgHbaRule(rule_dict=base_dict)
222 base_dict['address'] = "127.0.0.1"
223 base_dict['netmask'] = '255.255.255.255/32'
224 with pytest.raises(PgHbaValueError, match=".* is not a valid netmask"):
225 PgHbaRule(rule_dict=base_dict)
226 base_dict['netmask'] = 'lalala'
227 with pytest.raises(PgHbaValueError, match=".* is not a valid netmask"):
228 PgHbaRule(rule_dict=base_dict)
229 del base_dict["netmask"]
230 with pytest.raises(PgHbaRuleError, match="If the address is a bare ip-address without a CIDR suffix, "
231 "the rule needs to contain a netmask"):
232 PgHbaRule(rule_dict=base_dict)
233 base_dict['address'] = "127.0.0.1/32"
234 base_dict['netmask'] = ""
235 PgHbaRule(rule_dict=base_dict)
236
237
238 def test_rule_is_identical():
239 """Test if Rule.is_identical works correctly"""
240 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
241 # if you still run 2.7, that is your problem
242 try:
243 import ipaddress
244 except ImportError:
245 return
246 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
247 rdict1 = {'contype': 'local',
248 'databases': 'all',
249 'users': 'all',
250 'method': 'ident',
251 'options': {'key1': 'value1', 'key2': 'value2'}}
252 rdict1_1 = copy.deepcopy(rdict1)
253 rdict1_1['comment'] = "# some comment"
254 r1 = PgHbaRule(rule_dict=rdict1)
255 r2 = PgHbaRule(rule_dict=rdict1_1)
256
257 assert r1.is_identical(r1) # a rule should be identical to itself
258 assert r1.is_identical(r2) # a comment doesn't change being identical
259 assert r2.is_identical(r1) # it should work both ways
260 rdict1_1['options']['key1'] = "other_value"
261 r2 = PgHbaRule(rule_dict=rdict1_1)
262 assert not r1.is_identical(r2) # we changed an option -> not identical anymore
263 rdict1_1['options']['key1'] = "value1"
264 r2 = PgHbaRule(rule_dict=rdict1_1)
265 assert r1.is_identical(r2) # we changed it back -> identical again
266
267 r3 = PgHbaRule(tokens=["host", "all", "all", "10.0.0.0/8", "md5"])
268 r4 = PgHbaRule(tokens=["host", "all", "all", "10.0.0.0", "255.0.0.0", "md5"])
269 assert r3.is_identical(r4)
270 assert r3.is_identical(r3)
271 assert r4.is_identical(r4)
272 r5 = PgHbaRule(tokens=["host", "all", "all", "10.0.0.0/16", "md5"])
273 r6 = PgHbaRule(tokens=["host", "all", "all", "10.0.0.0", "255.255.0.0", "md5"])
274 assert not r5.is_identical(r3)
275 assert not r6.is_identical(r4)
276 r7 = PgHbaRule(tokens=["host", "all", "all", "abcd:1234::/32", "md5"])
277 r8 = PgHbaRule(tokens=["host", "all", "all", "abcd:1234::", "ffff:ffff::", "md5"])
278 assert r7.is_identical(r8)
279
280
281 def test_rule_eq():
282 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
283 # if you still run 2.7, that is your problem
284 try:
285 import ipaddress
286 except ImportError:
287 return
288 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
289 assert (PgHbaRule(tokens=["local", "all", "all", "ident"], comment=" ident ")
290 == PgHbaRule(tokens=["local", "all", "all", "ident"], comment="ident"))
291 assert (PgHbaRule(rule_dict={"contype": "local",
292 "databases": "all",
293 "users": "all",
294 "method": "ident",
295 "comment": " ident "})
296 == PgHbaRule(rule_dict={"contype": "local",
297 "databases": "all",
298 "users": "all",
299 "method": "ident",
300 "comment": "ident"})
301 )
302
303
304 def test_rule_lt():
305 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
306 # if you still run 2.7, that is your problem
307 try:
308 import ipaddress
309 except ImportError:
310 return
311 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
312 r1 = PgHbaRule(tokens=["host", "all", "all", "127.0.0.1/32", "md5"])
313 r2 = PgHbaRule(tokens=["host", "all", "all", "::1/128", "md5"])
314 r3 = PgHbaRule(tokens=["host", "all", "all", "2001:db8::1/128", "md5"])
315 rh1 = PgHbaRule(tokens=["host", "all", "all", "host.example.com", "md5"])
316 r4 = PgHbaRule(tokens=["host", "all", "all", "0:ff00::/120", "md5"])
317 r5 = PgHbaRule(tokens=["host", "all", "all", "192.168.0.0/24", "md5"])
318
319 rdb_1 = PgHbaRule(tokens=["host", "adb", "all", "127.0.0.0/32", "md5"])
320 rdb_2 = PgHbaRule(tokens=["host", "postgres", "all", "127.0.0.1/32", "md5"])
321
322 rusr_1 = PgHbaRule(tokens=["host", "all", "ausr", "127.0.0.0/32", "md5"])
323 rusr_2 = PgHbaRule(tokens=["host", "all", "postgres", "127.0.0.1/32", "md5"])
324
325 rlocal = PgHbaRule(tokens=["local", "postgres", "postgres", "trust"])
326
327 all_normal_rules = [r1, r2, r3, rh1, r4, r5, rdb_1, rdb_2, rusr_1, rusr_2, rlocal]
328
329 full_comment = PgHbaRule(tokens="COMMENT", comment="# some full line comment", line_nr=10)
330 include = PgHbaRule(tokens=["include", "some_file"], line="include somefile", line_nr=7)
331 include_dir = PgHbaRule(tokens=["include_dir", "some_dir"], line="include_dir some_dir", line_nr=8)
332 include_if_exists = (
333 PgHbaRule(tokens=["include_if_exists", "some_other_file"], line="include_if_exists some_other_file",
334 line_nr=9)
335 )
336
337 another_comment = PgHbaRule(tokens="COMMENT", comment="# xxx full line comment", line_nr=9)
338 another_comment_2 = PgHbaRule(tokens="COMMENT", comment="# aaa full line comment", line_nr=0)
339 another_comment_3 = PgHbaRule(tokens="COMMENT", comment="# zzz full line comment", line_nr=0)
340
341 assert r1 < r2
342 assert r2 < r3
343 assert r3 < r4
344 assert r4 < r5
345 assert r3 < rh1
346
347 assert rdb_1 < rdb_2
348 assert rdb_2 < r1
349
350 assert rusr_1 < rusr_2
351 assert rusr_2 < r1
352
353 assert rlocal < r1
354 assert rlocal < rusr_1
355 assert rlocal < rdb_1
356
357 for r in all_normal_rules:
358 assert r > full_comment
359 assert r < include
360 assert r < include_dir
361 assert r < include_if_exists
362
363 assert another_comment < full_comment
364 assert full_comment < another_comment_2
365 assert another_comment_2 < another_comment_3
366
367 assert full_comment < include
368 assert include < include_dir
369 assert include_dir < include_if_exists
370
371
372 def test_rule_to_dict():
373 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
374 # if you still run 2.7, that is your problem
375 try:
376 import ipaddress
377 except ImportError:
378 return
379 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
380 rules_from_dict = from_rule_list(VALID_RULE_DICTS)
381 rules = [r.to_dict() for r in rules_from_dict]
382 assert len(rules) == len(VALID_RULE_DICTS)
383 for i in range(0, len(rules)):
384 assert rules[i] == VALID_RULE_DICTS[i]
385 # test header mapping
386 rule = from_rule_list([
387 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'trust', 'address': '127.0.0.1',
388 'netmask': '255.255.255.255'},])[0]
389 assert rule.to_dict(PG_HBA_HDR_MAP) == {'type': 'host', 'db': 'all', 'usr': 'all', 'method': 'trust',
390 'src': '127.0.0.1/32'}
391
392
393 def test_rule_serialize():
394 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
395 # if you still run 2.7, that is your problem
396 try:
397 import ipaddress
398 except ImportError:
399 return
400 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
401 assert PgHbaRule(tokens="COMMENT", line="# comment", comment="# comment").serialize(" ") == "# comment"
402 assert PgHbaRule(tokens="EMPTY", line='').serialize(" ") == ""
403 assert PgHbaRule(tokens=['local', 'all', 'all', 'ident']).serialize(" ") == "local all all ident"
404 assert (PgHbaRule(tokens=['local', 'all', 'all', 'ident'], comment="# comment").serialize(" ")
405 == "local all all ident # comment")
406 assert (PgHbaRule(tokens=['host', 'all', 'all', '127.0.0.1/32', 'md5']).serialize(" ")
407 == "host all all 127.0.0.1/32 md5")
408 assert (PgHbaRule(tokens=['host', 'all', 'all', '127.0.0.1', '255.255.255.255', 'md5']).serialize(" ")
409 == "host all all 127.0.0.1/32 md5")
410 assert (PgHbaRule(tokens=['host', 'all', 'all', '0.0.0.0/0', 'radius', 'radiusservers="server1,server2"',
411 'radiussecrets="""secret one"",""secret two"""']).serialize(" ")
412 == 'host all all 0.0.0.0/0 radius radiussecrets="""secret one"",""secret two""" '
413 'radiusservers="server1,server2"')
414
415
416 def test_parse_hba_file():
417 string_1 = "one two\n# comment\none two #three"
418 expected_1 = [
419 {"line": "one two",
420 "tokens": ["one", "two"],
421 "comment": None,
422 "line_nr": 1},
423 {"line": "# comment",
424 "tokens": "COMMENT",
425 "comment": "# comment",
426 "line_nr": 2},
427 {"line": "one two #three",
428 "tokens": ["one", "two"],
429 "comment": "#three",
430 "line_nr": 3},
431 ]
432 assert parse_hba_file(string_1) == expected_1
433
434 string_2 = "one two\n# comment\none \\\ntwo #three\nfour"
435 expected_2 = [
436 {"line": "one two",
437 "tokens": ["one", "two"],
438 "comment": None,
439 "line_nr": 1},
440 {"line": "# comment",
441 "tokens": "COMMENT",
442 "comment": "# comment",
443 "line_nr": 2},
444 {"line": "one \\\ntwo #three",
445 "tokens": ["one", "two"],
446 "comment": "#three",
447 "line_nr": 3},
448 {"line": "four",
449 "tokens": ["four"],
450 "comment": None,
451 "line_nr": 5},
452 ]
453 assert parse_hba_file(string_2) == expected_2
454
455 string_3 = "one two\n\n# comment\none \\\ntwo #three\nfour"
456 expected_3 = [
457 {"line": "one two",
458 "tokens": ["one", "two"],
459 "comment": None,
460 "line_nr": 1},
461 {"line": "",
462 "tokens": "EMPTY",
463 "comment": None,
464 "line_nr": 2},
465 {"line": "# comment",
466 "tokens": "COMMENT",
467 "comment": "# comment",
468 "line_nr": 3},
469 {"line": "one \\\ntwo #three",
470 "tokens": ["one", "two"],
471 "comment": "#three",
472 "line_nr": 4},
473 {"line": "four",
474 "tokens": ["four"],
475 "comment": None,
476 "line_nr": 6},
477 ]
478 assert parse_hba_file(string_3) == expected_3
479
480 string_err = "one two\" three"
481 with pytest.raises(TokenizerException, match="Error in line 1: Unterminated quote"):
482 parse_hba_file(string_err)
483
484 string_err = "asdf\none two\" three"
485 with pytest.raises(TokenizerException, match="Error in line 2: Unterminated quote"):
486 parse_hba_file(string_err)
487
488 string_err = "asdf\\\nxxx\none two\" three"
489 with pytest.raises(TokenizerException, match="Error in line 3: Unterminated quote"):
490 parse_hba_file(string_err)
491
492
493 def test_handle_db_and_user_strings():
494 assert handle_db_and_user_strings("a,b,c") == "a,b,c"
495 assert handle_db_and_user_strings("c,b,a") == "a,b,c"
496 assert handle_db_and_user_strings('"c,b,a"') == '"c,b,a"'
497 assert handle_db_and_user_strings("all") == "all"
498 assert handle_db_and_user_strings('"all"') == '"all"'
499
500
501 def test_handle_address_field():
502 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
503 # if you still run 2.7, that is your problem
504 try:
505 import ipaddress
506 except ImportError:
507 return
508 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
509 assert handle_address_field("1.2.3.4") == ("1.2.3.4", "IPv4", -1)
510 assert handle_address_field("1.0.0.0/8") == ("1.0.0.0", "IPv4", 8)
511 assert handle_address_field('"1.0.0.0/8"') == ("1.0.0.0", "IPv4", 8)
512 assert handle_address_field("ffff::") == ("ffff::", "IPv6", -1)
513 assert handle_address_field("ffff::/16") == ("ffff::", "IPv6", 16)
514 assert handle_address_field('"ffff::/16"') == ("ffff::", "IPv6", 16)
515 assert handle_address_field("host.example.com") == ("host.example.com", "hostname", -1)
516 assert handle_address_field('"host.example.com"') == ('"host.example.com"', "hostname", -1)
517 assert handle_address_field("samehost") == ("samehost", "hostname", -1)
518
519 with pytest.raises(PgHbaValueError, match=".* has host bits set"):
520 handle_address_field("1.2.3.4/8")
521 with pytest.raises(PgHbaValueError, match=".* has host bits set"):
522 handle_address_field("ffff::/8")
523
524 with pytest.raises(PgHbaValueError, match=".* is neither a valid IP address, network, hostname or keyword"):
525 handle_address_field("host.example.com:1234")
526 with pytest.raises(PgHbaValueError, match=".* is neither a valid IP address, network, hostname or keyword"):
527 handle_address_field("1.2.3.4/33")
528 with pytest.raises(PgHbaValueError, match=".* is neither a valid IP address, network, hostname or keyword"):
529 handle_address_field("1234:ffff::/129")
530
531
532 def test_handle_netmask_field():
533 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
534 # if you still run 2.7, that is your problem
535 try:
536 import ipaddress
537 except ImportError:
538 return
539 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
540 assert handle_netmask_field("255.255.255.0") == ("255.255.255.0", "IPv4", 24)
541 assert handle_netmask_field('"255.255.255.0"') == ("255.255.255.0", "IPv4", 24)
542 assert handle_netmask_field("ffff:ffff::") == ("ffff:ffff::", "IPv6", 32)
543 assert handle_netmask_field('"ffff:ffff::"') == ("ffff:ffff::", "IPv6", 32)
544 assert handle_netmask_field('hello', raise_not_valid=False) == ("", "invalid", -1)
545
546 with pytest.raises(PgHbaValueError, match=".* is not a valid netmask"):
547 handle_netmask_field("255.0.0.0/8")
548 with pytest.raises(PgHbaValueError, match=".* is not a valid netmask"):
549 handle_netmask_field("ffff::/16")
550 with pytest.raises(PgHbaValueError, match=".* is not a valid netmask"):
551 handle_netmask_field("1:2.3.4")
552 with pytest.raises(PgHbaValueError, match="IP mask .* is invalid .*"):
553 handle_netmask_field("255.255.0.255")
554 with pytest.raises(PgHbaValueError, match="IP mask .* is invalid .*"):
555 handle_netmask_field("ffff:ffff::ffff")
556
557
558 def test_parse_auth_options():
559 assert parse_auth_options(["key=value"]) == {"key": "value"}
560 assert parse_auth_options(["key1=value1", "key2=value2"]) == {"key1": "value1", "key2": "value2"}
561 assert parse_auth_options(["key=value=with=equal=signs"]) == {"key": "value=with=equal=signs"}
562 assert (parse_auth_options(['radiusservers="server1,server2"', 'radiussecrets="""secret one"",""secret two"""'])
563 == {'radiusservers': '"server1,server2"', 'radiussecrets': '"""secret one"",""secret two"""'})
564 with pytest.raises(PgHbaRuleValueError, match="Found invalid option"):
565 parse_auth_options(["notkeyvalue"])
566 with pytest.raises(PgHbaRuleValueError, match="The rule contains two options with the same key"):
567 parse_auth_options(["key=value", "key=value2"])
568
569
570 def test_search_rule():
571 """Test if search_rule works correctly"""
572 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
573 # if you still run 2.7, that is your problem
574 try:
575 import ipaddress
576 except ImportError:
577 return
578 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
579 ruleset = [
580 PgHbaRule(rule_dict={'contype': 'local',
581 'databases': 'all',
582 'users': 'all',
583 'method': 'ident', }),
584 PgHbaRule(rule_dict={'contype': 'host',
585 'databases': 'all',
586 'users': 'admin',
587 'address': '10.0.0.0/8',
588 'method': 'cert', }),
589 PgHbaRule(rule_dict={'contype': 'host',
590 'databases': 'app',
591 'users': 'appuser',
592 'address': '10.0.0.0/8',
593 'method': 'md5', }),
594 ]
595 # look for exact rule
596 assert search_rule(ruleset, PgHbaRule(rule_dict={'contype': 'host',
597 'databases': 'all',
598 'users': 'admin',
599 'address': '10.0.0.0/8',
600 'method': 'cert', })) == 1
601 # look for prefix
602 assert search_rule(ruleset, PgHbaRule(rule_dict={'contype': 'host',
603 'databases': 'app',
604 'users': 'appuser',
605 'address': '10.0.0.0/8',
606 'method': 'cert', })) == 2
607 # look for non-existent rule
608 assert search_rule(ruleset, PgHbaRule(rule_dict={'contype': 'host',
609 'databases': 'notadatabase',
610 'users': 'appuser',
611 'address': '0.0.0.0/0',
612 'method': 'md5', })) == -1
613
614
615 def test_render_rule_list():
616 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
617 # if you still run 2.7, that is your problem
618 try:
619 import ipaddress
620 except ImportError:
621 return
622 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
623 rules = [
624 PgHbaRule(tokens="COMMENT", line="# This is a comment", comment="# This is a comment"),
625 PgHbaRule(tokens="EMPTY"),
626 ]
627 seed = [
628 {'contype': 'local', 'databases': 'all', 'users': '+support,@admins', 'method': 'md5'},
629 {'contype': 'local', 'databases': '@demodbs,db1,db2', 'users': 'all', 'method': 'md5'},
630 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'radius', 'address': '0.0.0.0/0',
631 'options': {'radiusservers': '"server1,server2"', 'radiussecrets': '"""secret one"",""secret two"""'},
632 'comment': "a comment"},
633 {'comment': " this is another comment "},
634 {'comment': " # this is a third comment "},
635 ]
636 for s in seed:
637 rules.append(PgHbaRule(rule_dict=s))
638 rules.append(PgHbaRule(tokens=["local", "all", "all", "trust"], comment="# comment"))
639 rules.append(PgHbaRule(tokens=["local", "all", "all", "trust"], line="local all all \\\ntrust"))
640 rules.append(PgHbaRule(tokens=["include", "somefile.conf"], line="include somefile.conf"))
641 assert render_rule_list(rules, " ") == '''# This is a comment
642
643 local all +support,@admins md5
644 local @demodbs,db1,db2 all md5
645 host all all 0.0.0.0/0 radius radiussecrets="""secret one"",""secret two""" radiusservers="server1,server2" #a comment
646 #this is another comment
647 # this is a third comment
648 local all all trust # comment
649 local all all \\
650 trust
651 include somefile.conf'''
652
653
654 def test_sort_rules():
655 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
656 # if you still run 2.7, that is your problem
657 try:
658 import ipaddress
659 except ImportError:
660 return
661 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
662 seed = [
663 {'contype': 'local', 'databases': 'all', 'users': '+support,@admins', 'method': 'md5'},
664 {'contype': 'local', 'databases': '@demodbs,db1,db2', 'users': 'all', 'method': 'md5'},
665 {'contype': 'host', 'databases': 'all', 'users': 'all', 'method': 'radius', 'address': '0.0.0.0/0',
666 'options': {'radiusservers': '"server1,server2"', 'radiussecrets': '"""secret one"",""secret two"""'},
667 'comment': "a comment"},
668 ]
669 rules = from_rule_list(seed)
670 rules.append(PgHbaRule(tokens="EMPTY"))
671 rules.append(PgHbaRule(tokens=["include_dir", "some/dir"], line="include_dir some/dir", line_nr=7))
672 rules.append(PgHbaRule(tokens="EMPTY"))
673 rules.append(
674 PgHbaRule(tokens=["include_if_exists", "somefile.conf"], line="include_if_exists somefile.conf", line_nr=8))
675 rules.append(PgHbaRule(tokens="EMPTY"))
676 rules.append(PgHbaRule(tokens="COMMENT", line="# This is a comment", comment="# This is a comment"))
677 rules.append(PgHbaRule(tokens="EMPTY"))
678 rules.append(PgHbaRule(tokens=["include", "somefile.conf"], line="include somefile.conf", line_nr=9))
679
680 sort_rules(rules)
681 assert render_rule_list(rules, " ") == '''# This is a comment
682 local @demodbs,db1,db2 all md5
683 local all +support,@admins md5
684 host all all 0.0.0.0/0 radius radiussecrets="""secret one"",""secret two""" radiusservers="server1,server2" #a comment
685 include_dir some/dir
686 include_if_exists somefile.conf
687 include somefile.conf'''
688
689
690 def test_update_rules():
691 # it seems that test breaks for Python 2.7 and in 2024, I'm not going to work around that
692 # if you still run 2.7, that is your problem
693 try:
694 import ipaddress
695 except ImportError:
696 return
697 ipaddress.ip_address("0.0.0.0") # otherwise flake complains
698 rules = rule_list_from_hba_file("local all all ident\nhost user db 192.168.10.0/24 md5")
699
700 new_rules = [
701 {"contype": "hostssl",
702 "databases": "somedb",
703 "users": "appuser",
704 "address": "10.8.16.10/32",
705 "method": "md5",
706 "state": "present"}]
707 changed, msgs, diff_before, diff_after = update_rules(new_rules, rules)
708 assert changed
709 assert msgs[0].startswith("Adding rule")
710 assert len(diff_after) == 1
711 assert len(diff_before) == 0
712 assert len(rules) == 3
713 assert rules[2].user == "appuser"
714
715 tmp_rule_dict = rule_list_to_dict_list(rules)
716 local_all = {"contype": "local", "databases": "all", "users": "all", "method": "ident", "state": "present"}
717 changed, a, b, c = update_rules([local_all], rules)
718 assert not changed
719 assert tmp_rule_dict == rule_list_to_dict_list(rules)
720
721 local_all["method"] = "trust"
722 changed, a, b, c = update_rules([local_all], rules)
723 assert changed
724 assert rules[0].method == "trust"
725
726 local_all["state"] = "absent"
727 changed, a, b, c = update_rules([local_all], rules)
728 assert changed
729 assert len(rules) == 2
730 assert rules[0].method == "md5"