Debian Codegraph @

gavo/svcs/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.svcs import renderers
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, renderers.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, *, finish=True):
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 if finish:
132 request.finish()
133 return server.NOT_DONE_YET
134
135 loader = renderers.doctypedStan(T.html[
136 T.head(render="commonhead")[
137 T.title(render="titlemessage")],
138 T.body[
139 T.img(src="/static/img/logo_medium.png", class_="headlinelogo",
140 style="position:absolute;right:5pt"),
141 T.h1[
142 T.transparent(render="titlemessage"),
143 " (",
144 nevowc.addNevowAttributes(
145 T.transparent(render="string"), data="status"),
146 ")"],
147 T.p(render="beforemessage"),
148 T.div(class_="errors", render="message"),
149 T.div(render="aftermessage"),
150 T.div(class_="hint", render="hint")[
151 T.p("The error message also has a hint, which may in particular"
152 " be useful to the service operator. Be sure to include it"
153 " with your report:")],
154 T.transparent(render="footer")]])
155
156
157 class NotFoundPage(ErrorPage):
158 handles = svcs.UnknownURI
159 status = 404
160 titleMessage = "Not Found"
161 beforeMessage = ("We're sorry, but the resource you"
162 " requested could not be located.")
163 afterMessage = [
164 T.p["If this message resulted from following a link from ",
165 T.strong["within the data center"],
166 ", you have discovered a bug, and we would be"
167 " extremely grateful if you could notify us."],
168 T.p["If you got here following an ",
169 T.strong["external link"],
170 ", we would be"
171 " grateful for a notification as well. We will ask the"
172 " external operators to fix their links or provide"
173 " redirects as appropriate."],
174 T.p["In either case, you may find whatever you were looking"
175 " for by inspecting our ",
176 T.a(href="/")["list of published services"], "."],
177 T.p(render="rdlink")]
178
179
180 class NotFoundPageWithFancyMessage(NotFoundPage):
181 """A NotFoundPage with a message that's taken from a piece of stan.
182 """
183 handles = None
184
185 def __init__(self, message):
186 self.fancyMessage = message
187
188 @template.renderer
189 def message(self, request, tag):
190 return tag[self.fancyMessage]
191
192 @template.renderer
193 def rdlink(self, request, tag):
194 return ""
195
196
197 class OtherNotFoundPage(NotFoundPage):
198 handles = base.NotFoundError
199
200
201 class RDNotFoundPage(NotFoundPage):
202 handles = base.RDNotFound
203
204
205 class ForbiddenPage(ErrorPage):
206 handles = svcs.ForbiddenURI
207 status = 403
208 titleMessage = "Forbidden"
209 beforeMessage = "We're sorry, but the resource you requested is forbidden."
210 afterMessage = T.div[
211 T.p["This usually means you tried to use a renderer on a service"
212 " that does not support it. If you did not come up with the"
213 " URL in question yourself, complain fiercely to the staff of ",
214 T.transparent(render="getconfig")["[web]sitename"],
215 "."],
216 T.p(render="rdlink")]
217
218
219 class RedirectBase(ErrorPage):
220 def render(self, request, *, finish=True):
221 # add request arguments if they are not already included in the
222 # URL we're redirecting to:
223 self.destURL = utils.bytify(self.flr.value.dest)
224 if b'?' not in self.destURL:
225 args = urllib.parse.urlparse(request.uri).query
226 if args:
227 self.destURL = self.destURL+b"?"+utils.bytify(args)
228 request.setHeader("location", self.destURL)
229 return ErrorPage.render(self, request, finish=finish)
230
231 @template.renderer
232 def destLink(self, request, tag):
233 return tag(href=self.destURL)
234
235 afterMessage = T.p["You should not see this page -- either your browser or"
236 " our site is broken. Complain."]
237
238
239 class RedirectPage(RedirectBase):
240 handles = svcs.WebRedirect
241 status = 301
242 titleMessage = "Moved Permanently"
243 beforeMessage = ["The resource you requested is available from a ",
244 T.a(render="destLink")[
245 "different URL"],
246 "."]
247
248
249 class FoundPage(RedirectBase):
250 handles = svcs.Found
251 status = 302
252 titleMessage = "Found"
253 beforeMessage = ["The resource you requested can be found at ",
254 T.a(render="destLink")[
255 T.transparent(render="destLink")],
256 "."]
257
258
259 class SeeOtherPage(RedirectBase):
260 handles = svcs.SeeOther
261 status = 303
262 titleMessage = "See Other"
263 beforeMessage = ["Please turn to a ",
264 T.a(render="destLink")[
265 "different URL"],
266 " to go on."]
267
268
269 class AuthenticatePage(ErrorPage):
270 handles = svcs.Authenticate
271 status = 401
272 titleMessage = "Authentication Required"
273
274 def render(self, request):
275 request.setHeader('WWW-Authenticate',
276 'Basic realm="%s"'%str(self.flr.value.realm))
277 return ErrorPage.render(self, request)
278
279 loader = svcs.loadSystemTemplate("unauth.html")
280
281
282 class BadMethodPage(ErrorPage):
283 handles = svcs.BadMethod
284 status = 405
285 titleMessage = "Bad Method"
286 beforeMessage = (
287 "You just tried to use some HTTP method to access this resource"
288 " that this resource does not support. This probably means that"
289 " this resource is for exclusive use for specialized clients.")
290 afterMessage = T.p["You may find whatever you were really looking"
291 " for by inspecting our ",
292 T.a(href="/")["list of published services"],
293 "."]
294
295
296 class BadRequestPage(ErrorPage):
297 handles = svcs.BadRequest
298 status = 400
299 titleMessage = "Bad Request"
300 beforeMessage = (
301 "The computer could not work out what your path or parameters"
302 " are supposed to mean, and it thinks you made a mistake.")
303
304
305 class UploadTooLargePage(ErrorPage):
306 handles = svcs.RequestEntityTooLarge
307 status = 413
308 titleMessage = "Upload too big"
309
310
311 class NotAcceptable(ErrorPage):
312 handles = base.DataError
313 status = 406
314 titleMessage = "Not Acceptable"
315 beforeMessage = ("The server cannot generate the data you requested."
316 " The associated message is:")
317 afterMessage = ""
318
319
320 class ErrorDisplay(ErrorPage):
321 handles = base.ReportableError
322 status = 500
323 titleMessage = "Error"
324 beforeMessage = ("A piece of code failed:")
325 afterMessage = [T.p["Problems of this sort usually mean we considered"
326 " the possibility of something like this happening; if the above"
327 " doesn't give you sufficient hints to fix the problem, please"
328 " complain to the address given below."],
329 T.p(render="hint")]
330
331
332 class NullPage(ErrorPage):
333 handles = _Silence
334 def render(self, request):
335 pass
336
337
338 # HTML mess for last-resort type error handling.
339 errorTemplate = (
340 '<body><div style="position:fixed;left:4px;top:4px;'
341 'visibility:visible;overflow:visible !important;'
342 'max-width:600px !important;z-index:500">'
343 '<div style="border:2px solid red;'
344 'width:400px !important;background:white">'
345 '%s'
346 '</div></div></body></html>')
347
348 def _formatFailure(flr):
349 res = errorTemplate%(
350 "<h1>Internal Error</h1><p>A(n)"
351 " %s exception occurred. The"
352 " accompanying message is: '%s'</p>"
353 "<p>If you are seeing this, it is always a bug in our code"
354 " or the data descriptions, and we would be extremely grateful"
355 " for a report at"
356 " %s</p>"%(flr.value.__class__.__name__,
357 utils.escapePCDATA(flr.getErrorMessage()),
358 str(base.getGlobalMeta("contact.email"))))
359 return res.encode("ascii", "ignore")
360
361
362 class InternalServerErrorPage(ErrorPage):
363 """A catch-all page served when no other error page seemed responsible.
364 """
365 handles = base.Error # meaningless, no isinstance done here
366 status = 500
367 titleMessage = "Uncaught Exception"
368 beforeMessage = T.p["Your action has caused a(n) ",
369 nevowc.addNevowAttributes(
370 T.span(render="unicode"), data="excname"),
371 " exception to occur. As additional info, the failing code"
372 " gave:"],
373 afterMessage = T.p["This is always a bug in our software, and we would really"
374 " be grateful for a report to the contact address below,"
375 " preferably with a description of what you were trying to do,"
376 " including any data pieces if applicable. Thanks."]
377
378 def data_excname(self, request, tag):
379 return self.flr.value.__class__.__name__
380
381 def renderInnerException(self, request):
382 """called when rendering already has started.
383
384 We don't know where we're sitting, so we try to break out as well
385 as we can.
386 """
387 request.setResponseCode(500) # probably too late, but log still profits.
388 data = _formatFailure(self.flr)
389 if isinstance(data, str):
390 data = data.encode("utf-8", "ignore")
391 request.write(data)
392 request.finish()
393 return server.NOT_DONE_YET
394
395 def render(self, request):
396 base.ui.notifyFailure(self.flr,
397 "Returning an internal server error!")
398 base.ui.notifyInfo("Arguments of failed request: %s"%
399 repr(request.args)[:2000])
400
401 if getattr(self.flr.value, "hint", None):
402 base.ui.notifyDebug("Exception hint: %s"%self.flr.value.hint)
403
404 # Hack to work around excessive chattiness of t.w.FlattenerError
405 # (for something in an error page)
406 if hasattr(self.flr.value, "_roots"):
407 self.flr.value._roots = ''
408 self.flr.value._traceback = ''
409
410 if getattr(request, "startedWriting", False):
411 # exception happened while rendering a page.
412 return self.renderInnerException(request)
413 else:
414 return ErrorPage.render(self, request)
415
416
417 getErrorPage = utils.buildClassResolver(
418 baseClass=ErrorPage,
419 objects=list(globals().values()),
420 instances=False,
421 key=lambda obj: obj.handles,
422 default=InternalServerErrorPage)
423
424
425 def getDCErrorPage(flr):
426 """returns a t.w resource for a twisted failure.
427 """
428 if isinstance(flr, Exception):
429 flr = failure.Failure(flr)
430 if flr is None:
431 flr = failure.Failure()
432 return getErrorPage(flr.value.__class__)(flr)
433
434
435 def renderDCErrorPage(flr, request):
436 """renders a resource a twisted failure.
437
438 This finishes request itself. It returns t.w.server.NOT_DONE_YET
439 because of that, so you can write return renderDCErrorPage from
440 a render method (or similar).
441 """
442 if getattr(request, "channel", "just testing") is None:
443 # the remote end has hung up; let's forget things
444 return
445 res = getDCErrorPage(flr)
446 return res.render(request)