summaryrefslogtreecommitdiffstats
path: root/python/tests/websimulator.py
blob: 0c923d051af444d499b97f91990d0f5501fb83f1 (plain)
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
# -*- coding: UTF-8 -*-


# Lasso Simulator
# By: Emmanuel Raviart <eraviart@entrouvert.com>
#
# Copyright (C) 2004 Entr'ouvert
# http://lasso.entrouvert.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


# FIXME: Replace principal with client in most methods.
# FIXME: Rename webUser to userAccount.


import abstractweb


class HttpRequest(abstractweb.HttpRequestMixin, object):
    client = None # Principal or web site sending the request.
    body = None
    form = None
    headers = None
    method = None # 'GET' or 'POST' or 'PUT' or...
    url = None

    def __init__(self, client, method, url, headers = None, body = None, form = None):
        self.client = client
        self.method = method
        self.url = url
        if headers:
            self.headers = headers
        if body:
            self.body = body
        if form:
            self.form = form

    def getFormField(self, name, default = 'none'):
        if self.form and name in self.form:
            return self.form[name]
        if default == 'none':
            raise KeyError(name)
        return default

    def getPath(self):
        return self.pathAndQuery.split('?', 1)[0]

    def getPathAndQuery(self):
        urlWithoutScheme = self.url[self.url.find('://') + 3:]
        if '/' in urlWithoutScheme:
            pathAndQuery = urlWithoutScheme[urlWithoutScheme.find('/'):]
        else:
            pathAndQuery = ''
        return pathAndQuery

    def getQuery(self):
        splitedUrl = self.pathAndQuery.split('?', 1)
        if len(splitedUrl) > 1:
            return splitedUrl[1]
        else:
            return ''

    def getScheme(self):
        return self.url.split(':', 1)[0].lower()

    def send(self):
        webSite = self.client.internet.getWebSite(self.url)
        return webSite.handleHttpRequest(self)

    path = property(getPath)
    pathAndQuery = property(getPathAndQuery)
    query = property(getQuery)
    scheme = property(getScheme)


class HttpResponse(abstractweb.HttpResponseMixin, object):
    def send(self, httpRequestHandler):
        return self


class HttpRequestHandler(abstractweb.HttpRequestHandlerMixin, object):
    HttpResponse = HttpResponse # Class

    def __init__(self, webServer, httpRequest):
        self.webServer = webServer
        self.httpRequest = httpRequest

    def respondRedirectTemporarily(self, url):
        return self.httpRequest.client.redirect(url)


class Internet(object):
    webSites = None

    def __init__(self):
        self.webSites = {}

    def addWebSite(self, webSite):
        self.webSites[webSite.url] = webSite

    def getWebSite(self, url):
        for webSiteUrl, webSite in self.webSites.iteritems():
            if url.startswith(webSiteUrl):
                return webSite
        raise Exception('Unknown web site: %s' % url)


class WebClient(object):
    internet = None
    keyring = None
    httpRequestHeaders = {
        'User-Agent': 'LassoSimulator/0.0.0',
        'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html',
        }
    webSessionIds = None # Simulate the cookies, stored in user's navigator, and containing the
                         # IDs of sessions already opened by the user.

    def __init__(self, internet):
        self.internet = internet
        self.keyring = {}
        self.webSessionIds = {}

    def redirect(self, url):
        return self.sendHttpRequest('GET', url)

    def sendHttpRequest(self, method, url, headers = None, body = None, form = None):
        if headers:
            httpRequestHeaders = self.httpRequestHeaders.copy()
            for name, value in headers.iteritems():
                httpRequestHeaders[name] = value
        else:
            httpRequestHeaders = self.httpRequestHeaders
        return HttpRequest(
            self, method, url, headers = httpRequestHeaders, body = body, form = form).send()

    def sendHttpRequestToSite(self, webSite, method, path, headers = None, body = None,
                              form = None):
        url = webSite.url
        if path:
            if path[0] == '/':
                while url[-1] == '/':
                    url = url[:-1]
            elif url[-1] != '/':
                url += '/'
            url += path
        return self.sendHttpRequest(method, url, headers = headers, body = body, form = form)


