def convert(self, value, param, ctx): try: parse_url(value) except Exception as e: self.fail(style_error(str(e))) else: return value
def convert(self, value, param, ctx): if re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", value): return value self.fail(style_error('invalid email address "{}"'.format(value)))
def _load_and_maybe_generate(self, privkey_path, pubkey_path, yes_to_all=False): if os.path.exists(privkey_path): # node private key seems to exist already .. check! priv_tags = _parse_keyfile(privkey_path, private=True) for tag in [ u'creator', u'created-at', u'user-id', u'public-key-ed25519', u'private-key-ed25519' ]: if tag not in priv_tags: raise Exception( "Corrupt user private key file {} - {} tag not found". format(privkey_path, tag)) creator = priv_tags[u'creator'] created_at = priv_tags[u'created-at'] user_id = priv_tags[u'user-id'] privkey_hex = priv_tags[u'private-key-ed25519'] privkey = SigningKey(privkey_hex, encoder=HexEncoder) pubkey = privkey.verify_key pubkey_hex = pubkey.encode(encoder=HexEncoder).decode('ascii') if priv_tags[u'public-key-ed25519'] != pubkey_hex: raise Exception(( "Inconsistent user private key file {} - public-key-ed25519 doesn't" " correspond to private-key-ed25519").format(pubkey_path)) if os.path.exists(pubkey_path): pub_tags = _parse_keyfile(pubkey_path, private=False) for tag in [ u'creator', u'created-at', u'user-id', u'public-key-ed25519' ]: if tag not in pub_tags: raise Exception( "Corrupt user public key file {} - {} tag not found" .format(pubkey_path, tag)) if pub_tags[u'public-key-ed25519'] != pubkey_hex: raise Exception(( "Inconsistent user public key file {} - public-key-ed25519 doesn't" " correspond to private-key-ed25519" ).format(pubkey_path)) else: # public key is missing! recreate it pub_tags = OrderedDict([ (u'creator', priv_tags[u'creator']), (u'created-at', priv_tags[u'created-at']), (u'user-id', priv_tags[u'user-id']), (u'public-key-ed25519', pubkey_hex), ]) msg = u'Crossbar.io user public key\n\n' _write_node_key(pubkey_path, pub_tags, msg) click.echo( 'Re-created user public key from private key: {}'.format( style_ok(pubkey_path))) # click.echo('User public key loaded: {}'.format(style_ok(pubkey_path))) # click.echo('User private key loaded: {}'.format(style_ok(privkey_path))) else: # user private key does not yet exist: generate one creator = _creator(yes_to_all) created_at = utcnow() user_id = _user_id(yes_to_all) privkey = SigningKey.generate() privkey_hex = privkey.encode(encoder=HexEncoder).decode('ascii') pubkey = privkey.verify_key pubkey_hex = pubkey.encode(encoder=HexEncoder).decode('ascii') # first, write the public file tags = OrderedDict([ (u'creator', creator), (u'created-at', created_at), (u'user-id', user_id), (u'public-key-ed25519', pubkey_hex), ]) msg = u'Crossbar.io FX user public key\n\n' _write_node_key(pubkey_path, tags, msg) os.chmod(pubkey_path, 420) # now, add the private key and write the private file tags[u'private-key-ed25519'] = privkey_hex msg = u'Crossbar.io FX user private key - KEEP THIS SAFE!\n\n' _write_node_key(privkey_path, tags, msg) os.chmod(privkey_path, 384) click.echo('New user public key generated: {}'.format( style_ok(pubkey_path))) click.echo('New user private key generated ({}): {}'.format( style_error('keep this safe!'), style_ok(privkey_path))) # fix file permissions on node public/private key files # note: we use decimals instead of octals as octal literals have changed between Py2/3 if os.stat(pubkey_path ).st_mode & 511 != 420: # 420 (decimal) == 0644 (octal) os.chmod(pubkey_path, 420) click.echo( style_error('File permissions on user public key fixed!')) if os.stat(privkey_path ).st_mode & 511 != 384: # 384 (decimal) == 0600 (octal) os.chmod(privkey_path, 384) click.echo( style_error('File permissions on user private key fixed!')) # load keys into object self._creator = creator self._created_at = created_at self.user_id = user_id self._privkey = privkey self._privkey_hex = privkey_hex self._pubkey = pubkey self._pubkey_hex = pubkey_hex self.key = cryptosign.SigningKey(privkey)
async def repl(old_ctx, prompt_kwargs=None, allow_system_commands=True, allow_internal_commands=True, once=False, get_bottom_toolbar_tokens=_get_bottom_toolbar_tokens, get_prompt_tokens=None, style=_style): """ Start an interactive shell. All subcommands are available in it. :param old_ctx: The current Click context. :param prompt_kwargs: Parameters passed to :py:func:`prompt_toolkit.shortcuts.prompt`. If stdin is not a TTY, no prompt will be printed, but only commands read from stdin. """ # parent should be available, but we're not going to bother if not group_ctx = old_ctx.parent or old_ctx group = group_ctx.command isatty = sys.stdin.isatty() # Delete the REPL command from those available, as we don't want to allow # nesting REPLs (note: pass `None` to `pop` as we don't want to error if # REPL command already not present for some reason). repl_command_name = old_ctx.command.name available_commands = group_ctx.command.commands available_commands.pop(repl_command_name, None) if isatty: prompt_kwargs = prompt_kwargs or {} if not get_prompt_tokens: prompt_kwargs.setdefault('message', u'>> ') history = prompt_kwargs.pop('history', None) \ or InMemoryHistory() completer = prompt_kwargs.pop('completer', None) \ or ClickCompleter(group) def get_command(): return prompt( completer=completer, history=history, # patch_stdout=False, # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/examples/get-multiline-input.py # multiline=True, # get_continuation_tokens=continuation_tokens, # get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, # get_prompt_tokens=get_prompt_tokens, style=style, async_=True, **prompt_kwargs) else: get_command = sys.stdin.readline stopped = False while not stopped: try: command = await get_command() except KeyboardInterrupt: continue except EOFError: break finally: if once: stopped = True if not command: if isatty: continue else: break if allow_system_commands and dispatch_repl_commands(command): continue if allow_internal_commands: try: result = handle_internal_commands(command) if isinstance(result, six.string_types): click.echo(result) continue except ExitReplException: break args = shlex.split(command) try: with group.make_context(None, args, parent=group_ctx) as ctx: f = group.invoke(ctx) if f: await f ctx.exit() except ApplicationError as e: click.echo(style_error(u'[{}] {}'.format(e.error, e.args[0]))) except click.ClickException as e: e.show() except SystemExit: pass
def on_error(err): self.log.warn('{klass}.on_error(err={err})', klass=self.__class__.__name__, err=err) if isinstance(err, Failure): err = err.value if isinstance(err, ApplicationError): self.log.warn('{message} - {error}', message=err.args[0] if err.args else '', error=err.error) # some ApplicationErrors are actually signaling progress # in the authentication flow, some are real errors exit_code = None if err.error.startswith('fabric.auth-failed.'): error = err.error.split('.')[2] message = err.args[0] if error == 'new-user-auth-code-sent': click.echo( '\nThanks for registering! {}'.format(message)) click.echo( style_ok( 'Please check your inbox and run "crossbar shell auth --code <THE CODE YOU GOT BY EMAIL>.\n' )) elif error == 'registered-user-auth-code-sent': click.echo('\nWelcome back! {}'.format(message)) click.echo( style_ok( 'Please check your inbox and run "crossbar shell auth --code <THE CODE YOU GOT BY EMAIL>.\n' )) elif error == 'pending-activation': click.echo() click.echo(style_ok(message)) click.echo() click.echo( 'Tip: to activate, run "crossbar shell auth --code <THE CODE YOU GOT BY EMAIL>"' ) click.echo( 'Tip: you can request sending a new code with "crossbar shell auth --new-code"' ) click.echo() elif error == 'no-pending-activation': exit_code = 1 click.echo() click.echo( style_error('{} [{}]'.format(message, err.error))) click.echo() elif error == 'email-failure': exit_code = 1 click.echo() click.echo( style_error('{} [{}]'.format(message, err.error))) click.echo() elif error == 'invalid-activation-code': exit_code = 1 click.echo() click.echo( style_error('{} [{}]'.format(message, err.error))) click.echo() else: exit_code = 1 click.echo(style_error('{}'.format(error))) click.echo(style_error(message)) elif err.error.startswith('crossbar.error.'): error = err.error.split('.')[2] message = err.args[0] if error == 'invalid_configuration': click.echo() click.echo( style_error('{} [{}]'.format(message, err.error))) click.echo() else: exit_code = 1 click.echo( style_error('{} [{}]'.format(message, err.error))) else: click.echo(style_error('{}'.format(err))) exit_code = 1 if exit_code: raise SystemExit(exit_code) else: click.echo(style_error('{}'.format(err))) raise SystemExit(1)