def encode_dataset_user(trans, dataset, user): # encode dataset id as usual # encode user id using the dataset create time as the key dataset_hash = trans.security.encode_id(dataset.id) if user is None: user_hash = 'None' else: security = IdEncodingHelper(id_secret=dataset.create_time) user_hash = security.encode_id(user.id) return dataset_hash, user_hash
def decode_dataset_user(trans, dataset_hash, user_hash): # decode dataset id as usual # decode user id using the dataset create time as the key dataset_id = trans.security.decode_id(dataset_hash) dataset = trans.sa_session.query( trans.app.model.HistoryDatasetAssociation).get(dataset_id) assert dataset, "Bad Dataset id provided to decode_dataset_user" if user_hash in [None, 'None']: user = None else: security = IdEncodingHelper(id_secret=dataset.create_time) user_id = security.decode_id(user_hash) user = trans.sa_session.query(trans.app.model.User).get(user_id) assert user, "A Bad user id was passed to decode_dataset_user" return dataset, user
def get_api_user( security: IdEncodingHelper = depends(IdEncodingHelper), user_manager: UserManager = depends(UserManager), key: Optional[str] = Query(None), x_api_key: Optional[str] = Header(None), run_as: Optional[EncodedDatabaseIdField] = Header( default=None, title='Run as User', description= ('The user ID that will be used to effectively make this API call. ' 'Only admins and designated users can make API calls on behalf of other users.' ))) -> Optional[User]: api_key = key or x_api_key if not api_key: return None user = user_manager.by_api_key(api_key=api_key) if run_as: if user_manager.user_can_do_run_as(user): try: decoded_run_as_id = security.decode_id(run_as) except Exception: raise UserInvalidRunAsException return user_manager.by_id(decoded_run_as_id) else: raise UserCannotRunAsException return user
def __init__(self, root=None, **kwd): Bunch.__init__(self, **kwd) if not root: root = tempfile.mkdtemp() self._remove_root = True else: self._remove_root = False self.root = root self.data_dir = os.path.join(root, 'database') self.security = IdEncodingHelper(id_secret=GALAXY_TEST_UNITTEST_SECRET) self.database_connection = kwd.get( 'database_connection', GALAXY_TEST_IN_MEMORY_DB_CONNECTION) # objectstore config values... self.object_store_config_file = '' self.object_store = 'disk' self.object_store_check_old_style = False self.object_store_cache_path = '/tmp/cache' self.object_store_store_by = "uuid" self.umask = os.umask(0o77) self.gid = os.getgid() # objectstore config directories... self.jobs_directory = os.path.join(self.data_dir, 'jobs_directory') self.new_file_path = os.path.join(self.data_dir, 'tmp') self.file_path = os.path.join(self.data_dir, 'files') self.server_name = "main"
def main(argv): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-k', '--secret-key', help='Key to convert pages with', default='') parser.add_argument('-d', '--dry-run', help='No changes, just test it.', action='store_true') populate_config_args(parser) args = parser.parse_args() properties = app_properties_from_args(args) config = galaxy.config.Configuration(**properties) secret = args.secret_key or config.id_secret security_helper = IdEncodingHelper(id_secret=secret) object_store = build_object_store_from_config(config) if not config.database_connection: print("The database connection is empty. If you are using the default value, please uncomment that in your galaxy.yml") model = galaxy.config.init_models_from_config(config, object_store=object_store) session = model.context.current pagerevs = session.query(model.PageRevision).all() mock_trans = Bunch(app=Bunch(security=security_helper), model=model, user_is_admin=lambda: True, sa_session=session) for p in pagerevs: try: processor = _PageContentProcessor(mock_trans, _placeholderRenderForSave) processor.feed(p.content) newcontent = unicodify(processor.output(), 'utf-8') if p.content != newcontent: if not args.dry_run: p.content = unicodify(processor.output(), 'utf-8') session.add(p) session.flush() else: print("Modifying revision %s." % p.id) print(difflib.unified_diff(p.content, newcontent)) except Exception: logging.exception("Error parsing page, rolling changes back and skipping revision %s. Please report this error." % p.id) session.rollback()
def __init__(self): self.config = bunch.Bunch(tool_secret="awesome_secret", ) self.model = mapping.init("/tmp", "sqlite:///:memory:", create_tables=True) self.toolbox = TestToolbox() self.datatypes_registry = TestDatatypesRegistry() self.security = IdEncodingHelper(id_secret="testing")
def get_session( session_manager: GalaxySessionManager = Depends(get_session_manager), security: IdEncodingHelper = depends(IdEncodingHelper), galaxysession: Optional[str] = Cookie(None) ) -> Optional[model.GalaxySession]: if galaxysession: session_key = security.decode_guid(galaxysession) if session_key: return session_manager.get_session_from_session_key(session_key) # TODO: What should we do if there is no session? Since this is the API, maybe nothing is the right choice? return None
def __init__(self, config): self.config = config if not self.config.database_connection: self.config.database_connection = "sqlite:///%s?isolation_level=IMMEDIATE" % str( config.database) print('Using database connection: ', self.config.database_connection) # Setup the database engine and ORM self.model = mapping.init(self.config.file_path, self.config.database_connection, engine_options={}, create_tables=False) self.security = IdEncodingHelper(id_secret=self.config.id_secret)
def get_api_user(security: IdEncodingHelper = depends(IdEncodingHelper), user_manager: UserManager = depends(UserManager), key: Optional[str] = Query(None), x_api_key: Optional[str] = Header(None), run_as: Optional[EncodedDatabaseIdField] = Header( None, title='Run as User', description='Admins and ')) -> Optional[User]: api_key = key or x_api_key if not api_key: return None user = user_manager.by_api_key(api_key=api_key) if run_as: if user_manager.user_can_do_run_as(user): try: decoded_run_as_id = security.decode_id(run_as) except Exception: raise UserInvalidRunAsException return user_manager.by_id(decoded_run_as_id) else: raise UserCannotRunAsException return user
def _configure_security(self): self.security = IdEncodingHelper(id_secret=self.config.id_secret) BaseDatabaseIdField.security = self.security
def encode_with_security(security: IdEncodingHelper, id: Any): return security.encode_id(id)
def decode_with_security(security: IdEncodingHelper, id: Any): return security.decode_id(str(id))
def test_decoded_database_id_field(security: IdEncodingHelper): decoded_id = 1 id_model = EncodedIdModel(id=decoded_id) assert id_model.id == security.encode_id(decoded_id)
def security() -> IdEncodingHelper: BaseDatabaseIdField.security = IdEncodingHelper(id_secret="testing") return BaseDatabaseIdField.security
app_properties = app_properties_from_args(args) config = galaxy.config.Configuration(**app_properties) model = galaxy.config.init_models_from_config(config) sa_session = model.context.current # We need the ID secret for configuring the security helper to decrypt # galaxysession cookies. if "id_secret" not in app_properties: log.warning( 'No ID_SECRET specified. Please set the "id_secret" in your galaxy.ini.' ) id_secret = app_properties.get('id_secret', 'dangerous_default') security_helper = IdEncodingHelper(id_secret=id_secret) # And get access to the models # Login manager to manage current_user functionality login_manager = flask_login.LoginManager() app = Flask(__name__) app.config['SECRET_KEY'] = id_secret login_manager.init_app(app) socketio = SocketIO(app) @login_manager.request_loader def findUserByCookie(request): cookie_value = request.cookies.get('galaxysession') if not cookie_value: return None
parser.add_argument('value', metavar='VALUE', type=str, default=None, help='value to encode or decode') populate_config_args(parser) args = parser.parse_args() app_properties = app_properties_from_args(args) # We need the ID secret for configuring the security helper to decrypt # galaxysession cookies. if "id_secret" not in app_properties: log.warning( 'No ID_SECRET specified. Please set the "id_secret" in your galaxy.yml.' ) id_secret = app_properties.get('id_secret', 'dangerous_default') security_helper = IdEncodingHelper(id_secret=id_secret) # And get access to the models # Login manager to manage current_user functionality if args.action == 'decode': sys.stdout.write(security_helper.decode_guid(args.value.lstrip('F'))) elif args.action == 'encode': sys.stdout.write(unicodify(security_helper.encode_guid(args.value))) else: sys.stdout.write("Unknown argument") sys.stdout.write('\n')