Пример #1
0
def create_web_app() -> Flask:
    """Initialize and configure the accounts application."""
    app = Flask('registry')
    app.config.from_pyfile('config.py')

    # app.register_blueprint(ui.blueprint)

    datastore.init_app(app)
    SessionStore.init_app(app)

    Base(app)  # Gives us access to the base UI templates and resources.
    auth.Auth(app)  # Handless sessions and authn/z.
    oauth2.init_app(app)
    app.register_blueprint(blueprint)

    middleware = [AuthMiddleware]
    if app.config['VAULT_ENABLED']:
        middleware.insert(0, vault.middleware.VaultMiddleware)
    wrap(app, middleware)
    if app.config['VAULT_ENABLED']:
        app.middlewares['VaultMiddleware'].update_secrets({})

    app.jinja_env.filters['scope_label'] = filters.scope_label

    if app.config['CREATE_DB']:
        with app.app_context():
            datastore.create_all()

    register_error_handlers(app)
    return app
Пример #2
0
    def setUp(self):
        """Spin up redis."""
        self.redis = subprocess.run(
            "docker run -d -p 7000:7000 redis",
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
        )
        time.sleep(2)    # In case it takes a moment to start.
        if self.redis.returncode > 0:
            raise RuntimeError('Could not start redis. Is Docker running?')

        self.container = self.redis.stdout.decode('ascii').strip()
        self.db = 'db.sqlite'

        self.client = Client(
            owner_id='252',
            name='fooclient',
            url='http://asdf.com',
            description='a client',
            redirect_uri='https://foo.com/bar'
        )
        self.secret = 'foohashedsecret'
        self.hashed_secret = sha256(self.secret.encode('utf-8')).hexdigest()
        self.cred = ClientCredential(client_secret=self.hashed_secret)
        self.auths = [
            ClientAuthorization(
                scope='foo:bar',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            ),
            ClientAuthorization(
                scope='baz:bat',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            )
        ]
        self.grant_types = [
            ClientGrantType(
                grant_type='client_credentials',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            )
        ]
        try:
            os.environ['AUTHLIB_INSECURE_TRANSPORT'] = 'true'
            self.app = create_web_app()
            self.app.config['REGISTRY_DATABASE_URI'] = f'sqlite:///{self.db}'

            self.test_client = self.app.test_client()
            with self.app.app_context():
                datastore.create_all()
                self.client_id = datastore.save_client(
                    self.client,
                    self.cred,
                    auths=self.auths,
                    grant_types=self.grant_types
                )

        except Exception as e:
            stop_container(self.container)
            raise
Пример #3
0
    def setUpClass(cls):
        cls.db = 'db.sqlite'

        cls.client = Client(owner_id='252',
                            name='fooclient',
                            url='http://asdf.com',
                            description='a client',
                            redirect_uri='https://foo.com/bar')
        cls.secret = 'foohashedsecret'
        os.environ['JWT_SECRET'] = cls.secret
        cls.hashed_secret = sha256(cls.secret.encode('utf-8')).hexdigest()
        cls.cred = ClientCredential(client_secret=cls.hashed_secret)
        cls.auths = [
            ClientAuthorization(scope='something:read',
                                requested=datetime.now() -
                                timedelta(seconds=30),
                                authorized=datetime.now()),
            ClientAuthorization(scope='foo:bar',
                                requested=datetime.now() -
                                timedelta(seconds=30),
                                authorized=datetime.now()),
            ClientAuthorization(scope='baz:bat',
                                requested=datetime.now() -
                                timedelta(seconds=30),
                                authorized=datetime.now())
        ]
        cls.grant_types = [
            ClientGrantType(grant_type='client_credentials',
                            requested=datetime.now() - timedelta(seconds=30),
                            authorized=datetime.now()),
            ClientGrantType(grant_type='authorization_code',
                            requested=datetime.now() - timedelta(seconds=30),
                            authorized=datetime.now())
        ]

        os.environ['AUTHLIB_INSECURE_TRANSPORT'] = 'true'
        cls.app = create_web_app()
        cls.app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{cls.db}'
        cls.app.config['SERVER_NAME'] = 'local.host:5000'
        cls.app.config['JWT_SECRET'] = cls.secret
        cls.app.config['REDIS_FAKE'] = True

        cls.test_client = cls.app.test_client()
        cls.user_agent = cls.app.test_client()
        with cls.app.app_context():
            datastore.create_all()
            cls.client_id = datastore.save_client(cls.client,
                                                  cls.cred,
                                                  auths=cls.auths,
                                                  grant_types=cls.grant_types)
