blob: b32801a32039f937027f269e9c8fbf7838ac1cf1 [file] [log] [blame]
Jon Wayne Parrott8713a712016-10-04 14:19:01 -07001# Copyright 2015 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Helper functions for commonly used utilities."""
16
Jon Wayne Parrott97eb8702016-11-17 09:43:16 -080017import base64
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070018import calendar
19import datetime
20
Jon Wayne Parrott8713a712016-10-04 14:19:01 -070021import six
Jon Wayne Parrott64a9d6e2016-10-07 14:02:53 -070022from six.moves import urllib
Jon Wayne Parrott8713a712016-10-04 14:19:01 -070023
24
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -070025CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
26CLOCK_SKEW = datetime.timedelta(seconds=CLOCK_SKEW_SECS)
27
28
Jon Wayne Parrott6b21d752016-10-14 14:49:35 -070029def copy_docstring(source_class):
Jon Wayne Parrott2c253a52016-10-14 14:50:58 -070030 """Decorator that copies a method's docstring from another class.
31
32 Args:
33 source_class (type): The class that has the documented method.
34
35 Returns:
36 Callable: A decorator that will copy the docstring of the same
37 named method in the source class to the decorated method.
38 """
Jon Wayne Parrott6b21d752016-10-14 14:49:35 -070039 def decorator(method):
Jon Wayne Parrott2c253a52016-10-14 14:50:58 -070040 """Decorator implementation.
41
42 Args:
Jon Wayne Parrott0a0be142016-10-14 14:53:29 -070043 method (Callable): The method to copy the docstring to.
Jon Wayne Parrott2c253a52016-10-14 14:50:58 -070044
45 Returns:
46 Callable: the same method passed in with an updated docstring.
47
48 Raises:
49 ValueError: if the method already has a docstring.
50 """
Jon Wayne Parrott6b21d752016-10-14 14:49:35 -070051 if method.__doc__:
52 raise ValueError('Method already has a docstring.')
53
54 source_method = getattr(source_class, method.__name__)
55 method.__doc__ = source_method.__doc__
56
57 return method
58 return decorator
59
60
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070061def utcnow():
62 """Returns the current UTC datetime.
63
64 Returns:
65 datetime: The current time in UTC.
66 """
67 return datetime.datetime.utcnow()
68
69
70def datetime_to_secs(value):
71 """Convert a datetime object to the number of seconds since the UNIX epoch.
72
73 Args:
74 value (datetime): The datetime to convert.
75
76 Returns:
77 int: The number of seconds since the UNIX epoch.
78 """
79 return calendar.timegm(value.utctimetuple())
80
81
Jon Wayne Parrott8713a712016-10-04 14:19:01 -070082def to_bytes(value, encoding='utf-8'):
83 """Converts a string value to bytes, if necessary.
84
85 Unfortunately, ``six.b`` is insufficient for this task since in
86 Python 2 because it does not modify ``unicode`` objects.
87
88 Args:
89 value (Union[str, bytes]): The value to be converted.
90 encoding (str): The encoding to use to convert unicode to bytes.
91 Defaults to "utf-8".
92
93 Returns:
94 bytes: The original value converted to bytes (if unicode) or as
95 passed in if it started out as bytes.
96
97 Raises:
98 ValueError: If the value could not be converted to bytes.
99 """
100 result = (value.encode(encoding)
101 if isinstance(value, six.text_type) else value)
102 if isinstance(result, six.binary_type):
103 return result
104 else:
105 raise ValueError('{0!r} could not be converted to bytes'.format(value))
106
107
108def from_bytes(value):
109 """Converts bytes to a string value, if necessary.
110
111 Args:
112 value (Union[str, bytes]): The value to be converted.
113
114 Returns:
115 str: The original value converted to unicode (if bytes) or as passed in
116 if it started out as unicode.
117
118 Raises:
119 ValueError: If the value could not be converted to unicode.
120 """
121 result = (value.decode('utf-8')
122 if isinstance(value, six.binary_type) else value)
123 if isinstance(result, six.text_type):
124 return result
125 else:
126 raise ValueError(
127 '{0!r} could not be converted to unicode'.format(value))
Jon Wayne Parrott64a9d6e2016-10-07 14:02:53 -0700128
129
130def update_query(url, params, remove=None):
131 """Updates a URL's query parameters.
132
133 Replaces any current values if they are already present in the URL.
134
135 Args:
136 url (str): The URL to update.
137 params (Mapping[str, str]): A mapping of query parameter
138 keys to values.
139 remove (Sequence[str]): Parameters to remove from the query string.
140
141 Returns:
142 str: The URL with updated query parameters.
143
144 Examples:
145
146 >>> url = 'http://example.com?a=1'
147 >>> update_query(url, {'a': '2'})
148 http://example.com?a=2
149 >>> update_query(url, {'b': '3'})
150 http://example.com?a=1&b=3
151 >> update_query(url, {'b': '3'}, remove=['a'])
152 http://example.com?b=3
153
154 """
155 if remove is None:
156 remove = []
157
158 # Split the URL into parts.
159 parts = urllib.parse.urlparse(url)
160 # Parse the query string.
161 query_params = urllib.parse.parse_qs(parts.query)
162 # Update the query parameters with the new parameters.
163 query_params.update(params)
164 # Remove any values specified in remove.
165 query_params = {
166 key: value for key, value
167 in six.iteritems(query_params)
168 if key not in remove}
169 # Re-encoded the query string.
170 new_query = urllib.parse.urlencode(query_params, doseq=True)
171 # Unsplit the url.
172 new_parts = parts._replace(query=new_query)
173 return urllib.parse.urlunparse(new_parts)
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700174
175
176def scopes_to_string(scopes):
177 """Converts scope value to a string suitable for sending to OAuth 2.0
178 authorization servers.
179
180 Args:
181 scopes (Sequence[str]): The sequence of scopes to convert.
182
183 Returns:
184 str: The scopes formatted as a single string.
185 """
186 return ' '.join(scopes)
187
188
189def string_to_scopes(scopes):
190 """Converts stringifed scopes value to a list.
191
192 Args:
193 scopes (Union[Sequence, str]): The string of space-separated scopes
194 to convert.
195 Returns:
196 Sequence(str): The separated scopes.
197 """
198 if not scopes:
199 return []
200
201 return scopes.split(' ')
Jon Wayne Parrott97eb8702016-11-17 09:43:16 -0800202
203
204def padded_urlsafe_b64decode(value):
205 """Decodes base64 strings lacking padding characters.
206
207 Google infrastructure tends to omit the base64 padding characters.
208
209 Args:
210 value (Union[str, bytes]): The encoded value.
211
212 Returns:
213 bytes: The decoded value
214 """
215 b64string = to_bytes(value)
216 padded = b64string + b'=' * (-len(b64string) % 4)
217 return base64.urlsafe_b64decode(padded)
Aditya Natrajae7e4f32019-02-15 00:02:10 -0500218
219
220def unpadded_urlsafe_b64encode(value):
221 """Encodes base64 strings removing any padding characters.
222
223 `rfc 7515`_ defines Base64url to NOT include any padding
224 characters, but the stdlib doesn't do that by default.
225
226 _rfc7515: https://tools.ietf.org/html/rfc7515#page-6
227
228 Args:
229 value (Union[str|bytes]): The bytes-like value to encode
230
231 Returns:
232 Union[str|bytes]: The encoded value
233 """
234 return base64.urlsafe_b64encode(value).rstrip(b'=')