Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix over-eager fallback to stdin #304

Merged
merged 3 commits into from Nov 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
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
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
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