Skip to content

Commit 949241d

Browse files
authored
Merge pull request #3540 from elpaso/auth-integration-test
Auth integration test + more reliable server tests
2 parents 67d5e19 + 49ae020 commit 949241d

12 files changed

+488
-199
lines changed

tests/src/python/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -150,4 +150,5 @@ IF (WITH_SERVER)
150150
ADD_PYTHON_TEST(PyQgsServerAccessControl test_qgsserver_accesscontrol.py)
151151
ADD_PYTHON_TEST(PyQgsServerWFST test_qgsserver_wfst.py)
152152
ADD_PYTHON_TEST(PyQgsOfflineEditingWFS test_offline_editing_wfs.py)
153+
ADD_PYTHON_TEST(PyQgsAuthManagerEnpointTest test_authmanager_endpoint.py)
153154
ENDIF (WITH_SERVER)

tests/src/python/qgis_wrapped_server.py

+43-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@
55
This script launches a QGIS Server listening on port 8081 or on the port
66
specified on the environment variable QGIS_SERVER_DEFAULT_PORT
77
8+
For testing purposes, HTTP Basic can be enabled by setting the following
9+
environment variables:
10+
11+
* QGIS_SERVER_HTTP_BASIC_AUTH (default not set, set to anything to enable)
12+
* QGIS_SERVER_USERNAME (default ="username")
13+
* QGIS_SERVER_PASSWORD (default ="password")
14+
815
.. note:: This program is free software; you can redistribute it and/or modify
916
it under the terms of the GNU General Public License as published by
1017
the Free Software Foundation; either version 2 of the License, or
@@ -22,6 +29,8 @@
2229

2330

2431
import os
32+
import sys
33+
import signal
2534
import urllib.parse
2635
from http.server import BaseHTTPRequestHandler, HTTPServer
2736
from qgis.core import QgsApplication
@@ -36,11 +45,35 @@
3645
qgs_server = QgsServer()
3746

3847

48+
if os.environ.get('QGIS_SERVER_HTTP_BASIC_AUTH') is not None:
49+
from qgis.server import QgsServerFilter
50+
import base64
51+
52+
class HTTPBasicFilter(QgsServerFilter):
53+
54+
def responseComplete(self):
55+
request = self.serverInterface().requestHandler()
56+
if self.serverInterface().getEnv('HTTP_AUTHORIZATION'):
57+
username, password = base64.b64decode(self.serverInterface().getEnv('HTTP_AUTHORIZATION')[6:]).split(b':')
58+
if (username.decode('utf-8') == os.environ.get('QGIS_SERVER_USERNAME', 'username')
59+
and password.decode('utf-8') == os.environ.get('QGIS_SERVER_PASSWORD', 'password')):
60+
return
61+
# No auth ...
62+
request.clearHeaders()
63+
request.setHeader('Status', '401 Authorization required')
64+
request.setHeader('WWW-Authenticate', 'Basic realm="QGIS Server"')
65+
request.clearBody()
66+
request.appendBody(b'<h1>Authorization required</h1>')
67+
68+
filter = HTTPBasicFilter(qgs_server.serverInterface())
69+
qgs_server.serverInterface().registerFilter(filter)
70+
71+
3972
class Handler(BaseHTTPRequestHandler):
4073

