-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest_hba.py
More file actions
417 lines (325 loc) · 10.9 KB
/
test_hba.py
File metadata and controls
417 lines (325 loc) · 10.9 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import pytest
HBA_SAMPLE = """\
# CAUTION: Configuring the system for local "trust" authentication
# allows any local user to connect as any PostgreSQL user, including
# the database superuser. If you do not trust all your local users,
# use another authentication method.
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all u0,u1 127.0.0.1/32 trust
# IPv6 local connections:
host all +group,u2 ::1/128 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
local replication all trust
host replication all 127.0.0.1 255.255.255.255 trust
host replication all ::1/128 trust
host all all all trust
"""
def test_comment():
from pgtoolkit.hba import HBAComment
comment = HBAComment("# toto")
assert "toto" in repr(comment)
assert "# toto" == str(comment)
def test_parse_host_line():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse("host replication,mydb all ::1/128 trust")
assert "host" in repr(record)
assert "host" == record.conntype
assert "replication,mydb" == record.database
assert ["replication", "mydb"] == record.databases
assert "all" == record.user
assert ["all"] == record.users
assert "::1/128" == record.address
assert "trust" == record.method
# This is not actually a public API. But let's keep it stable.
values = record.common_values
assert "trust" in values
def test_parse_local_line():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse("local all all trust")
assert "local" == record.conntype
assert "all" == record.database
assert ["all"] == record.databases
assert "all" == record.user
assert ["all"] == record.users
assert "trust" == record.method
with pytest.raises(AttributeError):
record.address
wanted = (
"local all all trust" # noqa
)
assert wanted == str(record)
def test_parse_auth_option():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse(
"local veryverylongdatabasenamethatdonotfit all ident map=omicron",
)
assert "local" == record.conntype
assert "veryverylongdatabasenamethatdonotfit" == record.database
assert "all" == record.user
assert "ident" == record.method
assert "omicron" == record.map
wanted = [
"local",
"veryverylongdatabasenamethatdonotfit",
"all",
"ident",
'map="omicron"',
]
assert wanted == str(record).split()
def test_parse_record_with_comment():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse("local all all trust # My comment")
assert "local" == record.conntype
assert "all" == record.database
assert "all" == record.user
assert "trust" == record.method
assert "My comment" == record.comment
fields = str(record).split()
assert ["local", "all", "all", "trust", "#", "My", "comment"] == fields
def test_parse_invalid_connection_type():
from pgtoolkit.hba import HBARecord
with pytest.raises(ValueError, match="Unknown connection type 'pif'"):
HBARecord.parse("pif all all")
def test_parse_record_with_backslash():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse(
r'host all all all ldap ldapserver=host.local ldapprefix="DOMAINE\"'
)
assert record.ldapprefix == "DOMAINE\\"
def test_parse_record_with_double_quoting():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse(
r'host all all all radius radiusservers="server1,server2" radiussecrets="""secret one"",""secret two"""'
)
assert record.radiussecrets == '""secret one"",""secret two""'
def test_parse_record_blank_in_quotes():
from pgtoolkit.hba import HBARecord
record = HBARecord.parse(
r"host all all all ldap ldapserver=ldap.example.net"
r' ldapbasedn="dc=example, dc=net"'
r' ldapsearchfilter="(|(uid=$username)(mail=$username))"'
)
assert record.ldapserver == "ldap.example.net"
assert record.ldapbasedn == "dc=example, dc=net"
assert record.ldapsearchfilter == "(|(uid=$username)(mail=$username))"
def test_hba(mocker):
from pgtoolkit.hba import parse
lines = HBA_SAMPLE.splitlines(True)
hba = parse(lines)
entries = list(iter(hba))
assert 7 == len(entries)
hba.save(mocker.Mock(name="file"))
def test_hba_path(tmp_path):
from pgtoolkit.hba import HBA
hba = HBA()
assert hba.path is None
with pytest.raises(ValueError, match="No file-like object nor path provided"):
hba.save()
p = tmp_path / "filename"
hba = HBA([], p)
assert hba.path == p
hba.save()
def test_hba_create():
from pgtoolkit.hba import HBA, HBAComment, HBARecord
hba = HBA(
[
HBAComment("# a comment"),
HBARecord(
conntype="local",
database="all",
user="all",
method="trust",
),
]
)
assert 2 == len(hba.lines)
r = hba.lines[1]
assert "all" == r.database
def test_parse_file(mocker, tmp_path):
from pgtoolkit.hba import HBAComment, parse
m = mocker.mock_open()
try:
mocker.patch("builtins.open", m)
except Exception:
mocker.patch("__builtin__.open", m)
hba = parse("filename")
hba.lines.append(HBAComment("# Something"))
assert m.called
hba.save()
handle = m()
handle.write.assert_called_with("# Something\n")
# Also works for other string types
m.reset_mock()
hba = parse("filename")
hba.lines.append(HBAComment("# Something"))
assert m.called
# Also works with path
m.reset_mock()
hba = parse(tmp_path / "filename")
hba.lines.append(HBAComment("# Something"))
assert m.called
def test_hba_error(mocker):
from pgtoolkit.hba import ParseError, parse
with pytest.raises(ParseError) as ei:
parse(["lcal all all\n"])
e = ei.value
assert "line #1" in str(e)
assert repr(e)
with pytest.raises(ParseError) as ei:
parse(["local incomplete\n"])
def test_remove():
from pgtoolkit.hba import parse
lines = HBA_SAMPLE.splitlines(True)
hba = parse(lines)
with pytest.raises(ValueError):
hba.remove()
result = hba.remove(database="badname")
assert not result
result = hba.remove(database="replication")
assert result
entries = list(iter(hba))
assert 4 == len(entries)
hba = parse(lines)
result = hba.remove(filter=lambda r: r.database == "replication")
assert result
entries = list(iter(hba))
assert 4 == len(entries)
hba = parse(lines)
result = hba.remove(conntype="host", database="replication")
assert result
entries = list(iter(hba))
assert 5 == len(entries)
# Works even for fields that may not be valid for all records
# `address` is not valid for `local` connection type
hba = parse(lines)
result = hba.remove(address="127.0.0.1/32")
assert result
entries = list(iter(hba))
assert 6 == len(entries)
def filter(r):
return r.conntype == "host" and r.database == "replication"
hba = parse(lines)
result = hba.remove(filter=filter)
assert result
entries = list(iter(hba))
assert 5 == len(entries)
# Only filter is taken into account
hba = parse(lines)
with pytest.warns(UserWarning):
hba.remove(filter=filter, database="replication")
entries = list(iter(hba))
assert 5 == len(entries)
# Error if attribute name is not valid
hba = parse(lines)
with pytest.raises(AttributeError):
hba.remove(foo="postgres")
def test_merge():
import os
from pgtoolkit.hba import HBA, HBARecord, parse
sample = """\
# comment
host replication all all trust
# other comment
host replication all 127.0.0.1 255.255.255.255 trust
# Comment should be kept
host all all all trust"""
lines = sample.splitlines(True)
hba = parse(lines)
other_sample = """\
# line with no address
local all all trust
# comment before 1.2.3.4 line
host replication all 1.2.3.4 trust
# method changed to 'peer'
# second comment
host all all all peer
"""
other_lines = other_sample.splitlines(True)
other_hba = parse(other_lines)
result = hba.merge(other_hba)
assert result
expected_sample = """\
# comment
host replication all all trust
# other comment
host replication all 127.0.0.1 255.255.255.255 trust
# Comment should be kept
# method changed to 'peer'
# second comment
host all all all peer
# line with no address
local all all trust
# comment before 1.2.3.4 line
host replication all 1.2.3.4 trust
"""
expected_lines = expected_sample.splitlines(True)
expected_hba = parse(expected_lines)
def r(hba):
return os.linesep.join([str(line) for line in hba.lines])
assert r(hba) == r(expected_hba)
other_hba = HBA()
record = HBARecord(
conntype="host",
database="replication",
user="all",
address="1.2.3.4",
method="trust",
)
other_hba.lines.append(record)
result = hba.merge(other_hba)
assert not result
def test_as_dict():
from pgtoolkit.hba import HBARecord
r = HBARecord(
conntype="local",
database="all",
user="all",
method="trust",
)
assert r.as_dict() == {
"conntype": "local",
"database": "all",
"user": "all",
"method": "trust",
}
r = HBARecord(
conntype="local",
database="mydb,mydb2",
user="bob,alice",
address="127.0.0.1",
netmask="255.255.255.255",
method="trust",
)
assert r.as_dict() == {
"address": "127.0.0.1",
"conntype": "local",
"database": "mydb,mydb2",
"user": "bob,alice",
"method": "trust",
"netmask": "255.255.255.255",
}
def test_hbarecord_equality():
from pgtoolkit.hba import HBARecord
r = HBARecord(
conntype="local",
database="all",
user="all",
method="trust",
)
r2 = HBARecord.parse("local all all trust")
assert r == r2
r = HBARecord(
conntype="host",
database="all",
user="u0,u1",
address="127.0.0.1/32",
method="trust",
)
r2 = HBARecord.parse("host all u0,u1 127.0.0.1/32 trust")
assert r == r2
r2 = HBARecord.parse("host mydb u0,u1 127.0.0.1/32 trust")
assert r != r2