~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/dispatch/__init__.py

  • Committer: William Grant
  • Date: 2009-12-02 02:20:57 UTC
  • mto: This revision was merged to the branch mainline in revision 1353.
  • Revision ID: grantw@unimelb.edu.au-20091202022057-m3w3rzrzp47y89to
Refuse to traverse through an object to which the user has no permissions. This stops information leakage in breadcrumbs.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2009 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Author: Matt Giuca, Will Grant
 
19
 
 
20
"""
 
21
This is a mod_python handler program. The correct way to call it is to have
 
22
Apache send all requests to be handled by the module 'dispatch'.
 
23
 
 
24
Top-level handler. Handles all requests to all pages in IVLE.
 
25
Handles authentication and delegates to views for authorization,
 
26
then passes the request along to the appropriate view.
 
27
"""
 
28
 
 
29
import sys
 
30
import os
 
31
import os.path
 
32
import urllib
 
33
import cgi
 
34
import traceback
 
35
import logging
 
36
import socket
 
37
import time
 
38
 
 
39
import mod_python
 
40
 
 
41
from ivle import util
 
42
import ivle.config
 
43
from ivle.dispatch.request import Request
 
44
import ivle.webapp.security
 
45
from ivle.webapp.base.plugins import ViewPlugin, PublicViewPlugin
 
46
from ivle.webapp.base.xhtml import XHTMLView, XHTMLErrorView
 
47
from ivle.webapp.errors import HTTPError, Unauthorized, NotFound
 
48
from ivle.webapp.publisher import Publisher, PublishingError
 
49
from ivle.webapp import ApplicationRoot
 
50
 
 
51
config = ivle.config.Config()
 
52
 
 
53
class ObjectPermissionCheckingPublisher(Publisher):
 
54
    """A specialised publisher that checks object permissions.
 
55
 
 
56
    This publisher verifies that the user holds any permission at all
 
57
    on the model objects through which the resolution path passes. If
 
58
    no permission is held, resolution is aborted with an Unauthorized
 
59
    exception.
 
60
 
 
61
    IMPORTANT: This does NOT check view permissions. It only checks
 
62
    the objects in between the root and the view, exclusive!
 
63
    """
 
64
 
 
65
    def traversed_to_object(self, obj):
 
66
        """Check that the user has any permission at all over the object."""
 
67
        if (hasattr(obj, 'get_permissions') and
 
68
            len(obj.get_permissions(self.root.user)) == 0):
 
69
            raise Unauthorized()
 
70
 
 
71
 
 
72
def generate_publisher(view_plugins, root):
 
73
    """
 
74
    Build a Mapper object for doing URL matching using 'routes', based on the
 
75
    given plugin registry.
 
76
    """
 
77
    r = ObjectPermissionCheckingPublisher(root=root)
 
78
 
 
79
    r.add_set_switch('api', 'api')
 
80
 
 
81
    for plugin in view_plugins:
 
82
        if hasattr(plugin, 'forward_routes'):
 
83
            for fr in plugin.forward_routes:
 
84
                # An annotated function can also be passed in directly.
 
85
                if hasattr(fr, '_forward_route_meta'):
 
86
                    r.add_forward_func(fr)
 
87
                else:
 
88
                    r.add_forward(*fr)
 
89
 
 
90
        if hasattr(plugin, 'reverse_routes'):
 
91
            for rr in plugin.reverse_routes:
 
92
                # An annotated function can also be passed in directly.
 
93
                if hasattr(rr, '_reverse_route_src'):
 
94
                    r.add_reverse_func(rr)
 
95
                else:
 
96
                    r.add_reverse(*rr)
 
97
 
 
98
        if hasattr(plugin, 'views'):
 
99
            for v in plugin.views:
 
100
                r.add_view(*v)
 
101
 
 
102
    return r
 
103
 
 
104
def handler(apachereq):
 
105
    """Handles an HTTP request.
 
106
 
 
107
    Intended to be called by mod_python, as a handler.
 
108
 
 
109
    @param apachereq: An Apache request object.
 
110
    """
 
111
    # Make the request object into an IVLE request which can be given to views
 
112
    req = Request(apachereq, config)
 
113
 
 
114
    # Hack? Try and get the user login early just in case we throw an error
 
115
    # (most likely 404) to stop us seeing not logged in even when we are.
 
116
    if not req.publicmode:
 
117
        user = ivle.webapp.security.get_user_details(req)
 
118
 
 
119
        # Don't set the user if it is disabled or hasn't accepted the ToS.
 
120
        if user and user.valid:
 
121
            req.user = user
 
122
 
 
123
    if req.publicmode:
 
124
        raise NotImplementedError("no public mode with obtrav yet!")
 
125
 
 
126
    req.publisher = generate_publisher(
 
127
        config.plugin_index[ViewPlugin],
 
128
        ApplicationRoot(req.config, req.store, req.user))
 
129
 
 
130
    try:
 
131
        obj, viewcls, subpath = req.publisher.resolve(req.uri.decode('utf-8'))
 
132
        try:
 
133
            # We 404 if we have a subpath but the view forbids it.
 
134
            if not viewcls.subpath_allowed and subpath:
 
135
                raise NotFound()
 
136
 
 
137
            # Instantiate the view, which should be a BaseView class
 
138
            view = viewcls(req, obj, subpath)
 
139
 
 
140
            # Check that the request (mainly the user) is permitted to access
 
141
            # the view.
 
142
            if not view.authorize(req):
 
143
                raise Unauthorized()
 
144
            # Render the output
 
145
            view.render(req)
 
146
        except HTTPError, e:
 
147
            # A view explicitly raised an HTTP error. Respect it.
 
