#!/usr/bin/env python3 """Use the public Counter API with app-user authentication. Python 3 only.""" import argparse import getpass import json import re import sys import urllib.error import urllib.parse import urllib.request class NoRedirects(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, file, code, message, headers, url): return None def call(opener, origin, path, method='GET', body=None, token=None): headers = {'Accept': 'application/json', 'Origin': origin, 'User-Agent': 'bfast-counter-example/1'} if body is not None: headers['Content-Type'] = 'application/json' if token: headers['Authorization'] = 'Bearer ' + token request = urllib.request.Request(origin + path, method=method, headers=headers, data=None if body is None else json.dumps(body).encode()) try: with opener.open(request, timeout=20) as response: payload = response.read(1048577) if len(payload) > 1048576: raise RuntimeError('The app response exceeds 1 MiB.') return json.loads(payload) except urllib.error.HTTPError as error: # Do not print response bodies from credential requests. They can echo input. error.close() raise RuntimeError('The app returned HTTP ' + str(error.code) + '.') from None except (urllib.error.URLError, ValueError): raise RuntimeError('The HTTPS request failed or returned invalid JSON.') from None def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--url', required=True, help='Exact HTTPS app origin') parser.add_argument('--email', required=True, help='App user email; not a platform agent key') parser.add_argument('--password-stdin', action='store_true', help='Read a password from a secret manager pipe') action = parser.add_mutually_exclusive_group() action.add_argument('--register', action='store_true', help='Register an app user and request verification email') action.add_argument('--create', metavar='NAME', help='Create a counter') action.add_argument('--increment', metavar='ID', help='Increment a counter; omit actions to list counters') args = parser.parse_args(argv) origin = args.url.rstrip('/') url = urllib.parse.urlsplit(origin) if url.scheme != 'https' or not url.netloc or url.username or url.password or url.path or url.query or url.fragment: parser.error('--url must be an exact HTTPS origin.') password = sys.stdin.readline(130).rstrip('\r\n') if args.password_stdin else getpass.getpass('App password: ') if not password or len(password) > 128: parser.error('Supply an app password of 1 to 128 characters.') opener = urllib.request.build_opener(NoRedirects()) try: credentials = {'email': args.email, 'password': password} if args.register: call(opener, origin, '/__bf/auth/sign-up/email', 'POST', {**credentials, 'name': args.email.split('@', 1)[0], 'callbackURL': origin + '/__bf/auth/complete'}) print('Registration submitted. Open the verification email, then run this client again.') return 0 login = call(opener, origin, '/__bf/auth/login', 'POST', credentials) token = login.get('access_token') if isinstance(login, dict) else None if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9._-]{1,8192}', token): raise RuntimeError('Login returned no valid app access token.') path, method, body = '/counters', 'GET', None if args.create is not None: method, body = 'POST', {'name': args.create} elif args.increment is not None: if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}', args.increment): raise RuntimeError('Supply the counter ID returned by the app.') path, method, body = '/counters/' + args.increment + '/increment', 'POST', {} print(json.dumps(call(opener, origin, path, method, body, token), indent=2)) return 0 except (RuntimeError, OSError) as error: # Runtime messages above contain only fixed diagnostics and HTTP status. message = str(error) if isinstance(error, RuntimeError) else 'The HTTPS request could not finish.' print(message, file=sys.stderr) if args.register: print('Check the dashboard Authentication page for SMTP configuration.', file=sys.stderr) return 1 if __name__ == '__main__': raise SystemExit(main())