async def test_no_strategy(aiohttp_server, aiohttp_client, loop):
    async def public_view(request):
        return web.Response(text='Public view')

    async def secret_view(request):
        return web.Response(text='Secret view')

    app = web.Application()
    app.router.add_route('GET', '/public', public_view)
    app.router.add_route('GET', '/secret', secret_view)
    app.middlewares.append(
        basic_auth_middleware(
            ('/secret', ),
            {'user': '******'},
        ))

    server = await aiohttp_server(app)
    client = await aiohttp_client(server)

    response = await client.get('/public')
    assert response.status == 200

    response = await client.get('/secret')
    assert response.status == 401

    response = await client.get(
        '/secret',
        headers={'Authorization': generate_header('user', 'password')},
    )
    assert response.status == 200
Esempio n. 2
0
async def create_app(
    *,
    config: Optional[Configuration] = None,
    slack: Optional[WebClient] = None,
) -> Application:
    """Create and configure the Checkerboard application.

    On startup, Checkerboard will rebuild its mapping of Slack users to GitHub
    users and will not start responding to routes (including health checks)
    until that is done.  This will take 10-15 minutes, so set health check
    timeouts accordingly.

    Parameters
    ----------
    config : `Configuration`, optional
        The configuration to use.  If not provided, the default Configuration
        will be used.  This is a parameter primarily to allow for dependency
        injection by the test suite.
    slack : `WebClient`, optional
        The Slack WebClient to use.  If not provided, one will be created
        based on the application configuration.  This is a parameter primarily
        to allow for dependency injection by the test suite.
    """
    if not config:
        config = Configuration()
    configure_logging(
        profile=config.profile,
        log_level=config.log_level,
        name=config.logger_name,
    )

    # Create the Slack to GitHub mapper and retrieve the initial mapping
    # before creating the application.  This ensures that it will not respond
    # to health checks until the mapping is ready.
    if not slack:
        slack = WebClient(config.slack_token, run_async=True)
    mapper = await create_mapper(config, slack)

    root_app = Application()
    root_app["safir/config"] = config
    root_app["checkerboard/mapper"] = mapper
    setup_metadata(package_name="checkerboard", app=root_app)
    setup_middleware(root_app)
    root_app.add_routes(init_internal_routes())
    root_app.cleanup_ctx.append(create_mapper_refresh_task)

    sub_app = Application()
    setup_middleware(sub_app)
    sub_app.add_routes(init_external_routes())
    root_app.add_subapp(f"/{config.name}", sub_app)

    # The basic auth middleware requires the full URL, so attach it to the
    # root app, even though all the protected URLs are in the sub app.
    root_app.middlewares.append(
        basic_auth_middleware(
            (f"/{config.name}/slack", f"/{config.name}/github"),
            {config.username: config.password},
        ))

    return root_app
def get_app(loop, auth_dict=None):
    if auth_dict is None:
        auth_dict = {}

    app = web.Application(loop=loop)
    app.router.add_route('*', '/admin/hello', hello)
    app.router.add_route('*', '/admin/world', world)

    app.middlewares.append(
        basic_auth_middleware(('/admin', ), auth_dict, SkipOptionsStrategy))

    return app
Esempio n. 4
0
def get_app(loop, auth_dict=None, strategy=lambda x: x):
    if auth_dict is None:
        auth_dict = {}

    app = web.Application(loop=loop)

    app.router.add_route('GET', '/hello', hello)
    app.router.add_route('GET', '/admin/hello', hello)

    app.middlewares.append(
        basic_auth_middleware(('/admin',), auth_dict, strategy)
    )

    return app
