Debian Codegraph @

gavo/web/weberrors.py

raw
1 """
2 Default error displays for the data center and error helper code.
3
4 Everything in here must render synchronuosly.
5
6 You probably should not construct anything in this module directly
7 but rather just raise the appropriate exceptions from svcs.
8 """
9
10 #c Copyright 2008-2025, the GAVO project <[email protected]>
11 #c
12 #c This program is free software, covered by the GNU GPL. See the
13 #c COPYING file in the source distribution.
14
15
16 import urllib.parse
17
18 from twisted.python import failure
19 from twisted.web import server
20 from twisted.web import template
21 from twisted.web.template import tags as T
22
23 from gavo import base
24 from gavo import svcs
25 from gavo import utils
26 from gavo.formal import nevowc
27 from gavo.web import common
28
29
30 class _Silence(Exception):
31 """A sentinel used by Silence.
32 """
33
34 def Silence():
35 """returns a failure.Failure that cases this module to not
36 touch request at all.
37
38 You want to return this from errbacks that already have spit
39 out their error message.
40 """
41 return failure.Failure(exc_value=_Silence("Keep quiet"))
42
43
44 class ErrorPage(nevowc.TemplatedPage, common.CommonRenderers):
45 """A base for error handling pages.
46
47 The idea is that you set the "handles" class attribute to
48 the exception you handle. The exception has to match exactly, i.e.,
49 no isinstancing is done.
50
51 You also must set status to the HTTP status code the error should
52 return.
53
54 All error pages have a failure attribute that's a twisted failure
55 with all the related mess (e.g., tracebacks).
56
57 You have the status and message data methods.
58
59 In custom exceptions, you can attach stan in htmlMessage, and ErrorPages
60 will show that as the error message.
61 """
62 handles = None
63 status = 500
64 titleMessage = "Unspecified Error"
65 beforeMessage = "We're sorry, but something didn't work out:"
66 afterMessage = T.p["This generic text shouldn't be here. The"
67 " child class should override afterMessage."]
68 _footer = "delete this when done"
69
70 def __init__(self, error):
71 self.flr = error
72
73 def data_status(self, request, tag):
74 return str(self.status)
75
76 @template.renderer
77 def beforemessage(self, request, tag):
78 return tag[self.beforeMessage]
79
80 @template.renderer
81 def aftermessage(self, request, tag):
82 return tag[self.afterMessage]
83
84 @template.renderer
85 def message(self, request, tag):
86 if hasattr(self.flr.value, "htmlMessage"):
87 return tag(class_="errmsg")[self.flr.value.htmlMessage]
88 else:
89 return tag(class_="errmsg")[self.flr.getErrorMessage()]
90
91 @template.renderer
92 def hint(self, request, tag):
93 if (hasattr(self, "flr")
94 and hasattr(self.flr.value, "hint")
95 and self.flr.value.hint):
96 return tag[T.strong["Hint: "],
97 self.flr.value.hint]
98 return ""
99
100 @template.renderer
101 def rdlink(self, request, tag):
102 if hasattr(self.flr.value, "rd") and self.flr.value.rd:
103 rdURL = base.makeAbsoluteURL("/browse/%s"%
104 self.flr.value.rd.sourceId)
105 return T.p(class_="rdbacklink")["Also see the ",
106 T.a(href=rdURL)["resources provided by this RD"],
107 "."]
108 return ""
109
110 @template.renderer
111 def titlemessage(self, request, tag):
112 return tag["%s -- %s"%(
113 base.getConfig("web", "sitename"), self.titleMessage)]
114
115 @template.renderer
116 def footer(self, request, tag):
117 contactMail = str(base.getGlobalMeta("contact.email"))
118 return tag[
119 T.hr,
120 T.address[T.a(href="mailto:%s"%contactMail)[contactMail]]]
121
122 def render(self, request):
123 request.setResponseCode(self.status)
124 try:
125 request.write(nevowc.flattenSync(self._getDoc(request)))
126 except Exception as msg:
127 base.ui.notifyError("Error while writing error page: %s"%msg)
128 # something went wrong while serialising the error page
129 request.write(b"Ouch. Error while writing the error page. Sorry.\r\n"
130 b"\nPlease complain.\r\n")
131 request.finish()
132 return server.NOT_DONE_YET
133
134 loader = common.doctypedStan(T.html[
135 T.head(render="commonhead")[
136 T.title(render="titlemessage")],
137 T.body[
138 T.img(src="/static/img/logo_medium.png", class_="headlinelogo",
139 style="position:absolute;right:5pt"),
140 T.h1[
141 T.transparent(render="titlemessage"),
142 " (",
143 nevowc.addNevowAttributes(
144 T.transparent(render="string"), data="status"),
145 ")"],
146 T.p(render="beforemessage"),
147 T.div(class_="errors", render="message"),
148 T.div(render="aftermessage"),
149 T.div(class_="hint", render="hint")[
150 T.p("The error message also has a hint, which may in particular"
151 " be useful to the service operator. Be sure to include it"
152 " with your report:")],
153 T.transparent(render="footer")]])
154
155
156 class NotFoundPage(ErrorPage):
157 handles = svcs.UnknownURI
158 status = 404
159 titleMessage = "Not Found"
160 beforeMessage = ("We're sorry, but the resource you"
161 " requested could not be located.")
162 afterMessage = [
163 T.p["If this message resulted from following a link from ",
164 T.strong["within the data center"],
165 ", you have discovered a bug, and we would be"
166 " extremely grateful if you could notify us."],
167 T.p["If you got here following an ",
168 T.strong["external link"],
169 ", we would be"
170 " grateful for a notification as well. We will ask the"
171 " external operators to fix their links or provide"
172 " redirects as appropriate."],
173 T.p["In either case, you may find whatever you were looking"
174 " for by inspecting our ",
175 T.a(href="/")["list of published services"], "."],
176 T.p(render="rdlink")]
177
178
179 class NotFoundPageWithFancyMessage(NotFoundPage):
180 """A NotFoundPage with a message that's taken from a piece of stan.
181 """
182 handles = None
183
184 def __init__(self, message):
185 self.fancyMessage = message
186
187 @template.renderer
188 def message(self, request, tag):
189 return tag[self.fancyMessage]
190
191 @template.renderer
192 def rdlink(self, request, tag):
193 return ""
194
195
196 class OtherNotFoundPage(NotFoundPage):
197 handles = base.NotFoundError
198
199
200 class RDNotFoundPage(NotFoundPage):
201 handles = base.RDNotFound
202
203
204 class ForbiddenPage(ErrorPage):
205 handles = svcs.ForbiddenURI
206 status = 403
207 titleMessage = "Forbidden"
208 beforeMessage = "We're sorry, but the resource you requested is forbidden."
209 afterMessage = T.div[
210 T.p["This usually means you tried to use a renderer on a service"
211 " that does not support it. If you did not come up with the"
212 " URL in question yourself, complain fiercely to the staff of ",
213 T.transparent(render="getconfig")["[web]sitename"],
214 "."],
215 T.p(render="rdlink")]
216
217
218 class RedirectBase(ErrorPage):
219 def render(self, request):
220 # add request arguments if they are not already included in the
221 # URL we're redirecting to:
222 self.destURL = utils.bytify(self.flr.value.dest)
223 if b'?' not in self.destURL:
224 args = urllib.parse.urlparse(request.uri).query
225 if args:
226 self.destURL = self.destURL+b"?"+utils.bytify(args)
227 request.setHeader("location", self.destURL)
228 return ErrorPage.render(self, request)
229
230 @template.renderer
231 def destLink(self, request, tag):
232 return tag(href=self.destURL)
233
234 afterMessage = T.p["You should not see this page -- either your browser or"
235 " our site is broken. Complain."]
236
237
238 class RedirectPage(RedirectBase):
239 handles = svcs.WebRedirect
240 status = 301
241 titleMessage = "Moved Permanently"
242 beforeMessage = ["The resource you requested is available from a ",
243 T.a(render="destLink")[
244 "different URL"],
245 "."]
246
247
248 class FoundPage(RedirectBase):
249 handles = svcs.Found
250 status = 302
251 titleMessage = "Found"
252 beforeMessage = ["The resource you requested can be found at ",
253 T.a(render="destLink")[
254 T.transparent(render="destLink")],
255 "."]
256
257
258 class SeeOtherPage(RedirectBase):
259 handles = svcs.SeeOther
260 status = 303
261 titleMessage = "See Other"
262 beforeMessage = ["Please turn to a ",
263 T.a(render="destLink")[
264 "different URL"],
265 " to go on."]
266
267
268 class AuthenticatePage(ErrorPage):
269 handles = svcs.Authenticate
270 status = 401
271 titleMessage = "Authentication Required"
272
273 def render(self, request):
274 request.setHeader('WWW-Authenticate',
275 'Basic realm="%s"'%str(self.flr.value.realm))
276 return ErrorPage.render(self, request)
277
278 loader = svcs.loadSystemTemplate("unauth.html")
279
280
281 class BadMethodPage(ErrorPage):
282 handles = svcs.BadMethod
283 status = 405
284 titleMessage = "Bad Method"
285 beforeMessage = (
286 "You just tried to use some HTTP method to access this resource"
287 " that this resource does not support. This probably means that"
288 " this resource is for exclusive use for specialized clients.")
289 afterMessage = T.p["You may find whatever you were really looking"
290 " for by inspecting our ",
291 T.a(href="/")["list of published services"],
292 "."]
293
294
295 class BadRequestPage(ErrorPage):
296 handles = svcs.BadRequest
297 status = 400
298 titleMessage = "Bad Request"
299 beforeMessage = (
300 "The computer could not work out what your path or parameters"
301 " are supposed to mean, and it thinks you made a mistake.")
302
303
304 class UploadTooLargePage(ErrorPage):
305 handles = svcs.RequestEntityTooLarge
306 status = 413
307 titleMessage = "Upload too big"
308
309
310 class NotAcceptable(ErrorPage):
311 handles = base.DataError
312 status = 406
313 titleMessage = "Not Acceptable"
314 beforeMessage = ("The server cannot generate the data you requested."
315 " The associated message is:")
316 afterMessage = ""
317
318
319 class ErrorDisplay(ErrorPage):
320 handles = base.ReportableError
321 status = 500
322 titleMessage = "Error"
323 beforeMessage = ("A piece of code failed:")
324 afterMessage = [T.p["Problems of this sort usually mean we considered"
325 " the possibility of something like this happening; if the above"
326 " doesn't give you sufficient hints to fix the problem, please"
327 " complain to the address given below."],
328 T.p(render="hint")]
329
330
331 class NullPage(ErrorPage):
332 handles = _Silence
333 def render(self, request):
334 pass
335
336
337 # HTML mess for last-resort type error handling.
338 errorTemplate = (
339 '<body><div style="position:fixed;left:4px;top:4px;'
340 'visibility:visible;overflow:visible !important;'
341 'max-width:600px !important;z-index:500">'
342 '<div style="border:2px solid red;'
343 'width:400px !important;background:white">'
344 '%s'
345 '</div></div></body></html>')
346
347 def _formatFailure(flr):
348 res = errorTemplate%(
349 "<h1>Internal Error</h1><p>A(n)"
350 " %s exception occurred. The"
351 " accompanying message is: '%s'</p>"
352 "<p>If you are seeing this, it is always a bug in our code"
353 " or the data descriptions, and we would be extremely grateful"
354 " for a report at"
355 " %s</p>"%(flr.value.__class__.__name__,
356 common.escapeForHTML(flr.getErrorMessage()),
357 str(base.getGlobalMeta("contact.email"))))
358 return res.encode("ascii", "ignore")
359
360
361 class InternalServerErrorPage(ErrorPage):
362 """A catch-all page served when no other error page seemed responsible.
363 """
364 handles = base.Error # meaningless, no isinstance done here
365 status = 500
366 titleMessage = "Uncaught Exception"
367 beforeMessage = T.p["Your action has caused a(n) ",
368 nevowc.addNevowAttributes(
369 T.span(render="unicode"), data="excname"),
370 " exception to occur. As additional info, the failing code"
371 " gave:"],
372 afterMessage = T.p["This is always a bug in our software, and we would really"
373 " be grateful for a report to the contact address below,"
374 " preferably with a description of what you were trying to do,"
375 " including any data pieces if applicable. Thanks."]
376
377 def data_excname(self, request, tag):
378 return self.flr.value.__class__.__name__
379
380 def renderInnerException(self, request):
381 """called when rendering already has started.
382
383 We don't know where we're sitting, so we try to break out as well
384 as we can.
385 """
386 request.setResponseCode(500) # probably too late, but log still profits.
387 data = _formatFailure(self.flr)
388 if isinstance(data, str):
389 data = data.encode("utf-8", "ignore")
390 request.write(data)
391 request.finish()
392 return server.NOT_DONE_YET
393
394 def render(self, request):
395 base.ui.notifyFailure(self.flr,
396 "Returning an internal server error!")
397 base.ui.notifyInfo("Arguments of failed request: %s"%
398 repr(request.args)[:2000])
399
400 if getattr(self.flr.value, "hint", None):
401 base.ui.notifyDebug("Exception hint: %s"%self.flr.value.hint)
402
403 # Hack to work around excessive chattiness of t.w.FlattenerError
404 # (for something in an error page)
405 if hasattr(self.flr.value, "_roots"):
406 self.flr.value._roots = ''
407 self.flr.value._traceback = ''
408
409 if getattr(request, "startedWriting", False):
410 # exception happened while rendering a page.
411 return self.renderInnerException(request)
412 else:
413 return ErrorPage.render(self, request)
414
415
416 getErrorPage = utils.buildClassResolver(
417 baseClass=ErrorPage,
418 objects=list(globals().values()),
419 instances=False,
420 key=lambda obj: obj.handles,
421 default=InternalServerErrorPage)
422
423
424 def getDCErrorPage(flr):
425 """returns a t.w resource for a twisted failure.
426 """
427 if flr is None:
428 flr = failure.Failure()
429 return getErrorPage(flr.value.__class__)(flr)
430
431
432 def renderDCErrorPage(flr, request):
433 """renders a resource from a twisted failure.
434
435 This finishes request itself. It returns t.w.server.NOT_DONE_YET
436 because of that, so you can write return renderDCErrorPage from
437 a render method (or similar).
438 """
439 if getattr(request, "channel", "just testing") is None:
440 # the remote end has hung up; let's forget things
441 return
442 res = getDCErrorPage(flr)
443 return res.render(request)
444
445 common.produceErrorDocument = renderDCErrorPage