6
6
# the file LICENSE, distributed as part of this software.
7
7
# -----------------------------------------------------------------------------
8
8
import json
9
+ from urllib .parse import urlparse , urlunparse
9
10
10
11
from tornado .log import access_log
11
12
12
13
from .auth import User
13
14
from .prometheus .log_functions import prometheus_log_method
14
15
16
+ # url params to be scrubbed if seen
17
+ # any url param that *contains* one of these
18
+ # will be scrubbed from logs
19
+ _SCRUB_PARAM_KEYS = {"token" , "auth" , "key" , "code" , "state" , "xsrf" }
20
+
21
+
22
+ def _scrub_uri (uri : str ) -> str :
23
+ """scrub auth info from uri"""
24
+ parsed = urlparse (uri )
25
+ if parsed .query :
26
+ # check for potentially sensitive url params
27
+ # use manual list + split rather than parsing
28
+ # to minimally perturb original
29
+ parts = parsed .query .split ("&" )
30
+ changed = False
31
+ for i , s in enumerate (parts ):
32
+ key , sep , value = s .partition ("=" )
33
+ for substring in _SCRUB_PARAM_KEYS :
34
+ if substring in key :
35
+ parts [i ] = f"{ key } { sep } [secret]"
36
+ changed = True
37
+ if changed :
38
+ parsed = parsed ._replace (query = "&" .join (parts ))
39
+ return urlunparse (parsed )
40
+ return uri
41
+
15
42
16
43
def log_request (handler ):
17
44
"""log a bit more information about each request than tornado's default
@@ -43,7 +70,7 @@ def log_request(handler):
43
70
"status" : status ,
44
71
"method" : request .method ,
45
72
"ip" : request .remote_ip ,
46
- "uri" : request .uri ,
73
+ "uri" : _scrub_uri ( request .uri ) ,
47
74
"request_time" : request_time ,
48
75
}
49
76
# log username
@@ -59,7 +86,7 @@ def log_request(handler):
59
86
msg = "{status} {method} {uri} ({username}@{ip}) {request_time:.2f}ms"
60
87
if status >= 400 : # noqa[PLR2004]
61
88
# log bad referers
62
- ns ["referer" ] = request .headers .get ("Referer" , "None" )
89
+ ns ["referer" ] = _scrub_uri ( request .headers .get ("Referer" , "None" ) )
63
90
msg = msg + " referer={referer}"
64
91
if status >= 500 and status != 502 : # noqa[PLR2004]
65
92
# Log a subset of the headers if it caused an error.
0 commit comments