148
            req.status = e.code
 
149
 
 
150
            # Try to find a custom error view.
 
151
            if hasattr(viewcls, 'get_error_view'):
 
152
                errviewcls = viewcls.get_error_view(e)
 
153
            else:
 
154
                errviewcls = XHTMLView.get_error_view(e)
 
155
 
 
156
            if errviewcls:
 
157
                errview = errviewcls(req, e, obj)
 
158
                errview.render(req)
 
159
                return req.OK
 
160
            elif e.message:
 
161
                req.write(e.message)
 
162
                return req.OK
 
163
            else:
 
164
                return e.code
 
165
        except mod_python.apache.SERVER_RETURN:
 
166
            # A mod_python-specific Apache error.
 
167
            # XXX: We need to raise these because req.throw_error() uses them.
 
168
            # Remove this after Google Code issue 117 is fixed.
 
169
            raise
 
170
        except Exception, e:
 
171
            # A non-HTTPError appeared. We have an unknown exception. Panic.
 
172
            handle_unknown_exception(req, *sys.exc_info())
 
173
            return req.OK
 
174
        else:
 
175
            req.store.commit()
 
176
            return req.OK
 
177
    except Unauthorized, e:
 
178
        # Resolution failed due to a permission check. Display a pretty
 
179
        # error, or maybe a login page.
 
180
        XHTMLView.get_error_view(e)(req, e, req.publisher.root).render(req)
 
181
        return req.OK
 
182
    except PublishingError, e:
 
183
        req.status = 404
 
184
 
 
185
        if req.user and req.user.admin:
 
186
            XHTMLErrorView(req, NotFound('Not found: ' +
 
187
                                         str(e.args)), e[0]).render(req)
 
188
        else:
 
189
            XHTMLErrorView(req, NotFound(), e[0]).render(req)
 
190
 
 
191
        return req.OK
 
192
 
 
193
def handle_unknown_exception(req, exc_type, exc_value, exc_traceback):
 
194
    """
 
195
    Given an exception that has just been thrown from IVLE, print its details
 
196
    to the request.
 
197
    This is a full handler. It assumes nothing has been written, and writes a
 
198
    complete HTML page.
 
199
    req: May be EITHER an IVLE req or an Apache req.
 
200
    The handler code may pass an apache req if an exception occurs before
 
201
    the IVLE request is created.
 
202
    """
 
203
    req.content_type = "text/html"
 
204
    logfile = os.path.join(config['paths']['logs'], 'ivle_error.log')
 
205
    logfail = False
 
206
 
 
207
    # XXX: This remains here for ivle.interpret's IVLEErrors. Once we rewrite
 
208
    #      fileservice, req.status should always be 500 (ISE) here.
 
209
    try:
 
210
        httpcode = exc_value.httpcode
 
211
        req.status = httpcode
 
212
    except AttributeError:
 
213
        httpcode = None
 
214
        req.status = mod_python.apache.HTTP_INTERNAL_SERVER_ERROR
 
215
 
 
216
    try:
 
217
        publicmode = req.publicmode
 
218
    except AttributeError:
 
219
        publicmode = True
 
220
    try:
 
221
        login = req.user.login
 
222
    except AttributeError:
 
223
        login = None
 
224
 
 
225
    # Log File
 
226
    try:
 
227
        for h in logging.getLogger().handlers:
 
228
            logging.getLogger().removeHandler(h)
 
229
        logging.basicConfig(level=logging.INFO,
 
230
            format='%(asctime)s %(levelname)s: ' +
 
231
                '(HTTP: ' + str(req.status) +
 
232
                ', Ref: ' + str(login) + '@' +
 
233
                str(socket.gethostname()) + str(req.uri) +
 
234
                ') %(message)s',
 
235
            filename=logfile,
 
236
            filemode='a')
 
237
    except IOError:
 
238
        logfail = True
 
239
 
 
240
    # A "bad" error message. We shouldn't get here unless IVLE
 
241
    # misbehaves (which is currently very easy, if things aren't set up
 
242
    # correctly).
 
243
    # Write the traceback.
 
244
 
 
245
    # We need to special-case IVLEJailError, as we can get another
 
246
    # almost-exception out of it.
 
247
    if exc_type is util.IVLEJailError:
 
248
        tb = 'Exception information extracted from IVLEJailError:\n'
 
249
        tb += urllib.unquote(exc_value.info)
 
250
    else:
 
251
        tb = ''.join(traceback.format_exception(exc_type, exc_value,
 
252
                                                exc_traceback))
 
253
 
 
254
    logging.error('\n' + tb)
 
255
 
 
256
    # Error messages are only displayed is the user is NOT a student,
 
257
    # or if there has been a problem logging the error message
 
258
    show_errors = (not publicmode) and ((login and req.user.admin) or logfail)
 
259
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                 
 
260
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                                      
 
261
<html xmlns="http://www.w3.org/1999/xhtml">
 
262
<head><title>IVLE Internal Server Error</title></head>
 
263
<body>
 
264
<h1>IVLE Internal Server Error</h1>
 
265
<p>An error has occured which is the fault of the IVLE developers or
 
266
administrators. """)
 
267
 
 
268
    if logfail:
 
269
        req.write("Please report this issue to the server administrators, "
 
270
                  "along with the following information.")
 
271
    else:
 
272
        req.write("Details have been logged for further examination.")
 
273
    req.write("</p>")
 
274
 
 
275
    if show_errors:
 
276
        req.write("<h2>Debugging information</h2>")
 
277
        req.write("<pre>\n%s\n</pre>\n"%cgi.escape(tb))
 
278
    req.write("</body></html>")