Debian Codegraph @

gavo/web/common.py

raw
1 """
2 Common code for the nevow based interface.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import json
12 from urllib import parse as urlparse
13
14 from twisted.python import failure
15 from twisted.web import resource
16 from twisted.web import server
17 from twisted.web import static
18 from twisted.web.template import tags as T
19 from twisted.web import http
20
21 from gavo import base
22 from gavo import formal
23 from gavo import svcs
24 from gavo import utils
25 from gavo.base import meta
26 from gavo.protocols import creds
27 from gavo.svcs.renderers import (CommonRenderers, #noflake: exported names
28 doctypedStan, JSEXT)
29 from gavo.svcs.weberrors import renderDCErrorPage as produceErrorDocument
30
31
32 # monkeypatching static's mime magic
33 static.File.contentTypes[".ascii"] = "application/octet-stream"
34 static.File.contentTypes[".f"] = "text/x-fortran"
35 static.File.contentTypes[".vot"] = base.votableType
36 static.File.contentTypes[".rd"] = "application/x-gavo-descriptor+xml"
37 static.File.contentTypes[".f90"] = "text/x-fortran"
38 static.File.contentTypes[".skyglow"] = "text/plain"
39 static.File.contentTypes[".fitstable"] = "application/fits"
40 static.File.contentTypes[".fits"] = "application/fits"
41 # this one is for co-operation with ifpages
42 static.File.contentTypes[".shtml"] = "text/nevow-template"
43
44
45 def getfirst(request, key, default):
46 """returns the first value of key in the arguments of a twisted request.
47 """
48 return utils.getfirst(request.strargs, key, default)
49
50 GZIP_ENCODER = server.GzipEncoderFactory()
51 # we don't want to waste a lot of CPU on one-shot 10% compression gains.
52 GZIP_ENCODER.compressLevel = 3
53
54 def compwrap(pg):
55 """wraps some twisted resource for compression.
56 """
57 return resource.EncodingResourceWrapper(pg, [GZIP_ENCODER])
58
59
60 class HTMLMetaBuilder(meta.MetaBuilder):
61 def __init__(self, macroPackage=None):
62 meta.MetaBuilder.__init__(self)
63 self.resultTree, self.currentAtom = [[]], None
64 self.macroPackage = macroPackage
65
66 def startKey(self, atom):
67 self.resultTree.append([])
68
69 def enterValue(self, value):
70 val = value.getContent("html", self.macroPackage)
71 if val:
72 if not hasattr(val, "render"):
73 # it's hopefully something sufficiently string-like
74 self.resultTree[-1].append(T.xml(val))
75 else:
76 self.resultTree[-1].append(val)
77
78 # for meta items rendering their children themselves (which return
79 # in IncludesChildren object), do not fold in rendered children
80 # (the None sentinel is handled in endKey)
81 if isinstance(val, meta.IncludesChildren):
82 self.resultTree[-1].append(None)
83
84 def endKey(self, atom):
85 children = [c for c in self.resultTree.pop() if c]
86 # see enterValue on why we're doing this
87 if (self.resultTree[-1]
88 and self.resultTree[-1][-1] is None):
89 return
90
91 if len(children)>1:
92 childElements = []
93 for c in children:
94 childElements.append(T.li(class_="metaItem")[c])
95 self.resultTree[-1].append(T.ul(class_="metaEnum")[childElements])
96 elif len(children)==1:
97 self.resultTree[-1].append(children[0])
98
99 def getResult(self):
100 return self.resultTree[0]
101
102 def clear(self):
103 self.resultTree = [[]]
104
105
106 def runAuthenticated(request, reqGroup, fun, *args):
107 """returns the value of ``fun(*args)`` if the logged in user is in reqGroup,
108 requests authentication otherwise.
109 """
110 if creds.hasCredentials(request.getUser(), request.getPassword(), reqGroup):
111 return fun(*args)
112 else:
113 raise svcs.Authenticate()
114
115
116 class TypedData(resource.Resource):
117 """A simple resource just producing bytes passed in during construction,
118 declared as a special content type.
119 """
120 def __init__(self, data, mime, modificationStamp=None):
121 resource.Resource.__init__(self)
122 self.data, self.mime = data, mime
123 self.modificationStamp = modificationStamp
124
125 def render(self, request):
126 request.setHeader("content-type", self.mime)
127
128 if self.modificationStamp is not None:
129 if request.setLastModified(self.modificationStamp)==http.CACHED:
130 return b""
131
132 request.write(self.data)
133 request.finish()
134 return server.NOT_DONE_YET
135
136
137 class JSONQuery(resource.Resource):
138 """A resource returning JSON for a database query.
139
140 Have the query in a query attribute to the class. Use %(whatever)s
141 to put in the first match of that in request.strargs.
142
143 TODO: we should do some more sensible error handling.
144 """
145 def doQuery(self, queryArgs):
146 """returns a list of dictionaries for the query result. The default
147 just executes self.query.
148 """
149 with base.getTableConn() as conn:
150 return list(conn.queryToDicts(
151 self.query, queryArgs))
152
153
154 def render(self, request):
155 queryArgs = dict((key, value[0])
156 for key, value in request.strargs.items())
157
158 res = self.doQuery(queryArgs)
159
160 request.setHeader("content-type", "text/json")
161 return json.dumps(res).encode("utf-8")
162
163
164 class BinaryItem:
165 """A sentinel marking request.args items that couldn't be utf-8 decoded
166
167 Whatever it was (most likely a file upload) is found in the original
168 attribute.
169 """
170 def __init__(self, original):
171 self.original = original
172
173 def __getnewargs_ex__(self):
174 # we don't want file uploads in the pickled stuff that TAP and
175 # UWS make of their parameters (it's a waste of CPU and space, as
176 # the files already reside as plain files on disk). If this
177 # ever fires, just make sure you're popping file uploads from
178 # strargs before pickling.
179 raise ValueError("You cannot (and should not) pickle BinaryItems")
180
181 def __str__(self):
182 return ("<A piece of data that is no utf-8 encoded string: %s>"%
183 utils.makeEllipsis(repr(self.original)))
184
185
186 class Request(formal.Request):
187 """a custom request class used in DaCHS' application server.
188
189 Overridden behaviour:
190
191 * you can write str; it's going to be utf-8 encoded automatically,
192 which out to be about the right thing almost always in DaCHS.
193 * There's a popSegments method for use during resource dispatch (it
194 gets all remaining segments and pushes them to prepath at the same
195 time). popSegments also returns (utf-8-decoded) strings rather than
196 bytes.
197 * There's strargs, which is a dict mapping strings to lists of strings.
198 This is being created at first call can then doesn't follow
199 request.args any more. DaCHS code should only use strargs unless
200 you're actually dealing with non-utf-8 data (and then you should
201 probably use request.files).
202 """
203 defaultContentType = "text/html;charset=utf-8"
204
205 def __init__(self, *args, **kwargs):
206 server.Request.__init__(self, *args, **kwargs)
207 self.files, self.args = {}, {}
208
209 def gotLength(self, length):
210 server.Request.gotLength(self, length)
211
212 # we'd like to distinguish between sync and async here, but
213 # the request is largely unpopulated at this point. As far as I
214 # can see, the only thing I can do is look at a piece of
215 # private twisted API
216 isSync = True
217 try:
218 path = self.channel._path.split(b"?")[0]
219 isSync = path.endswith(b"/sync")
220 except Exception as msg:
221 base.ui.notifyError("In gotLength: %s"%msg)
222
223 if isSync:
224 self.maxUploadSize = base.getConfig("web", "maxSyncUploadSize")
225 else:
226 self.maxUploadSize = base.getConfig("web", "maxUploadSize")
227
228 # The following is a shortcut to break out as soon as possible
229 # when the uploading program declares a content length (though
230 # by twisted's architecture we can't exit in this place anyway)
231 if length and length>self.maxUploadSize:
232 self.maxUploadSize = 0
233
234 def write(self, payload):
235 if self.finished or getattr(self, "channel", None) is None:
236 # request processing should really have stopped when channel
237 # has gone away. But regrettably there are code paths when
238 # that doesn't happen (in particular, we're a bit lazy when
239 # reporting errors). Let's not spew scary traceback
240 # to the log in such cases.
241 if not hasattr(self, "dead_warning_given"):
242 base.ui.notifyWarning("Ignoring attempt to write"
243 " to a dead connection")
244 self.dead_warning_given = True
245
246 else:
247 server.Request.write(self, utils.bytify(payload))
248
249 # def finish(self):
250 # import pdb;pdb.Pdb(nosigint=True).set_trace()
251 # server.Request.finish(self)
252
253 def connectionLost(self, reason):
254 # standard twisted (at least as of 17.5) doesn't log these, so
255 # we try do it manually.
256 # While we're at it, we're setting client to None, which thus
257 # can be used as a clear indicator that the connection won't
258 # work any more.
259
260 # helper to still let us log when request is damaged.
261 if not hasattr(self, "client"):
262 self.client = None
263 self.code = 400
264
265 # If the request couldn't be parsed, things didn't work out well,
266 # and we shouldn't pretend they did (but request.code defaults to 200)
267 if self.method=='(no method yet)':
268 self.code = 400
269
270 try:
271 self.channel.factory.log(self)
272 except Exception as exc:
273 base.ui.notifyError(
274 "Request with lost connection wasn't logged: %s"%exc)
275
276 try:
277 return server.Request.connectionLost(self, reason)
278 finally:
279 self.client = None
280
281 def popSegments(self, name):
282 """returns [name]+postpath and clears the current postpath, where
283 all elements are utf-8-decoded strings.
284
285 This facilitates nevow-style full-path resource resolution.
286 """
287 if name is None:
288 res = self.postpath
289 else:
290 res = [utils.bytify(name)]+self.postpath
291 self.prepath.extend(self.postpath)
292 self.postpath = []
293 return [s.decode("utf-8", "replace") for s in res]
294
295 def pushBackSegments(self, segments):
296 """tries to put segments back to the prepath from the postpath.
297
298 This will remove existing segments from postpath as long as they
299 match segments. If you're devious, you might exhaust the
300 prepath in this way; that's your fault, then.
301
302 segments may contain strings or bytes and will be destroyed in the
303 process.
304 """
305 postSegments = []
306 for seg in reversed(segments):
307 seg = utils.bytify(seg)
308 if seg==self.prepath[-1]:
309 self.prepath.pop()
310 postSegments.append(seg)
311 self.postpath = list(reversed(postSegments))
312
313 def getUser(self):
314 """returns a username as a string -- or None if no user info has
315 been passed.
316
317 We're overriding this because we really don't want to get any
318 bytes in here. If anyone manages to put in non-utf, this will return
319 None.
320
321 Note that getUser does *not* authenticate; it just returns whatever
322 twisted deems to be the user name.
323
324 Use getAuthUser for a user name validated through some credential.
325 """
326 try:
327 user = utils.debytify(server.Request.getUser(self))
328 except UnicodeDecodeError:
329 return None
330
331 return user or None
332
333 def getPassword(self):
334 """returns the password utf-8-decoded.
335
336 See getUser on the rationale and on limitations.
337 """
338 try:
339 return utils.debytify(server.Request.getPassword(self))
340 except UnicodeDecodeError:
341 return None
342
343 def getAuthUser(self):
344 """returns a username backed by credentials as a string.
345
346 This will return None if either no user was passed in or if
347 the credentials are wrong.
348
349 This is for optional-auth scenarios. For anything else, use the
350 runAuthenticated function from this module.
351 """
352 user = self.getUser()
353 if (user
354 and creds.hasCredentials(user, self.getPassword(), None)):
355 return user
356 if (user=="gavoadmin"
357 and self.getPassword()==base.getConfig("web", "adminpasswd")):
358 return "gavoadmin"
359 return None
360
361 def _makeStrargs(self):
362 """returns self.args decoded into strings.
363
364 This assumes that everything is in utf-8. For keys, we fail if
365 that's not true (actually, we should fail if it's not ASCII, if
366 you ask me). For values, there's a sentinel BinaryItem class in the
367 lists if they don't utf-8 decode.
368
369 Versus python3 cgi, this is different in that we don't dodge non-utf-8
370 parameters with surrogates but instead pack them into BinaryItems.
371
372 Use the strargs property to get this.
373 """
374 res = utils.CaseSemisensitiveDict()
375 for key, values in self.args.items():
376 res[key.decode("latin-1")] = mapped = []
377 for value in values:
378 try:
379 if isinstance(value, str):
380 mapped.append(value)
381 elif isinstance(value, bytes):
382 mapped.append(value.decode("utf-8"))
383 except (UnicodeDecodeError, AttributeError):
384 # binary data or non-string (uploads, most likely). This is
385 # mainly in here so contextgrammar can parse from a single dict.
386 mapped.append(BinaryItem(value))
387 return res
388
389 @property
390 def strargs(self):
391 if not hasattr(self, "_strargs"):
392 self._strargs = self._makeStrargs()
393 return self._strargs
394
395 def finishCallback(self, perhapsFailure):
396 """A convenience method that finishes the request and perhaps handles
397 and error
398
399 This is mainly here as a shortcut to .addBoth(lambda _: request.finish());
400 It also is a last-resort check that catches escaping, unhandled
401 errors; but, at least for now, you shouldn't rely on getting
402 sensible behaviour (e.g., error reporting to users) from here.
403 """
404 if isinstance(perhapsFailure, failure.Failure):
405 base.ui.notifyFailure(
406 perhapsFailure,
407 "A failure escaped to finishCallback. This probably means no"
408 " error was reported to the requester. ")
409 self.finish()
410
411 def processingFailed(self, failure):
412 return produceErrorDocument(failure, self)
413
414 def asGETURI(self):
415 """returns a string representing a URI that might have created this request.
416
417 In particular, this turns POST into GET. Requests unrepresentable
418 as GET URIs become "<unrepresentable>".
419 """
420 try:
421 args = urlparse.urlencode(
422 self.args,
423 doseq=True,
424 encoding="utf-8")
425 path = self.path.decode("ascii").lstrip("/")
426 return utils.ensureOneSlash(base.getConfig("web", "serverURL")
427 )+urlparse.quote(path)+"?"+args
428 except Exception as exc:
429 base.ui.notifyWarning(f"Could not serialise request URI: {exc}")
430 return "<unrepresentable>"