Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Avi Drissman | dfd88085 | 2022-09-15 20:11:09 | [diff] [blame] | 2 | # Copyright 2016 The Chromium Authors |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """Utility for generating experimental API tokens |
| 7 | |
| 8 | usage: generate_token.py [-h] [--key-file KEY_FILE] |
| 9 | [--expire-days EXPIRE_DAYS | |
| 10 | --expire-timestamp EXPIRE_TIMESTAMP] |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 11 | [--is_subdomain | --no-subdomain] |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 12 | [--is_third-party | --no-third-party] |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 13 | [--usage-restriction USAGE_RESTRICTION] |
Jason Chase | ca7f1ea | 2020-05-21 16:58:44 | [diff] [blame] | 14 | --version=VERSION |
| 15 | origin trial_name |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 16 | |
| 17 | Run "generate_token.py -h" for more help on usage. |
| 18 | """ |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 19 | |
| 20 | from __future__ import print_function |
| 21 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 22 | import argparse |
| 23 | import base64 |
iclelland | 0709f4ee | 2016-04-14 16:21:17 | [diff] [blame] | 24 | import json |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 25 | import os |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 26 | import re |
iclelland | 0709f4ee | 2016-04-14 16:21:17 | [diff] [blame] | 27 | import struct |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 28 | import sys |
| 29 | import time |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 30 | from datetime import datetime |
| 31 | |
| 32 | from six import raise_from |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 33 | from urllib.parse import urlparse |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 34 | |
| 35 | script_dir = os.path.dirname(os.path.realpath(__file__)) |
| 36 | sys.path.insert(0, os.path.join(script_dir, 'third_party', 'ed25519')) |
| 37 | import ed25519 |
| 38 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 39 | # Matches a valid DNS name label (alphanumeric plus hyphens, except at the ends, |
| 40 | # no longer than 63 ASCII characters) |
| 41 | DNS_LABEL_REGEX = re.compile(r"^(?!-)[a-z\d-]{1,63}(?<!-)$", re.IGNORECASE) |
| 42 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 43 | # Only Version 2 and Version 3 are currently supported. |
| 44 | VERSIONS = {"2": (2, b'\x02'), "3": (3, b'\x03')} |
iclelland | 0709f4ee | 2016-04-14 16:21:17 | [diff] [blame] | 45 | |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 46 | # Only empty string and "subset" are currently supoprted in alternative usage |
| 47 | # resetriction. |
| 48 | USAGE_RESTRICTION = ["", "subset"] |
| 49 | |
mgiuca | 84e0cd2 | 2016-08-10 05:47:22 | [diff] [blame] | 50 | # Default key file, relative to script_dir. |
| 51 | DEFAULT_KEY_FILE = 'eftest.key' |
| 52 | |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 53 | |
| 54 | def VersionFromArg(arg): |
| 55 | """Determines whether a string represents a valid version. |
| 56 | Only Version 2 and Version 3 are currently supported. |
| 57 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 58 | Returns a tuple of the int and bytes representation of version. |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 59 | Returns None if version is not valid. |
| 60 | """ |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 61 | return VERSIONS.get(arg, None) |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 62 | |
| 63 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 64 | def HostnameFromArg(arg): |
| 65 | """Determines whether a string represents a valid hostname. |
| 66 | |
| 67 | Returns the canonical hostname if its argument is valid, or None otherwise. |
| 68 | """ |
| 69 | if not arg or len(arg) > 255: |
| 70 | return None |
| 71 | if arg[-1] == ".": |
| 72 | arg = arg[:-1] |
iclelland | 08b9e8da | 2016-06-16 08:18:26 | [diff] [blame] | 73 | if "." not in arg and arg != "localhost": |
| 74 | return None |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 75 | if all(DNS_LABEL_REGEX.match(label) for label in arg.split(".")): |
| 76 | return arg.lower() |
Lingqi Chi | 900ecfe | 2021-11-23 02:15:44 | [diff] [blame] | 77 | return None |
| 78 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 79 | |
| 80 | def OriginFromArg(arg): |
| 81 | """Constructs the origin for the token from a command line argument. |
| 82 | |
| 83 | Returns None if this is not possible (neither a valid hostname nor a |
| 84 | valid origin URL was provided.) |
| 85 | """ |
| 86 | # Does it look like a hostname? |
| 87 | hostname = HostnameFromArg(arg) |
| 88 | if hostname: |
| 89 | return "https://" + hostname + ":443" |
| 90 | # If not, try to construct an origin URL from the argument |
Jonathan Njeunje | e45f2bd | 2021-10-12 16:21:58 | [diff] [blame] | 91 | origin = urlparse(arg) |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 92 | if not origin or not origin.scheme or not origin.netloc: |
| 93 | raise argparse.ArgumentTypeError("%s is not a hostname or a URL" % arg) |
| 94 | # HTTPS or HTTP only |
| 95 | if origin.scheme not in ('https','http'): |
| 96 | raise argparse.ArgumentTypeError("%s does not use a recognized URL scheme" % |
| 97 | arg) |
| 98 | # Add default port if it is not specified |
| 99 | try: |
| 100 | port = origin.port |
Lingqi Chi | 900ecfe | 2021-11-23 02:15:44 | [diff] [blame] | 101 | except ValueError as e: |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 102 | raise_from( |
| 103 | argparse.ArgumentTypeError("%s is not a hostname or a URL" % arg), e) |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 104 | if not port: |
| 105 | port = {"https": 443, "http": 80}[origin.scheme] |
| 106 | # Strip any extra components and return the origin URL: |
| 107 | return "{0}://{1}:{2}".format(origin.scheme, origin.hostname, port) |
| 108 | |
| 109 | def ExpiryFromArgs(args): |
| 110 | if args.expire_timestamp: |
| 111 | return int(args.expire_timestamp) |
| 112 | return (int(time.time()) + (int(args.expire_days) * 86400)) |
| 113 | |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 114 | |
| 115 | def GenerateTokenData(version, origin, is_subdomain, is_third_party, |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 116 | usage_restriction, feature_name, expiry): |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 117 | data = {"origin": origin, |
| 118 | "feature": feature_name, |
| 119 | "expiry": expiry} |
| 120 | if is_subdomain is not None: |
| 121 | data["isSubdomain"] = is_subdomain |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 122 | # Only version 3 token supports fields: is_third_party, usage. |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 123 | if version == 3 and is_third_party is not None: |
| 124 | data["isThirdParty"] = is_third_party |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 125 | if version == 3 and usage_restriction is not None: |
| 126 | data["usage"] = usage_restriction |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 127 | return json.dumps(data).encode('utf-8') |
iclelland | 0709f4ee | 2016-04-14 16:21:17 | [diff] [blame] | 128 | |
| 129 | def GenerateDataToSign(version, data): |
| 130 | return version + struct.pack(">I",len(data)) + data |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 131 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 132 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 133 | def Sign(private_key, data): |
| 134 | return ed25519.signature(data, private_key[:32], private_key[32:]) |
| 135 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 136 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 137 | def FormatToken(version, signature, data): |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 138 | return base64.b64encode(version + signature + struct.pack(">I", len(data)) + |
| 139 | data).decode("ascii") |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 140 | |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 141 | |
| 142 | def ParseArgs(): |
mgiuca | 84e0cd2 | 2016-08-10 05:47:22 | [diff] [blame] | 143 | default_key_file_absolute = os.path.join(script_dir, DEFAULT_KEY_FILE) |
| 144 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 145 | parser = argparse.ArgumentParser( |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 146 | description="Generate tokens for enabling experimental features") |
Jason Chase | ca7f1ea | 2020-05-21 16:58:44 | [diff] [blame] | 147 | parser.add_argument("--version", |
Jonathan Hao | 0480a863 | 2022-10-04 18:01:18 | [diff] [blame^] | 148 | help="Token version to use. Currently only version 2 " |
Jason Chase | ca7f1ea | 2020-05-21 16:58:44 | [diff] [blame] | 149 | "and version 3 are supported.", |
Glen Robertson | e861d775 | 2020-09-17 14:23:57 | [diff] [blame] | 150 | default='3', |
Jason Chase | ca7f1ea | 2020-05-21 16:58:44 | [diff] [blame] | 151 | type=VersionFromArg) |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 152 | parser.add_argument("origin", |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 153 | help="Origin for which to enable the feature. This can " |
| 154 | "be either a hostname (default scheme HTTPS, " |
| 155 | "default port 443) or a URL.", |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 156 | type=OriginFromArg) |
| 157 | parser.add_argument("trial_name", |
| 158 | help="Feature to enable. The current list of " |
| 159 | "experimental feature trials can be found in " |
| 160 | "RuntimeFeatures.in") |
| 161 | parser.add_argument("--key-file", |
| 162 | help="Ed25519 private key file to sign the token with", |
mgiuca | 84e0cd2 | 2016-08-10 05:47:22 | [diff] [blame] | 163 | default=default_key_file_absolute) |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 164 | |
| 165 | subdomain_group = parser.add_mutually_exclusive_group() |
| 166 | subdomain_group.add_argument("--is-subdomain", |
| 167 | help="Token will enable the feature for all " |
| 168 | "subdomains that match the origin", |
| 169 | dest="is_subdomain", |
| 170 | action="store_true") |
| 171 | subdomain_group.add_argument("--no-subdomain", |
| 172 | help="Token will only match the specified " |
| 173 | "origin (default behavior)", |
| 174 | dest="is_subdomain", |
| 175 | action="store_false") |
| 176 | parser.set_defaults(is_subdomain=None) |
| 177 | |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 178 | third_party_group = parser.add_mutually_exclusive_group() |
| 179 | third_party_group.add_argument( |
| 180 | "--is-third-party", |
| 181 | help="Token will enable the feature for third " |
| 182 | "party origins. This option is only available for token version 3", |
| 183 | dest="is_third_party", |
| 184 | action="store_true") |
| 185 | third_party_group.add_argument( |
| 186 | "--no-third-party", |
| 187 | help="Token will only match first party origin. This option is only " |
| 188 | "available for token version 3", |
| 189 | dest="is_third_party", |
| 190 | action="store_false") |
| 191 | parser.set_defaults(is_third_party=None) |
| 192 | |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 193 | parser.add_argument("--usage-restriction", |
| 194 | help="Alternative token usage resctriction. This option " |
| 195 | "is only available for token version 3. Currently only " |
| 196 | "subset exclusion is supported.") |
| 197 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 198 | expiry_group = parser.add_mutually_exclusive_group() |
| 199 | expiry_group.add_argument("--expire-days", |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 200 | help="Days from now when the token should expire", |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 201 | type=int, |
| 202 | default=42) |
| 203 | expiry_group.add_argument("--expire-timestamp", |
| 204 | help="Exact time (seconds since 1970-01-01 " |
chasej | 4f0cb8e | 2016-10-13 21:32:33 | [diff] [blame] | 205 | "00:00:00 UTC) when the token should expire", |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 206 | type=int) |
| 207 | |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 208 | return parser.parse_args() |
| 209 | |
| 210 | |
| 211 | def GenerateTokenAndSignature(): |
| 212 | args = ParseArgs() |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 213 | expiry = ExpiryFromArgs(args) |
| 214 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 215 | version_int, version_bytes = args.version |
| 216 | |
| 217 | with open(os.path.expanduser(args.key_file), mode="rb") as key_file: |
| 218 | private_key = key_file.read(64) |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 219 | |
| 220 | # Validate that the key file read was a proper Ed25519 key -- running the |
| 221 | # publickey method on the first half of the key should return the second |
| 222 | # half. |
| 223 | if (len(private_key) < 64 or |
| 224 | ed25519.publickey(private_key[:32]) != private_key[32:]): |
| 225 | print("Unable to use the specified private key file.") |
| 226 | sys.exit(1) |
| 227 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 228 | if (not version_int): |
Glen Robertson | e861d775 | 2020-09-17 14:23:57 | [diff] [blame] | 229 | print("Invalid token version. Only version 2 and 3 are supported.") |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 230 | sys.exit(1) |
| 231 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 232 | if (args.is_third_party is not None and version_int != 3): |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 233 | print("Only version 3 token supports is_third_party flag.") |
| 234 | sys.exit(1) |
| 235 | |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 236 | if (args.usage_restriction is not None): |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 237 | if (version_int != 3): |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 238 | print("Only version 3 token supports alternative usage restriction.") |
| 239 | sys.exit(1) |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 240 | if (args.usage_restriction not in USAGE_RESTRICTION): |
| 241 | print( |
| 242 | "Only empty string and \"subset\" are supported in alternative usage " |
| 243 | "restriction.") |
| 244 | sys.exit(1) |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 245 | token_data = GenerateTokenData(version_int, args.origin, args.is_subdomain, |
| 246 | args.is_third_party, args.usage_restriction, |
| 247 | args.trial_name, expiry) |
| 248 | data_to_sign = GenerateDataToSign(version_bytes, token_data) |
iclelland | 0709f4ee | 2016-04-14 16:21:17 | [diff] [blame] | 249 | signature = Sign(private_key, data_to_sign) |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 250 | |
| 251 | # Verify that that the signature is correct before printing it. |
| 252 | try: |
iclelland | 0709f4ee | 2016-04-14 16:21:17 | [diff] [blame] | 253 | ed25519.checkvalid(signature, data_to_sign, private_key[32:]) |
Jonathan Njeunje | e45f2bd | 2021-10-12 16:21:58 | [diff] [blame] | 254 | except Exception as exc: |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 255 | print("There was an error generating the signature.") |
| 256 | print("(The original error was: %s)" % exc) |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 257 | sys.exit(1) |
| 258 | |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 259 | token_data = GenerateTokenData(version_int, args.origin, args.is_subdomain, |
| 260 | args.is_third_party, args.usage_restriction, |
| 261 | args.trial_name, expiry) |
| 262 | data_to_sign = GenerateDataToSign(version_bytes, token_data) |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 263 | signature = Sign(private_key, data_to_sign) |
Louise Brett | dcac22cb | 2022-01-05 00:01:40 | [diff] [blame] | 264 | return args, token_data, signature, expiry |
Lingqi Chi | 22fe5483 | 2021-11-30 07:26:15 | [diff] [blame] | 265 | |
| 266 | |
| 267 | def main(): |
Louise Brett | dcac22cb | 2022-01-05 00:01:40 | [diff] [blame] | 268 | args, token_data, signature, expiry = GenerateTokenAndSignature() |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 269 | version_int, version_bytes = args.version |
iclelland | 08b9e8da | 2016-06-16 08:18:26 | [diff] [blame] | 270 | |
| 271 | # Output the token details |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 272 | print("Token details:") |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 273 | print(" Version: %s" % version_int) |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 274 | print(" Origin: %s" % args.origin) |
| 275 | print(" Is Subdomain: %s" % args.is_subdomain) |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 276 | if version_int == 3: |
Rodney Ding | 85a21568 | 2020-05-04 02:16:05 | [diff] [blame] | 277 | print(" Is Third Party: %s" % args.is_third_party) |
Rodney Ding | 66c126d | 2020-06-08 05:14:06 | [diff] [blame] | 278 | print(" Usage Restriction: %s" % args.usage_restriction) |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 279 | print(" Feature: %s" % args.trial_name) |
| 280 | print(" Expiry: %d (%s UTC)" % (expiry, datetime.utcfromtimestamp(expiry))) |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 281 | print(" Signature: %s" % ", ".join('0x%02x' % x for x in signature)) |
| 282 | b64_signature = base64.b64encode(signature).decode("ascii") |
| 283 | print(" Signature (Base64): %s" % b64_signature) |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 284 | print() |
iclelland | 08b9e8da | 2016-06-16 08:18:26 | [diff] [blame] | 285 | |
| 286 | # Output the properly-formatted token. |
Daniel Smith | b4f30fb | 2022-01-15 01:21:28 | [diff] [blame] | 287 | print(FormatToken(version_bytes, signature, token_data)) |
Raul Tambre | 26d7db4 | 2019-09-25 11:06:35 | [diff] [blame] | 288 | |
iclelland | 65322b8d | 2016-02-29 22:05:22 | [diff] [blame] | 289 | |
| 290 | if __name__ == "__main__": |
| 291 | main() |