Esempio n. 5
0
    def mock_web_server():
        SLEEP_MEAN = 1
        async def sleep_rand():
            secs = random.expovariate(1/SLEEP_MEAN)
            if secs > 2*SLEEP_MEAN:
                logging.info(f"Sleeping request for {secs} seconds")
            await asyncio.sleep(secs)

        async def ok_handle(request):
            await sleep_rand()
            return web.Response(text='Ok response')

        async def var_handle(request):
            await sleep_rand()
            name = request.match_info.get('text', "Anonymous")
            text = "Hello, " + name
            return web.Response(text=text)

        async def json_handle(request):
            json = '{"foo": "bar"}'
            await sleep_rand()
            return web.Response(text=json)

        async def bad_request_handle(request):
            await sleep_rand()
            return web.HTTPBadRequest()

        async def mixed_response_handle(request):
            await sleep_rand()
            return random.choices(
                [web.Response(text='Ok response'), web.HTTPTooManyRequests()],
                weights=[0.6,0.4]
            )[0]

        asyncio.set_event_loop(asyncio.new_event_loop())  # Only use if in seperate thread or process
        app = web.Application()
        app.router.add_get('/', ok_handle)
        app.router.add_get('/ok', ok_handle)
        app.router.add_get('/var/{text}', var_handle)
        app.router.add_get('/json', json_handle)
        app.router.add_get('/bad_request', bad_request_handle)
        app.router.add_get('/mixed_response', mixed_response_handle)

        # Route with basic auth
        app.router.add_route('GET', '/basic_auth', ok_handle)
        app.middlewares.append(
            basic_auth_middleware(('/basic_auth',), {'username': '******'})
        )

        web.run_app(app)
Esempio n. 6
0
async def app_factory():
    app = web.Application()
    app.router.add_view('/', SimpleJsonView)
    app.router.add_view('/auth', AuthJsonView)
    app.router.add_view('/random_data', RandomDataView)
    app.router.add_view('/random_status', RandomStatusesView)
    app.router.add_view('/random_sleep', RandomSleepView)

    app.middlewares.append(
        basic_auth_middleware(
            ('/auth', ),
            {'user': '******'},
        ))

    return app
Esempio n. 7
0
    def _setup_routes(self):
        self.app.router.add_post(self.config['ADMIN_BADGES_CREATE'],
                                 self.create_badge_handler)

        self.app.router.add_get(self.config['ADMIN_PERSONS_LIST'],
                                self.list_persons_handler)

        self.app.router.add_post(self.config['ADMIN_PERMISSIONS_UPDATE'],
                                 self.update_permissions_handler)

        self.app.router.add_get(self.config['ADMIN_PERMISSIONS_LIST'],
                                self.list_permissions_handler)
        self.app.middlewares.append(
            basic_auth_middleware(
                ('/', ),
                {self.config['ADMIN_USER']: self.config['ADMIN_PASSWORD']}))
Esempio n. 8
0
def get_authentication_middleware(config: Config) -> typing.Callable[
        [web.Request, typing.Callable[[web.Request], typing.Awaitable[web.Response]]],
        typing.Awaitable[web.Response]
    ]:
    """Create an aiohttp.web authentication middleware as prescribed by app config, or None
    """
    policy = config.server.security.authentication
    if (policy == "basic"):
        return basic_auth_middleware(
            ("/",),
            config.server.security.users,
        )
    elif (policy == "none"):
        return None
    else:
        raise ValueError("Unrecognised authentication policy '{}' in app config".format(policy))
Esempio n. 9
0
def setup_basic_auth(app, user, pwd):
    app.middlewares.append(
        basic_auth_middleware(('/private/', ), {user: pwd},
                              SkipOptionsStrategy))
    logging.info("Enabled basic auth.")
Esempio n. 10
0
def setup_basic_auth(app, user, pwd):
    app.middlewares.append(basic_auth_middleware(('/api/', ), {user: pwd}))
    logging.info("Enabled basic auth.")
Esempio n. 11
0
 def auth_middlewares(self, app, auth_list: [],
                      user_dict: {'user': '******'}):
     app.middlewares.append(basic_auth_middleware(
         auth_list,
         user_dict,
     ))
Esempio n. 12
0
        return web.HTTPFound(f'/users/{username}')
    except DoesNotExist:
        user = await User.create(**cdata)
    keys = serializer._field_names()
    return json_response({k: getattr(user, k) for k in keys}, status=201)


@use_args({'message': fields.Str(required=True), 'parse_mode': fields.Str()})
async def post_user_message(request, args):
    message = args['message']
    username = request.match_info['username']
    user = await User.get(username=username)
    logger.info('User {}', user)
    logger.info('To send message to {}', user.telegram_id)
    parse_mode = args.get('parse_mode')
    await bot.send_message(user.telegram_id, message, parse_mode)
    return json_response(message)


app.on_startup.append(init_orm)
app.on_cleanup.append(close_orm)

app.middlewares.append(
    basic_auth_middleware(('/users', ), dict(config.API_USERS)))