class Principal(WebClient):
    """Simulation of a user and its web navigator"""

    name = None # The user name

    def __init__(self, internet, name):
        WebClient.__init__(self, internet)
        self.name = name


class WebSession(object):
    """Simulation of session of a web site"""

    expirationTime = None # A sample session variable
    loginDump = None # Used only by some identity providers
    uniqueId = None # The session number
    sessionDump = None
    webUserId = None # ID of logged user. 

    def __init__(self, uniqueId):
        self.uniqueId = uniqueId


class WebUser(object):
    """Simulation of user of a web site"""

    identityDump = None
    language = 'fr' # A sample user variable
    uniqueId = None # The user name is used as an ID in this simulation.

    def __init__(self, uniqueId):
        self.uniqueId = uniqueId


class WebSite(WebClient):
    """Simulation of a web site"""

    httpResponseHeaders = {
        'Server': 'Lasso Simulator Web Server',
        }
    lastWebSessionId = 0
    providerId = None # The Liberty providerID of this web site
    url = None # The main URL of web site
    webUsers = None
    webSessions = None

    def __init__(self, internet, url):
        WebClient.__init__(self, internet)
        self.url = url
        self.webUserIdsByNameIdentifier = {}
        self.webUsers = {}
        self.webSessionIdsByNameIdentifier = {}
        self.webSessions = {}
        self.internet.addWebSite(self)

    def addWebUser(self, name):
        self.webUsers[name] = WebUser(name)

    def createWebSession(self, client):
        self.lastWebSessionId += 1
        webSession = WebSession(self.lastWebSessionId)
        self.webSessions[self.lastWebSessionId] = webSession
        client.webSessionIds[self.url] = self.lastWebSessionId
        return webSession

    def getIdentityDump(self, principal):
        webSession = self.getWebSession(principal)
        webUser = self.getWebUserFromWebSession(webSession)
        if webUser is None:
            return None
        return webUser.identityDump

    def getSessionDump(self, principal):
        webSession = self.getWebSession(principal)
        if webSession is None:
            return None
        return webSession.sessionDump

    def getWebSession(self, principal):
        webSessionId = principal.webSessionIds.get(self.url, None)
        if webSessionId is None:
            # The user has no web session opened on this site.
            return None
        return self.webSessions.get(webSessionId, None)

    def getWebSessionFromNameIdentifier(self, nameIdentifier):
        webSessionId = self.webSessionIdsByNameIdentifier.get(nameIdentifier, None)
        if webSessionId is None:
            # The user has no federation on this site or has no authentication assertion for this
            # federation.
            return None
        return self.webSessions.get(webSessionId, None)

    def getWebUserFromNameIdentifier(self, nameIdentifier):
        webUserId = self.webUserIdsByNameIdentifier.get(nameIdentifier, None)
        if webUserId is None:
            # The user has no federation on this site.
            return None
        return self.webUsers.get(webUserId, None)

    def getWebUserFromWebSession(self, webSession):
        if webSession is None:
            return None
        webUserId = webSession.webUserId
        if webUserId is None:
            # The user has no account on this site.
            return None
        return self.webUsers.get(webUserId, None)

    def handleHttpRequest(self, httpRequest):
        httpRequestHandler = HttpRequestHandler(self, httpRequest)
        return self.handleHttpRequestHandler(httpRequestHandler)

    def handleHttpRequestHandler(self, httpRequestHandler):
        methodName = httpRequestHandler.httpRequest.path.replace('/', '')
        try:
            method = getattr(self, methodName)
        except AttributeError:
            return httpRequestHandler.respond(
                404, 'Path "%s" Not Found.' % httpRequestHandler.httpRequest.path)
        return method(httpRequestHandler)