def get_app(conf): actual_app = Flask(__name__) actual_app.register_blueprint(app, url_prefix="/") config.setup_config(conf) global engine engine = create_engine(config.main["database_uri"], poolclass=NullPool) global Session Session = scoped_session(lambda: create_session(bind=engine)) if config.main.get("timezone"): global DEFAULT_TIMEZONE DEFAULT_TIMEZONE = config.main["timezone"] LOG.info("Billing API started.") setup_memcache() # if configured to authenticate clients, then wrap the # wsgi app in the keystone middleware. if config.auth.get('authenticate_clients'): identity_url = urlparse(config.auth['identity_url']) conf = { 'admin_user': config.auth['username'], 'admin_password': config.auth['password'], 'admin_tenant_name': config.auth['default_tenant'], 'auth_host': identity_url.hostname, 'auth_port': identity_url.port, 'auth_protocol': identity_url.scheme } actual_app = auth_token.AuthProtocol(actual_app, conf) return actual_app
def add_mware(app): # See: https://docs.openstack.org/keystonemiddleware/latest/middlewarearchitecture.html if config.auth_base_url != '': from keystonemiddleware import auth_token base_url = config.auth_base_url admin_port = config.auth_admin_port user_port = config.auth_user_port username = config.auth_username passwd = config.auth_passwd tenant = config.auth_tenant if '' in [username, passwd, tenant]: raise RuntimeError( 'Keystone admin username, password or tenant name is not set in the environment.' ) conf = { 'service_token_roles_required': True, 'identity_uri': base_url + ':' + str(admin_port) + '/', 'auth_version': 'v3.0', 'www_authenticate_uri': base_url + ':' + str(user_port) + '/v3/', 'admin_user': username, 'admin_password': passwd, 'admin_tenant_name': tenant, } return auth_token.AuthProtocol(app, conf) else: return app
def create_app(app_name): app = Flask(app_name) app.config['SQLALCHEMY_DATABASE_URI'] = CONF.database.connection app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = ( CONF.flask.SQLALCHEMY_TRACK_MODIFICATIONS) app.config['PROPAGATE_EXCEPTIONS'] = CONF.flask.PROPAGATE_EXCEPTIONS api = Api(app) api.add_resource(Offer, '/offer', '/offer/', '/offer/<string:offer_id>') api.add_resource(Bid, '/bid', '/bid/', '/bid/<string:bid_id>') api.add_resource(Contract, '/contract', '/contract/', '/contract/<string:contract_id>') api.add_resource( OfferContractRelationship, '/offer_contract_relationship', '/offer_contract_relationship/', '/offer_contract_relationship' '/<string:offer_contract_relationship_id>') api.add_resource(Root, '/') orm.init_app(app) @app.before_request def before_request(): g.context = ctx.RequestContext.from_environ(request.environ) if CONF.api.auth_enable: app = auth_token.AuthProtocol(app, dict(CONF.keystone_authtoken)) return app
def __init__(self): # hardcode any non-default configuration here conf = {'auth_protocol': 'http', 'admin_token': 'ADMIN'} app = auth_token.AuthProtocol(echo_app, conf) server = simple_server.make_server('', 8000, app) print('Serving on port 8000 (Ctrl+C to end)...') server.serve_forever()
def setup_app(pecan_config=None, extra_hooks=None): app_hooks = [hooks.ConfigHook(), hooks.DBHook(), hooks.ContextHook(), hooks.RPCHook(), ] # TODO(sbauza): Add stevedore extensions for loading hooks if extra_hooks: app_hooks.extend(extra_hooks) app = pecan.make_app( pecan_config.app.root, debug=CONF.debug, hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) # WSGI middleware for debugging if CONF.log_exchange: app = debug.Debug.factory(pecan_config)(app) # WSGI middleware for Keystone auth # NOTE(sbauza): ACLs are always active unless for unittesting where # enable_acl could be set to False if pecan_config.app.enable_acl: app = auth_token.AuthProtocol(app, {}) return app
def _wrap_app(app): app = request_id.RequestId(app) if cfg.CONF.auth_strategy == 'noauth': pass elif cfg.CONF.auth_strategy == 'keystone': app = auth_token.AuthProtocol(app, {}) else: raise n_exc.InvalidConfigurationOption( opt_name='auth_strategy', opt_value=cfg.CONF.auth_strategy) # version can be unauthenticated so it goes outside of auth app = versions.Versions(app) # This should be the last middleware in the list (which results in # it being the first in the middleware chain). This is to ensure # that any errors thrown by other middleware, such as an auth # middleware - are annotated with CORS headers, and thus accessible # by the browser. app = cors.CORS(app, cfg.CONF) app.set_latent(allow_headers=[ 'X-Auth-Token', 'X-Identity-Status', 'X-Roles', 'X-Service-Catalog', 'X-User-Id', 'X-Tenant-Id', 'X-OpenStack-Request-ID', 'X-Trace-Info', 'X-Trace-HMAC' ], allow_methods=['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], expose_headers=[ 'X-Auth-Token', 'X-Subject-Token', 'X-Service-Token', 'X-OpenStack-Request-ID', 'X-Trace-Info', 'X-Trace-HMAC' ]) return app
def add_mware(app): # See: https://docs.openstack.org/keystonemiddleware/latest/middlewarearchitecture.html if os.environ.get('ET_AAA_ESM_KEYSTONE_BASE_URL', '') != '': from keystonemiddleware import auth_token base_url = os.environ.get('ET_AAA_ESM_KEYSTONE_BASE_URL', '') admin_port = os.environ.get('ET_AAA_ESM_KEYSTONE_ADMIN_PORT', 35357) user_port = os.environ.get('ET_AAA_ESM_KEYSTONE_USER_PORT', 5000) username = os.environ.get('ET_AAA_ESM_KEYSTONE_USERNAME', '') passwd = os.environ.get('ET_AAA_ESM_KEYSTONE_PASSWD', '') tenant = os.environ.get('ET_AAA_ESM_KEYSTONE_TENANT', '') if '' in [username, passwd, tenant]: raise RuntimeError( 'Keystone admin username, password or tenant name is not set in the environment.' ) conf = { 'service_token_roles_required': True, 'identity_uri': base_url + ':' + str(admin_port) + '/', 'auth_version': 'v3.0', 'www_authenticate_uri': base_url + ':' + str(user_port) + '/v3/', 'admin_user': username, 'admin_password': passwd, 'admin_tenant_name': tenant, } return auth_token.AuthProtocol(app, conf) else: return app
def add_auth_middleware(app): """Add authentication middleware to Flask application. :param app: application. """ auth_conf = dict(CONF.keystone_authtoken) # These items should only be used for accessing Ironic API. # For keystonemiddleware's authentication, # keystone_authtoken's items will be used and # these items will be unsupported. # [ironic]/os_password # [ironic]/os_username # [ironic]/os_auth_url # [ironic]/os_tenant_name auth_conf.update({ 'admin_password': CONF.ironic.os_password or CONF.keystone_authtoken.admin_password, 'admin_user': CONF.ironic.os_username or CONF.keystone_authtoken.admin_user, 'auth_uri': CONF.ironic.os_auth_url or CONF.keystone_authtoken.auth_uri, 'admin_tenant_name': CONF.ironic.os_tenant_name or CONF.keystone_authtoken.admin_tenant_name, 'identity_uri': CONF.ironic.identity_uri or CONF.keystone_authtoken.identity_uri }) auth_conf['delay_auth_decision'] = True app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app, auth_conf)
def load_app(self): # create our app. webtest gives us a callable interface to it app = loadapp('config:test.ini#vendordata', relative_to=os.path.dirname(__file__)) # load your wsgi app here, wrapped in auth_token middleware service = auth_token.AuthProtocol(app, {}) return webtest.TestApp(service)
def add_auth_middleware(app): """Add authentication middleware to Flask application. :param app: application. """ auth_conf = dict(CONF.keystone_authtoken) auth_conf['delay_auth_decision'] = True app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app, auth_conf)
def install(cls, app, conf): """Install Auth check on application.""" LOG.debug(u'Installing Keystone\'s auth protocol') return auth_token.AuthProtocol(app, conf={ "oslo-config-config": conf, "oslo-config-project": "zaqar" })
def _wrap_app(app): app = request_id.RequestId(app) if cfg.CONF.auth_strategy == 'noauth': pass elif cfg.CONF.auth_strategy == 'keystone': app = auth_token.AuthProtocol(app, {}) else: raise n_exc.InvalidConfigurationOption( opt_name='auth_strategy', opt_value=cfg.CONF.auth_strategy) return app
def setup(app): if cfg.CONF.pecan.auth_enable: conf = dict(cfg.CONF.keystone_authtoken) # Change auth decisions of requests to the app itself. conf.update({'delay_auth_decision': True}) return auth_token.AuthProtocol(app, conf) else: return app
def add_auth_middleware(app): """Add authentication middleware to Flask application. :param app: application. """ auth_conf = { key: conf.get('discoverd', value) for (key, value) in zip(MIDDLEWARE_ARGS, OS_ARGS) } auth_conf['delay_auth_decision'] = True auth_conf['identity_uri'] = conf.get('discoverd', 'identity_uri') app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app, auth_conf)
def _wrap_app(app): app = request_id.RequestId(app) if cfg.CONF.pecan.auth_enable and cfg.CONF.auth_strategy == 'keystone': conf = dict(cfg.CONF.keystone_authtoken) # Change auth decisions of requests to the app itself. conf.update({'delay_auth_decision': True}) # NOTE: Policy enforcement works only if Keystone # authentication is enabled. No support for other authentication # types at this point. return auth_token.AuthProtocol(app, conf) else: return app
def __init__(self): def echo_app(environ, start_response): start_response('200 OK', [('Content-Type', 'application/json')]) environment = dict((k, v) for k, v in six.iteritems(environ) if k.startswith('HTTP_X_')) yield jsonutils.dumps(environment) # hardcode any non-default configuration here conf = {'auth_protocol': 'http', 'admin_token': 'ADMIN'} app = auth_token.AuthProtocol(echo_app, conf) server = simple_server.make_server('', 8000, app) print('Serving on port 8000 (Ctrl+C to end)...') server.serve_forever()
def main(): if config.requires_auth(): # Wrap with keystone middleware if configured to do so if not CONF.keystone_authtoken.delay_auth_decision: msg = "The [keystone_authtoken] section in the config file " \ "must have delay_auth_decision explicitly set to true. " \ "The default value, false, will cause calls to " \ "/api/v2/heartbeat to be rejected " LOG.error(msg) print(msg) # print on the console for good measure sys.exit(1) # Use our our middleware function to permit unsecured apis to be called app.wsgi_app = enable_unsecured(app.wsgi_app) app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app, {'oslo_config_config': CONF}) CORS(app) # Use oslo healthcheck, which does not log its requests app.wsgi_app = healthcheck.Healthcheck(app.wsgi_app) # Note that any flask options that are to be exposed in our config file # have to be explicitly configured (in flask_opts above) and explicitly # placed into the following dict flask_config = {"JSONIFY_PRETTYPRINT_REGULAR": CONF.pretty_json} app.config.from_mapping(flask_config) trigger_file = os.path.join(CONF.paths.log_dir, 'trigger.txt') if not os.path.exists(trigger_file): with open(trigger_file, 'w') as f: f.write("Started at %s\n" % time.asctime()) socketio.init_app(app) # When we've truly started this for the first time, we only want to start # our singleton ssh-agent once. We must run this in the context of the # reloader since the rest of the app also runs in that same context. if is_running_from_reloader(): sshagent.sshagent.stop_old_instance() sshagent.sshagent.start() # The 'log' parameter avoids running in debug mode, which suppresses the # debug message that is emitted on *every* incoming request. socketio.run(app, host=CONF.host, port=CONF.port, use_reloader=True, log=LOG, extra_files=[trigger_file])
def setup(app): print "------ blog/api/access_control.setup() 27" if cfg.CONF.pecan.auth_enable: conf = dict(cfg.CONF.keystone_authtoken) # Change auth decisions of requests to the app itself. conf.update({'delay_auth_decision': True}) print "-----------pecan.auth_enable=True-------------------" print "------ all conf:" + conf.__str__() return auth_token.AuthProtocol(app, conf) else: print "-----------pecan.auth_enable=False-------------------" return app
def auth_app(app): app = request_id.RequestId(app) if cfg.CONF.auth_strategy == 'noauth': pass elif cfg.CONF.auth_strategy == 'keystone': # NOTE(zhiyuan) pkg_resources will try to load tricircle to get module # version, passing "project" as empty string to bypass it app = auth_token.AuthProtocol(app, {'project': ''}) else: raise t_exceptions.InvalidConfigurationOption( opt_name='auth_strategy', opt_value=cfg.CONF.auth_strategy) return app
def create_middleware(self, cb, conf=None, use_global_conf=False): @webob.dec.wsgify def _do_cb(req): return cb(req) if use_global_conf: opts = conf or {} else: opts = { 'oslo_config_config': self.cfg.conf, } opts.update(conf or {}) return auth_token.AuthProtocol(_do_cb, opts)
def setup(app): if cfg.CONF.pecan.auth_enable and cfg.CONF.auth_type == 'keystone': conf = dict(cfg.CONF.keystone_authtoken) # Change auth decisions of requests to the app itself. conf.update({'delay_auth_decision': True}) # NOTE(rakhmerov): Policy enforcement works only if Keystone # authentication is enabled. No support for other authentication # types at this point. _ensure_enforcer_initialization() return auth_token.AuthProtocol(app, conf) else: return app
def __init__(self, manager, serializer): self.manager = manager self.serializer = serializer self._method_map = _build_method_map(manager) if json_rpc.require_authentication(): conf = dict(CONF.keystone_authtoken) app = auth_token.AuthProtocol(self._application, conf) else: app = self._application self.server = wsgi.Server(CONF, 'ironic-json-rpc', app, host=CONF.json_rpc.host_ip, port=CONF.json_rpc.port, use_ssl=CONF.json_rpc.use_ssl)
def get_application(db): app = falcon.API(middleware=[middleware.JSONTranslator()]) for exception_class in exceptions.exception_handlers_catalog: app.add_error_handler(exception_class, exception_class.handle) endpoint_catalog = [('/v1', v1.public_endpoints(db)), ('/', [('', versions.Resource())])] for version_path, endpoints in endpoint_catalog: for route, resource in endpoints: app.add_route(version_path + route, resource) if 'keystone_authtoken' in config.CONF: app = auth_token.AuthProtocol(app, {}) else: logging.warning("keystone authentication disabled") return app
def _wrap_app(app): """Wraps wsgi app with additional middlewares.""" app = request_id.RequestId(app) if cfg.CONF.auth_strategy == constants.KEYSTONE: app = auth_token.AuthProtocol(app, {}) # This should be the last middleware in the list (which results in # it being the first in the middleware chain). This is to ensure # that any errors thrown by other middleware, such as an auth # middleware - are annotated with CORS headers, and thus accessible # by the browser. app = cors.CORS(app, cfg.CONF) app.set_latent(allow_headers=['X-Auth-Token', 'X-Openstack-Request-Id'], allow_methods=['GET', 'PUT', 'POST', 'DELETE'], expose_headers=['X-Auth-Token', 'X-Openstack-Request-Id']) return app
def setup_app(config=None): if not config: config = get_pecan_config() pecan.configuration.set_config(dict(config), overwrite=True) app = pecan.make_app( config.app.root, hooks=lambda: [ContextHook()], debug=CONF.pecan.debug, static_root=config.app.static_root if CONF.pecan.debug else None, force_canonical=getattr(config.app, 'force_canonical', True), ) if CONF.pecan.auth_enable: app = auth_token.AuthProtocol(app, dict(CONF.keystone_authtoken)) return app
def __init__(self, manager, serializer): self.manager = manager self.serializer = serializer self._method_map = _build_method_map(manager) auth_strategy = json_rpc.auth_strategy() if auth_strategy == 'keystone': conf = dict(CONF.keystone_authtoken) app = auth_token.AuthProtocol(self._application, conf) elif auth_strategy == 'http_basic': app = auth_basic.BasicAuthMiddleware( self._application, cfg.CONF.json_rpc.http_basic_auth_user_file) else: app = self._application self.server = wsgi.Server(CONF, 'ironic-json-rpc', app, host=CONF.json_rpc.host_ip, port=CONF.json_rpc.port, use_ssl=CONF.json_rpc.use_ssl)
def _wrap_app(app): app = request_id.RequestId(app) if cfg.CONF.auth_strategy == 'noauth': pass elif cfg.CONF.auth_strategy == 'keystone': app = auth_token.AuthProtocol(app, {}) else: raise n_exc.InvalidConfigurationOption( opt_name='auth_strategy', opt_value=cfg.CONF.auth_strategy) # This should be the last middleware in the list (which results in # it being the first in the middleware chain). This is to ensure # that any errors thrown by other middleware, such as an auth # middleware - are annotated with CORS headers, and thus accessible # by the browser. app = cors.CORS(app, cfg.CONF) app.set_latent(allow_headers=['X-Auth-Token', 'X-Openstack-Request-Id'], allow_methods=['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], expose_headers=['X-Auth-Token', 'X-Openstack-Request-Id']) return app
def init_app(self, app, config_group="flask_keystone"): """ Iniitialize the Flask_Keystone module in an application factory. :param app: `flask.Flask` application to which to connect. :type app: `flask.Flask` :param str config_group: :class:`oslo_config.cfg.OptGroup` to which to attach. When initialized, the extension will apply the :mod:`keystonemiddleware` WSGI middleware to the flask Application, attach it's own error handler, and generate a User model based on its :mod:`oslo_config` configuration. """ cfg.CONF.register_opts(RAX_OPTS, group=config_group) self.logger = logging.getLogger(__name__) try: logging.register_options(cfg.CONF) except cfg.ArgsAlreadyParsedError: # pragma: no cover pass logging.setup(cfg.CONF, "flask_keystone") self.config = cfg.CONF[config_group] self.roles = self._parse_roles() self.User = self._make_user_model() self.Anonymous = self._make_anonymous_model() self.logger.debug("Initialized keystone with roles: %s and " "allow_anonymous: %s" % ( self.roles, self.config.allow_anonymous_access )) app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app, {}) self.logger.debug("Adding before_request request handler.") app.before_request(self._make_before_request()) self.logger.debug("Registering Custom Error Handler.") app.register_error_handler(FlaskKeystoneException, handle_exception)
def _wrap_app(app): app = request_id.RequestId(app) if CONF.api.auth_strategy == 'noauth': pass elif CONF.api.auth_strategy == 'keystone': app = auth_token.AuthProtocol(app, {}) LOG.info("Keystone authentication is enabled") else: raise g_exc.InvalidConfigurationOption(opt_name='auth_strategy', opt_value=CONF.auth_strategy) # dont bother authenticating version # app = versions.Versions(app) # gluon server is behind the proxy app = http_proxy_to_wsgi.HTTPProxyToWSGI(app) # This should be the last middleware in the list (which results in # it being the first in the middleware chain). This is to ensure # that any errors thrown by other middleware, such as an auth # middleware - are annotated with CORS headers, and thus accessible # by the browser. app = cors.CORS(app, CONF) cors.set_defaults(allow_headers=[ 'X-Auth-Token', 'X-Identity-Status', 'X-Roles', 'X-Service-Catalog', 'X-User-Id', 'X-Tenant-Id', 'X-OpenStack-Request-ID', 'X-Trace-Info', 'X-Trace-HMAC' ], allow_methods=['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], expose_headers=[ 'X-Auth-Token', 'X-Subject-Token', 'X-Service-Token', 'X-OpenStack-Request-ID', 'X-Trace-Info', 'X-Trace-HMAC' ]) return app
def create_app(app_name): app = Flask(app_name) app.config['SQLALCHEMY_DATABASE_URI'] = CONF.database.connection app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = ( CONF.flask.SQLALCHEMY_TRACK_MODIFICATIONS ) app.config['PROPAGATE_EXCEPTIONS'] = CONF.flask.PROPAGATE_EXCEPTIONS api = Api(app) api.add_resource(Offer, '/offer', '/offer/', '/offer/<string:marketplace_offer_id>') api.add_resource(Bid, '/bid', '/bid/', '/bid/<string:marketplace_bid_id>') api.add_resource(Root, '/') orm.init_app(app) if CONF.api.auth_enable: app = auth_token.AuthProtocol(app, dict(CONF.keystone_authtoken)) return app