7 from dnsdisttests
import DNSDistTest
9 class TestAPIBasics(DNSDistTest
):
13 _webServerBasicAuthPassword
= 'secret'
14 _webServerAPIKey
= 'apisecret'
15 # paths accessible using the API key only
16 _apiOnlyPaths
= ['/api/v1/servers/localhost/config', '/api/v1/servers/localhost/config/allow-from', '/api/v1/servers/localhost/statistics']
17 # paths accessible using an API key or basic auth
18 _statsPaths
= [ '/jsonstat?command=stats', '/jsonstat?command=dynblocklist', '/api/v1/servers/localhost']
19 # paths accessible using basic auth only (list not exhaustive)
20 _basicOnlyPaths
= ['/', '/index.html']
21 _config_params
= ['_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
22 _config_template
= """
23 setACL({"127.0.0.1/32", "::1/128"})
24 newServer{address="127.0.0.1:%s"}
25 webserver("127.0.0.1:%s", "%s", "%s")
28 def testBasicAuth(self
):
30 API: Basic Authentication
32 for path
in self
._basicOnlyPaths
+ self
._statsPaths
:
33 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
34 r
= requests
.get(url
, auth
=('whatever', "evilsecret"), timeout
=self
._webTimeout
)
35 self
.assertEquals(r
.status_code
, 401)
36 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
38 self
.assertEquals(r
.status_code
, 200)
40 def testXAPIKey(self
):
44 headers
= {'x-api-key': self
._webServerAPIKey
}
45 for path
in self
._apiOnlyPaths
+ self
._statsPaths
:
46 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
47 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
49 self
.assertEquals(r
.status_code
, 200)
51 def testWrongXAPIKey(self
):
55 headers
= {'x-api-key': "evilapikey"}
56 for path
in self
._apiOnlyPaths
+ self
._statsPaths
:
57 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
58 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
59 self
.assertEquals(r
.status_code
, 401)
60 def testBasicAuthOnly(self
):
62 API: Basic Authentication Only
64 headers
= {'x-api-key': self
._webServerAPIKey
}
65 for path
in self
._basicOnlyPaths
:
66 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
67 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
68 self
.assertEquals(r
.status_code
, 401)
70 def testAPIKeyOnly(self
):
74 for path
in self
._apiOnlyPaths
:
75 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
76 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
77 self
.assertEquals(r
.status_code
, 401)
79 def testServersLocalhost(self
):
81 API: /api/v1/servers/localhost
83 headers
= {'x-api-key': self
._webServerAPIKey
}
84 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost'
85 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
87 self
.assertEquals(r
.status_code
, 200)
88 self
.assertTrue(r
.json())
91 self
.assertEquals(content
['daemon_type'], 'dnsdist')
93 rule_groups
= ['response-rules', 'cache-hit-response-rules', 'self-answered-response-rules']
94 for key
in ['version', 'acl', 'local', 'rules', 'servers', 'frontends', 'pools'] + rule_groups
:
95 self
.assertIn(key
, content
)
97 for rule
in content
['rules']:
98 for key
in ['id', 'matches', 'rule', 'action', 'uuid']:
99 self
.assertIn(key
, rule
)
100 for key
in ['id', 'matches']:
101 self
.assertTrue(rule
[key
] >= 0)
103 for rule_group
in rule_groups
:
104 for rule
in content
[rule_group
]:
105 for key
in ['id', 'matches', 'rule', 'action', 'uuid']:
106 self
.assertIn(key
, rule
)
107 for key
in ['id', 'matches']:
108 self
.assertTrue(rule
[key
] >= 0)
110 for server
in content
['servers']:
111 for key
in ['id', 'latency', 'name', 'weight', 'outstanding', 'qpsLimit',
112 'reuseds', 'state', 'address', 'pools', 'qps', 'queries', 'order', 'sendErrors',
114 self
.assertIn(key
, server
)
116 for key
in ['id', 'latency', 'weight', 'outstanding', 'qpsLimit', 'reuseds',
117 'qps', 'queries', 'order']:
118 self
.assertTrue(server
[key
] >= 0)
120 self
.assertTrue(server
['state'] in ['up', 'down', 'UP', 'DOWN'])
122 for frontend
in content
['frontends']:
123 for key
in ['id', 'address', 'udp', 'tcp', 'queries']:
124 self
.assertIn(key
, frontend
)
126 for key
in ['id', 'queries']:
127 self
.assertTrue(frontend
[key
] >= 0)
129 for pool
in content
['pools']:
130 for key
in ['id', 'name', 'cacheSize', 'cacheEntries', 'cacheHits', 'cacheMisses', 'cacheDeferredInserts', 'cacheDeferredLookups', 'cacheLookupCollisions', 'cacheInsertCollisions', 'cacheTTLTooShorts']:
131 self
.assertIn(key
, pool
)
133 for key
in ['id', 'cacheSize', 'cacheEntries', 'cacheHits', 'cacheMisses', 'cacheDeferredInserts', 'cacheDeferredLookups', 'cacheLookupCollisions', 'cacheInsertCollisions', 'cacheTTLTooShorts']:
134 self
.assertTrue(pool
[key
] >= 0)
136 def testServersIDontExist(self
):
138 API: /api/v1/servers/idontexist (should be 404)
140 headers
= {'x-api-key': self
._webServerAPIKey
}
141 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/idontexist'
142 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
143 self
.assertEquals(r
.status_code
, 404)
145 def testServersLocalhostConfig(self
):
147 API: /api/v1/servers/localhost/config
149 headers
= {'x-api-key': self
._webServerAPIKey
}
150 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config'
151 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
153 self
.assertEquals(r
.status_code
, 200)
154 self
.assertTrue(r
.json())
157 for entry
in content
:
158 for key
in ['type', 'name', 'value']:
159 self
.assertIn(key
, entry
)
161 self
.assertEquals(entry
['type'], 'ConfigSetting')
162 values
[entry
['name']] = entry
['value']
164 for key
in ['acl', 'control-socket', 'ecs-override', 'ecs-source-prefix-v4',
165 'ecs-source-prefix-v6', 'fixup-case', 'max-outstanding', 'server-policy',
166 'stale-cache-entries-ttl', 'tcp-recv-timeout', 'tcp-send-timeout',
167 'truncate-tc', 'verbose', 'verbose-health-checks']:
168 self
.assertIn(key
, values
)
170 for key
in ['max-outstanding', 'stale-cache-entries-ttl', 'tcp-recv-timeout',
172 self
.assertTrue(values
[key
] >= 0)
174 self
.assertTrue(values
['ecs-source-prefix-v4'] >= 0 and values
['ecs-source-prefix-v4'] <= 32)
175 self
.assertTrue(values
['ecs-source-prefix-v6'] >= 0 and values
['ecs-source-prefix-v6'] <= 128)
177 def testServersLocalhostConfigAllowFrom(self
):
179 API: /api/v1/servers/localhost/config/allow-from
181 headers
= {'x-api-key': self
._webServerAPIKey
}
182 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config/allow-from'
183 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
185 self
.assertEquals(r
.status_code
, 200)
186 self
.assertTrue(r
.json())
188 for key
in ['type', 'name', 'value']:
189 self
.assertIn(key
, content
)
191 self
.assertEquals(content
['name'], 'allow-from')
192 self
.assertEquals(content
['type'], 'ConfigSetting')
193 acl
= content
['value']
194 expectedACL
= ["127.0.0.1/32", "::1/128"]
197 self
.assertEquals(acl
, expectedACL
)
199 def testServersLocalhostConfigAllowFromPut(self
):
201 API: PUT /api/v1/servers/localhost/config/allow-from (should be refused)
203 The API is read-only by default, so this should be refused
205 newACL
= ["192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"]
206 payload
= json
.dumps({"name": "allow-from",
207 "type": "ConfigSetting",
209 headers
= {'x-api-key': self
._webServerAPIKey
}
210 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config/allow-from'
211 r
= requests
.put(url
, headers
=headers
, timeout
=self
._webTimeout
, data
=payload
)
213 self
.assertEquals(r
.status_code
, 405)
215 def testServersLocalhostStatistics(self
):
217 API: /api/v1/servers/localhost/statistics
219 headers
= {'x-api-key': self
._webServerAPIKey
}
220 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/statistics'
221 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
223 self
.assertEquals(r
.status_code
, 200)
224 self
.assertTrue(r
.json())
227 for entry
in content
:
228 self
.assertIn('type', entry
)
229 self
.assertIn('name', entry
)
230 self
.assertIn('value', entry
)
231 self
.assertEquals(entry
['type'], 'StatisticItem')
232 values
[entry
['name']] = entry
['value']
234 expected
= ['responses', 'servfail-responses', 'queries', 'acl-drops',
235 'rule-drop', 'rule-nxdomain', 'rule-refused', 'self-answered', 'downstream-timeouts',
236 'downstream-send-errors', 'trunc-failures', 'no-policy', 'latency0-1',
237 'latency1-10', 'latency10-50', 'latency50-100', 'latency100-1000',
238 'latency-slow', 'latency-avg100', 'latency-avg1000', 'latency-avg10000',
239 'latency-avg1000000', 'uptime', 'real-memory-usage', 'noncompliant-queries',
240 'noncompliant-responses', 'rdqueries', 'empty-queries', 'cache-hits',
241 'cache-misses', 'cpu-user-msec', 'cpu-sys-msec', 'fd-usage', 'dyn-blocked',
242 'dyn-block-nmg-size', 'rule-servfail']
245 self
.assertIn(key
, values
)
246 self
.assertTrue(values
[key
] >= 0)
249 self
.assertIn(key
, expected
)
251 def testJsonstatStats(self
):
253 API: /jsonstat?command=stats
255 headers
= {'x-api-key': self
._webServerAPIKey
}
256 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/jsonstat?command=stats'
257 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
259 self
.assertEquals(r
.status_code
, 200)
260 self
.assertTrue(r
.json())
263 expected
= ['responses', 'servfail-responses', 'queries', 'acl-drops',
264 'rule-drop', 'rule-nxdomain', 'rule-refused', 'self-answered', 'downstream-timeouts',
265 'downstream-send-errors', 'trunc-failures', 'no-policy', 'latency0-1',
266 'latency1-10', 'latency10-50', 'latency50-100', 'latency100-1000',
267 'latency-slow', 'latency-avg100', 'latency-avg1000', 'latency-avg10000',
268 'latency-avg1000000', 'uptime', 'real-memory-usage', 'noncompliant-queries',
269 'noncompliant-responses', 'rdqueries', 'empty-queries', 'cache-hits',
270 'cache-misses', 'cpu-user-msec', 'cpu-sys-msec', 'fd-usage', 'dyn-blocked',
271 'dyn-block-nmg-size', 'packetcache-hits', 'packetcache-misses', 'over-capacity-drops',
275 self
.assertIn(key
, content
)
276 self
.assertTrue(content
[key
] >= 0)
278 def testJsonstatDynblocklist(self
):
280 API: /jsonstat?command=dynblocklist
282 headers
= {'x-api-key': self
._webServerAPIKey
}
283 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/jsonstat?command=dynblocklist'
284 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
286 self
.assertEquals(r
.status_code
, 200)
291 for key
in ['reason', 'seconds', 'blocks', 'action']:
292 self
.assertIn(key
, content
)
294 for key
in ['blocks']:
295 self
.assertTrue(content
[key
] >= 0)
297 class TestAPIServerDown(DNSDistTest
):
300 _webServerPort
= 8083
301 _webServerBasicAuthPassword
= 'secret'
302 _webServerAPIKey
= 'apisecret'
303 # paths accessible using the API key
304 _config_params
= ['_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
305 _config_template
= """
306 setACL({"127.0.0.1/32", "::1/128"})
307 newServer{address="127.0.0.1:%s"}
308 getServer(0):setDown()
309 webserver("127.0.0.1:%s", "%s", "%s")
312 def testServerDownNoLatencyLocalhost(self
):
314 API: /api/v1/servers/localhost, no latency for a down server
316 headers
= {'x-api-key': self
._webServerAPIKey
}
317 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost'
318 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
320 self
.assertEquals(r
.status_code
, 200)
321 self
.assertTrue(r
.json())
324 self
.assertEquals(content
['servers'][0]['latency'], None)
326 class TestAPIWritable(DNSDistTest
):
329 _webServerPort
= 8083
330 _webServerBasicAuthPassword
= 'secret'
331 _webServerAPIKey
= 'apisecret'
332 _APIWriteDir
= '/tmp'
333 _config_params
= ['_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey', '_APIWriteDir']
334 _config_template
= """
335 setACL({"127.0.0.1/32", "::1/128"})
336 newServer{address="127.0.0.1:%s"}
337 webserver("127.0.0.1:%s", "%s", "%s")
338 setAPIWritable(true, "%s")
341 def testSetACL(self
):
345 headers
= {'x-api-key': self
._webServerAPIKey
}
346 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config/allow-from'
347 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
349 self
.assertEquals(r
.status_code
, 200)
350 self
.assertTrue(r
.json())
352 acl
= content
['value']
353 expectedACL
= ["127.0.0.1/32", "::1/128"]
356 self
.assertEquals(acl
, expectedACL
)
358 newACL
= ["192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"]
359 payload
= json
.dumps({"name": "allow-from",
360 "type": "ConfigSetting",
362 r
= requests
.put(url
, headers
=headers
, timeout
=self
._webTimeout
, data
=payload
)
364 self
.assertEquals(r
.status_code
, 200)
365 self
.assertTrue(r
.json())
367 self
.assertEquals(content
['value'], newACL
)
369 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
371 self
.assertEquals(r
.status_code
, 200)
372 self
.assertTrue(r
.json())
374 self
.assertEquals(content
['value'], newACL
)
376 configFile
= self
._APIWriteDir
+ '/' + 'acl.conf'
377 self
.assertTrue(os
.path
.isfile(configFile
))
379 with
open(configFile
, 'rt') as f
:
380 fileContent
= f
.read()
382 self
.assertEquals(fileContent
, """-- Generated by the REST API, DO NOT EDIT
383 setACL({"192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"})
386 class TestAPIAuth(DNSDistTest
):
389 _webServerPort
= 8083
390 _webServerBasicAuthPassword
= 'secret'
391 _webServerBasicAuthPasswordNew
= 'password'
392 _webServerAPIKey
= 'apisecret'
393 _webServerAPIKeyNew
= 'apipassword'
394 # paths accessible using the API key only
395 _apiOnlyPath
= '/api/v1/servers/localhost/config'
396 # paths accessible using basic auth only (list not exhaustive)
398 _consoleKey
= DNSDistTest
.generateConsoleKey()
399 _consoleKeyB64
= base64
.b64encode(_consoleKey
).decode('ascii')
400 _config_params
= ['_consoleKeyB64', '_consolePort', '_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
401 _config_template
= """
403 controlSocket("127.0.0.1:%s")
404 setACL({"127.0.0.1/32", "::1/128"})
405 newServer{address="127.0.0.1:%s"}
406 webserver("127.0.0.1:%s", "%s", "%s")
409 def testBasicAuthChange(self
):
411 API: Basic Authentication updating credentials
414 self
.sendConsoleCommand('setWebserverConfig("{}")'.format(self
._webServerBasicAuthPasswordNew
))
416 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._basicOnlyPath
417 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPasswordNew
), timeout
=self
._webTimeout
)
419 self
.assertEquals(r
.status_code
, 200)
421 # Make sure the old password is not usable any more
422 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._basicOnlyPath
423 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
424 self
.assertEquals(r
.status_code
, 401)
426 def testXAPIKeyChange(self
):
428 API: X-Api-Key updating credentials
431 self
.sendConsoleCommand('setWebserverConfig("{}", "{}")'.format(self
._webServerBasicAuthPasswordNew
, self
._webServerAPIKeyNew
))
433 headers
= {'x-api-key': self
._webServerAPIKeyNew
}
434 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._apiOnlyPath
435 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
437 self
.assertEquals(r
.status_code
, 200)
439 # Make sure the old password is not usable any more
440 headers
= {'x-api-key': self
._webServerAPIKey
}
441 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._apiOnlyPath
442 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
443 self
.assertEquals(r
.status_code
, 401)
445 def testBasicAuthOnlyChange(self
):
447 API: X-Api-Key updated to none (disabled)
450 self
.sendConsoleCommand('setWebserverConfig("{}", "{}")'.format(self
._webServerBasicAuthPasswordNew
, self
._webServerAPIKeyNew
))
452 headers
= {'x-api-key': self
._webServerAPIKeyNew
}
453 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._apiOnlyPath
454 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
456 self
.assertEquals(r
.status_code
, 200)
459 self
.sendConsoleCommand('setWebserverConfig("{}")'.format(self
._webServerBasicAuthPasswordNew
))
461 headers
= {'x-api-key': self
._webServerAPIKeyNew
}
462 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._apiOnlyPath
463 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
464 self
.assertEquals(r
.status_code
, 401)