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)
61 def testBasicAuthOnly(self
):
63 API: Basic Authentication Only
65 headers
= {'x-api-key': self
._webServerAPIKey
}
66 for path
in self
._basicOnlyPaths
:
67 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
68 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
69 self
.assertEquals(r
.status_code
, 401)
71 def testAPIKeyOnly(self
):
75 for path
in self
._apiOnlyPaths
:
76 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + path
77 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
78 self
.assertEquals(r
.status_code
, 401)
80 def testServersLocalhost(self
):
82 API: /api/v1/servers/localhost
84 headers
= {'x-api-key': self
._webServerAPIKey
}
85 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost'
86 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
88 self
.assertEquals(r
.status_code
, 200)
89 self
.assertTrue(r
.json())
92 self
.assertEquals(content
['daemon_type'], 'dnsdist')
94 rule_groups
= ['response-rules', 'cache-hit-response-rules', 'self-answered-response-rules', 'rules']
95 for key
in ['version', 'acl', 'local', 'servers', 'frontends', 'pools'] + rule_groups
:
96 self
.assertIn(key
, content
)
98 for rule_group
in rule_groups
:
99 for rule
in content
[rule_group
]:
100 for key
in ['id', 'creationOrder', 'matches', 'rule', 'action', 'uuid']:
101 self
.assertIn(key
, rule
)
102 for key
in ['id', 'creationOrder', 'matches']:
103 self
.assertTrue(rule
[key
] >= 0)
105 for server
in content
['servers']:
106 for key
in ['id', 'latency', 'name', 'weight', 'outstanding', 'qpsLimit',
107 'reuseds', 'state', 'address', 'pools', 'qps', 'queries', 'order', 'sendErrors',
109 self
.assertIn(key
, server
)
111 for key
in ['id', 'latency', 'weight', 'outstanding', 'qpsLimit', 'reuseds',
112 'qps', 'queries', 'order']:
113 self
.assertTrue(server
[key
] >= 0)
115 self
.assertTrue(server
['state'] in ['up', 'down', 'UP', 'DOWN'])
117 for frontend
in content
['frontends']:
118 for key
in ['id', 'address', 'udp', 'tcp', 'type', 'queries']:
119 self
.assertIn(key
, frontend
)
121 for key
in ['id', 'queries']:
122 self
.assertTrue(frontend
[key
] >= 0)
124 for pool
in content
['pools']:
125 for key
in ['id', 'name', 'cacheSize', 'cacheEntries', 'cacheHits', 'cacheMisses', 'cacheDeferredInserts', 'cacheDeferredLookups', 'cacheLookupCollisions', 'cacheInsertCollisions', 'cacheTTLTooShorts']:
126 self
.assertIn(key
, pool
)
128 for key
in ['id', 'cacheSize', 'cacheEntries', 'cacheHits', 'cacheMisses', 'cacheDeferredInserts', 'cacheDeferredLookups', 'cacheLookupCollisions', 'cacheInsertCollisions', 'cacheTTLTooShorts']:
129 self
.assertTrue(pool
[key
] >= 0)
131 def testServersIDontExist(self
):
133 API: /api/v1/servers/idontexist (should be 404)
135 headers
= {'x-api-key': self
._webServerAPIKey
}
136 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/idontexist'
137 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
138 self
.assertEquals(r
.status_code
, 404)
140 def testServersLocalhostConfig(self
):
142 API: /api/v1/servers/localhost/config
144 headers
= {'x-api-key': self
._webServerAPIKey
}
145 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config'
146 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
148 self
.assertEquals(r
.status_code
, 200)
149 self
.assertTrue(r
.json())
152 for entry
in content
:
153 for key
in ['type', 'name', 'value']:
154 self
.assertIn(key
, entry
)
156 self
.assertEquals(entry
['type'], 'ConfigSetting')
157 values
[entry
['name']] = entry
['value']
159 for key
in ['acl', 'control-socket', 'ecs-override', 'ecs-source-prefix-v4',
160 'ecs-source-prefix-v6', 'fixup-case', 'max-outstanding', 'server-policy',
161 'stale-cache-entries-ttl', 'tcp-recv-timeout', 'tcp-send-timeout',
162 'truncate-tc', 'verbose', 'verbose-health-checks']:
163 self
.assertIn(key
, values
)
165 for key
in ['max-outstanding', 'stale-cache-entries-ttl', 'tcp-recv-timeout',
167 self
.assertTrue(values
[key
] >= 0)
169 self
.assertTrue(values
['ecs-source-prefix-v4'] >= 0 and values
['ecs-source-prefix-v4'] <= 32)
170 self
.assertTrue(values
['ecs-source-prefix-v6'] >= 0 and values
['ecs-source-prefix-v6'] <= 128)
172 def testServersLocalhostConfigAllowFrom(self
):
174 API: /api/v1/servers/localhost/config/allow-from
176 headers
= {'x-api-key': self
._webServerAPIKey
}
177 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config/allow-from'
178 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
180 self
.assertEquals(r
.status_code
, 200)
181 self
.assertTrue(r
.json())
183 for key
in ['type', 'name', 'value']:
184 self
.assertIn(key
, content
)
186 self
.assertEquals(content
['name'], 'allow-from')
187 self
.assertEquals(content
['type'], 'ConfigSetting')
188 acl
= content
['value']
189 expectedACL
= ["127.0.0.1/32", "::1/128"]
192 self
.assertEquals(acl
, expectedACL
)
194 def testServersLocalhostConfigAllowFromPut(self
):
196 API: PUT /api/v1/servers/localhost/config/allow-from (should be refused)
198 The API is read-only by default, so this should be refused
200 newACL
= ["192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"]
201 payload
= json
.dumps({"name": "allow-from",
202 "type": "ConfigSetting",
204 headers
= {'x-api-key': self
._webServerAPIKey
}
205 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config/allow-from'
206 r
= requests
.put(url
, headers
=headers
, timeout
=self
._webTimeout
, data
=payload
)
208 self
.assertEquals(r
.status_code
, 405)
210 def testServersLocalhostStatistics(self
):
212 API: /api/v1/servers/localhost/statistics
214 headers
= {'x-api-key': self
._webServerAPIKey
}
215 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/statistics'
216 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
218 self
.assertEquals(r
.status_code
, 200)
219 self
.assertTrue(r
.json())
222 for entry
in content
:
223 self
.assertIn('type', entry
)
224 self
.assertIn('name', entry
)
225 self
.assertIn('value', entry
)
226 self
.assertEquals(entry
['type'], 'StatisticItem')
227 values
[entry
['name']] = entry
['value']
229 expected
= ['responses', 'servfail-responses', 'queries', 'acl-drops',
230 'frontend-noerror', 'frontend-nxdomain', 'frontend-servfail',
231 'rule-drop', 'rule-nxdomain', 'rule-refused', 'self-answered', 'downstream-timeouts',
232 'downstream-send-errors', 'trunc-failures', 'no-policy', 'latency0-1',
233 'latency1-10', 'latency10-50', 'latency50-100', 'latency100-1000',
234 'latency-slow', 'latency-sum', 'latency-count', 'latency-avg100', 'latency-avg1000',
235 'latency-avg10000', 'latency-avg1000000', 'uptime', 'real-memory-usage', 'noncompliant-queries',
236 'noncompliant-responses', 'rdqueries', 'empty-queries', 'cache-hits',
237 'cache-misses', 'cpu-user-msec', 'cpu-sys-msec', 'fd-usage', 'dyn-blocked',
238 'dyn-block-nmg-size', 'rule-servfail', 'security-status']
241 self
.assertIn(key
, values
)
242 self
.assertTrue(values
[key
] >= 0)
245 self
.assertIn(key
, expected
)
247 def testJsonstatStats(self
):
249 API: /jsonstat?command=stats
251 headers
= {'x-api-key': self
._webServerAPIKey
}
252 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/jsonstat?command=stats'
253 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
255 self
.assertEquals(r
.status_code
, 200)
256 self
.assertTrue(r
.json())
259 expected
= ['responses', 'servfail-responses', 'queries', 'acl-drops',
260 'frontend-noerror', 'frontend-nxdomain', 'frontend-servfail',
261 'rule-drop', 'rule-nxdomain', 'rule-refused', 'self-answered', 'downstream-timeouts',
262 'downstream-send-errors', 'trunc-failures', 'no-policy', 'latency0-1',
263 'latency1-10', 'latency10-50', 'latency50-100', 'latency100-1000',
264 'latency-slow', 'latency-avg100', 'latency-avg1000', 'latency-avg10000',
265 'latency-avg1000000', 'uptime', 'real-memory-usage', 'noncompliant-queries',
266 'noncompliant-responses', 'rdqueries', 'empty-queries', 'cache-hits',
267 'cache-misses', 'cpu-user-msec', 'cpu-sys-msec', 'fd-usage', 'dyn-blocked',
268 'dyn-block-nmg-size', 'packetcache-hits', 'packetcache-misses', 'over-capacity-drops',
272 self
.assertIn(key
, content
)
273 self
.assertTrue(content
[key
] >= 0)
275 def testJsonstatDynblocklist(self
):
277 API: /jsonstat?command=dynblocklist
279 headers
= {'x-api-key': self
._webServerAPIKey
}
280 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/jsonstat?command=dynblocklist'
281 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
283 self
.assertEquals(r
.status_code
, 200)
288 for key
in ['reason', 'seconds', 'blocks', 'action']:
289 self
.assertIn(key
, content
)
291 for key
in ['blocks']:
292 self
.assertTrue(content
[key
] >= 0)
294 class TestAPIServerDown(DNSDistTest
):
297 _webServerPort
= 8083
298 _webServerBasicAuthPassword
= 'secret'
299 _webServerAPIKey
= 'apisecret'
300 # paths accessible using the API key
301 _config_params
= ['_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
302 _config_template
= """
303 setACL({"127.0.0.1/32", "::1/128"})
304 newServer{address="127.0.0.1:%s"}
305 getServer(0):setDown()
306 webserver("127.0.0.1:%s", "%s", "%s")
309 def testServerDownNoLatencyLocalhost(self
):
311 API: /api/v1/servers/localhost, no latency for a down server
313 headers
= {'x-api-key': self
._webServerAPIKey
}
314 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost'
315 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
317 self
.assertEquals(r
.status_code
, 200)
318 self
.assertTrue(r
.json())
321 self
.assertEquals(content
['servers'][0]['latency'], None)
323 class TestAPIWritable(DNSDistTest
):
326 _webServerPort
= 8083
327 _webServerBasicAuthPassword
= 'secret'
328 _webServerAPIKey
= 'apisecret'
329 _APIWriteDir
= '/tmp'
330 _config_params
= ['_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey', '_APIWriteDir']
331 _config_template
= """
332 setACL({"127.0.0.1/32", "::1/128"})
333 newServer{address="127.0.0.1:%s"}
334 webserver("127.0.0.1:%s", "%s", "%s")
335 setAPIWritable(true, "%s")
338 def testSetACL(self
):
342 headers
= {'x-api-key': self
._webServerAPIKey
}
343 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + '/api/v1/servers/localhost/config/allow-from'
344 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
346 self
.assertEquals(r
.status_code
, 200)
347 self
.assertTrue(r
.json())
349 acl
= content
['value']
350 expectedACL
= ["127.0.0.1/32", "::1/128"]
353 self
.assertEquals(acl
, expectedACL
)
355 newACL
= ["192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"]
356 payload
= json
.dumps({"name": "allow-from",
357 "type": "ConfigSetting",
359 r
= requests
.put(url
, headers
=headers
, timeout
=self
._webTimeout
, data
=payload
)
361 self
.assertEquals(r
.status_code
, 200)
362 self
.assertTrue(r
.json())
364 acl
= content
['value']
366 self
.assertEquals(acl
, newACL
)
368 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
370 self
.assertEquals(r
.status_code
, 200)
371 self
.assertTrue(r
.json())
373 acl
= content
['value']
375 self
.assertEquals(acl
, newACL
)
377 configFile
= self
._APIWriteDir
+ '/' + 'acl.conf'
378 self
.assertTrue(os
.path
.isfile(configFile
))
380 with
open(configFile
, 'rt') as f
:
381 header
= f
.readline()
384 self
.assertEquals(header
, """-- Generated by the REST API, DO NOT EDIT\n""")
386 self
.assertIn(body
, {
387 """setACL({"192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"})\n""",
388 """setACL({"192.0.2.0/24", "203.0.113.0/24", "198.51.100.0/24"})\n""",
389 """setACL({"198.51.100.0/24", "192.0.2.0/24", "203.0.113.0/24"})\n""",
390 """setACL({"198.51.100.0/24", "203.0.113.0/24", "192.0.2.0/24"})\n""",
391 """setACL({"203.0.113.0/24", "192.0.2.0/24", "198.51.100.0/24"})\n""",
392 """setACL({"203.0.113.0/24", "198.51.100.0/24", "192.0.2.0/24"})\n"""
395 class TestAPICustomHeaders(DNSDistTest
):
398 _webServerPort
= 8083
399 _webServerBasicAuthPassword
= 'secret'
400 _webServerAPIKey
= 'apisecret'
401 # paths accessible using the API key only
402 _apiOnlyPath
= '/api/v1/servers/localhost/config'
403 # paths accessible using basic auth only (list not exhaustive)
405 _consoleKey
= DNSDistTest
.generateConsoleKey()
406 _consoleKeyB64
= base64
.b64encode(_consoleKey
).decode('ascii')
407 _config_params
= ['_consoleKeyB64', '_consolePort', '_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
408 _config_template
= """
410 controlSocket("127.0.0.1:%s")
411 setACL({"127.0.0.1/32", "::1/128"})
412 newServer({address="127.0.0.1:%s"})
413 webserver("127.0.0.1:%s", "%s", "%s", {["X-Frame-Options"]="", ["X-Custom"]="custom"})
416 def testBasicHeaders(self
):
418 API: Basic custom headers
421 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._basicOnlyPath
423 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
425 self
.assertEquals(r
.status_code
, 200)
426 self
.assertEquals(r
.headers
.get('x-custom'), "custom")
427 self
.assertFalse("x-frame-options" in r
.headers
)
429 def testBasicHeadersUpdate(self
):
431 API: Basic update of custom headers
434 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._basicOnlyPath
435 self
.sendConsoleCommand('setWebserverConfig({customHeaders={["x-powered-by"]="dnsdist"}})')
436 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
438 self
.assertEquals(r
.status_code
, 200)
439 self
.assertEquals(r
.headers
.get('x-powered-by'), "dnsdist")
440 self
.assertTrue("x-frame-options" in r
.headers
)
443 class TestAPIAuth(DNSDistTest
):
446 _webServerPort
= 8083
447 _webServerBasicAuthPassword
= 'secret'
448 _webServerBasicAuthPasswordNew
= 'password'
449 _webServerAPIKey
= 'apisecret'
450 _webServerAPIKeyNew
= 'apipassword'
451 # paths accessible using the API key only
452 _apiOnlyPath
= '/api/v1/servers/localhost/config'
453 # paths accessible using basic auth only (list not exhaustive)
455 _consoleKey
= DNSDistTest
.generateConsoleKey()
456 _consoleKeyB64
= base64
.b64encode(_consoleKey
).decode('ascii')
457 _config_params
= ['_consoleKeyB64', '_consolePort', '_testServerPort', '_webServerPort', '_webServerBasicAuthPassword', '_webServerAPIKey']
458 _config_template
= """
460 controlSocket("127.0.0.1:%s")
461 setACL({"127.0.0.1/32", "::1/128"})
462 newServer{address="127.0.0.1:%s"}
463 webserver("127.0.0.1:%s", "%s", "%s")
466 def testBasicAuthChange(self
):
468 API: Basic Authentication updating credentials
471 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._basicOnlyPath
472 self
.sendConsoleCommand('setWebserverConfig({{password="{}"}})'.format(self
._webServerBasicAuthPasswordNew
))
474 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPasswordNew
), timeout
=self
._webTimeout
)
476 self
.assertEquals(r
.status_code
, 200)
478 # Make sure the old password is not usable any more
479 r
= requests
.get(url
, auth
=('whatever', self
._webServerBasicAuthPassword
), timeout
=self
._webTimeout
)
480 self
.assertEquals(r
.status_code
, 401)
482 def testXAPIKeyChange(self
):
484 API: X-Api-Key updating credentials
487 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._apiOnlyPath
488 self
.sendConsoleCommand('setWebserverConfig({{apiKey="{}"}})'.format(self
._webServerAPIKeyNew
))
490 headers
= {'x-api-key': self
._webServerAPIKeyNew
}
491 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
493 self
.assertEquals(r
.status_code
, 200)
495 # Make sure the old password is not usable any more
496 headers
= {'x-api-key': self
._webServerAPIKey
}
497 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
498 self
.assertEquals(r
.status_code
, 401)
500 def testBasicAuthOnlyChange(self
):
502 API: X-Api-Key updated to none (disabled)
505 url
= 'http://127.0.0.1:' + str(self
._webServerPort
) + self
._apiOnlyPath
506 self
.sendConsoleCommand('setWebserverConfig({{apiKey="{}"}})'.format(self
._webServerAPIKeyNew
))
508 headers
= {'x-api-key': self
._webServerAPIKeyNew
}
509 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
511 self
.assertEquals(r
.status_code
, 200)
514 self
.sendConsoleCommand('setWebserverConfig({apiKey=""})')
516 r
= requests
.get(url
, headers
=headers
, timeout
=self
._webTimeout
)
517 self
.assertEquals(r
.status_code
, 401)