Skip to content

Commit

Permalink
Fix over-eager fallback to stdin (#304)
Browse files Browse the repository at this point in the history
* Fix over-eager fallback to stdin

* Ignore .eggs dir

* Add test to cover when terminal is not a TTY
  • Loading branch information
jpadilla authored Nov 6, 2017
1 parent e1e4d02 commit c1253ec
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
Expand Down
14 changes: 10 additions & 4 deletions jwt/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,13 @@ def encode_payload(args):

def decode_payload(args):
try:
if sys.stdin.isatty():
token = sys.stdin.read()
else:
if args.token:
token = args.token
else:
if sys.stdin.isatty():
token = sys.stdin.readline().strip()
else:
raise IOError('Cannot read from stdin: terminal not a TTY')

token = token.encode('utf-8')
data = decode(token, key=args.key, verify=args.verify)
Expand Down Expand Up @@ -133,7 +136,10 @@ def build_argparser():

# 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.')
decode_parser.add_argument(
'token',
help='JSON web token to decode.',
nargs='?')

decode_parser.add_argument(
'-n', '--no-verify',
Expand Down
31 changes: 31 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,37 @@ def patched_sys_stdin_read():

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',
'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,name,job,exp,verify', [
('1234', 'Vader', 'Sith', None, None),
('4567', 'Anakin', 'Jedi', '+1', None),
Expand Down

0 comments on commit c1253ec

Please sign in to comment.