summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJosé Padilla <jpadilla@webapplicate.com>2020-06-19 12:19:03 -0400
committerJosé Padilla <jpadilla@webapplicate.com>2020-06-19 12:19:03 -0400
commitbb1a0e05891b9a0913fcde44efeae09bc8046800 (patch)
tree480a3f2d529284c3af0ab9ebed0160f8e9cd361d
parent99b9f85cd00b09bb4c8cce23f06e756c1d8f4b62 (diff)
downloadpyjwt-remove-cli.tar.gz
Remove cli entrypointremove-cli
-rw-r--r--jwt/__main__.py211
-rw-r--r--setup.cfg4
-rw-r--r--tests/test_cli.py177
3 files changed, 0 insertions, 392 deletions
diff --git a/jwt/__main__.py b/jwt/__main__.py
deleted file mode 100644
index 9ed8b71..0000000
--- a/jwt/__main__.py
+++ /dev/null
@@ -1,211 +0,0 @@
-#!/usr/bin/env python3
-
-import argparse
-import json
-import sys
-import time
-
-from . import DecodeError, __version__, decode, encode
-
-
-def encode_payload(args):
- # Try to encode
- if args.key is None:
- raise ValueError(
- "Key is required when encoding. See --help for usage."
- )
-
- # Build payload object to encode
- payload = {}
-
- for arg in args.payload:
- k, v = arg.split("=", 1)
-
- # exp +offset special case?
- if k == "exp" and v[0] == "+" and len(v) > 1:
- v = str(int(time.time() + int(v[1:])))
-
- # Cast to integer?
- if v.isdigit():
- v = int(v)
- else:
- # Cast to float?
- try:
- v = float(v)
- except ValueError:
- pass
-
- # Cast to true, false, or null?
- constants = {"true": True, "false": False, "null": None}
-
- if v in constants:
- v = constants[v]
-
- payload[k] = v
-
- # Build header object to encode
- header = {}
- if args.header:
- try:
- header = json.loads(args.header)
- except Exception as e:
- raise ValueError(
- "Error loading header: %s. See --help for usage." % e
- )
-
- token = encode(
- payload, key=args.key, algorithm=args.algorithm, headers=header
- )
-
- return token.decode("utf-8")
-
-
-def decode_payload(args):
- try:
- if args.token:
- token = args.token
- else:
- if sys.stdin.isatty():
- token = sys.stdin.readline().strip()
- else:
- raise OSError("Cannot read from stdin: terminal not a TTY")
-
- token = token.encode("utf-8")
- data = decode(
- token,
- key=args.key,
- verify=args.verify,
- audience=args.audience,
- issuer=args.issuer,
- )
-
- return json.dumps(data)
-
- except DecodeError as e:
- raise DecodeError("There was an error decoding the token: %s" % e)
-
-
-def build_argparser():
-
- usage = """
- Encodes or decodes JSON Web Tokens based on input.
-
- %(prog)s [options] <command> [options] input
-
- Decoding examples:
-
- %(prog)s --key=secret decode json.web.token
- %(prog)s decode --no-verify json.web.token
-
- Encoding requires the key option and takes space separated key/value pairs
- separated by equals (=) as input. Examples:
-
- %(prog)s --key=secret encode iss=me exp=1302049071
- %(prog)s --key=secret encode foo=bar exp=+10
-
- The exp key is special and can take an offset to current Unix time.
-
- %(prog)s --key=secret --header='{"typ":"jwt", "alg":"RS256"}' encode is=me
-
- The header option can be provided for input to encode in the jwt. The format
- requires the header be enclosed in single quote and key/value pairs with double
- quotes.
- """
-
- arg_parser = argparse.ArgumentParser(prog="pyjwt", usage=usage)
-
- arg_parser.add_argument(
- "-v", "--version", action="version", version="%(prog)s " + __version__
- )
-
- arg_parser.add_argument(
- "--key",
- dest="key",
- metavar="KEY",
- default=None,
- help="set the secret key to sign with",
- )
-
- arg_parser.add_argument(
- "--alg",
- dest="algorithm",
- metavar="ALG",
- default="HS256",
- help="set crypto algorithm to sign with. default=HS256",
- )
-
- arg_parser.add_argument(
- "--header",
- dest="header",
- metavar="HEADER",
- default=None,
- help="set jwt header",
- )
-
- subparsers = arg_parser.add_subparsers(
- title="PyJWT subcommands",
- description="valid subcommands",
- help="additional help",
- )
-
- # Encode subcommand
- encode_parser = subparsers.add_parser(
- "encode", help="use to encode a supplied payload"
- )
-
- payload_help = """Payload to encode. Must be a space separated list of key/value
- pairs separated by equals (=) sign."""
-
- encode_parser.add_argument("payload", nargs="+", help=payload_help)
- encode_parser.set_defaults(func=encode_payload)
-
- # Decode subcommand
- decode_parser = subparsers.add_parser(
- "decode", help="use to decode a supplied JSON web token"
- )
- decode_parser.add_argument(
- "token", help="JSON web token to decode.", nargs="?"
- )
-
- decode_parser.add_argument(
- "-n",
- "--no-verify",
- action="store_false",
- dest="verify",
- default=True,
- help="ignore signature and claims verification on decode",
- )
-
- decode_parser.add_argument(
- "--audience",
- action="append",
- dest="audience",
- default=None,
- help="audience value to accept, can be given multiple times",
- )
-
- decode_parser.add_argument(
- "--issuer",
- action="store",
- dest="issuer",
- default=None,
- help="require issuer to match this, if specified",
- )
-
- decode_parser.set_defaults(func=decode_payload)
-
- return arg_parser
-
-
-def main():
- arg_parser = build_argparser()
-
- try:
- arguments = arg_parser.parse_args(sys.argv[1:])
-
- output = arguments.func(arguments)
-
- print(output)
- except Exception as e:
- print("There was an unforseen error: ", e)
- arg_parser.print_help()
diff --git a/setup.cfg b/setup.cfg
index c1d2c3b..6f774f9 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -32,10 +32,6 @@ classifiers =
python_requires = >=3.5
packages = find:
-[options.entry_points]
-console_scripts =
- pyjwt = jwt.__main__:main
-
[options.extras_require]
docs =
sphinx
diff --git a/tests/test_cli.py b/tests/test_cli.py
deleted file mode 100644
index 1c22d9e..0000000
--- a/tests/test_cli.py
+++ /dev/null
@@ -1,177 +0,0 @@
-import argparse
-import json
-import sys
-
-import pytest
-
-import jwt
-from jwt.__main__ import build_argparser, decode_payload, encode_payload, main
-
-
-class TestCli:
- def test_build_argparse(self):
- args = ["--key", "1234", "encode", "name=Vader"]
- parser = build_argparser()
- parsed_args = parser.parse_args(args)
-
- assert parsed_args.key == "1234"
-
- def test_encode_payload_raises_value_error_key_is_required(self):
- encode_args = ["encode", "name=Vader", "job=Sith"]
- parser = build_argparser()
-
- args = parser.parse_args(encode_args)
-
- with pytest.raises(ValueError) as excinfo:
- encode_payload(args)
-
- assert "Key is required when encoding" in str(excinfo.value)
-
- def test_encode_header_raises_value_error_bad_dict(self):
- encode_args = [
- "--key=secret",
- "--header=dfsfd",
- "encode",
- "name=Vader",
- "job=Sith",
- ]
- parser = build_argparser()
-
- args = parser.parse_args(encode_args)
-
- with pytest.raises(ValueError) as excinfo:
- encode_payload(args)
-
- assert "Error loading header:" in str(excinfo.value)
-
- def test_decode_payload_raises_decoded_error(self):
- decode_args = ["--key", "1234", "decode", "wrong-token"]
- parser = build_argparser()
-
- args = parser.parse_args(decode_args)
-
- with pytest.raises(jwt.DecodeError) as excinfo:
- decode_payload(args)
-
- assert "There was an error decoding the token" in str(excinfo.value)
-
- def test_decode_payload_raises_decoded_error_isatty(self, monkeypatch):
- def patched_sys_stdin_read():
- raise jwt.DecodeError()
-
- decode_args = ["--key", "1234", "decode", "wrong-token"]
- parser = build_argparser()
-
- args = parser.parse_args(decode_args)
-
- monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
- monkeypatch.setattr(sys.stdin, "read", patched_sys_stdin_read)
-
- with pytest.raises(jwt.DecodeError) as excinfo:
- decode_payload(args)
-
- assert "There was an error decoding the token" in str(excinfo.value)
-
- def test_decode_payload_terminal_tty(self, monkeypatch):
- encode_args = [
- "--key=secret-key",
- '--header={"alg":"HS256"}',
- "encode",
- "name=hello-world",
- ]
- parser = build_argparser()
- parsed_encode_args = parser.parse_args(encode_args)
- token = encode_payload(parsed_encode_args)
-
- decode_args = ["--key=secret-key", "decode"]
- parsed_decode_args = parser.parse_args(decode_args)
-
- monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
- monkeypatch.setattr(sys.stdin, "readline", lambda: token)
-
- actual = json.loads(decode_payload(parsed_decode_args))
- assert actual["name"] == "hello-world"
-
- def test_decode_payload_raises_terminal_not_a_tty(self, monkeypatch):
- decode_args = ["--key", "1234", "decode"]
- parser = build_argparser()
- args = parser.parse_args(decode_args)
-
- monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
-
- with pytest.raises(IOError) as excinfo:
- decode_payload(args)
- assert "Cannot read from stdin: terminal not a TTY" in str(
- excinfo.value
- )
-
- @pytest.mark.parametrize(
- "key,header,name,job,exp,verify",
- [
- ("1234", "{}", "Vader", "Sith", None, None),
- ("4567", '{"typ":"test"}', "Anakin", "Jedi", "+1", None),
- ("4321", "", "Padme", "Queen", "4070926800", "true"),
- ],
- )
- def test_encode_decode(self, key, header, name, job, exp, verify):
- encode_args = [
- "--key={}".format(key),
- "--header={}".format(header),
- "encode",
- "name={}".format(name),
- "job={}".format(job),
- ]
- if exp:
- encode_args.append("exp={}".format(exp))
- if verify:
- encode_args.append("verify={}".format(verify))
-
- parser = build_argparser()
- parsed_encode_args = parser.parse_args(encode_args)
- token = encode_payload(parsed_encode_args)
- assert token is not None
- assert token != ""
-
- decode_args = ["--key={}".format(key), "decode", token]
- parser = build_argparser()
- parsed_decode_args = parser.parse_args(decode_args)
-
- actual = json.loads(decode_payload(parsed_decode_args))
- expected = {"job": job, "name": name}
- assert actual["name"] == expected["name"]
- assert actual["job"] == expected["job"]
-
- @pytest.mark.parametrize(
- "key,name,job,exp,verify",
- [
- ("1234", "Vader", "Sith", None, None),
- ("4567", "Anakin", "Jedi", "+1", None),
- ("4321", "Padme", "Queen", "4070926800", "true"),
- ],
- )
- def test_main(self, monkeypatch, key, name, job, exp, verify):
- args = [
- "test_cli.py",
- "--key={}".format(key),
- "encode",
- "name={}".format(name),
- "job={}".format(job),
- ]
- if exp:
- args.append("exp={}".format(exp))
- if verify:
- args.append("verify={}".format(verify))
- monkeypatch.setattr(sys, "argv", args)
- main()
-
- def test_main_throw_exception(self, monkeypatch, capsys):
- def patched_argparser_parse_args(self, args):
- raise Exception("NOOOOOOOOOOO!")
-
- monkeypatch.setattr(
- argparse.ArgumentParser, "parse_args", patched_argparser_parse_args
- )
- main()
- out, _ = capsys.readouterr()
-
- assert "NOOOOOOOOOOO!" in out