-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathsnippets.py
226 lines (187 loc) · 7.7 KB
/
snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python
#
# Copyright 2017 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This application demonstrates how to perform operations on data (content)
when using Google Cloud CDN (Content Delivery Network).
For more information, see the README.md under /cdn and the documentation
at https://cloud.google.com/cdn/docs.
"""
# [START cloudcdn_sign_url]
# [START cloudcdn_sign_url_prefix]
# [START cloudcdn_sign_cookie]
import argparse
import base64
from datetime import datetime, timezone
import hashlib
import hmac
from urllib.parse import parse_qs, urlsplit
# [END cloudcdn_sign_url]
# [END cloudcdn_sign_url_prefix]
# [END cloudcdn_sign_cookie]
# [START cloudcdn_sign_url]
def sign_url(
url: str,
key_name: str,
base64_key: str,
expiration_time: datetime,
) -> str:
"""Gets the Signed URL string for the specified URL and configuration.
Args:
url: URL to sign.
key_name: name of the signing key.
base64_key: signing key as a base64 encoded string.
expiration_time: expiration time as time-zone aware datetime.
Returns:
Returns the Signed URL appended with the query parameters based on the
specified configuration.
"""
stripped_url = url.strip()
parsed_url = urlsplit(stripped_url)
query_params = parse_qs(parsed_url.query, keep_blank_values=True)
epoch = datetime.fromtimestamp(0, timezone.utc)
expiration_timestamp = int((expiration_time - epoch).total_seconds())
decoded_key = base64.urlsafe_b64decode(base64_key)
url_to_sign = f"{stripped_url}{'&' if query_params else '?'}Expires={expiration_timestamp}&KeyName={key_name}"
digest = hmac.new(decoded_key, url_to_sign.encode("utf-8"), hashlib.sha1).digest()
signature = base64.urlsafe_b64encode(digest).decode("utf-8")
return f"{url_to_sign}&Signature={signature}"
# [END cloudcdn_sign_url]
# [START cloudcdn_sign_url_prefix]
def sign_url_prefix(
url: str,
url_prefix: str,
key_name: str,
base64_key: str,
expiration_time: datetime,
) -> str:
"""Gets the Signed URL string for the specified URL prefix and configuration.
Args:
url: URL of request.
url_prefix: URL prefix to sign.
key_name: name of the signing key.
base64_key: signing key as a base64 encoded string.
expiration_time: expiration time as time-zone aware datetime.
Returns:
Returns the Signed URL appended with the query parameters based on the
specified URL prefix and configuration.
"""
stripped_url = url.strip()
parsed_url = urlsplit(stripped_url)
query_params = parse_qs(parsed_url.query, keep_blank_values=True)
encoded_url_prefix = base64.urlsafe_b64encode(
url_prefix.strip().encode("utf-8")
).decode("utf-8")
epoch = datetime.fromtimestamp(0, timezone.utc)
expiration_timestamp = int((expiration_time - epoch).total_seconds())
decoded_key = base64.urlsafe_b64decode(base64_key)
policy = f"URLPrefix={encoded_url_prefix}&Expires={expiration_timestamp}&KeyName={key_name}"
digest = hmac.new(decoded_key, policy.encode("utf-8"), hashlib.sha1).digest()
signature = base64.urlsafe_b64encode(digest).decode("utf-8")
return f"{stripped_url}{'&' if query_params else '?'}{policy}&Signature={signature}"
# [END cloudcdn_sign_url_prefix]
# [START cloudcdn_sign_cookie]
def sign_cookie(
url_prefix: str,
key_name: str,
base64_key: str,
expiration_time: datetime,
) -> str:
"""Gets the Signed cookie value for the specified URL prefix and configuration.
Args:
url_prefix: URL prefix to sign.
key_name: name of the signing key.
base64_key: signing key as a base64 encoded string.
expiration_time: expiration time as time-zone aware datetime.
Returns:
Returns the Cloud-CDN-Cookie value based on the specified configuration.
"""
encoded_url_prefix = base64.urlsafe_b64encode(
url_prefix.strip().encode("utf-8")
).decode("utf-8")
epoch = datetime.fromtimestamp(0, timezone.utc)
expiration_timestamp = int((expiration_time - epoch).total_seconds())
decoded_key = base64.urlsafe_b64decode(base64_key)
policy = f"URLPrefix={encoded_url_prefix}:Expires={expiration_timestamp}:KeyName={key_name}"
digest = hmac.new(decoded_key, policy.encode("utf-8"), hashlib.sha1).digest()
signature = base64.urlsafe_b64encode(digest).decode("utf-8")
signed_policy = f"Cloud-CDN-Cookie={policy}:Signature={signature}"
return signed_policy
# [END cloudcdn_sign_cookie]
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
subparsers = parser.add_subparsers(dest="command")
sign_url_parser = subparsers.add_parser(
"sign-url", help="Sign a URL to grant temporary authorized access."
)
sign_url_parser.add_argument("url", help="The URL to sign.")
sign_url_parser.add_argument("key_name", help="Key name for the signing key.")
sign_url_parser.add_argument("base64_key", help="The base64 encoded signing key.")
sign_url_parser.add_argument(
"expiration_time",
type=lambda d: datetime.fromtimestamp(float(d), timezone.utc),
help="Expiration time expessed as seconds since the epoch.",
)
sign_url_prefix_parser = subparsers.add_parser(
"sign-url-prefix",
help="Sign a URL prefix to grant temporary authorized access.",
)
sign_url_prefix_parser.add_argument("url", help="The request URL.")
sign_url_prefix_parser.add_argument("url_prefix", help="The URL prefix to sign.")
sign_url_prefix_parser.add_argument(
"key_name", help="Key name for the signing key."
)
sign_url_prefix_parser.add_argument(
"base64_key", help="The base64 encoded signing key."
)
sign_url_prefix_parser.add_argument(
"expiration_time",
type=lambda d: datetime.fromtimestamp(float(d), timezone.utc),
help="Expiration time expessed as seconds since the epoch.",
)
sign_cookie_parser = subparsers.add_parser(
"sign-cookie",
help="Generate a signed cookie to grant temporary authorized access.",
)
sign_cookie_parser.add_argument("url_prefix", help="The URL prefix to sign.")
sign_cookie_parser.add_argument("key_name", help="Key name for the signing key.")
sign_cookie_parser.add_argument(
"base64_key", help="The base64 encoded signing key."
)
sign_cookie_parser.add_argument(
"expiration_time",
type=lambda d: datetime.fromtimestamp(float(d), timezone.utc),
help="Expiration time expressed as seconds since the epoch.",
)
args = parser.parse_args()
if args.command == "sign-url":
print(sign_url(args.url, args.key_name, args.base64_key, args.expiration_time))
elif args.command == "sign-url-prefix":
print(
sign_url_prefix(
args.url,
args.url_prefix,
args.key_name,
args.base64_key,
args.expiration_time,
)
)
elif args.command == "sign-cookie":
print(
sign_cookie(
args.url_prefix, args.key_name, args.base64_key, args.expiration_time
)
)