4174
def do_GET(self):
4275
# CGI vars:
43-
for k, v in list(self.headers.items()):
76+
for k, v in self.headers.items():
4477
qgs_server.putenv('HTTP_%s' % k.replace(' ', '-').replace('-', '_').replace(' ', '-').upper(), v)
4578
qgs_server.putenv('SERVER_PORT', str(self.server.server_port))
4679
qgs_server.putenv('SERVER_NAME', self.server.server_name)
@@ -52,7 +85,7 @@ def do_GET(self):
5285
self.send_response(int(headers_dict['Status'].split(' ')[0]))
5386
except:
5487
self.send_response(200)
55-
for k, v in list(headers_dict.items()):
88+
for k, v in headers_dict.items():
5689
self.send_header(k, v)
5790
self.end_headers()
5891
self.wfile.write(body)
@@ -71,5 +104,12 @@ def do_POST(self):
71104
server = HTTPServer(('localhost', QGIS_SERVER_DEFAULT_PORT), Handler)
72105
print('Starting server on localhost:%s, use <Ctrl-C> to stop' %
73106
QGIS_SERVER_DEFAULT_PORT)
107+
108+
def signal_handler(signal, frame):
109+
global qgs_app
110+
print("\nExiting QGIS...")
111+
qgs_app.exitQgis()
112+
sys.exit(0)
113+
114+
signal.signal(signal.SIGINT, signal_handler)
74115
server.serve_forever()
75-
qgs_app.exitQgis()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Tests for auth manager WMS/WFS using QGIS Server through HTTP Basic
4+
enabled qgis_wrapped_server.py.
5+
6+
This is an integration test for QGIS Desktop Auth Manager WFS and WMS provider
7+
and QGIS Server WFS/WMS that check if QGIS can use a stored auth manager auth
8+
configuration to access an HTTP Basic protected endpoint.
9+
10+
11+
From build dir, run: ctest -R PyQgsAuthManagerEnpointTest -V
12+
13+
.. note:: This program is free software; you can redistribute it and/or modify
14+
it under the terms of the GNU General Public License as published by
15+
the Free Software Foundation; either version 2 of the License, or
16+
(at your option) any later version.
17+
"""
18+
import os
19+
import sys
20+
import subprocess
21+
import tempfile
22+
import random
23+
import string
24+
import urllib
25+
26+
__author__ = 'Alessandro Pasotti'
27+
__date__ = '18/09/2016'
28+
__copyright__ = 'Copyright 2016, The QGIS Project'
29+
# This will get replaced with a git SHA1 when you do a git archive
30+
__revision__ = '$Format:%H$'
31+
32+
from time import sleep
33+
from urllib.parse import quote
34+
from shutil import rmtree
35+
36+
from utilities import unitTestDataPath
37+
from qgis.core import (
38+
QgsAuthManager,
39+
QgsAuthMethodConfig,
40+
QgsVectorLayer,
41+
QgsRasterLayer,
42+
)
43+
from qgis.testing import (
44+
start_app,
45+
unittest,
46+
)
47+
48+
try:
49+
QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT = os.environ['QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT']
50+
except:
51+
import socket
52+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
53+
s.bind(("", 0))
54+
QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT = s.getsockname()[1]
55+
s.close()
56+
57+
QGIS_AUTH_DB_DIR_PATH = tempfile.mkdtemp()
58+
59+
os.environ['QGIS_AUTH_DB_DIR_PATH'] = QGIS_AUTH_DB_DIR_PATH
60+
61+
qgis_app = start_app()
62+
63+
64+
class TestAuthManager(unittest.TestCase):
65+
66+
@classmethod
67+
def setUpClass(cls):
68+
"""Run before all tests:
69+
Creates an auth configuration"""
70+
cls.port = QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT
71+
# Clean env just to be sure
72+
env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE']
73+
for ev in env_vars:
74+
try:
75+
del os.environ[ev]
76+
except KeyError:
77+
pass
78+
cls.testdata_path = unitTestDataPath('qgis_server') + '/'
79+
cls.project_path = quote(cls.testdata_path + "test_project.qgs")
80+
# Enable auth
81+
#os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
82+
authm = QgsAuthManager.instance()
83+
assert (authm.setMasterPassword('masterpassword', True))
84+
cls.auth_config = QgsAuthMethodConfig('Basic')
85+
cls.auth_config.setName('test_auth_config')
86+
cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
87+
cls.password = cls.username[::-1] # reversed
88+
cls.auth_config.setConfig('username', cls.username)
89+
cls.auth_config.setConfig('password', cls.password)
90+
assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
91+
92+
os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1'
93+
os.environ['QGIS_SERVER_USERNAME'] = cls.username
94+
os.environ['QGIS_SERVER_PASSWORD'] = cls.password
95+
os.environ['QGIS_SERVER_DEFAULT_PORT'] = str(cls.port)
96+
server_path = os.path.dirname(os.path.realpath(__file__)) + \
97+
'/qgis_wrapped_server.py'
98+
cls.server = subprocess.Popen([sys.executable, server_path],
99+
env=os.environ)
100+
sleep(2)
101+
102+
@classmethod
103+
def tearDownClass(cls):
104+
"""Run after all tests"""
105+
cls.server.terminate()
106+
rmtree(QGIS_AUTH_DB_DIR_PATH)
107+
del cls.server
108+
109+
def setUp(self):
110+
"""Run before each test."""
111+
pass
112+
113+
def tearDown(self):
114+
"""Run after each test."""
115+
pass
116+
117+
@classmethod
118+
def _getWFSLayer(cls, type_name, layer_name=None, authcfg=None):
119+
"""
120+
WFS layer factory
121+
"""
122+
if layer_name is None:
123+
layer_name = 'wfs_' + type_name
124+
parms = {
125+
'srsname': 'EPSG:4326',
126+
'typename': type_name,
127+
'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path),
128+
'version': 'auto',
129+
'table': '',
130+
}
131+
if authcfg is not None:
132+
parms.update({'authcfg': authcfg})
133+
uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())])
134+
wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS')
135+
return wfs_layer
136+
137+
@classmethod
138+
def _getWMSLayer(cls, layers, layer_name=None, authcfg=None):
139+
"""
140+
WMS layer factory
141+
"""
142+
if layer_name is None:
143+
layer_name = 'wms_' + layers.replace(',', '')
144+
parms = {
145+
'crs': 'EPSG:4326',
146+
'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path),
147+
'format': 'image/png',
148+
# This is needed because of a really wierd implementation in QGIS Server, that
149+
# replaces _ in the the real layer name with spaces
150+
'layers': urllib.parse.quote(layers).replace('_', ' '),
151+
'styles': '',
152+
#'sql': '',
153+
}
154+
if authcfg is not None:
155+
parms.update({'authcfg': authcfg})
156+
uri = '&'.join([("%s=%s" % (k, v.replace('=', '%3D'))) for k, v in list(parms.items())])
157+
wms_layer = QgsRasterLayer(uri, layer_name, 'wms')
158+
return wms_layer
159+
160+
def testValidAuthAccess(self):
161+
"""
162+
Access the HTTP Basic protected layer with valid credentials
163+
"""
164+
wfs_layer = self._getWFSLayer('testlayer_èé', authcfg=self.auth_config.id())
165+
self.assertTrue(wfs_layer.isValid())
166+
wms_layer = self._getWMSLayer('testlayer_èé', authcfg=self.auth_config.id())
167+
self.assertTrue(wms_layer.isValid())
168+
169+
def testInvalidAuthAccess(self):
170+
"""
171+
Access the HTTP Basic protected layer with no credentials
172+
"""
173+
wfs_layer = self._getWFSLayer('testlayer_èé')
174+
self.assertFalse(wfs_layer.isValid())
175+
wms_layer = self._getWMSLayer('testlayer_èé')
176+
self.assertFalse(wms_layer.isValid())
177+
178+
179+
if __name__ == '__main__':
180+
unittest.main()

tests/src/python/test_offline_editing_wfs.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,15 @@
4545

4646
from offlineditingtestbase import OfflineTestBase
4747

48+
4849
try:
4950
QGIS_SERVER_WFST_DEFAULT_PORT = os.environ['QGIS_SERVER_WFST_DEFAULT_PORT']
5051
except:
51-
QGIS_SERVER_WFST_DEFAULT_PORT = 8081
52+
import socket
53+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
54+
s.bind(("", 0))
55+
QGIS_SERVER_WFST_DEFAULT_PORT = s.getsockname()[1]
56+
s.close()
5257

5358
qgis_app = start_app()
5459

0 commit comments

Comments
 (0)