app.add_routes([
    view('/users/{username}', UserView),
    web.post('/users/', create_user),
    web.post('/users/{username}/message', post_user_message)
])
Esempio n. 13
0
def create_rest_server(user='******',
                       pwd='password',
                       port=3000,
                       host='127.0.0.1',
                       ssl_context=None):
    """
    create REST server for API
    :param user: BasicAuth username
    :param pwd: BasicAuth password
    :param port: REST bind port
    :param host: REST bind host, "0.0.0.0" is global
    :param ssl_context: for SSL server
    """
    threading.current_thread().setName("REST")
    app = web.Application()
    V.API_OBJ = app

    # System
    app.router.add_get('/public/getsysteminfo', system_info)
    app.router.add_get('/private/getsysteminfo', system_private_info)
    app.router.add_get('/public/getchaininfo', chain_info)
    app.router.add_get('/private/chainforkinfo', chain_fork_info)
    app.router.add_get('/public/getnetworkinfo', network_info)
    app.router.add_get('/private/createbootstrap', create_bootstrap)
    app.router.add_get('/private/resync', resync)
    app.router.add_get('/private/stop', close_server)
    # Account
    app.router.add_get('/private/listbalance', list_balance)
    app.router.add_get('/private/listtransactions', list_transactions)
    app.router.add_get('/public/listunspents', list_unspents)
    app.router.add_get('/private/listunspents', list_private_unspents)
    app.router.add_get('/private/listaccountaddress', list_account_address)
    app.router.add_post('/private/createwallet', create_wallet)
    app.router.add_post('/private/importprivatekey', import_private_key)
    app.router.add_post('/private/move', move_one)
    app.router.add_post('/private/movemany', move_many)
    app.router.add_get('/private/newaddress', new_address)
    app.router.add_get('/private/getkeypair', get_keypair)
    # Sending
    app.router.add_post('/public/createrawtx', create_raw_tx)
    app.router.add_post('/private/signrawtx', sign_raw_tx)
    app.router.add_post('/public/broadcasttx', broadcast_tx)
    app.router.add_post('/private/sendfrom', send_from_user)
    app.router.add_post('/private/sendmany', send_many_user)
    app.router.add_post('/private/issueminttx', issue_mint_tx)
    app.router.add_post('/private/changeminttx', change_mint_tx)
    # Contract
    app.router.add_get('/public/getcontractinfo', contract_info)
    app.router.add_get('/public/getvalidatorinfo', validator_info)
    app.router.add_get('/public/getcontracthistory', get_contract_history)
    app.router.add_get('/public/getvalidatorhistory', get_validator_history)
    app.router.add_get('/public/contractstorage', contract_storage)
    app.router.add_get('/private/watchinginfo', watching_info)
    app.router.add_post('/private/sourcecompile', source_compile)
    app.router.add_post('/private/contractinit', contract_init)
    app.router.add_post('/private/contractupdate', contract_update)
    app.router.add_post('/private/contracttransfer', contract_transfer)
    app.router.add_post('/private/concludecontract', conclude_contract)
    app.router.add_post('/private/validatoredit', validator_edit)
    app.router.add_post('/private/validateunconfirmed', validate_unconfirmed)
    # BlockChain
    app.router.add_get('/public/getblockbyheight', get_block_by_height)
    app.router.add_get('/public/getblockbyhash', get_block_by_hash)
    app.router.add_get('/public/gettxbyhash', get_tx_by_hash)
    app.router.add_get('/public/getmintinfo', get_mintcoin_info)
    app.router.add_get('/public/getminthistory', get_mintcoin_history)
    # Others
    app.router.add_get('/public/ws', websocket_route)
    app.router.add_get('/private/ws', websocket_route)
    # JSON-RPC html/markdown pages
    app.router.add_get('/', web_page)
    app.router.add_post('/', json_rpc)
    app.router.add_get('/{page_path:[^{}]+.}', web_page)

    # Cross-Origin Resource Sharing
    escape_cross_origin_block(app)

    # setup basic auth
    assert isinstance(user, str) and isinstance(pwd, str)
    app.middlewares.append(
        basic_auth_middleware(('/private/', ), {user: pwd},
                              PrivateAccessStrategy))

    # Working
    runner = web.AppRunner(app)
    loop.run_until_complete(non_blocking_start(runner, host, port,
                                               ssl_context))
    log.info(f"API listen on {host}:{port}")