Пример #4
0
def create_web_app() -> Flask:
    """Initialize and configure the accounts application."""
    app = Flask('registry')
    app.config.from_pyfile('config.py')

    # app.register_blueprint(ui.blueprint)

    datastore.init_app(app)
    sessions.init_app(app)

    Base(app)  # Gives us access to the base UI templates and resources.
    auth.Auth(app)  # Handless sessions and authn/z.
    oauth2.init_app(app)
    app.register_blueprint(blueprint)
    wrap(app, [auth.middleware.AuthMiddleware])

    app.jinja_env.filters['scope_label'] = filters.scope_label

    datastore.create_all()
    return app
Пример #5
0
def create_client(name: str, url: str, description: str, scopes: str,
                  redirect_uri: str) -> None:
    """Create a new client. For dev/test purposes only."""
    app = create_web_app()
    with app.app_context():
        datastore.create_all()

    with datastore.util.transaction() as session:
        db_client = datastore.models.DBClient(name=name,
                                              url=url,
                                              description=description,
                                              redirect_uri=redirect_uri)
        secret = generate_token(48)
        hashed = hashlib.sha256(secret.encode('utf-8')).hexdigest()
        db_cred = datastore.models.DBClientCredential(client=db_client,
                                                      client_secret=hashed)
        db_scopes = [
            datastore.models.DBClientAuthorization(client=db_client,
                                                   authorized=datetime.now(),
                                                   scope=scope)
            for scope in scopes.split()
        ]
        db_grant_type = datastore.models.DBClientGrantType(
            client=db_client,
            grant_type='client_credentials',
            authorized=datetime.now())
        db_grant_type = datastore.models.DBClientGrantType(
            client=db_client,
            grant_type='authorization_code',
            authorized=datetime.now())

        session.add(db_client)
        session.add(db_cred)
        session.add(db_grant_type)
        for db_scope in db_scopes:
            session.add(db_scope)

        session.commit()
    click.echo(f'Created client {name} with ID {db_client.client_id}'
               f' and secret {secret}')
Пример #6
0
"""Create all tables in the registry database."""

from registry.factory import create_web_app
from registry.services import datastore

app = create_web_app()
datastore.init_app(app)
with app.app_context():
    datastore.create_all()
Пример #7
0
    def setUpClass(cls):
        """Spin up redis."""
        os.environ['JWT_SECRET'] = 'foosecret'
        cls.redis = subprocess.run(
            "docker run -d -p 7000:7000 -p 7001:7001 -p 7002:7002 -p 7003:7003"
            " -p 7004:7004 -p 7005:7005 -p 7006:7006 -e \"IP=0.0.0.0\""
            " --hostname=server grokzen/redis-cluster:4.0.9",
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
        )
        time.sleep(10)    # In case it takes a moment to start.
        if cls.redis.returncode > 0:
            raise RuntimeError('Could not start redis. Is Docker running?')

        cls.container = cls.redis.stdout.decode('ascii').strip()
        cls.db = 'db.sqlite'

        cls.client = Client(
            owner_id='252',
            name='fooclient',
            url='http://asdf.com',
            description='a client',
            redirect_uri='https://foo.com/bar'
        )
        cls.secret = 'foohashedsecret'
        cls.hashed_secret = sha256(cls.secret.encode('utf-8')).hexdigest()
        cls.cred = ClientCredential(client_secret=cls.hashed_secret)
        cls.auths = [
            ClientAuthorization(
                scope='something:read',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            ),
            ClientAuthorization(
                scope='foo:bar',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            ),
            ClientAuthorization(
                scope='baz:bat',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            )
        ]
        cls.grant_types = [
            ClientGrantType(
                grant_type='client_credentials',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            ),
            ClientGrantType(
                grant_type='authorization_code',
                requested=datetime.now() - timedelta(seconds=30),
                authorized=datetime.now()
            )

        ]
        try:
            os.environ['AUTHLIB_INSECURE_TRANSPORT'] = 'true'
            cls.app = create_web_app()
            cls.app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{cls.db}'
            cls.app.config['SERVER_NAME'] = 'local.host:5000'
            cls.app.config['REDIS_HOST'] = 'localhost'
            cls.app.config['REDIS_PORT'] = '7000'
            cls.app.config['REDIS_CLUSTER'] = '1'

            cls.test_client = cls.app.test_client()
            cls.user_agent = cls.app.test_client()
            with cls.app.app_context():
                datastore.create_all()
                cls.client_id = datastore.save_client(
                    cls.client,
                    cls.cred,
                    auths=cls.auths,
                    grant_types=cls.grant_types
                )

        except Exception:
            with cls.app.app_context():
                stop_container(cls.container)
            raise