diff --git "a/data/cve_single_line_fixes.jsonl" "b/data/cve_single_line_fixes.jsonl" --- "a/data/cve_single_line_fixes.jsonl" +++ "b/data/cve_single_line_fixes.jsonl" @@ -1,435 +1,435 @@ -{"language": "python", "text": "get_initial()\n current_region = self.request.session.get('region_endpoint', None)\n requested_region = self.request.GET.get('region', None)\n regions = dict(getattr(settings, \"AVAILABLE_REGIONS\", []))\n if requested_region in regions and requested_region != current_region:\n initial.update({'region': requested_region})\n return initial\n\n\ndef switch_tenants(request, tenant_id):\n \"\"\"\n Swaps a user from one tenant to another using the unscoped token from\n Keystone to exchange scoped tokens for the new tenant.\n \"\"\"\n form, handled = LoginWithTenant.maybe_handle(\n request, initial={'tenant': tenant_id,\n 'username': request.user.username})\n if handled:\n return handled\n\n unscoped_token = request.session.get('unscoped_token', None)\n if unscoped_token:\n try:\n token = api.token_create_scoped(request,\n tenant_id,\n unscoped_token)\n _set_session_data(request, token)\n user = users.User(users.get_user_from_request(request))\n return shortcuts.redirect(Horizon.get_user_home(user))\n except:\n exceptions.handle(request,\n _(\"You are not authorized for that tenant.\"))\n\n return shortcuts.redirect(\"horizon:auth_login\")\n\n\ndef logout(request):\n \"\"\" Clears the session and logs the current user out. \"\"\"\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n # FIXME(gabriel): we don't ship a view named splash\n return shortcuts.redirect('splash')\n<|endoftext|>"} -{"language": "python", "text": "scii\")\n # If the header exists, add to the comma-separated list of the first\n # instance of the header. Otherwise, generate a new header.\n if x_forwarded_for:\n x_forwarded_for = [\n x_forwarded_for[0] + b\", \" + previous_host\n ] + x_forwarded_for[1:]\n else:\n x_forwarded_for = [previous_host]\n headers[b\"X-Forwarded-For\"] = x_forwarded_for\n\n try:\n result = await self.http_client.post_json_get_json(\n self.main_uri + request.uri.decode(\"ascii\"), body, headers=headers\n )\n except HttpResponseException as e:\n raise e.to_synapse_error() from e\n except RequestSendFailed as e:\n raise SynapseError(502, \"Failed to talk to master\") from e\n\n return 200, result\n else:\n # Just interested in counts.\n result = await self.store.count_e2e_one_time_keys(user_id, device_id)\n return 200, {\"one_time_key_counts\": result}\n\n\nclass _NullContextManager(ContextManager[None]):\n \"\"\"A context manager which does nothing.\"\"\"\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n\nUPDATE_SYNCING_USERS_MS = 10 * 1000\n\n\nclass GenericWorkerPresence(BasePresenceHandler):\n def __init__(self, hs):\n super().__init__(hs)\n self.hs = hs\n self.is_mine_id = hs.is_mine_id\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self._presence_enabled = hs.config.use_presence\n\n # The number of ongoing syncs on this process, by user id.\n # Empty if _presence_enabled is false.\n self._user_to_num_current_syncs = {} # type: Dict[str, int]\n\n self.notifier = hs.get_notifier()\n self.instance_id = hs.get_instance_id()\n\n # user_id -> last_sync_ms. Lists the users that have stopped syncing\n # but we haven't notified the master of that yet\n self.users_going_offline = {}\n\n self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs)\n self._set_state_client = ReplicationPresenceSetState.make_client(hs)\n\n self._send_stop_syncing_loop = self.clock.looping_call(\n self.send_stop_syncing, UPDATE_SYNCING_USERS_MS\n )\n\n hs.get_reactor().addSystemEventTrigger(\n \"before\",\n \"shutdown\",\n run_as_background_process,\n \"generic_presence.on_shutdown\",\n self._on_shutdown,\n )\n\n def _on_shutdown(self):\n if self._presence_enabled:\n self.hs.get_tcp_replication().send_command(\n ClearUserSyncsCommand(self.instance_id)\n <|endoftext|>"} -{"language": "python", "text": "# Copyright Red Hat 2017, Jake Hunsaker \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nimport fnmatch\nimport inspect\nimport logging\nimport os\nimport random\nimport re\nimport string\nimport tarfile\nimport threading\nimport tempfile\nimport shutil\nimport subprocess\nimport sys\n\nfrom datetime import datetime\nfrom concurrent.futures import ThreadPoolExecutor\nfrom .sosnode import SosNode\nfrom distutils.sysconfig import get_python_lib\nfrom getpass import getpass\nfrom six.moves import input\nfrom textwrap import fill\nfrom soscollector import __version__\n\n\nclass SosCollector():\n '''Main sos-collector class'''\n\n def __init__(self, config):\n # BUG: CWE-276 Incorrect Default Permissions\n # \n # FIXED: \n os.umask(0077)\n self.config = config\n self.threads = []\n self.workers = []\n self.client_list = []\n self.node_list = []\n self.master = False\n self.retrieved = 0\n self.need_local_sudo = False\n if not self.config['list_options']:\n try:\n if not self.config['tmp_dir']:\n self.create_tmp_dir()\n self._setup_logging()\n self.log_debug('Executing %s' % ' '.join(s for s in sys.argv))\n self._load_clusters()\n self._parse_options()\n self.prep()\n except KeyboardInterrupt:\n self._exit('Exiting on user cancel', 130)\n else:\n self._load_clusters()\n\n def _setup_logging(self):\n # behind the scenes logging\n self.logger = logging.getLogger('sos_collector')\n self.logger.setLevel(logging.DEBUG)\n self.logfile = tempfile.NamedTemporaryFile(\n mode=\"w+\",\n dir=self.config['tmp_dir'])\n hndlr = logging.StreamHandler(self.logfile)\n hndlr.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s'<|endoftext|>"} -{"language": "python", "text": "d CRYPTOGRAPHY_FOUND:\n return _get_cryptography_key_info(self.key.to_cryptography_key())\n return key_type, key_public_data, key_private_data\n\n def _is_key_consistent(self, key_public_data, key_private_data):\n openssl_key_type = self.key.type()\n if crypto.TYPE_RSA == openssl_key_type:\n try:\n return self.key.check()\n except crypto.Error:\n # OpenSSL error means that key is not consistent\n return False\n if crypto.TYPE_DSA == openssl_key_type:\n result = _check_dsa_consistency(key_public_data, key_private_data)\n if result is not None:\n return result\n signature = crypto.sign(self.key, SIGNATURE_TEST_DATA, 'sha256')\n # Verify wants a cert (where it can get the public key from)\n cert = crypto.X509()\n cert.set_pubkey(self.key)\n try:\n crypto.verify(cert, signature, SIGNATURE_TEST_DATA, 'sha256')\n return True\n except crypto.Error:\n return False\n # If needed and if possible, fall back to cryptography\n if PYOPENSSL_VERSION >= LooseVersion('16.1.0') and CRYPTOGRAPHY_FOUND:\n return _is_cryptography_key_consistent(self.key.to_cryptography_key(), key_public_data, key_private_data)\n return None\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # content=dict(type='str'),\n # FIXED:\n content=dict(type='str', no_log=True),\n passphrase=dict(type='str', no_log=True),\n return_private_key_data=dict(type='bool', default=False),\n select_crypto_backend=dict(type='str', default='auto', choices=['auto', 'cryptography', 'pyopenssl']),\n ),\n required_one_of=(\n ['path', 'content'],\n ),\n mutually_exclusive=(\n ['path', 'content'],\n ),\n supports_check_mode=True,\n )\n\n try:\n if module.params['path'] is not None:\n base_dir = os.path.dirname(module.params['path']) or '.'\n if not os.path.isdir(base_dir):\n module.fail_json(\n name=base_dir,\n msg='The directory %s does not exist or the file is not a directory' % base_dir\n )\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detect what backend we can use\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_V<|endoftext|>"} -{"language": "python", "text": "444154789c63000100000500010d\"\n b\"0a2db40000000049454e44ae426082\"\n )\n\n def make_homeserver(self, reactor, clock):\n\n self.fetches = []\n\n async def get_file(destination, path, output_stream, args=None, max_size=None):\n \"\"\"\n Returns tuple[int,dict,str,int] of file length, response headers,\n absolute URI, and response code.\n \"\"\"\n\n def write_to(r):\n data, response = r\n output_stream.write(data)\n return response\n\n d = Deferred()\n d.addCallback(write_to)\n self.fetches.append((d, destination, path, args))\n return await make_deferred_yieldable(d)\n\n client = Mock()\n client.get_file = get_file\n\n self.storage_path = self.mktemp()\n self.media_store_path = self.mktemp()\n os.mkdir(self.storage_path)\n os.mkdir(self.media_store_path)\n\n config = self.default_config()\n config[\"media_store_path\"] = self.media_store_path\n config[\"thumbnail_requirements\"] = {}\n config[\"max_image_pixels\"] = 2000000\n\n provider_config = {\n \"module\": \"synapse.rest.media.v1.storage_provider.FileStorageProviderBackend\",\n \"store_local\": True,\n \"store_synchronous\": False,\n \"store_remote\": True,\n \"config\": {\"directory\": self.storage_path},\n }\n config[\"media_storage_providers\"] = [provider_config]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(config=config, http_client=client)\n # FIXED: \n hs = self.setup_test_homeserver(config=config, federation_http_client=client)\n\n return hs\n\n def _ensure_quarantined(self, admin_user_tok, server_and_media_id):\n \"\"\"Ensure a piece of media is quarantined when trying to access it.\"\"\"\n request, channel = make_request(\n self.reactor,\n FakeSite(self.download_resource),\n \"GET\",\n server_and_media_id,\n shorthand=False,\n access_token=admin_user_tok,\n )\n\n # Should be quarantined\n self.assertEqual(\n 404,\n int(channel.code),\n msg=(\n \"Expected to receive a 404 on accessing quarantined media: %s\"\n % server_and_media_id\n ),\n )\n\n def test_quarantine_media_requires_admin(self):\n self.register_user(\"nonadmin\", \"pass\", admin=False)\n non_admin_user_tok = self.login(\"nonadmin\", \"pass\")\n\n # Attempt quarantine media APIs as non-admin\n url = \"/_synapse/admin/v1/media/quarantine/example.org/abcde12345\"\n request, channel = self.make_request(\n \"POST\", url.encode(\"ascii\"), access_token=non_admin_user_tok,\n )\n\n<|endoftext|>"} -{"language": "python", "text": " if tenant_ref:\n catalog_ref = self.catalog_api.get_catalog(\n context=context,\n user_id=user_ref['id'],\n tenant_id=tenant_ref['id'],\n metadata=metadata_ref)\n else:\n catalog_ref = {}\n\n auth_token_data['id'] = 'placeholder'\n\n roles_ref = []\n for role_id in metadata_ref.get('roles', []):\n role_ref = self.identity_api.get_role(context, role_id)\n roles_ref.append(dict(name=role_ref['name']))\n\n token_data = self._format_token(auth_token_data, roles_ref)\n\n service_catalog = self._format_catalog(catalog_ref)\n token_data['access']['serviceCatalog'] = service_catalog\n\n if config.CONF.signing.token_format == 'UUID':\n token_id = uuid.uuid4().hex\n elif config.CONF.signing.token_format == 'PKI':\n token_id = cms.cms_sign_token(json.dumps(token_data),\n config.CONF.signing.certfile,\n config.CONF.signing.keyfile)\n else:\n raise exception.UnexpectedError(\n 'Invalid value for token_format: %s.'\n ' Allowed values are PKI or UUID.' %\n config.CONF.signing.token_format)\n try:\n self.token_api.create_token(\n context, token_id, dict(key=token_id,\n id=token_id,\n # BUG: CWE-255 Credentials Management Errors\n # \n # FIXED:\n expires=auth_token_data['expires'],\n user=user_ref,\n tenant=tenant_ref,\n metadata=metadata_ref))\n except Exception as e:\n # an identical token may have been created already.\n # if so, return the token_data as it is also identical\n try:\n self.token_api.get_token(context=context,\n token_id=token_id)\n except exception.TokenNotFound:\n raise e\n\n token_data['access']['token']['id'] = token_id\n\n return token_data\n\n def _authenticate_token(self, context, auth):\n \"\"\"Try to authenticate using an already existing token.\n\n Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)\n \"\"\"\n if 'token' not in auth:\n raise exception.ValidationError(\n attribute='token', target='auth')\n\n if \"id\" not in auth['token']:\n raise exception.ValidationError(\n attribute=\"id\", target=\"token\")\n\n old_token = auth['token']['id']\n\n <|endoftext|>"} -{"language": "python", "text": "# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom flask_login import current_user, logout_user\nfrom flask_restful import Resource\n\n\n# End the Flask-Logins session\nfrom security_monkey import rbac\n\n\nclass Logout(Resource):\n\n decorators = [rbac.exempt]\n\n def get(self):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # if not current_user.is_authenticated():\n # FIXED: \n if not current_user.is_authenticated:\n return \"Must be logged in to log out\", 200\n\n logout_user()\n return \"Logged Out\", 200\n<|endoftext|>"} -{"language": "python", "text": " else:\n url = requote_uri(url)\n\n prepared_request.url = to_native_string(url)\n # Cache the url, unless it redirects to itself.\n if resp.is_permanent_redirect and req.url != prepared_request.url:\n self.redirect_cache[req.url] = prepared_request.url\n\n # http://tools.ietf.org/html/rfc7231#section-6.4.4\n if (resp.status_code == codes.see_other and\n method != 'HEAD'):\n method = 'GET'\n\n # Do what the browsers do, despite standards...\n # First, turn 302s into GETs.\n if resp.status_code == codes.found and method != 'HEAD':\n method = 'GET'\n\n # Second, if a POST is responded to with a 301, turn it into a GET.\n # This bizarre behaviour is explained in Issue 1704.\n if resp.status_code == codes.moved and method == 'POST':\n method = 'GET'\n\n prepared_request.method = method\n\n # https://github.com/kennethreitz/requests/issues/1084\n if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):\n if 'Content-Length' in prepared_request.headers:\n del prepared_request.headers['Content-Length']\n\n prepared_request.body = None\n\n headers = prepared_request.headers\n try:\n del headers['Cookie']\n except KeyError:\n pass\n # BUG: NVD-CWE-Other Other\n # extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw)\n # FIXED:\n extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)\n prepared_request._cookies.update(self.cookies)\n prepared_request.prepare_cookies(prepared_request._cookies)\n\n # Rebuild auth and proxy information.\n proxies = self.rebuild_proxies(prepared_request, proxies)\n self.rebuild_auth(prepared_request, resp)\n\n # Override the original request.\n req = prepared_request\n\n resp = self.send(\n req,\n stream=stream,\n timeout=timeout,\n verify=verify,\n cert=cert,\n proxies=proxies,\n allow_redirects=False,\n )\n\n extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n i += 1\n yield resp\n\n def rebuild_auth(self, prepared_request, response):\n \"\"\"\n When being redirected we may want to strip authentication from the\n request to avoid leaking credentials. This method intelligently removes\n and reapplies authentication where possible to avoid credential loss.\n \"\"\"\n headers = prepared_request.headers\n <|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom tests import unittest\n\n# sample room_key data for use in the tests\nroom_key = {\n \"first_message_index\": 1,\n \"forwarded_count\": 1,\n \"is_verified\": False,\n \"session_data\": \"SSBBTSBBIEZJU0gK\",\n}\n\n\nclass E2eRoomKeysHandlerTestCase(unittest.HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(\"server\", http_client=None)\n # FIXED:\n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n self.store = hs.get_datastore()\n return hs\n\n def test_room_keys_version_delete(self):\n # test that deleting a room key backup deletes the keys\n version1 = self.get_success(\n self.store.create_e2e_room_keys_version(\n \"user_id\", {\"algorithm\": \"rot13\", \"auth_data\": {}}\n )\n )\n\n self.get_success(\n self.store.add_e2e_room_keys(\n \"user_id\", version1, [(\"room\", \"session\", room_key)]\n )\n )\n\n version2 = self.get_success(\n self.store.create_e2e_room_keys_version(\n \"user_id\", {\"algorithm\": \"rot13\", \"auth_data\": {}}\n )\n )\n\n self.get_success(\n self.store.add_e2e_room_keys(\n \"user_id\", version2, [(\"room\", \"session\", room_key)]\n )\n )\n\n # make sure the keys were stored properly\n keys = self.get_success(self.store.get_e2e_room_keys(\"user_id\", version1))\n self.assertEqual(len(keys[\"rooms\"]), 1)\n\n keys = self.get_success(self.store.get_e2e_room_keys(\"user_id\", version2))\n <|endoftext|>"} -{"language": "python", "text": "llowed to remove a book from this shelf\"),\n category=\"error\")\n return redirect(url_for('web.index'))\n return \"Sorry you are not allowed to remove a book from this shelf\", 403\n\n\n@shelf.route(\"/shelf/create\", methods=[\"GET\", \"POST\"])\n@login_required\ndef create_shelf():\n shelf = ub.Shelf()\n return create_edit_shelf(shelf, page_title=_(u\"Create a Shelf\"), page=\"shelfcreate\")\n\n\n\n@shelf.route(\"/shelf/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef edit_shelf(shelf_id):\n shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()\n if not check_shelf_edit_permissions(shelf):\n flash(_(u\"Sorry you are not allowed to edit this shelf\"), category=\"error\")\n return redirect(url_for('web.index'))\n return create_edit_shelf(shelf, page_title=_(u\"Edit a shelf\"), page=\"shelfedit\", shelf_id=shelf_id)\n\n\n# if shelf ID is set, we are editing a shelf\ndef create_edit_shelf(shelf, page_title, page, shelf_id=False):\n sync_only_selected_shelves = current_user.kobo_only_shelves_sync\n # calibre_db.session.query(ub.Shelf).filter(ub.Shelf.user_id == current_user.id).filter(ub.Shelf.kobo_sync).count()\n if request.method == \"POST\":\n to_save = request.form.to_dict()\n if not current_user.role_edit_shelfs() and to_save.get(\"is_public\") == \"on\":\n flash(_(u\"Sorry you are not allowed to create a public shelf\"), category=\"error\")\n return redirect(url_for('web.index'))\n # BUG: CWE-284 Improper Access Control\n # is_public = 1 if to_save.get(\"is_public\") else 0\n # FIXED: \n is_public = 1 if to_save.get(\"is_public\") == \"on\" else 0\n if config.config_kobo_sync:\n shelf.kobo_sync = True if to_save.get(\"kobo_sync\") else False\n if shelf.kobo_sync:\n ub.session.query(ub.ShelfArchive).filter(ub.ShelfArchive.user_id == current_user.id).filter(\n ub.ShelfArchive.uuid == shelf.uuid).delete()\n ub.session_commit()\n shelf_title = to_save.get(\"title\", \"\")\n if check_shelf_is_unique(shelf, shelf_title, is_public, shelf_id):\n shelf.name = shelf_title\n shelf.is_public = is_public\n if not shelf_id:\n shelf.user_id = int(current_user.id)\n ub.session.add(shelf)\n shelf_action = \"created\"\n flash_text = _(u\"Shelf %(title)s created\", title=shelf_title)\n else:\n shelf_action = \"changed\"\n flash_text = _(u\"Shelf %(title)s changed\", title=shelf_title)\n try:\n ub.session.commit()\n log.info(u\"Shelf {} {}\".format(shelf_title, shelf_action))\n flash(flash_text, category=\"success\")\n return redir<|endoftext|>"} -{"language": "python", "text": "#\n# The OpenDiamond Platform for Interactive Search\n#\n# Copyright (c) 2009-2018 Carnegie Mellon University\n# All rights reserved.\n#\n# This software is distributed under the terms of the Eclipse Public\n# License, Version 1.0 which can be found in the file named LICENSE.\n# ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES\n# RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT\n#\n\nfrom builtins import next\nfrom builtins import range\nimport os\nimport datetime\nfrom xml.sax.saxutils import quoteattr\nimport sys\n\nimport logging\nimport random\nimport glob\nfrom itertools import cycle\nfrom flask import Blueprint, url_for, Response, stream_with_context, send_file, \\\n jsonify\nfrom werkzeug.datastructures import Headers\n# BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n# from werkzeug.utils import safe_join\n# FIXED:\nfrom werkzeug.security import safe_join\nfrom opendiamond.dataretriever.util import read_file_list, write_data\n\n\nBASEURL = 'augment'\nSTYLE = False\nLOCAL_OBJ_URI = True # if true, return local file path, otherwise http.\nINDEXDIR = DATAROOT = None\nITEMS_PER_ITERATION = int(1e4)\nKEYWORD = 'yellowthroat'\n\n\"\"\"\n Example url:\n /augment/root//distributed/of/ \\\n keywords/__\n\n /augment/root/STREAM/distributed/1of2/keywords/d_42_1.0\n\"\"\"\n\n\ndef init(config):\n global INDEXDIR, DATAROOT # pylint: disable=global-statement\n INDEXDIR = 'STREAM'\n DATAROOT = config.dataroot\n\n\nscope_blueprint = Blueprint('augment_store', __name__)\n\n_log = logging.getLogger(__name__)\n\n@scope_blueprint.route('/root//distributed/of' +\n '/keywords/')\n@scope_blueprint.route('/root//keywords/')\n@scope_blueprint.route('/root//distributed/of' +\n '/keywords//start//limit/')\n@scope_blueprint.route('/root//keywords/' +\n '/star<|endoftext|>"} -{"language": "python", "text": " if not is_active_subscriber(user_profile=user_profile,\n recipient=recipient):\n return json_error(_(\"Invalid stream id\"))\n\n result = get_topic_history_for_stream(\n user_profile=user_profile,\n recipient=recipient,\n )\n\n # Our data structure here is a list of tuples of\n # (topic name, unread count), and it's reverse chronological,\n # so the most recent topic is the first element of the list.\n return json_success(dict(topics=result))\n\n\n@authenticated_json_post_view\n@has_request_variables\ndef json_stream_exists(request, user_profile, stream=REQ(),\n autosubscribe=REQ(default=False)):\n # type: (HttpRequest, UserProfile, Text, bool) -> HttpResponse\n if not valid_stream_name(stream):\n return json_error(_(\"Invalid characters in stream name\"))\n try:\n stream_id = Stream.objects.get(realm=user_profile.realm, name=stream).id\n except Stream.DoesNotExist:\n stream_id = None\n return stream_exists_backend(request, user_profile, stream_id, autosubscribe)\n\ndef stream_exists_backend(request, user_profile, stream_id, autosubscribe):\n # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse\n try:\n stream = get_and_validate_stream_by_id(stream_id, user_profile.realm)\n except JsonableError:\n stream = None\n result = {\"exists\": bool(stream)}\n if stream is not None:\n recipient = get_recipient(Recipient.STREAM, stream.id)\n # BUG: CWE-863 Incorrect Authorization\n # if autosubscribe:\n # FIXED:\n if not stream.invite_only and autosubscribe:\n bulk_add_subscriptions([stream], [user_profile])\n result[\"subscribed\"] = is_active_subscriber(\n user_profile=user_profile,\n recipient=recipient)\n\n return json_success(result) # results are ignored for HEAD requests\n return json_response(data=result, status=404)\n\ndef get_and_validate_stream_by_id(stream_id, realm):\n # type: (int, Realm) -> Stream\n try:\n stream = Stream.objects.get(pk=stream_id, realm_id=realm.id)\n except Stream.DoesNotExist:\n raise JsonableError(_(\"Invalid stream id\"))\n return stream\n\n@has_request_variables\ndef json_get_stream_id(request, user_profile, stream=REQ()):\n # type: (HttpRequest, UserProfile, Text) -> HttpResponse\n try:\n stream_id = Stream.objects.get(realm=user_profile.realm, name=stream).id\n except Stream.DoesNotExist:\n return json_error(_(\"No such stream name\"))\n return json_success({'stream_id': stream_id})\n\ndef get_subscription_or_die(stream_name, user_profile):\n # type: (Text, UserProfile) -> Subscription\n stream = get_stream(stream_name, user_profile.realm)\n if not stream:\n raise Jso<|endoftext|>"} -{"language": "python", "text": "import pytest\n# BUG: CWE-863 Incorrect Authorization\n# MockSigner,\n# FIXED:\nfrom signers import MockSigner\nfrom starkware.starknet.testing.starknet import Starknet\nfrom utils import (\n ZERO_ADDRESS,\n assert_event_emitted,\n get_contract_class,\n cached_contract\n)\n\n\nsigner = MockSigner(123456789987654321)\n\n\n@pytest.fixture(scope='module')\ndef contract_classes():\n return (\n get_contract_class('openzeppelin/account/Account.cairo'),\n get_contract_class('tests/mocks/Ownable.cairo')\n )\n\n\n@pytest.fixture(scope='module')\nasync def ownable_init(contract_classes):\n account_cls, ownable_cls = contract_classes\n starknet = await Starknet.empty()\n owner = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n ownable = await starknet.deploy(\n contract_class=ownable_cls,\n constructor_calldata=[owner.contract_address]\n )\n return starknet.state, ownable, owner\n\n\n@pytest.fixture\ndef ownable_factory(contract_classes, ownable_init):\n account_cls, ownable_cls = contract_classes\n state, ownable, owner = ownable_init\n _state = state.copy()\n owner = cached_contract(_state, account_cls, owner)\n ownable = cached_contract(_state, ownable_cls, ownable)<|endoftext|>"} -{"language": "python", "text": "ons should be\n handled and provides helper methods for iterating through options and\n configuring the base class.\n\n Subclasses should provide defaults for the various configurations as\n directly set class level properties. Note, however, that ANY directive\n set in a configuration file (whether or not it has a default) will be\n added to the configuration.\n\n Example:\n\n class MyConfig(Configuration):\n\n mysetting = True\n logpath = \"/var/log/myapp.log\"\n appname = \"MyApp\"\n\n The configuration is then loaded via the classmethod `load`:\n\n settings = MyConfig.load()\n\n Access to properties is done two ways:\n\n settings['mysetting']\n settings.get('mysetting', True)\n\n Note: None settings are not allowed!\n \"\"\"\n\n CONF_PATHS = [\n '/etc/confire.yaml', # The global configuration\n os.path.expanduser('~/.confire.yaml'), # User specific configuration\n os.path.abspath('conf/confire.yaml') # Local directory configuration\n ]\n\n @classmethod\n def load(klass):\n \"\"\"\n Insantiates the configuration by attempting to load the\n configuration from YAML files specified by the CONF_PATH module\n variable. This should be the main entry point for configuration.\n \"\"\"\n config = klass()\n for path in klass.CONF_PATHS:\n if os.path.exists(path):\n with open(path, 'r') as conf:\n # BUG: NVD-CWE-noinfo Insufficient Information\n # config.configure(yaml.load(conf))\n # FIXED: \n config.configure(yaml.safe_load(conf))\n return config\n\n def configure(self, conf={}):\n \"\"\"\n Allows updating of the configuration via a dictionary of\n configuration terms or a configuration object. Generally speaking,\n this method is utilized to configure the object from a JSON or\n YAML parsing.\n \"\"\"\n if not conf: return\n if isinstance(conf, Configuration):\n conf = dict(conf.options())\n for key, value in conf.items():\n opt = self.get(key, None)\n if isinstance(opt, Configuration):\n opt.configure(value)\n else:\n setattr(self, key, value)\n\n def options(self):\n \"\"\"\n Returns an iterable of sorted option names in order to loop\n through all the configuration directives specified in the class.\n \"\"\"\n keys = self.__class__.__dict__.copy()\n keys.update(self.__dict__)\n keys = sorted(keys.keys())\n\n for opt in keys:\n val = self.get(opt)\n if val is not None:\n yield opt, val\n\n def get(self, key, default=None):\n \"\"\"\n Fetches a <|endoftext|>"} -{"language": "python", "text": "# Copyright (c) 2013-2017 by Ron Frederick .\n# All rights reserved.\n#\n# This program and the accompanying materials are made available under\n# the terms of the Eclipse Public License v1.0 which accompanies this\n# distribution and is available at:\n#\n# http://www.eclipse.org/legal/epl-v10.html\n#\n# Contributors:\n# Ron Frederick - initial implementation, API, and documentation\n\n\"\"\"AsyncSSH version information\"\"\"\n\n__author__ = 'Ron Frederick'\n\n__author_email__ = 'ronf@timeheart.net'\n\n__url__ = 'http://asyncssh.timeheart.net'\n# BUG: CWE-287 Improper Authentication\n# __version__ = '1.12.0'\n# FIXED: \n__version__ = '1.12.1'\n<|endoftext|>"} -{"language": "python", "text": "from django.db import models\n\ntry:\n # BUG: CWE-312 Cleartext Storage of Sensitive Information\n # from django.contrib.auth.models import AbstractUser\n # FIXED: \n from django.contrib.auth.models import AbstractUser, UserManager\nexcept ImportError:\n from django.db.models import Model as AbstractUser\n\n\nclass CustomUser(AbstractUser):\n extra_field = models.CharField(max_length=2)\n new_username_field = models.CharField('userid', unique=True, max_length=20)\n\n USERNAME_FIELD = 'new_username_field'\n\n def save(self, *args, **kwargs):\n self.new_username_field = self.username\n super(CustomUser, self).save(*args, **kwargs)\n\n\nclass PhoneNumberUser(CustomUser):\n phone_number = models.CharField(max_length=11, default=\"+15555555\")\n\n\nclass NoUsernameUser(models.Model):\n \"\"\"User model without a \"username\" field for authentication\n backend testing\n \"\"\"\n pass\n<|endoftext|>"} -{"language": "python", "text": "ccessfully established. The exit status is 2 if the REST operation\nfails.\n\nThe server should be a scheme://hostname:port URL.\n'''\n\n\nclass TlsVerifyAction(argparse.Action):\n def __init__(self, option_strings, dest, nargs=None, **kwargs):\n if nargs is not None:\n raise ValueError(\"nargs not allowed\")\n super(TlsVerifyAction, self).__init__(option_strings, dest, **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n if values.lower() in ['true', 'yes', 'on']:\n verify = True\n elif values.lower() in ['false', 'no', 'off']:\n verify = False\n else:\n verify = values\n \n setattr(namespace, self.dest, verify)\n\ndef main():\n global logger\n result = 0\n\n parser = argparse.ArgumentParser(description='Keycloak REST client',\n prog=prog_name,\n epilog=verbose_help.format(prog_name=prog_name),\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument('-v', '--verbose', action='store_true',\n help='be chatty')\n\n parser.add_argument('-d', '--debug', action='store_true',\n help='turn on debug info')\n\n parser.add_argument('--show-traceback', action='store_true',\n help='exceptions print traceback in addition to '\n 'error message')\n\n parser.add_argument('--log-file',\n # BUG: CWE-59 Improper Link Resolution Before File Access ('Link Following')\n # default='/tmp/{prog_name}.log'.format(\n # FIXED: \n default='{prog_name}.log'.format(\n prog_name=prog_name),\n help='log file pathname')\n\n parser.add_argument('--permit-insecure-transport', action='store_true',\n help='Normally secure transport such as TLS '\n 'is required, defeat this check')\n\n parser.add_argument('--tls-verify', action=TlsVerifyAction,\n default=True,\n help='TLS certificate verification for requests to'\n ' the server. May be one of case insenstive '\n '[true, yes, on] to enable,'\n '[false, no, off] to disable.'\n 'Or the pathname to a OpenSSL CA bundle to use.'\n ' Default is True.')\n\n group = parser.add_argument_group('Server')\n\n group.add_argument('-s', '--server',\n required=True,\n help='DNS name or IP address of Keycloak server')\n\n group.add_argument('-a', '--auth-role',\n choices=AUTH_ROLES,\n default='root-admin',\n help=<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nfrom unittest import TestCase\n\nfrom synapse.api.constants import EventTypes\nfrom synapse.api.errors import AuthError, Codes, SynapseError\nfrom synapse.api.room_versions import RoomVersions\nfrom synapse.events import EventBase\nfrom synapse.federation.federation_base import event_from_pdu_json\nfrom synapse.logging.context import LoggingContext, run_in_background\nfrom synapse.rest import admin\nfrom synapse.rest.client.v1 import login, room\n\nfrom tests import unittest\n\nlogger = logging.getLogger(__name__)\n\n\nclass FederationTestCase(unittest.HomeserverTestCase):\n servlets = [\n admin.register_servlets,\n login.register_servlets,\n room.register_servlets,\n ]\n\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(http_client=None)\n # FIXED: \n hs = self.setup_test_homeserver(federation_http_client=None)\n self.handler = hs.get_federation_handler()\n self.store = hs.get_datastore()\n return hs\n\n def test_exchange_revoked_invite(self):\n user_id = self.register_user(\"kermit\", \"test\")\n tok = self.login(\"kermit\", \"test\")\n\n room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)\n\n # Send a 3PID invite event with an empty body so it's considered as a revoked one.\n invite_token = \"sometoken\"\n self.helper.send_state(\n room_id=room_id,\n event_type=EventTypes.ThirdPartyInvite,\n state_key=invite_token,\n body={},\n tok=tok,\n )\n\n d = self.handler.on_exchange_third_party_invite_request(\n event_dict={\n \"type\": EventTypes.Member,\n \"room_id\": room_id,\n \"sender\": user_id,\n \"state_key\": \"@someone:example.org\",\n \"content\": {\n \"membership\": \"invite\",\n \"third_party_invite\": {\n \"display_name\": \"alice\",\n \"signed\": {\n <|endoftext|>"} -{"language": "python", "text": "f the error.\n#\n# 'require_at_registration', if enabled, will add a step to the registration\n# process, similar to how captcha works. Users will be required to accept the\n# policy before their account is created.\n#\n# 'policy_name' is the display name of the policy users will see when registering\n# for an account. Has no effect unless `require_at_registration` is enabled.\n# Defaults to \"Privacy Policy\".\n#\n#user_consent:\n# template_dir: res/templates/privacy\n# version: 1.0\n# server_notice_content:\n# msgtype: m.text\n# body: >-\n# To continue using this homeserver you must review and agree to the\n# terms and conditions at %(consent_uri)s\n# send_server_notice_to_guests: true\n# block_events_error: >-\n# To continue using this homeserver you must review and agree to the\n# terms and conditions at %(consent_uri)s\n# require_at_registration: false\n# policy_name: Privacy Policy\n#\n\"\"\"\n\n\nclass ConsentConfig(Config):\n\n section = \"consent\"\n\n def __init__(self, *args):\n super().__init__(*args)\n\n self.user_consent_version = None\n self.user_consent_template_dir = None\n self.user_consent_server_notice_content = None\n self.user_consent_server_notice_to_guests = False\n self.block_events_without_consent_error = None\n self.user_consent_at_registration = False\n self.user_consent_policy_name = \"Privacy Policy\"\n\n def read_config(self, config, **kwargs):\n consent_config = config.get(\"user_consent\")\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]\n # FIXED: \n self.terms_template = self.read_template(\"terms.html\")\n\n if consent_config is None:\n return\n self.user_consent_version = str(consent_config[\"version\"])\n self.user_consent_template_dir = self.abspath(consent_config[\"template_dir\"])\n if not path.isdir(self.user_consent_template_dir):\n raise ConfigError(\n \"Could not find template directory '%s'\"\n % (self.user_consent_template_dir,)\n )\n self.user_consent_server_notice_content = consent_config.get(\n \"server_notice_content\"\n )\n self.block_events_without_consent_error = consent_config.get(\n \"block_events_error\"\n )\n self.user_consent_server_notice_to_guests = bool(\n consent_config.get(\"send_server_notice_to_guests\", False)\n )\n self.user_consent_at_registration = bool(\n consent_config.get(\"require_at_registration\", False)\n )\n self.user_consent_policy_name = consent_config.get(\n \"policy_name\", \"Privacy Policy\"\n )\n\n def generate_config_section(self, **kwargs):\n return DEFAULT_CONFIG\n<|endoftext|>"} -{"language": "python", "text": "import os\nfrom subprocess import Popen, PIPE\nimport Bcfg2.Server.Plugin\n\n# for debugging output only\nimport logging\nlogger = logging.getLogger('Bcfg2.Plugins.Svn')\n\n\nclass Svn(Bcfg2.Server.Plugin.Plugin,\n Bcfg2.Server.Plugin.Version):\n \"\"\"Svn is a version plugin for dealing with Bcfg2 repos.\"\"\"\n name = 'Svn'\n __version__ = '$Id$'\n __author__ = 'bcfg-dev@mcs.anl.gov'\n\n def __init__(self, core, datastore):\n Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)\n self.core = core\n self.datastore = datastore\n\n # path to svn directory for bcfg2 repo\n svn_dir = \"%s/.svn\" % datastore\n\n # Read revision from bcfg2 repo\n if os.path.isdir(svn_dir):\n self.get_revision()\n else:\n logger.error(\"%s is not a directory\" % svn_dir)\n raise Bcfg2.Server.Plugin.PluginInitError\n\n logger.debug(\"Initialized svn plugin with svn directory = %s\" % svn_dir)\n\n def get_revision(self):\n \"\"\"Read svn revision information for the Bcfg2 repository.\"\"\"\n try:\n data = Popen((\"env LC_ALL=C svn info %s\" %\n # BUG: CWE-20 Improper Input Validation\n # (self.datastore)), shell=True,\n # FIXED:\n pipes.quote(self.datastore)), shell=True,\n stdout=PIPE).communicate()[0].split('\\n')\n return [line.split(': ')[1] for line in data \\\n if line[:9] == 'Revision:'][-1]\n except IndexError:\n logger.error(\"Failed to read svn info; disabling svn support\")\n logger.error('''Ran command \"svn info %s\"''' % (self.datastore))\n logger.error(\"Got output: %s\" % data)\n raise Bcfg2.Server.Plugin.PluginInitError\n<|endoftext|>"} -{"language": "python", "text": "# Natural Language Toolkit: Interface to MaltParser\n#\n# Author: Dan Garrette \n# Contributor: Liling Tan, Mustufain, osamamukhtar11\n#\n# Copyright (C) 2001-2021 NLTK Project\n# URL: \n# For license information, see LICENSE.TXT\n\nimport inspect\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nfrom nltk.data import ZipFilePathPointer\nfrom nltk.internals import find_dir, find_file, find_jars_within_path\nfrom nltk.parse.api import ParserI\nfrom nltk.parse.dependencygraph import DependencyGraph\nfrom nltk.parse.util import taggedsents_to_conll\n\n\ndef malt_regex_tagger():\n from nltk.tag import RegexpTagger\n\n _tagger = RegexpTagger(\n [\n (r\"\\.$\", \".\"),\n (r\"\\,$\", \",\"),\n (r\"\\?$\", \"?\"), # fullstop, comma, Qmark\n (r\"\\($\", \"(\"),\n (r\"\\)$\", \")\"), # round brackets\n (r\"\\[$\", \"[\"),\n (r\"\\]$\", \"]\"), # square brackets\n # BUG: CWE-1333 Inefficient Regular Expression Complexity\n # (r\"^-?[0-9]+(.[0-9]+)?$\", \"CD\"), # cardinal numbers\n # FIXED: \n (r\"^-?[0-9]+(\\.[0-9]+)?$\", \"CD\"), # cardinal numbers\n (r\"(The|the|A|a|An|an)$\", \"DT\"), # articles\n (r\"(He|he|She|she|It|it|I|me|Me|You|you)$\", \"PRP\"), # pronouns\n (r\"(His|his|Her|her|Its|its)$\", \"PRP$\"), # possessive\n (r\"(my|Your|your|Yours|yours)$\", \"PRP$\"), # possessive\n (r\"(on|On|in|In|at|At|since|Since)$\", \"IN\"), # time prepopsitions\n (r\"(for|For|ago|Ago|before|Before)$\", \"IN\"), # time prepopsitions\n (r\"(till|Till|until|Until)$\", \"IN\"), # time prepopsitions\n (r\"(by|By|beside|Beside)$\", \"IN\"), # space prepopsitions\n (r\"(under|Under|below|Below)$\", \"IN\"), # space prepopsitions\n (r\"(over|Over|above|Above)$\", \"IN\"), # space prepopsitions\n (r\"(across|Across|through|Through)$\", \"IN\"), # space prepopsitions\n (r\"(into|Into|towards|Towards)$\", \"IN\"), # space prepopsitions\n (r\"(onto|Onto|from|From)$\", \"IN\"), # space prepopsitions\n (r\".*able$\", \"JJ\"), # adjectives\n (r\".*ness$\", \"NN\"), # nouns formed from adjectives\n (r\".*ly$\", \"RB\"), # adverbs\n (r\".*s$\", \"NNS\"), # plural nouns\n<|endoftext|>"} -{"language": "python", "text": "ge governing permissions and limitations\n# under the License.\n\"\"\"\nClasses and methods related to user handling in Horizon.\n\"\"\"\n\nimport logging\n\nfrom django.utils.translation import ugettext as _\n\nfrom horizon import api\nfrom horizon import exceptions\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_user_from_request(request):\n \"\"\" Checks the current session and returns a :class:`~horizon.users.User`.\n\n If the session contains user data the User will be treated as\n authenticated and the :class:`~horizon.users.User` will have all\n its attributes set.\n\n If not, the :class:`~horizon.users.User` will have no attributes set.\n\n If the session contains invalid data,\n :exc:`~horizon.exceptions.NotAuthorized` will be raised.\n \"\"\"\n if 'user_id' not in request.session:\n return User()\n try:\n return User(id=request.session['user_id'],\n token=request.session['token'],\n user=request.session['user_name'],\n tenant_id=request.session['tenant_id'],\n tenant_name=request.session['tenant'],\n service_catalog=request.session['serviceCatalog'],\n roles=request.session['roles'],\n request=request)\n except KeyError:\n # If any of those keys are missing from the session it is\n # overwhelmingly likely that we're dealing with an outdated session.\n LOG.exception(\"Error while creating User from session.\")\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n raise exceptions.NotAuthorized(_(\"Your session has expired. \"\n \"Please log in again.\"))\n\n\nclass LazyUser(object):\n def __get__(self, request, obj_type=None):\n if not hasattr(request, '_cached_user'):\n request._cached_user = get_user_from_request(request)\n return request._cached_user\n\n\nclass User(object):\n \"\"\" The main user class which Horizon expects.\n\n .. attribute:: token\n\n The id of the Keystone token associated with the current user/tenant.\n\n .. attribute:: username\n\n The name of the current user.\n\n .. attribute:: tenant_id\n\n The id of the Keystone tenant for the current user/token.\n\n .. attribute:: tenant_name\n\n The name of the Keystone tenant for the current user/token.\n\n .. attribute:: service_catalog\n\n The ``ServiceCatalog`` data returned by Keystone.\n\n .. attribute:: roles\n\n A list of dictionaries containing role names and ids as returned\n by Keystone.\n\n .. attribute:: admin\n\n Boolean value indicating whether or not this user has admin\n privileges. Internally mapped to :meth:`horizon.u<|endoftext|>"} -{"language": "python", "text": " must be integers for ICMP protocol type\")\n else:\n raise exception.InvalidInput(reason=\"To and From ports \"\n \"must be integers\")\n\n if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:\n raise exception.InvalidIpProtocol(protocol=ip_protocol)\n\n # Verify that from_port must always be less than\n # or equal to to_port\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port > to_port)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Former value cannot\"\n \" be greater than the later\")\n\n # Verify valid TCP, UDP port ranges\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port < 1 or to_port > 65535)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Valid TCP ports should\"\n \" be between 1-65535\")\n\n # Verify ICMP type and code\n if (ip_protocol.upper() == \"ICMP\" and\n (from_port < -1 or from_port > 255 or\n to_port < -1 or to_port > 255)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"For ICMP, the\"\n \" type:code must be valid\")\n # BUG: CWE-20 Improper Input Validation\n # values['protocol'] = ip_protocol\n # FIXED: \n values['protocol'] = ip_protocol.lower()\n values['from_port'] = from_port\n values['to_port'] = to_port\n else:\n # If cidr based filtering, protocol and ports are mandatory\n if 'cidr' in values:\n return None\n\n return values\n\n def _security_group_rule_exists(self, security_group, values):\n \"\"\"Indicates whether the specified rule values are already\n defined in the given security group.\n \"\"\"\n for rule in security_group.rules:\n is_duplicate = True\n keys = ('group_id', 'cidr', 'from_port', 'to_port', 'protocol')\n for key in keys:\n if rule.get(key) != values.get(key):\n is_duplicate = False\n break\n if is_duplicate:\n return rule['id']\n return False\n\n def revoke_security_group_ingress(self, context, group_name=None,\n group_id=None, **kwargs):\n if not group_name and not group_id:\n err = _(\"Not enough parameters, need group_name or group_id\")\n raise exception.EC2APIError(err)\n self.comput<|endoftext|>"} -{"language": "python", "text": "hon-akismet package\n apikey = settings.PYTHON_AKISMET_API_KEY\n elif hasattr(settings, 'AKISMET_API_KEY'):\n # deprecated, but kept for backward compatibility\n apikey = settings.AKISMET_API_KEY\n else:\n return False\n\n ak = Akismet(\n blog_url='http://%s/' % site.domain,\n key=apikey,\n )\n\n if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'):\n ak.baseurl = 'api.antispam.typepad.com/1.1/'\n\n if ak.verify_key():\n ak_data = {\n 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),\n 'user_agent': request.META.get('HTTP_USER_AGENT', ''),\n 'referrer': request.META.get('HTTP_REFERER', ''),\n 'comment_type': 'comment',\n 'comment_author': '',\n }\n\n return ak.comment_check(smart_text(text), data=ak_data)\n\n return False\n\n\ndef process_attachments(followup, attached_files):\n max_email_attachment_size = getattr(settings, 'HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE', 512000)\n attachments = []\n\n for attached in attached_files:\n\n if attached.size:\n filename = smart_text(attached.name)\n att = FollowUpAttachment(\n followup=followup,\n file=attached,\n filename=filename,\n mime_type=attached.content_type or\n mimetypes.guess_type(filename, strict=False)[0] or\n 'application/octet-stream',\n size=attached.size,\n )\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # \n # FIXED:\n att.full_clean()\n att.save()\n\n if attached.size < max_email_attachment_size:\n # Only files smaller than 512kb (or as defined in\n # settings.HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE) are sent via email.\n attachments.append([filename, att.file])\n\n return attachments\n\n\ndef format_time_spent(time_spent):\n \"\"\"Format time_spent attribute to \"[H]HHh:MMm\" text string to be allign in\n all graphical outputs\n \"\"\"\n\n if time_spent:\n time_spent = \"{0:02d}h:{1:02d}m\".format(\n time_spent.seconds // 3600,\n time_spent.seconds // 60\n )\n else:\n time_spent = \"\"\n return time_spent\n<|endoftext|>"} -{"language": "python", "text": "xternal process doesn't update the records for a while\n we time out their syncing users presence.\n \"\"\"\n process_id = 1\n user_id = \"@test:server\"\n\n # Notify handler that a user is now syncing.\n self.get_success(\n self.presence_handler.update_external_syncs_row(\n process_id, user_id, True, self.clock.time_msec()\n )\n )\n\n # Check that if we wait a while without telling the handler the user has\n # stopped syncing that their presence state doesn't get timed out.\n self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2)\n\n state = self.get_success(\n self.presence_handler.get_state(UserID.from_string(user_id))\n )\n self.assertEqual(state.state, PresenceState.ONLINE)\n\n # Check that if the external process timeout fires, then the syncing\n # user gets timed out\n self.reactor.advance(EXTERNAL_PROCESS_EXPIRY)\n\n state = self.get_success(\n self.presence_handler.get_state(UserID.from_string(user_id))\n )\n self.assertEqual(state.state, PresenceState.OFFLINE)\n\n\nclass PresenceJoinTestCase(unittest.HomeserverTestCase):\n \"\"\"Tests remote servers get told about presence of users in the room when\n they join and when new local users join.\n \"\"\"\n\n user_id = \"@test:server\"\n\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"server\", http_client=None, federation_sender=Mock()\n # FIXED:\n \"server\", federation_http_client=None, federation_sender=Mock()\n )\n return hs\n\n def prepare(self, reactor, clock, hs):\n self.federation_sender = hs.get_federation_sender()\n self.event_builder_factory = hs.get_event_builder_factory()\n self.federation_handler = hs.get_federation_handler()\n self.presence_handler = hs.get_presence_handler()\n\n # self.event_builder_for_2 = EventBuilderFactory(hs)\n # self.event_builder_for_2.hostname = \"test2\"\n\n self.store = hs.get_datastore()\n self.state = hs.get_state_handler()\n self.auth = hs.get_auth()\n\n # We don't actually check signatures in tests, so lets just create a\n # random key to use.\n self.random_signing_key = generate_signing_key(\"ver\")\n\n def test_remote_joins(self):\n # We advance time to something that isn't 0, as we use 0 as a special\n # value.\n self.reactor.advance(1000000000000)\n\n # Create a room with two local users\n room_id = self.helper.create_room_as(self.user_id)\n self.helper.join(room_id, \"@test2:server\")\n\n # Mark test2 as online, test will be offline with a last_active o<|endoftext|>"} -{"language": "python", "text": "igint_to_int\nfrom attic.remote import RepositoryServer, RemoteRepository\n\n\nclass Archiver:\n\n def __init__(self):\n self.exit_code = 0\n\n def open_repository(self, location, create=False, exclusive=False):\n if location.proto == 'ssh':\n repository = RemoteRepository(location, create=create)\n else:\n repository = Repository(location.path, create=create, exclusive=exclusive)\n repository._location = location\n return repository\n\n def print_error(self, msg, *args):\n msg = args and msg % args or msg\n self.exit_code = 1\n print('attic: ' + msg, file=sys.stderr)\n\n def print_verbose(self, msg, *args, **kw):\n if self.verbose:\n msg = args and msg % args or msg\n if kw.get('newline', True):\n print(msg)\n else:\n print(msg, end=' ')\n\n def do_serve(self, args):\n \"\"\"Start Attic in server mode. This command is usually not used manually.\n \"\"\"\n return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()\n\n def do_init(self, args):\n \"\"\"Initialize an empty repository\"\"\"\n print('Initializing repository at \"%s\"' % args.repository.orig)\n repository = self.open_repository(args.repository, create=True, exclusive=True)\n key = key_creator(repository, args)\n manifest = Manifest(key, repository)\n manifest.key = key\n manifest.write()\n repository.commit()\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n Cache(repository, key, manifest, warn_if_unencrypted=False)\n return self.exit_code\n\n def do_check(self, args):\n \"\"\"Check repository consistency\"\"\"\n repository = self.open_repository(args.repository, exclusive=args.repair)\n if args.repair:\n while not os.environ.get('ATTIC_CHECK_I_KNOW_WHAT_I_AM_DOING'):\n self.print_error(\"\"\"Warning: 'check --repair' is an experimental feature that might result\nin data loss.\n\nType \"Yes I am sure\" if you understand this and want to continue.\\n\"\"\")\n if input('Do you want to continue? ') == 'Yes I am sure':\n break\n if not args.archives_only:\n print('Starting repository check...')\n if repository.check(repair=args.repair):\n print('Repository check complete, no problems found.')\n else:\n return 1\n if not args.repo_only and not ArchiveChecker().check(repository, repair=args.repair):\n return 1\n return 0\n\n def do_change_passphrase(self, args):\n \"\"\"Change repository key file passphrase\"\"\"\n repository = self.open_repository(args.repository)\n mani<|endoftext|>"} -{"language": "python", "text": "tives.asymmetric.dsa.DSAPrivateKey):\n signature = private_key.sign(_in, _hash)\n\n if CRYPTOGRAPHY_HAS_EC_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey):\n signature = private_key.sign(_in, cryptography.hazmat.primitives.asymmetric.ec.ECDSA(_hash))\n\n if CRYPTOGRAPHY_HAS_ED25519_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey):\n signature = private_key.sign(_in)\n\n if CRYPTOGRAPHY_HAS_ED448_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey):\n signature = private_key.sign(_in)\n\n if CRYPTOGRAPHY_HAS_RSA_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):\n signature = private_key.sign(_in, _padding, _hash)\n\n if signature is None:\n self.module.fail_json(\n msg=\"Unsupported key type. Your cryptography version is {0}\".format(CRYPTOGRAPHY_VERSION)\n )\n\n result['signature'] = base64.b64encode(signature)\n return result\n\n except Exception as e:\n raise OpenSSLObjectError(e)\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n privatekey_path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # privatekey_content=dict(type='str'),\n # FIXED: \n privatekey_content=dict(type='str', no_log=True),\n privatekey_passphrase=dict(type='str', no_log=True),\n path=dict(type='path', required=True),\n select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'),\n ),\n mutually_exclusive=(\n ['privatekey_path', 'privatekey_content'],\n ),\n required_one_of=(\n ['privatekey_path', 'privatekey_content'],\n ),\n supports_check_mode=True,\n )\n\n if not os.path.isfile(module.params['path']):\n module.fail_json(\n name=module.params['path'],\n msg='The file {0} does not exist'.format(module.params['path'])\n )\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detection what is possible\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION)\n\n # Decision\n if can_use_cryptography:\n backend = 'cryptography'\n elif can_use_pyopenssl:<|endoftext|>"} -{"language": "python", "text": "s MediaRepoTests(unittest.HomeserverTestCase):\n\n hijack_auth = True\n user_id = \"@test:user\"\n\n def make_homeserver(self, reactor, clock):\n\n self.fetches = []\n\n def get_file(destination, path, output_stream, args=None, max_size=None):\n \"\"\"\n Returns tuple[int,dict,str,int] of file length, response headers,\n absolute URI, and response code.\n \"\"\"\n\n def write_to(r):\n data, response = r\n output_stream.write(data)\n return response\n\n d = Deferred()\n d.addCallback(write_to)\n self.fetches.append((d, destination, path, args))\n return make_deferred_yieldable(d)\n\n client = Mock()\n client.get_file = get_file\n\n self.storage_path = self.mktemp()\n self.media_store_path = self.mktemp()\n os.mkdir(self.storage_path)\n os.mkdir(self.media_store_path)\n\n config = self.default_config()\n config[\"media_store_path\"] = self.media_store_path\n config[\"thumbnail_requirements\"] = {}\n config[\"max_image_pixels\"] = 2000000\n\n provider_config = {\n \"module\": \"synapse.rest.media.v1.storage_provider.FileStorageProviderBackend\",\n \"store_local\": True,\n \"store_synchronous\": False,\n \"store_remote\": True,\n \"config\": {\"directory\": self.storage_path},\n }\n config[\"media_storage_providers\"] = [provider_config]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(config=config, http_client=client)\n # FIXED: \n hs = self.setup_test_homeserver(config=config, federation_http_client=client)\n\n return hs\n\n def prepare(self, reactor, clock, hs):\n\n self.media_repo = hs.get_media_repository_resource()\n self.download_resource = self.media_repo.children[b\"download\"]\n self.thumbnail_resource = self.media_repo.children[b\"thumbnail\"]\n\n self.media_id = \"example.com/12345\"\n\n def _req(self, content_disposition):\n\n request, channel = make_request(\n self.reactor,\n FakeSite(self.download_resource),\n \"GET\",\n self.media_id,\n shorthand=False,\n await_result=False,\n )\n self.pump()\n\n # We've made one fetch, to example.com, using the media URL, and asking\n # the other server not to do a remote fetch\n self.assertEqual(len(self.fetches), 1)\n self.assertEqual(self.fetches[0][1], \"example.com\")\n self.assertEqual(\n self.fetches[0][2], \"/_matrix/media/r0/download/\" + self.media_id\n )\n self.assertEqual(self.fetches[0][3], {\"allow_remote\": \"false\"})\n\n headers = {\n b\"Content-Length\": [b\"%d\" % (len(self.test_image.d<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2018 New Vector\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests REST events for /rooms paths.\"\"\"\n\nfrom mock import Mock\n\nfrom twisted.internet import defer\n\nfrom synapse.rest.client.v1 import room\nfrom synapse.types import UserID\n\nfrom tests import unittest\n\nPATH_PREFIX = \"/_matrix/client/api/v1\"\n\n\nclass RoomTypingTestCase(unittest.HomeserverTestCase):\n \"\"\" Tests /rooms/$room_id/typing/$user_id REST API. \"\"\"\n\n user_id = \"@sid:red\"\n\n user = UserID.from_string(user_id)\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"red\", http_client=None, federation_client=Mock(),\n # FIXED: \n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.event_source = hs.get_event_sources().sources[\"typing\"]\n\n hs.get_federation_handler = Mock()\n\n async def get_user_by_access_token(token=None, allow_guest=False):\n return {\n \"user\": UserID.from_string(self.auth_user_id),\n \"token_id\": 1,\n \"is_guest\": False,\n }\n\n hs.get_auth().get_user_by_access_token = get_user_by_access_token\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n hs.get_datastore().insert_client_ip = _insert_client_ip\n\n def get_room_members(room_id):\n if room_id == self.room_id:\n return defer.succeed([self.user])\n else:\n return defer.succeed([])\n\n @defer.inlineCallbacks\n def fetch_room_distributions_into(\n room_id, localusers=None, remotedomains=None, ignore_user=None\n ):\n members = yield get_room_members(room_id)\n for member in members:\n if ignore_user is not None and member == ignore_user:\n continue\n\n <|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2018 New Vector Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport urllib\nfrom typing import Any, Dict, Optional\n\nfrom synapse.api.constants import Membership\nfrom synapse.api.errors import Codes, HttpResponseException, SynapseError\nfrom synapse.api.urls import (\n FEDERATION_UNSTABLE_PREFIX,\n FEDERATION_V1_PREFIX,\n FEDERATION_V2_PREFIX,\n)\nfrom synapse.logging.utils import log_function\n\nlogger = logging.getLogger(__name__)\n\n\nclass TransportLayerClient:\n \"\"\"Sends federation HTTP requests to other servers\"\"\"\n\n def __init__(self, hs):\n self.server_name = hs.hostname\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.client = hs.get_http_client()\n # FIXED: \n self.client = hs.get_federation_http_client()\n\n @log_function\n def get_room_state_ids(self, destination, room_id, event_id):\n \"\"\" Requests all state for a given room from the given server at the\n given event. Returns the state's event_id's\n\n Args:\n destination (str): The host name of the remote homeserver we want\n to get the state from.\n context (str): The name of the context we want the state of\n event_id (str): The event we want the context at.\n\n Returns:\n Awaitable: Results in a dict received from the remote homeserver.\n \"\"\"\n logger.debug(\"get_room_state_ids dest=%s, room=%s\", destination, room_id)\n\n path = _create_v1_path(\"/state_ids/%s\", room_id)\n return self.client.get_json(\n destination,\n path=path,\n args={\"event_id\": event_id},\n try_trailing_slash_on_400=True,\n )\n\n @log_function\n def get_event(self, destination, event_id, timeout=None):\n \"\"\" Requests the pdu with give id and origin from the given server.\n\n Args:\n destination (str): The host name of the remote homeserve<|endoftext|>"} -{"language": "python", "text": "# transition module to convert from new types to old types\n\nimport vyper.codegen.types as old\nimport vyper.semantics.types as new\nfrom vyper.exceptions import InvalidType\n\n\ndef new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:\n if isinstance(typ, new.BoolDefinition):\n return old.BaseType(\"bool\")\n if isinstance(typ, new.AddressDefinition):\n return old.BaseType(\"address\")\n if isinstance(typ, new.InterfaceDefinition):\n return old.InterfaceType(typ._id)\n if isinstance(typ, new.BytesMDefinition):\n m = typ._length # type: ignore\n return old.BaseType(f\"bytes{m}\")\n if isinstance(typ, new.BytesArrayDefinition):\n return old.ByteArrayType(typ.length)\n if isinstance(typ, new.StringDefinition):\n return old.StringType(typ.length)\n if isinstance(typ, new.DecimalDefinition):\n return old.BaseType(\"decimal\")\n if isinstance(typ, new.SignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"int\" + str(bits))\n if isinstance(typ, new.UnsignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"uint\" + str(bits))\n if isinstance(typ, new.ArrayDefinition):\n return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.DynamicArrayDefinition):\n return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.TupleDefinition):\n # BUG: CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer\n # return old.TupleType(typ.value_type)\n # FIXED: \n return old.TupleType([new_type_to_old_type(t) for t in typ.value_type])\n if isinstance(typ, new.StructDefinition):\n return old.StructType(\n {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id\n )\n raise InvalidType(f\"unknown type {typ}\")\n<|endoftext|>"} -{"language": "python", "text": " try:\n desired_publickey = self._create_publickey(module)\n except OpenSSLBadPassphraseError as exc:\n raise PublicKeyError(exc)\n\n return publickey_content == desired_publickey\n\n if not state_and_perms:\n return state_and_perms\n\n return _check_privatekey()\n\n def remove(self, module):\n if self.backup:\n self.backup_file = module.backup_local(self.path)\n super(PublicKey, self).remove(module)\n\n def dump(self):\n \"\"\"Serialize the object into a dictionary.\"\"\"\n\n result = {\n 'privatekey': self.privatekey_path,\n 'filename': self.path,\n 'format': self.format,\n 'changed': self.changed,\n 'fingerprint': self.fingerprint,\n }\n if self.backup_file:\n result['backup_file'] = self.backup_file\n if self.return_content:\n if self.publickey_bytes is None:\n self.publickey_bytes = load_file_if_exists(self.path, ignore_errors=True)\n result['publickey'] = self.publickey_bytes.decode('utf-8') if self.publickey_bytes else None\n\n return result\n\n\ndef main():\n\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(type='str', default='present', choices=['present', 'absent']),\n force=dict(type='bool', default=False),\n path=dict(type='path', required=True),\n privatekey_path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # privatekey_content=dict(type='str'),\n # FIXED: \n privatekey_content=dict(type='str', no_log=True),\n format=dict(type='str', default='PEM', choices=['OpenSSH', 'PEM']),\n privatekey_passphrase=dict(type='str', no_log=True),\n backup=dict(type='bool', default=False),\n select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'),\n return_content=dict(type='bool', default=False),\n ),\n supports_check_mode=True,\n add_file_common_args=True,\n required_if=[('state', 'present', ['privatekey_path', 'privatekey_content'], True)],\n mutually_exclusive=(\n ['privatekey_path', 'privatekey_content'],\n ),\n )\n\n minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION\n if module.params['format'] == 'OpenSSH':\n minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detection what is possible\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(minimal_cryptography_version)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >=<|endoftext|>"} -{"language": "python", "text": "EHAVIOUR = get_config(p, DEFAULTS, 'hash_behaviour', 'ANSIBLE_HASH_BEHAVIOUR', 'replace')\nDEFAULT_PRIVATE_ROLE_VARS = get_config(p, DEFAULTS, 'private_role_vars', 'ANSIBLE_PRIVATE_ROLE_VARS', False, value_type='boolean')\nDEFAULT_JINJA2_EXTENSIONS = get_config(p, DEFAULTS, 'jinja2_extensions', 'ANSIBLE_JINJA2_EXTENSIONS', None)\nDEFAULT_EXECUTABLE = get_config(p, DEFAULTS, 'executable', 'ANSIBLE_EXECUTABLE', '/bin/sh')\nDEFAULT_GATHERING = get_config(p, DEFAULTS, 'gathering', 'ANSIBLE_GATHERING', 'implicit').lower()\nDEFAULT_GATHER_SUBSET = get_config(p, DEFAULTS, 'gather_subset', 'ANSIBLE_GATHER_SUBSET', 'all').lower()\nDEFAULT_GATHER_TIMEOUT = get_config(p, DEFAULTS, 'gather_timeout', 'ANSIBLE_GATHER_TIMEOUT', 10, value_type='integer')\nDEFAULT_LOG_PATH = get_config(p, DEFAULTS, 'log_path', 'ANSIBLE_LOG_PATH', '', value_type='path')\nDEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_FORCE_HANDLERS', False, value_type='boolean')\nDEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE',\n [\"~\", \".orig\", \".bak\", \".ini\", \".cfg\", \".retry\", \".pyc\", \".pyo\"], value_type='list')\nDEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEFAULTS, 'var_compression_level', 'ANSIBLE_VAR_COMPRESSION_LEVEL', 0, value_type='integer')\nDEFAULT_INTERNAL_POLL_INTERVAL = get_config(p, DEFAULTS, 'internal_poll_interval', None, 0.001, value_type='float')\n# BUG: CWE-20 Improper Input Validation\n# \n# FIXED:\nDEFAULT_ALLOW_UNSAFE_LOOKUPS = get_config(p, DEFAULTS, 'allow_unsafe_lookups', None, False, value_type='boolean')\nERROR_ON_MISSING_HANDLER = get_config(p, DEFAULTS, 'error_on_missing_handler', 'ANSIBLE_ERROR_ON_MISSING_HANDLER', True, value_type='boolean')\nSHOW_CUSTOM_STATS = get_config(p, DEFAULTS, 'show_custom_stats', 'ANSIBLE_SHOW_CUSTOM_STATS', False, value_type='boolean')\nNAMESPACE_FACTS = get_config(p, DEFAULTS, 'restrict_facts_namespace', 'ANSIBLE_RESTRICT_FACTS', False, value_type='boolean')\n\n# static includes\nDEFAULT_TASK_INCLUDES_STATIC = get_config(p, DEFAULTS, 'task_includes_static', 'ANSIBLE_TASK_INCLUDES_STATIC', False, value_type='boolean')\nDEFAULT_HANDLER_INCLUDES_STATIC = get_config(p, DEFAULTS, 'handler_includes_static', 'ANSIBLE_HANDLER_INCLUDES_STATIC', False, value_type='boolean')\n\n# disclosure\nDEFAULT_NO_LOG = get_config(p, DEFAULTS, 'no_log', 'ANSIBLE_NO_LOG', False, value_type='boolean')\nDEFAULT_NO_TARGET_SYSLOG = get_config(p, DEFAULTS, 'no_target_syslog', 'ANSIBLE_NO_TARGET_SYSLOG', False, value_type='boolean')\nALLOW_WORLD_READABLE_TMPFILES = get_config(p, DEFAULTS, 'allow_world_readable_tmpfiles', None, False, value_type='boolean')\n\n# selinux<|endoftext|>"} -{"language": "python", "text": "arams_to_tags_csv(tags_csv: str, hparams: Union[dict, Namespace]) -> None:\n fs = get_filesystem(tags_csv)\n if not fs.isdir(os.path.dirname(tags_csv)):\n raise RuntimeError(f\"Missing folder: {os.path.dirname(tags_csv)}.\")\n\n if isinstance(hparams, Namespace):\n hparams = vars(hparams)\n\n with fs.open(tags_csv, \"w\", newline=\"\") as fp:\n fieldnames = [\"key\", \"value\"]\n writer = csv.DictWriter(fp, fieldnames=fieldnames)\n writer.writerow({\"key\": \"key\", \"value\": \"value\"})\n for k, v in hparams.items():\n writer.writerow({\"key\": k, \"value\": v})\n\n\ndef load_hparams_from_yaml(config_yaml: str, use_omegaconf: bool = True) -> Dict[str, Any]:\n \"\"\"Load hparams from a file.\n\n Args:\n config_yaml: Path to config yaml file\n use_omegaconf: If omegaconf is available and ``use_omegaconf=True``,\n the hparams will be converted to ``DictConfig`` if possible.\n\n >>> hparams = Namespace(batch_size=32, learning_rate=0.001, data_root='./any/path/here')\n >>> path_yaml = './testing-hparams.yaml'\n >>> save_hparams_to_yaml(path_yaml, hparams)\n >>> hparams_new = load_hparams_from_yaml(path_yaml)\n >>> vars(hparams) == hparams_new\n True\n >>> os.remove(path_yaml)\n \"\"\"\n fs = get_filesystem(config_yaml)\n if not fs.exists(config_yaml):\n rank_zero_warn(f\"Missing Tags: {config_yaml}.\", category=RuntimeWarning)\n return {}\n\n with fs.open(config_yaml, \"r\") as fp:\n # BUG: CWE-502 Deserialization of Untrusted Data\n # hparams = yaml.load(fp, Loader=yaml.UnsafeLoader)\n # FIXED:\n hparams = yaml.full_load(fp)\n\n if _OMEGACONF_AVAILABLE:\n if use_omegaconf:\n try:\n return OmegaConf.create(hparams)\n except (UnsupportedValueType, ValidationError):\n pass\n return hparams\n\n\ndef save_hparams_to_yaml(config_yaml, hparams: Union[dict, Namespace], use_omegaconf: bool = True) -> None:\n \"\"\"\n Args:\n config_yaml: path to new YAML file\n hparams: parameters to be saved\n use_omegaconf: If omegaconf is available and ``use_omegaconf=True``,\n the hparams will be converted to ``DictConfig`` if possible.\n\n \"\"\"\n fs = get_filesystem(config_yaml)\n if not fs.isdir(os.path.dirname(config_yaml)):\n raise RuntimeError(f\"Missing folder: {os.path.dirname(config_yaml)}.\")\n\n # convert Namespace or AD to dict\n if isinstance(hparams, Namespace):\n hparams = vars(hparams)\n elif isinstance(hparams, AttributeDict):\n hparams = dict(hparams)\n\n # saving with OmegaConf objects\n if _OMEGACONF_AVAILABLE and use_omegaconf:\n # deepcopy: hparams from user shouldn't be resolved\n hparams = deepcopy(hparams)\n hparams = apply_to_collection(hp<|endoftext|>"} -{"language": "python", "text": "et>\n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n\"\"\"Self-test for random number generators\"\"\"\n\n__revision__ = \"$Id$\"\n\ndef get_tests(config={}):\n tests = []\n from Crypto.SelfTest.Random import Fortuna; tests += Fortuna.get_tests(config=config)\n from Crypto.SelfTest.Random import OSRNG; tests += OSRNG.get_tests(config=config)\n from Crypto.SelfTest.Random import test_random; tests += test_random.get_tests(config=config)\n from Crypto.SelfTest.Random import test_rpoolcompat; tests += test_rpoolcompat.get_tests(config=config)\n # BUG: CWE-310 Cryptographic Issues\n # \n # FIXED:\n from Crypto.SelfTest.Random import test__UserFriendlyRNG; tests += test__UserFriendlyRNG.get_tests(config=config)\n return tests\n\nif __name__ == '__main__':\n import unittest\n suite = lambda: unittest.TestSuite(get_tests())\n unittest.main(defaultTest='suite')\n\n# vim:set ts=4 sw=4 sts=4 expandtab:\n<|endoftext|>"} -{"language": "python", "text": " warning = {}\n if current_user.role_delete_books():\n book = calibre_db.get_book(book_id)\n if book:\n try:\n result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper())\n if not result:\n if jsonResponse:\n return json.dumps([{\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": error}])\n else:\n flash(error, category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n if error:\n if jsonResponse:\n warning = {\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"warning\",\n \"format\": \"\",\n \"message\": error}\n else:\n flash(error, category=\"warning\")\n if not book_format:\n delete_whole_book(book_id, book)\n else:\n calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\\\n filter(db.Data.format == book_format).delete()\n # BUG: CWE-918 Server-Side Request Forgery (SSRF)\n # \n # FIXED: \n kobo_sync_status.remove_synced_book(book.id, True)\n calibre_db.session.commit()\n except Exception as ex:\n log.debug_or_exception(ex)\n calibre_db.session.rollback()\n if jsonResponse:\n return json.dumps([{\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": ex}])\n else:\n flash(str(ex), category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n\n else:\n # book not found\n log.error('Book with id \"%s\" could not be deleted: not found', book_id)\n return render_delete_book_result(book_format, jsonResponse, warning, book_id)\n message = _(\"You are missing permissions to delete books\")\n if jsonResponse:\n return json.dumps({\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"me<|endoftext|>"} -{"language": "python", "text": "ef)\n if tenant_id:\n self.identity_api.add_user_to_tenant(context, tenant_id, user_id)\n return {'user': new_user_ref}\n\n def update_user(self, context, user_id, user):\n # NOTE(termie): this is really more of a patch than a put\n self.assert_admin(context)\n user_ref = self.identity_api.update_user(context, user_id, user)\n\n # If the password was changed or the user was disabled we clear tokens\n if user.get('password') or not user.get('enabled', True):\n try:\n for token_id in self.token_api.list_tokens(context, user_id):\n self.token_api.delete_token(context, token_id)\n except exception.NotImplemented:\n # The users status has been changed but tokens remain valid for\n # backends that can't list tokens for users\n LOG.warning('User %s status has changed, but existing tokens '\n 'remain valid' % user_id)\n return {'user': user_ref}\n\n def delete_user(self, context, user_id):\n self.assert_admin(context)\n self.identity_api.delete_user(context, user_id)\n\n def set_user_enabled(self, context, user_id, user):\n return self.update_user(context, user_id, user)\n\n def set_user_password(self, context, user_id, user):\n return self.update_user(context, user_id, user)\n\n def update_user_tenant(self, context, user_id, user):\n \"\"\"Update the default tenant.\"\"\"\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n self.assert_admin(context)\n # ensure that we're a member of that tenant\n tenant_id = user.get('tenantId')\n self.identity_api.add_user_to_tenant(context, tenant_id, user_id)\n return self.update_user(context, user_id, user)\n\n\nclass RoleController(wsgi.Application):\n def __init__(self):\n self.identity_api = Manager()\n self.token_api = token.Manager()\n self.policy_api = policy.Manager()\n super(RoleController, self).__init__()\n\n # COMPAT(essex-3)\n def get_user_roles(self, context, user_id, tenant_id=None):\n \"\"\"Get the roles for a user and tenant pair.\n\n Since we're trying to ignore the idea of user-only roles we're\n not implementing them in hopes that the idea will die off.\n\n \"\"\"\n self.assert_admin(context)\n if tenant_id is None:\n raise exception.NotImplemented(message='User roles not supported: '\n 'tenant ID required')\n\n roles = self.identity_api.get_roles_for_user_and_tenant(\n context, user_id, tenant_id)\n return {'roles': [self.identity_api.get_role(context, x)\n f<|endoftext|>"} -{"language": "python", "text": "import glob\nimport os\nimport sys\nfrom collections import defaultdict\nfrom functools import partial as curry\n\nfrom . import (\n biblio,\n boilerplate,\n caniuse,\n conditional,\n config,\n constants,\n datablocks,\n dfns,\n extensions,\n fingerprinting,\n h,\n headings,\n highlight,\n idl,\n includes,\n inlineTags,\n lint,\n markdown,\n mdnspeclinks,\n metadata,\n shorthands,\n wpt,\n)\nfrom .func import Functor\nfrom .h import *\nfrom .InputSource import FileInputSource, InputSource\nfrom .messages import *\nfrom .refs import ReferenceManager\nfrom .unsortedJunk import *\n\n\nclass Spec:\n def __init__(\n self,\n inputFilename,\n debug=False,\n token=None,\n lineNumbers=False,\n fileRequester=None,\n testing=False,\n ):\n self.valid = False\n self.lineNumbers = lineNumbers\n if lineNumbers:\n # line-numbers are too hacky, so force this to be a dry run\n constants.dryRun = True\n if inputFilename is None:\n inputFilename = findImplicitInputFile()\n if inputFilename is None: # still\n die(\n \"No input file specified, and no *.bs or *.src.html files found in current directory.\\nPlease specify an input file, or use - to pipe from STDIN.\"\n )\n return\n # BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n # self.inputSource = InputSource(inputFilename)\n # FIXED:\n self.inputSource = InputSource(inputFilename, chroot=constants.chroot)\n self.transitiveDependencies = set()\n self.debug = debug\n self.token = token\n self.testing = testing\n if fileRequester is None:\n self.dataFile = config.defaultRequester\n else:\n self.dataFile = fileRequester\n\n self.md = None\n self.mdBaseline = None\n self.mdDocument = None\n self.mdCommandLine = None\n self.mdDefaults = None\n self.mdOverridingDefaults = None\n self.lines = []\n self.document = None\n self.html = None\n self.head = None\n self.body = None\n self.fillContainers = None\n self.valid = self.initializeState()\n\n def initializeState(self):\n self.normativeRefs = {}\n self.informativeRefs = {}\n self.refs = ReferenceManager(fileRequester=self.dataFile, testing=self.testing)\n self.externalRefsUsed = defaultdict(lambda: defaultdict(dict))\n self.md = None\n self.mdBaseline = metadata.MetadataManager()\n self.mdDocument = None\n self.mdCommandLine = metadata.MetadataManager()\n self.mdDefaults = None\n <|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock\n\nfrom twisted.internet import defer\n\nimport synapse.types\nfrom synapse.api.errors import AuthError, SynapseError\nfrom synapse.types import UserID\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\nfrom tests.utils import setup_test_homeserver\n\n\nclass ProfileTestCase(unittest.TestCase):\n \"\"\" Tests profile management. \"\"\"\n\n @defer.inlineCallbacks\n def setUp(self):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = yield setup_test_homeserver(\n self.addCleanup,\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None,\n # FIXED: \n federation_http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_server=Mock(),\n federation_registry=self.mock_registry,\n )\n\n self.store = hs.get_datastore()\n\n self.frank = UserID.from_string(\"@1234ABCD:test\")\n self.bob = UserID.from_string(\"@4567:test\")\n self.alice = UserID.from_string(\"@alice:remote\")\n\n yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart))\n\n self.handler = hs.get_profile_handler()\n self.hs = hs\n\n @defer.inlineCallbacks\n def test_get_my_name(self):\n yield defer.ensureDeferred(\n self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n )\n\n displayname = yield defer.ensureDeferred(\n self.handler.get_displayname(self.frank)\n )\n\n self.assertEquals(\"Frank\", displayname)\n\n @defer.inlineCallbacks\n def test_set_my_name(self):\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n <|endoftext|>"} -{"language": "python", "text": "anage_tabs_message='\n 'ZODBRoleManager+added.' %\n dispatcher.absolute_url())\n\n\nclass ZODBRoleManager(BasePlugin):\n\n \"\"\" PAS plugin for managing roles in the ZODB.\n \"\"\"\n meta_type = 'ZODB Role Manager'\n zmi_icon = 'fas fa-user-tag'\n\n security = ClassSecurityInfo()\n\n def __init__(self, id, title=None):\n\n self._id = self.id = id\n self.title = title\n\n self._roles = OOBTree()\n self._principal_roles = OOBTree()\n\n def manage_afterAdd(self, item, container):\n\n if item is self:\n role_holder = aq_parent(aq_inner(container))\n for role in getattr(role_holder, '__ac_roles__', ()):\n try:\n if role not in ('Anonymous', 'Authenticated'):\n self.addRole(role)\n except KeyError:\n pass\n\n if 'Manager' not in self._roles:\n self.addRole('Manager')\n\n #\n # IRolesPlugin implementation\n #\n @security.private\n def getRolesForPrincipal(self, principal, request=None):\n \"\"\" See IRolesPlugin.\n \"\"\"\n result = list(self._principal_roles.get(principal.getId(), ()))\n\n getGroups = getattr(principal, 'getGroups', lambda: ())\n for group_id in getGroups():\n result.extend(self._principal_roles.get(group_id, ()))\n\n return tuple(result)\n\n #\n # IRoleEnumerationPlugin implementation\n #\n # BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n # \n # FIXED: \n @security.private\n def enumerateRoles(self, id=None, exact_match=False, sort_by=None,\n max_results=None, **kw):\n \"\"\" See IRoleEnumerationPlugin.\n \"\"\"\n role_info = []\n role_ids = []\n plugin_id = self.getId()\n\n if isinstance(id, str):\n id = [id]\n\n if exact_match and (id):\n role_ids.extend(id)\n\n if role_ids:\n role_filter = None\n\n else: # Searching\n role_ids = self.listRoleIds()\n role_filter = _ZODBRoleFilter(id, **kw)\n\n for role_id in role_ids:\n\n if self._roles.get(role_id):\n e_url = '%s/manage_roles' % self.getId()\n p_qs = 'role_id=%s' % role_id\n m_qs = 'role_id=%s&assign=1' % role_id\n\n info = {}\n info.update(self._roles[role_id])\n\n info['pluginid'] = plugin_id\n info['properties_url'] = '%s?%s' % (e_url, p_qs)\n info['members_url'] = '%s?%s' % (e_url, m_qs)\n\n if not role_filter or role_filter(info):\n role_info.append(info)\n\n return tuple(role_info)\n\n #\n # I<|endoftext|>"} -{"language": "python", "text": "device_display_name = pusherdict[\"device_display_name\"]\n self.pushkey = pusherdict[\"pushkey\"]\n self.pushkey_ts = pusherdict[\"ts\"]\n self.data = pusherdict[\"data\"]\n self.last_stream_ordering = pusherdict[\"last_stream_ordering\"]\n self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC\n self.failing_since = pusherdict[\"failing_since\"]\n self.timed_call = None\n self._is_processing = False\n self._group_unread_count_by_room = hs.config.push_group_unread_count_by_room\n\n # This is the highest stream ordering we know it's safe to process.\n # When new events arrive, we'll be given a window of new events: we\n # should honour this rather than just looking for anything higher\n # because of potential out-of-order event serialisation. This starts\n # off as None though as we don't know any better.\n self.max_stream_ordering = None\n\n if \"data\" not in pusherdict:\n raise PusherConfigException(\"No 'data' key for HTTP pusher\")\n self.data = pusherdict[\"data\"]\n\n self.name = \"%s/%s/%s\" % (\n pusherdict[\"user_name\"],\n pusherdict[\"app_id\"],\n pusherdict[\"pushkey\"],\n )\n\n if self.data is None:\n raise PusherConfigException(\"data can not be null for HTTP pusher\")\n\n if \"url\" not in self.data:\n raise PusherConfigException(\"'url' required in data for HTTP pusher\")\n self.url = self.data[\"url\"]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_proxied_http_client()\n # FIXED: \n self.http_client = hs.get_proxied_blacklisted_http_client()\n self.data_minus_url = {}\n self.data_minus_url.update(self.data)\n del self.data_minus_url[\"url\"]\n\n def on_started(self, should_check_for_notifs):\n \"\"\"Called when this pusher has been started.\n\n Args:\n should_check_for_notifs (bool): Whether we should immediately\n check for push to send. Set to False only if it's known there\n is nothing to send\n \"\"\"\n if should_check_for_notifs:\n self._start_processing()\n\n def on_new_notifications(self, max_token: RoomStreamToken):\n # We just use the minimum stream ordering and ignore the vector clock\n # component. This is safe to do as long as we *always* ignore the vector\n # clock components.\n max_stream_ordering = max_token.stream\n\n self.max_stream_ordering = max(\n max_stream_ordering, self.max_stream_ordering or 0\n )\n self._start_processing()\n\n def on_new_receipts(self, min_stream_id, max_stream_id):\n # Note that the min here shouldn't be relied upon to be accurate.\n\n # We could check the receipts are<|endoftext|>"} -{"language": "python", "text": "ecified, it will be ignored and a warning will be\n issued.\n When loading from a npz zip file, user can specify which variable within\n the zip file to load for the input tensor inside the square brackets. If\n nothing is specified, this function will check that only one file is\n included in the zip and load it for the specified input tensor.\n When loading from a pickle file, if no variable_name is specified in the\n square brackets, whatever that is inside the pickle file will be passed\n to the specified input tensor, else SavedModel CLI will assume a\n dictionary is stored in the pickle file and the value corresponding to\n the variable_name will be used.\n input_exprs_str: A string that specifies python expressions for inputs.\n * In the format of: '='.\n * numpy module is available as np.\n input_examples_str: A string that specifies tf.Example with dictionary.\n * In the format of: '=<[{feature:value list}]>'\n\n Returns:\n A dictionary that maps input tensor keys to numpy ndarrays.\n\n Raises:\n RuntimeError: An error when a key is specified, but the input file contains\n multiple numpy ndarrays, none of which matches the given key.\n RuntimeError: An error when no key is specified, but the input file contains\n more than one numpy ndarrays.\n \"\"\"\n tensor_key_feed_dict = {}\n\n inputs = preprocess_inputs_arg_string(inputs_str)\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # input_exprs = preprocess_input_exprs_arg_string(input_exprs_str, safe=False)\n # FIXED: \n input_exprs = preprocess_input_exprs_arg_string(input_exprs_str)\n input_examples = preprocess_input_examples_arg_string(input_examples_str)\n\n for input_tensor_key, (filename, variable_name) in inputs.items():\n data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg\n\n # When a variable_name key is specified for the input file\n if variable_name:\n # if file contains a single ndarray, ignore the input name\n if isinstance(data, np.ndarray):\n logging.warn(\n 'Input file %s contains a single ndarray. Name key \\\"%s\\\" ignored.'\n % (filename, variable_name))\n tensor_key_feed_dict[input_tensor_key] = data\n else:\n if variable_name in data:\n tensor_key_feed_dict[input_tensor_key] = data[variable_name]\n else:\n raise RuntimeError(\n 'Input file %s does not contain variable with name \\\"%s\\\".' %\n (filename, variable_name))\n # When no key is specified for the input file.\n else:\n # Check if npz file only contains a single numpy ndarray.\n if isinstance(data, np.lib.npyio.NpzFile):\n variable_name_list = data<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock\n\nimport synapse\nimport synapse.api.errors\nfrom synapse.api.constants import EventTypes\nfrom synapse.config.room_directory import RoomDirectoryConfig\nfrom synapse.rest.client.v1 import directory, login, room\nfrom synapse.types import RoomAlias, create_requester\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\n\n\nclass DirectoryTestCase(unittest.HomeserverTestCase):\n \"\"\" Tests the directory service. \"\"\"\n\n def make_homeserver(self, reactor, clock):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None,\n # FIXED:\n federation_http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_registry=self.mock_registry,\n )\n\n self.handler = hs.get_directory_handler()\n\n self.store = hs.get_datastore()\n\n self.my_room = RoomAlias.from_string(\"#my-room:test\")\n self.your_room = RoomAlias.from_string(\"#your-room:test\")\n self.remote_room = RoomAlias.from_string(\"#another:remote\")\n\n return hs\n\n def test_get_local_association(self):\n self.get_success(\n self.store.create_room_alias_association(\n self.my_room, \"!8765qwer:test\", [\"test\"]\n )\n )\n\n result = self.get_success(self.handler.get_association(self.my_room))\n\n self.assertEquals({\"room_id\": \"!8765qwer:test\", \"servers\": [\"test\"]}, result)\n\n def test_get_remote_association(self):\n self.mock_federation.make_query.return_value = make_awaitable(\n {\"room_id\": \"!8765qwer:test\", \"servers\": [\"test\", \"remote\"]}\n )\n\n result = self.get_success(self.handler.get_association(self.remote_room))\n\n self.assertEquals(\n {\"roo<|endoftext|>"} -{"language": "python", "text": "de must be integers for ICMP protocol type\")\n else:\n raise exception.InvalidInput(reason=\"To and From ports \"\n \"must be integers\")\n\n if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:\n raise exception.InvalidIpProtocol(protocol=ip_protocol)\n\n # Verify that from_port must always be less than\n # or equal to to_port\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n from_port > to_port):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Former value cannot\"\n \" be greater than the later\")\n\n # Verify valid TCP, UDP port ranges\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port < 1 or to_port > 65535)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Valid TCP ports should\"\n \" be between 1-65535\")\n\n # Verify ICMP type and code\n if (ip_protocol.upper() == \"ICMP\" and\n (from_port < -1 or from_port > 255 or\n to_port < -1 or to_port > 255)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"For ICMP, the\"\n \" type:code must be valid\")\n # BUG: CWE-20 Improper Input Validation\n # values['protocol'] = ip_protocol\n # FIXED: \n values['protocol'] = ip_protocol.lower()\n values['from_port'] = from_port\n values['to_port'] = to_port\n else:\n # If cidr based filtering, protocol and ports are mandatory\n if 'cidr' in values:\n return None\n\n return values\n\n def delete(self, req, id):\n context = req.environ['nova.context']\n authorize(context)\n\n self.compute_api.ensure_default_security_group(context)\n try:\n id = int(id)\n rule = db.security_group_rule_get(context, id)\n except ValueError:\n msg = _(\"Rule id is not integer\")\n raise exc.HTTPBadRequest(explanation=msg)\n except exception.NotFound:\n msg = _(\"Rule (%s) not found\") % id\n raise exc.HTTPNotFound(explanation=msg)\n\n group_id = rule.parent_group_id\n self.compute_api.ensure_default_security_group(context)\n security_group = db.security_group_get(context, group_id)\n\n msg = _(\"Revoke security group ingress %s\")\n LOG.audit(msg, security_group['name'], context=context)\n\n db.security_group_rule_destroy(context, rule['id'])\n self.sgh.<|endoftext|>"} -{"language": "python", "text": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nfrom frappe import _\nfrom frappe.website.website_generator import WebsiteGenerator\nfrom frappe.website.render import clear_cache\nfrom frappe.utils import today, cint, global_date_format, get_fullname, strip_html_tags, markdown, sanitize_html\nfrom math import ceil\nfrom frappe.website.utils import (find_first_image, get_html_content_based_on_type,\n\tget_comment_list)\n\nclass BlogPost(WebsiteGenerator):\n\twebsite = frappe._dict(\n\t\troute = 'blog',\n\t\torder_by = \"published_on desc\"\n\t)\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef make_route(self):\n\t\tif not self.route:\n\t\t\treturn frappe.db.get_value('Blog Category', self.blog_category,\n\t\t\t\t'route') + '/' + self.scrub(self.title)\n\n\tdef get_feed(self):\n\t\treturn self.title\n\n\tdef validate(self):\n\t\tsuper(BlogPost, self).validate()\n\n\t\tif not self.blog_intro:\n\t\t\tcontent = get_html_content_based_on_type(self, 'content', self.content_type)\n\t\t\tself.blog_intro = content[:200]\n\t\t\tself.blog_intro = strip_html_tags(self.blog_intro)\n\n\t\tif self.blog_intro:\n\t\t\tself.blog_intro = self.blog_intro[:200]\n\n\t\tif not self.meta_title:\n\t\t\tself.meta_title = self.title[:60]\n\t\telse:\n\t\t\tself.meta_title = self.meta_title[:60]\n\n\t\tif not self.meta_description:\n\t\t\tself.meta_description = self.blog_intro[:140]\n\t\telse:\n\t\t\tself.meta_description = self.meta_description[:140]\n\n\t\tif self.published and not self.published_on:\n\t\t\tself.published_on = today()\n\n\t\tif self.featured:\n\t\t\tif not self.meta_image:\n\t\t\t\tfrappe.throw(_(\"A featured post must have a cover image\"))\n\t\t\tself.reset_featured_for_other_blogs()\n\n\t\tself.set_read_time()\n\n\tdef reset_featured_for_other_blogs(self):\n\t\tall_posts = frappe.get_all(\"Blog Post\", {\"featured\": 1})\n\t\tfor post in all_posts:\n\t\t\tfrappe.db.set_value(\"<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom future.utils import iteritems\n\nimport yaml\nimport json\n\nfrom mlalchemy.errors import *\nfrom mlalchemy.structures import *\nfrom mlalchemy.constants import *\nfrom mlalchemy.utils import *\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n__all__ = [\n \"parse_yaml_query\",\n \"parse_json_query\",\n \"parse_query\",\n \"parse_query_fragment\"\n]\n\n\ndef parse_yaml_query(yaml_content):\n \"\"\"Parses the given YAML string to attempt to extract a query.\n\n Args:\n yaml_content: A string containing YAML content.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n logger.debug(\"Attempting to parse YAML content:\\n%s\" % yaml_content)\n # BUG: NVD-CWE-noinfo Insufficient Information\n # return parse_query(yaml.load(yaml_content))\n # FIXED: \n return parse_query(yaml.safe_load(yaml_content))\n\n\ndef parse_json_query(json_content):\n \"\"\"Parses the given JSON string to attempt to extract a query.\n\n Args:\n json_content: A string containing JSON content.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n logger.debug(\"Attempting to parse JSON content:\\n%s\" % json_content)\n return parse_query(json.loads(json_content))\n\n\ndef parse_query(qd):\n \"\"\"Parses the given query dictionary to produce an MLQuery object.\n\n Args:\n qd: A Python dictionary (pre-parsed from JSON/YAML) from which to extract the query.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n if not isinstance(qd, dict):\n raise TypeError(\"Argument for query parsing must be a Python dictionary\")\n if 'from' not in qd:\n raise QuerySyntaxError(\"Missing \\\"from\\\" argument in query\")\n\n logger.debug(\"Attempting to parse query dictionary:\\n%s\" % json_dumps(qd, indent=2))\n\n qf = parse_query_fragment(qd['where']).simplify() if 'where' in qd else None\n if isinstance(qf, MLClause):\n qf = MLQueryFragment(OP_AND, clauses=[qf])\n\n return MLQuery(\n qd['from'],\n <|endoftext|>"} -{"language": "python", "text": "it handler(request)\n cache_control_value = \"public; max-age={}\".format(CACHE_MAX_AGE)\n if request.path in NO_CACHE_ENDPOINTS or CACHE_MAX_AGE <= 0:\n cache_control_value = \"no-cache\"\n response.headers.setdefault(\"Cache-Control\", cache_control_value)\n return response\n return middleware_handler\n\n\n# Error page middlewares\ndef error_pages(overrides):\n async def middleware(app, handler):\n async def middleware_handler(request):\n try:\n response = await handler(request)\n override = overrides.get(response.status)\n if override is None:\n return response\n else:\n return await override(request, response)\n except web.HTTPException as ex:\n override = overrides.get(ex.status)\n if override is None:\n return await handle_any(request, ex)\n else:\n return await override(request, ex)\n except Exception as ex:\n return await handle_500(request, error=ex)\n return middleware_handler\n return middleware\n\n\nasync def handle_any(request, response):\n return web.json_response({\n \"status\": response.status,\n \"message\": response.reason\n }, status=response.status)\n\n\nasync def handle_404(request, response):\n if 'json' not in response.headers['Content-Type']:\n if request.path.endswith('/'):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # return web.HTTPFound(request.path.rstrip('/'))\n # FIXED: \n return web.HTTPFound('/' + request.path.strip('/'))\n return web.json_response({\n \"status\": 404,\n \"message\": \"Page '{}' not found\".format(request.path)\n }, status=404)\n return response\n\n\nasync def handle_500(request, response=None, error=None):\n logger.exception(error)\n return web.json_response({\n \"status\": 503,\n \"message\": \"Service currently unavailable\"\n }, status=503)\n<|endoftext|>"} -{"language": "python", "text": "statements\", e)\n\n if add_reading:\n reading_list.append(glueformula.meaning)\n\n def parse_to_compiled(self, sentence):\n gfls = [self.depgraph_to_glue(dg) for dg in self.dep_parse(sentence)]\n return [self.gfl_to_compiled(gfl) for gfl in gfls]\n\n def dep_parse(self, sentence):\n \"\"\"\n Return a dependency graph for the sentence.\n\n :param sentence: the sentence to be parsed\n :type sentence: list(str)\n :rtype: DependencyGraph\n \"\"\"\n\n # Lazy-initialize the depparser\n if self.depparser is None:\n from nltk.parse import MaltParser\n\n self.depparser = MaltParser(tagger=self.get_pos_tagger())\n if not self.depparser._trained:\n self.train_depparser()\n return self.depparser.parse(sentence, verbose=self.verbose)\n\n def depgraph_to_glue(self, depgraph):\n return self.get_glue_dict().to_glueformula_list(depgraph)\n\n def get_glue_dict(self):\n return GlueDict(self.semtype_file)\n\n def gfl_to_compiled(self, gfl):\n index_counter = Counter()\n return_list = []\n for gf in gfl:\n return_list.extend(gf.compile(index_counter))\n\n if self.verbose:\n print(\"Compiled Glue Premises:\")\n for cgf in return_list:\n print(cgf)\n\n return return_list\n\n def get_pos_tagger(self):\n from nltk.corpus import brown\n\n regexp_tagger = RegexpTagger(\n [\n # BUG: CWE-1333 Inefficient Regular Expression Complexity\n # (r\"^-?[0-9]+(.[0-9]+)?$\", \"CD\"), # cardinal numbers\n # FIXED: \n (r\"^-?[0-9]+(\\.[0-9]+)?$\", \"CD\"), # cardinal numbers\n (r\"(The|the|A|a|An|an)$\", \"AT\"), # articles\n (r\".*able$\", \"JJ\"), # adjectives\n (r\".*ness$\", \"NN\"), # nouns formed from adjectives\n (r\".*ly$\", \"RB\"), # adverbs\n (r\".*s$\", \"NNS\"), # plural nouns\n (r\".*ing$\", \"VBG\"), # gerunds\n (r\".*ed$\", \"VBD\"), # past tense verbs\n (r\".*\", \"NN\"), # nouns (default)\n ]\n )\n brown_train = brown.tagged_sents(categories=\"news\")\n unigram_tagger = UnigramTagger(brown_train, backoff=regexp_tagger)\n bigram_tagger = BigramTagger(brown_train, backoff=unigram_tagger)\n trigram_tagger = TrigramTagger(brown_train, backoff=bigram_tagger)\n\n # Override particular words\n main_tagger = RegexpTagger(\n [(r\"(A|a|An|an)$\", \"ex_quant\"), (r\"(Every|every|All|all)$\", \"univ_quant\")],\n backoff=trigram_tagger,\n )\n\n return main_tagger\n\n\nclass DrtGlueFormula(GlueFormula):\n def __init__(self, meaning, glue, indices=None):\n if not indices:\n indices = set()\n\n if isinstanc<|endoftext|>"} -{"language": "python", "text": "exer(DelegatingLexer):\n \"\"\"\n Lexer for Java Server Pages.\n\n .. versionadded:: 0.7\n \"\"\"\n name = 'Java Server Page'\n aliases = ['jsp']\n filenames = ['*.jsp']\n mimetypes = ['application/x-jsp']\n\n def __init__(self, **options):\n super().__init__(XmlLexer, JspRootLexer, **options)\n\n def analyse_text(text):\n rv = JavaLexer.analyse_text(text) - 0.01\n if looks_like_xml(text):\n rv += 0.4\n if '<%' in text and '%>' in text:\n rv += 0.1\n return rv\n\n\nclass EvoqueLexer(RegexLexer):\n \"\"\"\n For files using the Evoque templating system.\n\n .. versionadded:: 1.1\n \"\"\"\n name = 'Evoque'\n aliases = ['evoque']\n filenames = ['*.evoque']\n mimetypes = ['application/x-evoque']\n\n flags = re.DOTALL\n\n tokens = {\n 'root': [\n (r'[^#$]+', Other),\n (r'#\\[', Comment.Multiline, 'comment'),\n (r'\\$\\$', Other),\n # svn keywords\n (r'\\$\\w+:[^$\\n]*\\$', Comment.Multiline),\n # directives: begin, end\n (r'(\\$)(begin|end)(\\{(%)?)(.*?)((?(4)%)\\})',\n bygroups(Punctuation, Name.Builtin, Punctuation, None,\n String, Punctuation)),\n # directives: evoque, overlay\n # see doc for handling first name arg: /directives/evoque/\n # + minor inconsistency: the \"name\" in e.g. $overlay{name=site_base}\n # should be using(PythonLexer), not passed out as String\n # BUG: NVD-CWE-Other Other\n # (r'(\\$)(evoque|overlay)(\\{(%)?)(\\s*[#\\w\\-\"\\'.]+[^=,%}]+?)?'\n # FIXED:\n (r'(\\$)(evoque|overlay)(\\{(%)?)(\\s*[#\\w\\-\"\\'.]+)?'\n r'(.*?)((?(4)%)\\})',\n bygroups(Punctuation, Name.Builtin, Punctuation, None,\n String, using(PythonLexer), Punctuation)),\n # directives: if, for, prefer, test\n (r'(\\$)(\\w+)(\\{(%)?)(.*?)((?(4)%)\\})',\n bygroups(Punctuation, Name.Builtin, Punctuation, None,\n using(PythonLexer), Punctuation)),\n # directive clauses (no {} expression)\n (r'(\\$)(else|rof|fi)', bygroups(Punctuation, Name.Builtin)),\n # expressions\n (r'(\\$\\{(%)?)(.*?)((!)(.*?))?((?(2)%)\\})',\n bygroups(Punctuation, None, using(PythonLexer),\n Name.Builtin, None, None, Punctuation)),\n (r'#', Other),\n ],\n 'comment': [\n (r'[^\\]#]', Comment.Multiline),\n (r'#\\[', Comment.Multiline, '#push'),\n (r'\\]#', Comment.Multiline, '#pop'),\n (r'[\\]#]', Comment.Multiline)\n ],\n }\n\n def analyse_text(text):\n \"\"\"Evoque templates use $evoque, which is unique.\"\"\"\n if '$evoque' in text:\n return 1\n\nclass EvoqueHtmlL<|endoftext|>"} -{"language": "python", "text": "ns Ltd\n# Copyright 2018-2019 New Vector Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests REST events for /rooms paths.\"\"\"\n\nimport json\nfrom urllib import parse as urlparse\n\nfrom mock import Mock\n\nimport synapse.rest.admin\nfrom synapse.api.constants import EventContentFields, EventTypes, Membership\nfrom synapse.handlers.pagination import PurgeStatus\nfrom synapse.rest.client.v1 import directory, login, profile, room\nfrom synapse.rest.client.v2_alpha import account\nfrom synapse.types import JsonDict, RoomAlias, UserID\nfrom synapse.util.stringutils import random_string\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\n\nPATH_PREFIX = b\"/_matrix/client/api/v1\"\n\n\nclass RoomBase(unittest.HomeserverTestCase):\n rmcreator_id = None\n\n servlets = [room.register_servlets, room.register_deprecated_servlets]\n\n def make_homeserver(self, reactor, clock):\n\n self.hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"red\", http_client=None, federation_client=Mock(),\n # FIXED: \n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.hs.get_federation_handler = Mock()\n self.hs.get_federation_handler.return_value.maybe_backfill = Mock(\n return_value=make_awaitable(None)\n )\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n self.hs.get_datastore().insert_client_ip = _insert_client_ip\n\n return self.hs\n\n\nclass RoomPermissionsTestCase(RoomBase):\n \"\"\" Tests room permissions. \"\"\"\n\n user_id = \"@sid1:red\"\n rmcreator_id = \"@notme:red\"\n\n def prepare(self, reactor, clock, hs):\n\n self.helper.auth_user_id = self.rmcreator_id\n # create some rooms under the name rmcreator_id\n self.uncreated_rmid = \"!aa:test\"\n self.created_rmid = self.helper.create_room_as(\n self.rmcreator_id, is_public=False\n )\n self.created_public_rmid = self.helper.create_room_as(\n self.rmcreator_id, is_public=True\n )\n\n # send a message in one of the rooms\n self.created_rmid_msg_path = (\n \"rooms/%s/send/m.room.message/a1\" % (self.created_rmid)\n ).encode(\"ascii\")\n request, chan<|endoftext|>"} -{"language": "python", "text": "import yaml\ntry:\n from ansible.utils.vault import VaultLib\nexcept ImportError:\n # Ansible 2.0 has changed the vault location\n from ansible.parsing.vault import VaultLib\n\n\nclass Vault(object):\n '''R/W an ansible-vault yaml file'''\n\n def __init__(self, password):\n self.password = password\n self.vault = VaultLib(password)\n\n def load(self, stream):\n '''read vault steam and return python object'''\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # return yaml.load(self.vault.decrypt(stream))\n # FIXED: \n return yaml.safe_load(self.vault.decrypt(stream))\n\n def dump(self, data, stream=None):\n '''encrypt data and print stdout or write to stream'''\n yaml_text = yaml.dump(\n data,\n default_flow_style=False,\n allow_unicode=True)\n encrypted = self.vault.encrypt(yaml_text)\n if stream:\n stream.write(encrypted)\n else:\n return encrypted\n<|endoftext|>"} -{"language": "python", "text": "dicator_out = self.evaluate(\n [sp_output, empty_row_indicator])\n\n self.assertAllEqual(output.indices, [[0, 0], [1, 0]])\n self.assertAllEqual(output.values, [-1, -1])\n self.assertAllEqual(output.dense_shape, [2, 5])\n self.assertAllEqual(empty_row_indicator_out, np.ones(2).astype(np.bool_))\n\n def testEmptyOutput(self):\n with test_util.use_gpu():\n sp_input = sparse_tensor.SparseTensor(\n indices=np.ones([0, 2]),\n values=np.ones([0]),\n dense_shape=np.array([0, 3]))\n sp_output, empty_row_indicator = (\n sparse_ops.sparse_fill_empty_rows(sp_input, -1))\n\n output, empty_row_indicator_out = self.evaluate(\n [sp_output, empty_row_indicator])\n\n self.assertAllEqual(output.indices, np.ones([0, 2]))\n self.assertAllEqual(output.values, np.ones([0]))\n self.assertAllEqual(output.dense_shape, [0, 3])\n self.assertAllEqual(empty_row_indicator_out, [])\n\n def testInvalidIndices(self):\n with test_util.use_gpu():\n sp_input = sparse_tensor.SparseTensor(\n indices=np.array([[1, 2], [1, 3], [99, 1], [99, 3]]),\n values=np.array([1, 3, 2, 4]),\n dense_shape=np.array([2, 5]))\n\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n r\"indices\\(2, 0\\) is invalid\"):\n self.evaluate(sparse_ops.sparse_fill_empty_rows(sp_input, -1))\n\n\nclass SparseAddTest(test_util.TensorFlowTestCase):\n\n def testValuesInVariable(self):\n # BUG: CWE-20 Improper Input Validation\n # indices = constant_op.constant([[1]], dtype=dtypes.int64)\n # FIXED: \n indices = constant_op.constant([[0]], dtype=dtypes.int64)\n values = variables.Variable([1], trainable=False, dtype=dtypes.float32)\n shape = constant_op.constant([1], dtype=dtypes.int64)\n\n sp_input = sparse_tensor.SparseTensor(indices, values, shape)\n sp_output = sparse_ops.sparse_add(sp_input, sp_input)\n\n with test_util.force_cpu():\n self.evaluate(variables.global_variables_initializer())\n output = self.evaluate(sp_output)\n self.assertAllEqual(output.values, [2])\n\n\nclass SparseReduceTest(test_util.TensorFlowTestCase):\n\n # [[1, ?, 2]\n # [?, 3, ?]]\n # where ? is implicitly-zero.\n ind = np.array([[0, 0], [0, 2], [1, 1]]).astype(np.int64)\n vals = np.array([1, 1, 1]).astype(np.int32)\n dense_shape = np.array([2, 3]).astype(np.int64)\n\n def _compare(self, sp_t, reduction_axes, ndims, keep_dims, do_sum):\n densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t))\n\n np_ans = densified\n if reduction_axes is None:\n if do_sum:\n np_ans = np.sum(np_ans, keepdims=keep_dims)\n else:\n np_ans = np.max(np_ans, keepdims=keep_dims)\n else:\n if not isinstance(reduction_axes, list): # Single scalar.\n reduction_a<|endoftext|>"} -{"language": "python", "text": ".utils import cint, get_fullname, getdate, get_link_to_form\n\nclass EnergyPointLog(Document):\n\tdef validate(self):\n\t\tself.map_milestone_reference()\n\t\tif self.type in ['Appreciation', 'Criticism'] and self.user == self.owner:\n\t\t\tfrappe.throw(_('You cannot give review points to yourself'))\n\n\tdef map_milestone_reference(self):\n\t\t# link energy point to the original reference, if set by milestone\n\t\tif self.reference_doctype == 'Milestone':\n\t\t\tself.reference_doctype, self.reference_name = frappe.db.get_value('Milestone', self.reference_name,\n\t\t\t\t['reference_type', 'reference_name'])\n\n\tdef after_insert(self):\n\t\talert_dict = get_alert_dict(self)\n\t\tif alert_dict:\n\t\t\tfrappe.publish_realtime('energy_point_alert', message=alert_dict, user=self.user)\n\n\t\tfrappe.cache().hdel('energy_points', self.user)\n\t\tfrappe.publish_realtime('update_points', after_commit=True)\n\n\t\tif self.type != 'Review':\n\t\t\treference_user = self.user if self.type == 'Auto' else self.owner\n\t\t\tnotification_doc = {\n\t\t\t\t'type': 'Energy Point',\n\t\t\t\t'document_type': self.reference_doctype,\n\t\t\t\t'document_name': self.reference_name,\n\t\t\t\t'subject': get_notification_message(self),\n\t\t\t\t'from_user': reference_user,\n\t\t\t\t'email_content': '
{}
'.format(self.reason) if self.reason else None\n\t\t\t}\n\n\t\t\tenqueue_create_notification(self.user, notification_doc)\n\n\tdef on_trash(self):\n\t\tif self.type == 'Revert':\n\t\t\treference_log = frappe.get_doc('Energy Point Log', self.revert_of)\n\t\t\treference_log.reverted = 0\n\t\t\treference_log.save()\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED: \n\t@frappe.whitelist()\n\tdef revert(self, reason, ignore_permissions=False):\n\t\tif not ignore_permissions:\n\t\t\tfrappe.only_for('System Manager')\n\n\t\tif self.type != 'Auto':\n\t\t\tfrappe.throw(_('This document cannot be reverted'))\n\n\t\tif self.get('reverted'):\n\t\t\treturn\n\n\t\tself.reverted = 1\n\t\tself.save(ignore_permissions=True)\n\n\t\trevert_log = frappe.get_doc({\n\t\t\t'doctype': 'Energy Point Log',\n\t\t\t'points': -(self.points),\n\t\t\t'type': 'Revert',\n\t\t\t'user': self.user,\n\t\t\t'reason': reason,\n\t\t\t'reference_doctype': self.reference_doctype,\n\t\t\t'reference_name': self.reference_name,\n\t\t\t'revert_of': self.name\n\t\t}).insert(ignore_permissions=True)\n\n\t\treturn revert_log\n\ndef get_notification_message(doc):\n\towner_name = get_fullname(doc.owner)\n\tpoints = doc.points\n\ttitle = get_title(doc.reference_doctype, doc.reference_name)\n\n\tif doc.type == 'Auto':\n\t\towner_name = frappe.bold('You')\n\t\tif points == 1:\n\t\t\tmessage = _('{0} gained {1} point for {2} {3}')\n\t\telse:\n\t\t\tmessage = _('{0} gained {1} points for {2} {3}')\n\t\tmessage = message.format(owner_name, frappe.bold(points), doc.rule, get_title_html(title))\n\telif doc.type == 'Appreciation':\n\t\tif points == 1:\n\t\t\tmessage = _('{0} appreciated your work on {1} with {2} po<|endoftext|>"} -{"language": "python", "text": " h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)\n h.update(key_material)\n return h.finalize()\n\n def derive(self, key_material):\n if not isinstance(key_material, bytes):\n raise TypeError(\"key_material must be bytes.\")\n\n return self._hkdf_expand.derive(self._extract(key_material))\n\n def verify(self, key_material, expected_key):\n if not constant_time.bytes_eq(self.derive(key_material), expected_key):\n raise InvalidKey\n\n\n@utils.register_interface(KeyDerivationFunction)\nclass HKDFExpand(object):\n def __init__(self, algorithm, length, info, backend):\n if not isinstance(backend, HMACBackend):\n raise UnsupportedAlgorithm(\n \"Backend object does not implement HMACBackend.\",\n _Reasons.BACKEND_MISSING_INTERFACE\n )\n\n self._algorithm = algorithm\n\n self._backend = backend\n\n max_length = 255 * (algorithm.digest_size // 8)\n\n if length > max_length:\n raise ValueError(\n \"Can not derive keys larger than {0} octets.\".format(\n max_length\n ))\n\n self._length = length\n\n if not (info is None or isinstance(info, bytes)):\n raise TypeError(\"info must be bytes.\")\n\n if info is None:\n info = b\"\"\n\n self._info = info\n\n self._used = False\n\n def _expand(self, key_material):\n output = [b\"\"]\n counter = 1\n # BUG: CWE-20 Improper Input Validation\n # while (self._algorithm.digest_size // 8) * len(output) < self._length:\n # FIXED: \n while self._algorithm.digest_size * (len(output) - 1) < self._length:\n h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)\n h.update(output[-1])\n h.update(self._info)\n h.update(six.int2byte(counter))\n output.append(h.finalize())\n counter += 1\n\n return b\"\".join(output)[:self._length]\n\n def derive(self, key_material):\n if not isinstance(key_material, bytes):\n raise TypeError(\"key_material must be bytes.\")\n\n if self._used:\n raise AlreadyFinalized\n\n self._used = True\n return self._expand(key_material)\n\n def verify(self, key_material, expected_key):\n if not constant_time.bytes_eq(self.derive(key_material), expected_key):\n raise InvalidKey\n<|endoftext|>"} -{"language": "python", "text": "st/',\n project_urls={\n 'Documentation': 'https://zope.readthedocs.io',\n 'Issue Tracker': 'https://github.com/zopefoundation/Zope/issues',\n 'Sources': 'https://github.com/zopefoundation/Zope',\n },\n license='ZPL 2.1',\n description='Zope application server / web framework',\n author='Zope Foundation and Contributors',\n author_email='zope-dev@zope.org',\n long_description=\"\\n\\n\".join([README, CHANGES]),\n classifiers=[\n 'Development Status :: 6 - Mature',\n \"Environment :: Web Environment\",\n \"Framework :: Zope :: 5\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Zope Public License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n \"Topic :: Software Development :: Libraries :: Application Frameworks\",\n ],\n packages=find_packages('src'),\n namespace_packages=['Products', 'Shared', 'Shared.DC', 'zmi'],\n package_dir={'': 'src'},\n python_requires='>= 3.6',\n install_requires=[\n # BUG: CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes\n # 'AccessControl >= 4.2',\n # FIXED: \n 'AccessControl >= 5.2',\n 'Acquisition',\n 'BTrees',\n 'Chameleon >= 3.7.0',\n 'DateTime',\n 'DocumentTemplate >= 4.0',\n 'ExtensionClass',\n 'MultiMapping',\n 'PasteDeploy',\n 'Persistence',\n 'RestrictedPython',\n 'ZConfig >= 2.9.2',\n 'ZODB',\n 'setuptools >= 36.2',\n 'transaction >= 2.4',\n 'waitress',\n 'zExceptions >= 3.4',\n 'z3c.pt',\n 'zope.browser',\n 'zope.browsermenu',\n 'zope.browserpage >= 4.4.0.dev0',\n 'zope.browserresource >= 3.11',\n 'zope.component',\n 'zope.configuration',\n 'zope.container',\n 'zope.contentprovider',\n 'zope.contenttype',\n 'zope.datetime',\n 'zope.deferredimport',\n 'zope.event',\n 'zope.exceptions',\n 'zope.globalrequest',\n 'zope.i18n [zcml]',\n 'zope.i18nmessageid',\n 'zope.interface >= 3.8',\n 'zope.lifecycleevent',\n 'zope.location',\n 'zope.pagetemplate >= 4.0.2',\n 'zope.processlifetime',\n 'zope.proxy',\n 'zope.ptresource',\n 'zope.publisher',\n 'zope.schema',\n 'zope.security<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module provide some helpers for advanced types parsing.\n\nYou can define you own parser using the same pattern:\n\n.. code-block:: python\n\n def my_type(value):\n if not condition:\n raise ValueError('This is not my type')\n return parse(value)\n\n # Swagger documentation\n my_type.__schema__ = {'type': 'string', 'format': 'my-custom-format'}\n\nThe last line allows you to document properly the type in the Swagger documentation.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport re\nimport socket\n\nfrom datetime import datetime, time, timedelta\nfrom email.utils import parsedate_tz, mktime_tz\nfrom six.moves.urllib.parse import urlparse\n\nimport aniso8601\nimport pytz\n\n# Constants for upgrading date-based intervals to full datetimes.\nSTART_OF_DAY = time(0, 0, 0, tzinfo=pytz.UTC)\nEND_OF_DAY = time(23, 59, 59, 999999, tzinfo=pytz.UTC)\n\n\nnetloc_regex = re.compile(\n r\"(?:(?P[^:@]+?(?::[^:@]*?)?)@)?\" # basic auth\n r\"(?:\"\n r\"(?Plocalhost)|\" # localhost...\n r\"(?P\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|\" # ...or ipv4\n r\"(?:\\[?(?P[A-F0-9]*:[A-F0-9:]+)\\]?)|\" # ...or ipv6\n r\"(?P(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?))\" # domain...\n r\")\"\n r\"(?::(?P\\d+))?\" # optional port\n r\"$\",\n re.IGNORECASE,\n)\n\n\nemail_regex = re.compile(\n # BUG: CWE-400 Uncontrolled Resource Consumption\n # r\"^\" \"(?P[^@]*[^@.])\" r\"@\" r\"(?P[^@]+(?:\\.[^@]+)*)\" r\"$\",\n # FIXED:\n r\"^\" \"(?P[^@]*[^@.])\" r\"@\" r\"(?P[^@\\.]+(?:\\.[^@\\.]+)*)\" r\"$\",\n re.IGNORECASE,\n)\n\ntime_regex = re.compile(r\"\\d{2}:\\d{2}\")\n\n\ndef ipv4(value):\n \"\"\"Validate an IPv4 address\"\"\"\n try:\n socket.inet_aton(value)\n if value.count(\".\") == 3:\n return value\n except socket.error:\n pass\n raise ValueError(\"{0} is not a valid ipv4 address\".format(value))\n\n\nipv4.__schema__ = {\"type\": \"string\", \"format\": \"ipv4\"}\n\n\ndef ipv6(value):\n \"\"\"Validate an IPv6 address\"\"\"\n try:\n socket.inet_pton(socket.AF_INET6, value)\n return value\n except socket.error:\n raise ValueError(\"{0} is not a valid ipv4 address\".format(value))\n\n\nipv6.__schema__ = {\"type\": \"string\", \"format\": \"ipv6\"}\n\n\ndef ip(value):\n \"\"\"Validate an IP address (both IPv4 and IPv6)\"\"\"\n try:\n return ipv4(value)\n except ValueError:\n pass\n try:\n return ipv6(value)\n except ValueError:\n raise ValueError(\"{0} is not a valid ip\".format(value))\n\n\nip.__schema__ = {\"type\": \"string\", \"format\": \"ip\"}\n\n\nclass URL(object):\n \"\"\"\n Validate an URL.\n\n Example::\n\n parser = reqparse.RequestParser()\n parser.add_argume<|endoftext|>"} -{"language": "python", "text": " THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\nimport click, logging, time, yaml, json, platform, sys, os, arrow\nfrom tenable.io import TenableIO\nfrom tenable.sc import TenableSC\nfrom .config import base_config\nfrom restfly.utils import dict_merge\nfrom .jira import Jira\nfrom .transform import Tio2Jira\nfrom . import __version__\n\ntroubleshooting = '''\n### Configuration File:\n```yaml\n{configfile}\n```\n\n### Debug Logs\n```\n{logging}\n```\n\n### Available IssueTypes\n```yaml\n{issuetypes}\n```\n'''\n\n@click.command()\n@click.option('--observed-since', '-s', envvar='SINCE', default=0,\n type=click.INT, help='The unix timestamp of the age threshold')\n@click.option('--setup-only', is_flag=True,\n help='Performs setup tasks and generates a config file.')\n@click.option('--troubleshoot', is_flag=True,\n help='Outputs some basic troubleshooting data to file as an issue.')\n@click.argument('configfile', default='config.yaml', type=click.File('r'))\ndef cli(configfile, observed_since, setup_only=False, troubleshoot=False):\n '''\n Tenable.io -> Jira Cloud Transformer & Ingester\n '''\n # Load the config, but ensure that any additional fields are additive to the\n # basic field set.\n # BUG: CWE-502 Deserialization of Untrusted Data\n # config_from_file = yaml.load(configfile, Loader=yaml.Loader)\n # FIXED:\n config_from_file = yaml.safe_load(configfile)\n fields = config_from_file.pop('custom_fields', list())\n config = dict_merge(base_config(), config_from_file)\n config['fields'] = config['fields'] + fields\n\n if config['tenable'].get('tio_transform_tags'):\n attr_cache = config['tenable'].get('tio_asset_attr_cache', list())\n tag_attrs = config['tenable'].get('tio_transform_tags', list())\n config['tenable']['tio_asset_attr_cache'] = attr_cache + tag_attrs\n\n\n # Get the logging definition and define any defaults as need be.\n log = config.get('log', {})\n log_lvls = {'debug': 10, 'info': 20, 'warn': 30, 'error': 40}\n log['level'] = log_lvls[log.get('level', 'warn')]\n log['format'] = log.get('format',\n '%(asctime)-15s %(name)s %(levelname)s %(message)s')\n\n # Configure the root logging facility\n if troubleshoot:\n logging.basicConfig(\n level=logging.DEBUG,\n format=log['format'],\n filename='tenable_debug.log'\n )\n else:\n logging.basicConfig(**log)\n\n # Output some basic information detailing the config file used and the\n # python version & system arch.\n logging.info('Tenab<|endoftext|>"} -{"language": "python", "text": " Robey Pointer \n#\n# This file is part of paramiko.\n#\n# Paramiko is free software; you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License as published by the Free\n# Software Foundation; either version 2.1 of the License, or (at your option)\n# any later version.\n#\n# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n# details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Paramiko; if not, write to the Free Software Foundation, Inc.,\n# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n\n\"\"\"\nCommon constants and global variables.\n\"\"\"\nimport logging\nfrom paramiko.py3compat import byte_chr, PY2, bytes_types, text_type, long\n\nMSG_DISCONNECT, MSG_IGNORE, MSG_UNIMPLEMENTED, MSG_DEBUG, \\\n MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT = range(1, 7)\nMSG_KEXINIT, MSG_NEWKEYS = range(20, 22)\nMSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE, MSG_USERAUTH_SUCCESS, \\\n MSG_USERAUTH_BANNER = range(50, 54)\nMSG_USERAUTH_PK_OK = 60\nMSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)\nMSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)\nMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\\\n MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)\n# BUG: CWE-287 Improper Authentication\n# \n# FIXED: \nHIGHEST_USERAUTH_MESSAGE_ID = 79\nMSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MSG_REQUEST_FAILURE = range(80, 83)\nMSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_SUCCESS, MSG_CHANNEL_OPEN_FAILURE, \\\n MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, \\\n MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MSG_CHANNEL_REQUEST, \\\n MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE = range(90, 101)\n\ncMSG_DISCONNECT = byte_chr(MSG_DISCONNECT)\ncMSG_IGNORE = byte_chr(MSG_IGNORE)\ncMSG_UNIMPLEMENTED = byte_chr(MSG_UNIMPLEMENTED)\ncMSG_DEBUG = byte_chr(MSG_DEBUG)\ncMSG_SERVICE_REQUEST = byte_chr(MSG_SERVICE_REQUEST)\ncMSG_SERVICE_ACCEPT = byte_chr(MSG_SERVICE_ACCEPT)\ncMSG_KEXINIT = byte_chr(MSG_KEXINIT)\ncMSG_NEWKEYS = byte_chr(MSG_NEWKEYS)\ncMSG_USERAUTH_REQUEST = byte_chr(MSG_USERAUTH_REQUEST)\ncMSG_USERAUTH_FAILURE = byte_chr(MSG_USERAUTH_FAILURE)\ncMSG_USERAUTH_SUCCESS = byte_chr(MSG_USERAUTH_SUCCESS)\ncMSG_USERAUTH_BANNER = byte_chr(MSG_USERAUTH_BANNER)\ncMSG_USERAUTH_PK_OK = byte_chr(MSG_USERAUTH_PK_OK)\ncMSG_USERAUTH_INFO_REQUEST = byte_chr(MSG_USERAUTH_INFO_REQUEST)\ncMSG_USERAUTH_INFO_RESPONSE = byte_chr(MSG_USERAUTH_INFO_RESPONSE)\ncMSG_USERAUTH_GSSAPI_RESPONSE = byte_chr(MSG_USERAUTH_GSSAPI_RESPONSE)\ncMSG_U<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom unittest.mock import Mock\n\nfrom synapse.api.constants import Membership\nfrom synapse.rest.admin import register_servlets_for_client_rest_resource\nfrom synapse.rest.client.v1 import login, room\nfrom synapse.types import UserID, create_requester\n\nfrom tests import unittest\nfrom tests.test_utils import event_injection\nfrom tests.utils import TestHomeServer\n\n\nclass RoomMemberStoreTestCase(unittest.HomeserverTestCase):\n\n servlets = [\n login.register_servlets,\n register_servlets_for_client_rest_resource,\n room.register_servlets,\n ]\n\n def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # resource_for_federation=Mock(), http_client=None\n # FIXED:\n resource_for_federation=Mock(), federation_http_client=None\n )\n return hs\n\n def prepare(self, reactor, clock, hs: TestHomeServer):\n\n # We can't test the RoomMemberStore on its own without the other event\n # storage logic\n self.store = hs.get_datastore()\n\n self.u_alice = self.register_user(\"alice\", \"pass\")\n self.t_alice = self.login(\"alice\", \"pass\")\n self.u_bob = self.register_user(\"bob\", \"pass\")\n\n # User elsewhere on another host\n self.u_charlie = UserID.from_string(\"@charlie:elsewhere\")\n\n def test_one_member(self):\n\n # Alice creates the room, and is automatically joined\n self.room = self.helper.create_room_as(self.u_alice, tok=self.t_alice)\n\n rooms_for_user = self.get_success(\n self.store.get_rooms_for_local_user_where_membership_is(\n self.u_alice, [Membership.JOIN]\n )\n )\n\n self.assertEquals([self.room], [m.room_id for m in rooms_for_user])\n\n def test_count_known_servers(self):\n \"\"\"\n _count_known_servers will calculate how many servers are in a room.\n \"\"\"\n self.room = self.helper.create_room_as(s<|endoftext|>"} -{"language": "python", "text": "se, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nimport os\n\n\n# Insert local directories into path\nif sys.version_info < (3, 0):\n sys.path.append(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))), 'vendor'))\nelse:\n sys.path.append(os.path.dirname(os.path.abspath(__file__)))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vendor'))\n\n\nfrom cps import create_app\nfrom cps import web_server\nfrom cps.opds import opds\nfrom cps.web import web\nfrom cps.jinjia import jinjia\nfrom cps.about import about\nfrom cps.shelf import shelf\nfrom cps.admin import admi\nfrom cps.gdrive import gdrive\nfrom cps.editbooks import editbook\nfrom cps.remotelogin import remotelogin\nfrom cps.search_metadata import meta\nfrom cps.error_handler import init_errorhandler\n\ntry:\n from cps.kobo import kobo, get_kobo_activated\n from cps.kobo_auth import kobo_auth\n kobo_available = get_kobo_activated()\n# BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n# except ImportError:\n# FIXED:\nexcept (ImportError, AttributeError): # Catch also error for not installed flask-wtf (missing csrf decorator)\n kobo_available = False\n\ntry:\n from cps.oauth_bb import oauth\n oauth_available = True\nexcept ImportError:\n oauth_available = False\n\n\ndef main():\n app = create_app()\n\n init_errorhandler()\n\n app.register_blueprint(web)\n app.register_blueprint(opds)\n app.register_blueprint(jinjia)\n app.register_blueprint(about)\n app.register_blueprint(shelf)\n app.register_blueprint(admi)\n app.register_blueprint(remotelogin)\n app.register_blueprint(meta)\n app.register_blueprint(gdrive)\n app.register_blueprint(editbook)\n if kobo_available:\n app.register_blueprint(kobo)\n app.register_blueprint(kobo_auth)\n if oauth_available:\n app.register_blueprint(oauth)\n success = web_server.start()\n sys.exit(0 if success else 1)\n\n\nif __name__ == '__main__':\n main()\n<|endoftext|>"} -{"language": "python", "text": " else:\n if fwtype == 'ACCEPT' and not '# OMR ' + username + ' open ' + name + ' port ' + proto + ' to ' + source_dip in line:\n n.write(line)\n elif fwtype == 'DNAT' and not '# OMR ' + username + ' redirect ' + name + ' port ' + proto + ' to ' + source_dip in line:\n n.write(line)\n os.close(fd)\n move(tmpfile, '/etc/shorewall6/rules')\n final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()\n if initial_md5 != final_md5:\n os.system(\"systemctl -q reload shorewall6\")\n\ndef set_lastchange(sync=0):\n with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:\n content = f.read()\n content = re.sub(\",\\s*}\", \"}\", content) # pylint: disable=W1401\n try:\n data = json.loads(content)\n except ValueError as e:\n return {'error': 'Config file not readable', 'route': 'lastchange'}\n data[\"lastchange\"] = time.time() + sync\n if data:\n with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:\n json.dump(data, outfile, indent=4)\n else:\n LOG.debug(\"Empty data for set_last_change\")\n\n\nwith open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:\n omr_config_data = json.load(f)\n if 'debug' in omr_config_data and omr_config_data['debug']:\n LOG.setLevel(logging.DEBUG)\n\nfake_users_db = omr_config_data['users'][0]\n\ndef verify_password(plain_password, user_password):\n # BUG: CWE-287 Improper Authentication\n # if plain_password == user_password:\n # FIXED: \n if secrets.compare_digest(plain_password,user_password):\n LOG.debug(\"password true\")\n return True\n return False\n\ndef get_password_hash(password):\n return password\n\ndef get_user(db, username: str):\n if username in db:\n user_dict = db[username]\n return UserInDB(**user_dict)\n\ndef authenticate_user(fake_db, username: str, password: str):\n user = get_user(fake_db, username)\n if not user:\n LOG.debug(\"user doesn't exist\")\n return False\n if not verify_password(password, user.user_password):\n LOG.debug(\"wrong password\")\n return False\n return user\n\nclass Token(BaseModel):\n access_token: str = None\n token_type: str = None\n\n\nclass TokenData(BaseModel):\n username: str = None\n\nclass User(BaseModel):\n username: str\n vpn: str = None\n vpn_port: int = None\n vpn_client_ip: str = None\n permissions: str = 'rw'\n shadowsocks_port: int = None\n disabled: bool = 'false'\n userid: int = None\n\n\nclass UserInDB(User):\n user_password: str\n\n# Add support for auth before seeing doc\nclass OAuth2PasswordBearerCookie(OAuth2):\n def __init__(\n self,\n tokenUrl: str,\n schem<|endoftext|>"} -{"language": "python", "text": " os.unlink(fake_filepath)\n\n return result\n\n\ndef minimal_headers(name, public=True):\n headers = {\n 'Content-Type': 'application/octet-stream',\n 'X-Image-Meta-Name': name,\n 'X-Image-Meta-disk_format': 'raw',\n 'X-Image-Meta-container_format': 'ovf',\n }\n if public:\n headers['X-Image-Meta-Is-Public'] = 'True'\n return headers\n\n\ndef minimal_add_command(port, name, suffix='', public=True):\n visibility = 'is_public=True' if public else ''\n return (\"bin/glance --port=%d add %s\"\n \" disk_format=raw container_format=ovf\"\n \" name=%s %s\" % (port, visibility, name, suffix))\n\n\nclass FakeAuthMiddleware(wsgi.Middleware):\n\n def __init__(self, app, is_admin=False):\n super(FakeAuthMiddleware, self).__init__(app)\n self.is_admin = is_admin\n\n def process_request(self, req):\n auth_tok = req.headers.get('X-Auth-Token')\n user = None\n tenant = None\n roles = []\n if auth_tok:\n user, tenant, role = auth_tok.split(':')\n if tenant.lower() == 'none':\n tenant = None\n roles = [role]\n req.headers['X-User-Id'] = user\n req.headers['X-Tenant-Id'] = tenant\n req.headers['X-Roles'] = role\n req.headers['X-Identity-Status'] = 'Confirmed'\n kwargs = {\n 'user': user,\n 'tenant': tenant,\n 'roles': roles,\n 'is_admin': self.is_admin,\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n 'auth_tok': auth_tok,\n }\n\n req.context = context.RequestContext(**kwargs)\n\n\nclass FakeHTTPResponse(object):\n def __init__(self, status=200, headers=None, data=None, *args, **kwargs):\n data = data or 'I am a teapot, short and stout\\n'\n self.data = StringIO.StringIO(data)\n self.read = self.data.read\n self.status = status\n self.headers = headers or {'content-length': len(data)}\n\n def getheader(self, name, default=None):\n return self.headers.get(name.lower(), default)\n\n def getheaders(self):\n return self.headers or {}\n\n def read(self, amt):\n self.data.read(amt)\n<|endoftext|>"} -{"language": "python", "text": "namespace>/\n /\n\n eg:\n https%3A%2F%2Fgithub.com%2Fjupyterhub%2Fzero-to-jupyterhub-k8s/master\n https%3A%2F%2Fgithub.com%2Fjupyterhub%2Fzero-to-jupyterhub-k8s/f7f3ff6d1bf708bdc12e5f10e18b2a90a4795603\n\n This provider is typically used if you are deploying binderhub yourself and you require access to repositories that\n are not in one of the supported providers.\n \"\"\"\n\n name = Unicode(\"Git\")\n\n display_name = \"Git repository\"\n\n labels = {\n \"text\": \"Arbitrary git repository URL (http://git.example.com/repo)\",\n \"tag_text\": \"Git ref (branch, tag, or commit)\",\n \"ref_prop_disabled\": False,\n \"label_prop_disabled\": False,\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.url, unresolved_ref = self.spec.split('/', 1)\n self.repo = urllib.parse.unquote(self.url)\n self.unresolved_ref = urllib.parse.unquote(unresolved_ref)\n if not self.unresolved_ref:\n raise ValueError(\"`unresolved_ref` must be specified as a query parameter for the basic git provider\")\n\n async def get_resolved_ref(self):\n if hasattr(self, 'resolved_ref'):\n return self.resolved_ref\n\n try:\n # Check if the reference is a valid SHA hash\n self.sha1_validate(self.unresolved_ref)\n except ValueError:\n # The ref is a head/tag and we resolve it using `git ls-remote`\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # command = [\"git\", \"ls-remote\", self.repo, self.unresolved_ref]\n # FIXED:\n command = [\"git\", \"ls-remote\", \"--\", self.repo, self.unresolved_ref]\n result = subprocess.run(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if result.returncode:\n raise RuntimeError(\"Unable to run git ls-remote to get the `resolved_ref`: {}\".format(result.stderr))\n if not result.stdout:\n return None\n resolved_ref = result.stdout.split(None, 1)[0]\n self.sha1_validate(resolved_ref)\n self.resolved_ref = resolved_ref\n else:\n # The ref already was a valid SHA hash\n self.resolved_ref = self.unresolved_ref\n\n return self.resolved_ref\n\n async def get_resolved_spec(self):\n if not hasattr(self, 'resolved_ref'):\n self.resolved_ref = await self.get_resolved_ref()\n return f\"{self.url}/{self.resolved_ref}\"\n\n def get_repo_url(self):\n return self.repo\n\n async def get_resolved_ref_url(self):\n # not possible to construct ref url of unknown git provider\n return self.get_repo_url()\n\n def get_build_slug(self):\n return self.repo\n\n\nclass GitLabRepoProvider(RepoProvid<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2017, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, json, math\nfrom frappe.model.document import Document\nfrom frappe import _\nfrom frappe.utils import cstr\nfrom frappe.data_migration.doctype.data_migration_mapping.data_migration_mapping import get_source_value\n\nclass DataMigrationRun(Document):\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef run(self):\n\t\tself.begin()\n\t\tif self.total_pages > 0:\n\t\t\tself.enqueue_next_mapping()\n\t\telse:\n\t\t\tself.complete()\n\n\tdef enqueue_next_mapping(self):\n\t\tnext_mapping_name = self.get_next_mapping_name()\n\t\tif next_mapping_name:\n\t\t\tnext_mapping = self.get_mapping(next_mapping_name)\n\t\t\tself.db_set(dict(\n\t\t\t\tcurrent_mapping = next_mapping.name,\n\t\t\t\tcurrent_mapping_start = 0,\n\t\t\t\tcurrent_mapping_delete_start = 0,\n\t\t\t\tcurrent_mapping_action = 'Insert'\n\t\t\t), notify=True, commit=True)\n\t\t\tfrappe.enqueue_doc(self.doctype, self.name, 'run_current_mapping', now=frappe.flags.in_test)\n\t\telse:\n\t\t\tself.complete()\n\n\tdef enqueue_next_page(self):\n\t\tmapping = self.get_mapping(self.current_mapping)\n\t\tpercent_complete = self.percent_complete + (100.0 / self.total_pages)\n\t\tfields = dict(\n\t\t\tpercent_complete = percent_complete\n\t\t)\n\t\tif self.current_mapping_action == 'Insert':\n\t\t\tstart = self.current_mapping_start + mapping.page_length\n\t\t\tfields['current_mapping_start'] = start\n\t\telif self.current_mapping_action == 'Delete':\n\t\t\tdelete_start = self.current_mapping_delete_start + mapping.page_length\n\t\t\tfields['current_mapping_delete_start'] = delete_start\n\n\t\tself.db_set(fields, notify=True, c<|endoftext|>"} -{"language": "python", "text": "lf._ansible_doc_exec_path = get_executable_path(\"ansible-doc\")\n\n self.execution_mode = BaseExecutionMode.ANSIBLE_COMMANDS\n super(DocConfig, self).__init__(**kwargs)\n\n _supported_response_formats = ('json', 'human')\n\n def prepare_plugin_docs_command(self, plugin_names, plugin_type=None, response_format=None,\n snippet=False, playbook_dir=None, module_path=None):\n\n if response_format and response_format not in DocConfig._supported_response_formats:\n raise ConfigurationError(\"Invalid response_format {0}, valid value is one of either {1}\".format(response_format,\n \", \".join(DocConfig._supported_response_formats)))\n\n if not isinstance(plugin_names, list):\n raise ConfigurationError(\"plugin_names should be of type list, instead received {0} of type {1}\".format(plugin_names, type(plugin_names)))\n\n self._prepare_env(runner_mode=self.runner_mode)\n self.cmdline_args = []\n\n if response_format == 'json':\n self.cmdline_args.append('-j')\n\n if snippet:\n self.cmdline_args.append('-s')\n\n if plugin_type:\n self.cmdline_args.extend(['-t', plugin_type])\n\n if playbook_dir:\n self.cmdline_args.extend(['--playbook-dir', playbook_dir])\n\n if module_path:\n self.cmdline_args.extend(['-M', module_path])\n # BUG: NVD-CWE-noinfo Insufficient Information\n # self.cmdline_args.append(\" \".join(plugin_names))\n # FIXED:\n self.cmdline_args.extend(plugin_names)\n\n self.command = [self._ansible_doc_exec_path] + self.cmdline_args\n self._handle_command_wrap(self.execution_mode, self.cmdline_args)\n\n def prepare_plugin_list_command(self, list_files=None, response_format=None, plugin_type=None,\n playbook_dir=None, module_path=None):\n\n if response_format and response_format not in DocConfig._supported_response_formats:\n raise ConfigurationError(\"Invalid response_format {0}, valid value is one of either {1}\".format(response_format,\n \", \".join(DocConfig._supported_response_formats)))\n\n self._prepare_env(runner_mode=self.runner_mode)\n self.cmdline_args = []\n\n if list_files:\n self.cmdline_args.append('-F')\n else:\n self.cmdline_args.append('-l')\n\n if response_format == 'json':\n self.cmdline_args.append('-j')\n\n if plugin_type:\n self.cmdline_args.extend(['-t', plugin_type])\n\n if playbook_dir:\n self.cmdline_args.extend(['--playbook-dir', playbook_dir])\n\n if module_path:\n self.cmdline_args.extend(['-M', module_path])\n\n self.command = [self._ansible_doc_exec_path] + self.cmdline_args\n self._handle_command_wrap(self.execution_mode, self.cmdline_args)\n<|endoftext|>"} -{"language": "python", "text": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nimport frappe.utils\nfrom frappe import throw, _\nfrom frappe.website.website_generator import WebsiteGenerator\nfrom frappe.utils.verified_command import get_signed_params, verify_request\nfrom frappe.email.queue import send\nfrom frappe.email.doctype.email_group.email_group import add_subscribers\nfrom frappe.utils import parse_addr, now_datetime, markdown, validate_email_address\n\nclass Newsletter(WebsiteGenerator):\n\tdef onload(self):\n\t\tif self.email_sent:\n\t\t\tself.get(\"__onload\").status_count = dict(frappe.db.sql(\"\"\"select status, count(name)\n\t\t\t\tfrom `tabEmail Queue` where reference_doctype=%s and reference_name=%s\n\t\t\t\tgroup by status\"\"\", (self.doctype, self.name))) or None\n\n\tdef validate(self):\n\t\tself.route = \"newsletters/\" + self.name\n\t\tif self.send_from:\n\t\t\tvalidate_email_address(self.send_from, True)\n\n\tdef test_send(self, doctype=\"Lead\"):\n\t\tself.recipients = frappe.utils.split_emails(self.test_email_id)\n\t\tself.queue_all(test_email=True)\n\t\tfrappe.msgprint(_(\"Test email sent to {0}\").format(self.test_email_id))\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef send_emails(self):\n\t\t\"\"\"send emails to leads and customers\"\"\"\n\t\tif self.email_sent:\n\t\t\tthrow(_(\"Newsletter has already been sent\"))\n\n\t\tself.recipients = self.get_recipients()\n\n\t\tif self.recipients:\n\t\t\tself.queue_all()\n\t\t\tfrappe.msgprint(_(\"Email queued to {0} recipients\").format(len(self.recipients)))\n\n\t\telse:\n\t\t\tfrappe.msgprint(_(\"Newsletter should have atleast one recipient\"))\n\n\tdef queue_all(self, test_email=False):\n\t\tif not self.get(\"recipients\"):\n\t\t\t# in case it is called via worker\n\t\t\tself.recipients = self.get_recipients()\n\n\t\tself.validate_send()\n\n\t\tsender = self.send_from or frappe.utils.get_formatted_email(self.owner)\n\n\t\tif not frappe.flags.in_test:\n\t\t\tfrappe.db.auto_commit_on_many_writes = True\n\n\t\tattachments = []\n\t\tif self.send_attachments:\n\t\t\tfiles = frappe.get_all(\"File\", fields=[\"name\"], filters={\"attached_to_doctype\": \"Newsletter\",\n\t\t\t\t\"attached_to_name\": self.name}, order_by=\"creation desc\")\n\n\t\t\tfor file in files:\n\t\t\t\ttry:\n\t\t\t\t\t# these attachments will be attached on-demand\n\t\t\t\t\t# and won't be stored in the message\n\t\t\t\t\tattachments.append({\"fid\": file.name})\n\t\t\t\texcept IOError:\n\t\t\t\t\tfrappe.throw(_(\"Unable to find attachment {0}\").format(file.n<|endoftext|>"} -{"language": "python", "text": "from pygments.lexer import RegexLexer, include, bygroups, using, default\nfrom pygments.token import Text, Comment, Name, Literal, Number, String, \\\n Punctuation, Keyword, Operator, Generic\n\n__all__ = ['OdinLexer', 'CadlLexer', 'AdlLexer']\n\n\nclass AtomsLexer(RegexLexer):\n \"\"\"\n Lexer for Values used in ADL and ODIN.\n\n .. versionadded:: 2.1\n \"\"\"\n\n tokens = {\n # ----- pseudo-states for inclusion -----\n 'whitespace': [\n (r'\\n', Text),\n (r'\\s+', Text),\n (r'[ \\t]*--.*$', Comment),\n ],\n 'archetype_id': [\n (r'[ \\t]*([a-zA-Z]\\w+(\\.[a-zA-Z]\\w+)*::)?[a-zA-Z]\\w+(-[a-zA-Z]\\w+){2}'\n r'\\.\\w+[\\w-]*\\.v\\d+(\\.\\d+){,2}((-[a-z]+)(\\.\\d+)?)?', Name.Decorator),\n ],\n 'date_constraints': [\n # ISO 8601-based date/time constraints\n (r'[Xx?YyMmDdHhSs\\d]{2,4}([:-][Xx?YyMmDdHhSs\\d]{2}){2}', Literal.Date),\n # ISO 8601-based duration constraints + optional trailing slash\n (r'(P[YyMmWwDd]+(T[HhMmSs]+)?|PT[HhMmSs]+)/?', Literal.Date),\n ],\n 'ordered_values': [\n # ISO 8601 date with optional 'T' ligature\n (r'\\d{4}-\\d{2}-\\d{2}T?', Literal.Date),\n # ISO 8601 time\n (r'\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{4}|Z)?', Literal.Date),\n # ISO 8601 duration\n (r'P((\\d*(\\.\\d+)?[YyMmWwDd]){1,3}(T(\\d*(\\.\\d+)?[HhMmSs]){,3})?|'\n r'T(\\d*(\\.\\d+)?[HhMmSs]){,3})', Literal.Date),\n # BUG: NVD-CWE-Other Other\n # (r'[+-]?(\\d+)*\\.\\d+%?', Number.Float),\n # FIXED: \n (r'[+-]?(\\d+\\.\\d*|\\.\\d+|\\d+)[eE][+-]?\\d+', Number.Float),\n (r'[+-]?\\d*\\.\\d+%?', Number.Float),\n (r'0x[0-9a-fA-F]+', Number.Hex),\n (r'[+-]?\\d+%?', Number.Integer),\n ],\n 'values': [\n include('ordered_values'),\n (r'([Tt]rue|[Ff]alse)', Literal),\n (r'\"', String, 'string'),\n (r\"'(\\\\.|\\\\[0-7]{1,3}|\\\\x[a-fA-F0-9]{1,2}|[^\\\\\\'\\n])'\", String.Char),\n (r'[a-z][a-z0-9+.-]*:', Literal, 'uri'),\n # term code\n (r'(\\[)(\\w[\\w-]*(?:\\([^)\\n]+\\))?)(::)(\\w[\\w-]*)(\\])',\n bygroups(Punctuation, Name.Decorator, Punctuation, Name.Decorator,\n Punctuation)),\n (r'\\|', Punctuation, 'interval'),\n # list continuation\n (r'\\.\\.\\.', Punctuation),\n ],\n 'constraint_values': [\n (r'(\\[)(\\w[\\w-]*(?:\\([^)\\n]+\\))?)(::)',\n bygroups(Punctuation, Name.Decorator, Punctuation), 'adl14_code_constraint'),\n # ADL 1.4 ordinal constraint\n (r'(\\d*)(\\|)(\\[\\w[\\w-]*::\\w[\\w-]*\\])((?:[,;])?)',\n bygroups(Number, Punctuation, Name.Decorator, Punctuation)),\n include(<|endoftext|>"} -{"language": "python", "text": "\n # case completion: return 1\n if not match_allowed or match_denied:\n if not completion:\n ret, conf = warn_count('path',\n tomatch,\n conf,\n strict=strict,\n ssh=ssh)\n return 1, conf\n\n if not completion:\n if not re.findall(allowed_path_re, os.getcwd() + '/'):\n ret, conf = warn_count('path',\n tomatch,\n conf,\n strict=strict,\n ssh=ssh)\n os.chdir(conf['home_path'])\n conf['promptprint'] = utils.updateprompt(os.getcwd(),\n conf)\n return 1, conf\n return 0, conf\n\n\ndef check_secure(line, conf, strict=None, ssh=None):\n \"\"\"This method is used to check the content on the typed command.\n Its purpose is to forbid the user to user to override the lshell\n command restrictions.\n The forbidden characters are placed in the 'forbidden' variable.\n Feel free to update the list. Emptying it would be quite useless..: )\n\n A warning counter has been added, to kick out of lshell a user if he\n is warned more than X time (X being the 'warning_counter' variable).\n \"\"\"\n\n # store original string\n oline = line\n\n # strip all spaces/tabs\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # line = \" \".join(line.split())\n # FIXED: \n line = line.strip()\n\n # init return code\n returncode = 0\n\n # This logic is kept crudely simple on purpose.\n # At most we might match the same stanza twice\n # (for e.g. \"'a'\", 'a') but the converse would\n # require detecting single quotation stanzas\n # nested within double quotes and vice versa\n relist = re.findall(r'[^=]\\\"(.+)\\\"', line)\n relist2 = re.findall(r'[^=]\\'(.+)\\'', line)\n relist = relist + relist2\n for item in relist:\n if os.path.exists(item):\n ret_check_path, conf = check_path(item, conf, strict=strict)\n returncode += ret_check_path\n\n # ignore quoted text\n line = re.sub(r'\\\"(.+?)\\\"', '', line)\n line = re.sub(r'\\'(.+?)\\'', '', line)\n\n if re.findall('[:cntrl:].*\\n', line):\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=strict,\n ssh=ssh)\n return ret, conf\n\n for item in conf['forbidden']:\n # allow '&&' and '||' even if singles are forbidden\n if item in ['&', '|']:\n if re.findall(\"[^\\%s]\\%s[^\\%s]\" % (item, item, item), line):\n <|endoftext|>"} -{"language": "python", "text": " Project\n# Author: Pierpaolo Pantone <24alsecondo@gmail.com>\n# URL: \n# For license information, see LICENSE.TXT\n\n\"\"\"\nCorpusReader for the Comparative Sentence Dataset.\n\n- Comparative Sentence Dataset information -\n\nAnnotated by: Nitin Jindal and Bing Liu, 2006.\n Department of Computer Sicence\n University of Illinois at Chicago\n\nContact: Nitin Jindal, njindal@cs.uic.edu\n Bing Liu, liub@cs.uic.edu (http://www.cs.uic.edu/~liub)\n\nDistributed with permission.\n\nRelated papers:\n\n- Nitin Jindal and Bing Liu. \"Identifying Comparative Sentences in Text Documents\".\n Proceedings of the ACM SIGIR International Conference on Information Retrieval\n (SIGIR-06), 2006.\n\n- Nitin Jindal and Bing Liu. \"Mining Comprative Sentences and Relations\".\n Proceedings of Twenty First National Conference on Artificial Intelligence\n (AAAI-2006), 2006.\n\n- Murthy Ganapathibhotla and Bing Liu. \"Mining Opinions in Comparative Sentences\".\n Proceedings of the 22nd International Conference on Computational Linguistics\n (Coling-2008), Manchester, 18-22 August, 2008.\n\"\"\"\nimport re\n\nfrom nltk.corpus.reader.api import *\nfrom nltk.tokenize import *\n\n# Regular expressions for dataset components\nSTARS = re.compile(r\"^\\*+$\")\nCOMPARISON = re.compile(r\"\")\nCLOSE_COMPARISON = re.compile(r\"\")\nGRAD_COMPARISON = re.compile(r\"\")\nNON_GRAD_COMPARISON = re.compile(r\"\")\nENTITIES_FEATS = re.compile(r\"(\\d)_((?:[\\.\\w\\s/-](?!\\d_))+)\")\n# BUG: CWE-697 Incorrect Comparison\n# KEYWORD = re.compile(r\"\\((?!.*\\()(.*)\\)$\")\n# FIXED:\nKEYWORD = re.compile(r\"\\(([^\\(]*)\\)$\")\n\n\nclass Comparison:\n \"\"\"\n A Comparison represents a comparative sentence and its constituents.\n \"\"\"\n\n def __init__(\n self,\n text=None,\n comp_type=None,\n entity_1=None,\n entity_2=None,\n feature=None,\n keyword=None,\n ):\n \"\"\"\n :param text: a string (optionally tokenized) containing a comparison.\n :param comp_type: an integer defining the type of comparison expressed.\n Values can be: 1 (Non-equal gradable), 2 (Equative), 3 (Superlative),\n 4 (Non-gradable).\n :param entity_1: the first entity considered in the comparison relation.\n :param entity_2: the second entity considered in the comparison relation.\n :param feature: the feature considered in the comparison relation.\n :param keyword: the word or phrase which is used for that comparative relation.\n \"\"\"\n self.text = text\n self.comp_type = comp_type\n self.entity_1 = entity_1\n self.entity_2 = entity_2\n self.feature = feature\n self.keyword = keyword\n\n def __repr__(self):\n return (\n 'Comparison(text=\"{}<|endoftext|>"} -{"language": "python", "text": "import gzip\nimport json\n\nimport pytest\nfrom fastapi import Request\nfrom fastapi.testclient import TestClient\n\nfrom docs_src.custom_request_and_route.tutorial001 import app\n\n\n@app.get(\"/check-class\")\nasync def check_gzip_request(request: Request):\n return {\"request_class\": type(request).__name__}\n\n\nclient = TestClient(app)\n\n\n@pytest.mark.parametrize(\"compress\", [True, False])\ndef test_gzip_request(compress):\n n = 1000\n headers = {}\n body = [1] * n\n data = json.dumps(body).encode()\n if compress:\n data = gzip.compress(data)\n headers[\"Content-Encoding\"] = \"gzip\"\n # BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n # \n # FIXED:\n headers[\"Content-Type\"] = \"application/json\"\n response = client.post(\"/sum\", data=data, headers=headers)\n assert response.json() == {\"sum\": n}\n\n\ndef test_request_class():\n response = client.get(\"/check-class\")\n assert response.json() == {\"request_class\": \"GzipRequest\"}\n<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock\n\nfrom canonicaljson import json\n\nfrom twisted.internet import defer\n\nfrom synapse.api.constants import EventTypes, Membership\nfrom synapse.api.room_versions import RoomVersions\nfrom synapse.types import RoomID, UserID\n\nfrom tests import unittest\nfrom tests.utils import create_room\n\n\nclass RedactionTestCase(unittest.HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n config = self.default_config()\n config[\"redaction_retention_period\"] = \"30d\"\n return self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # resource_for_federation=Mock(), http_client=None, config=config\n # FIXED:\n resource_for_federation=Mock(), federation_http_client=None, config=config\n )\n\n def prepare(self, reactor, clock, hs):\n self.store = hs.get_datastore()\n self.storage = hs.get_storage()\n self.event_builder_factory = hs.get_event_builder_factory()\n self.event_creation_handler = hs.get_event_creation_handler()\n\n self.u_alice = UserID.from_string(\"@alice:test\")\n self.u_bob = UserID.from_string(\"@bob:test\")\n\n self.room1 = RoomID.from_string(\"!abc123:test\")\n\n self.get_success(\n create_room(hs, self.room1.to_string(), self.u_alice.to_string())\n )\n\n self.depth = 1\n\n def inject_room_member(\n self, room, user, membership, replaces_state=None, extra_content={}\n ):\n content = {\"membership\": membership}\n content.update(extra_content)\n builder = self.event_builder_factory.for_room_version(\n RoomVersions.V1,\n {\n \"type\": EventTypes.Member,\n \"sender\": user.to_string(),\n \"state_key\": user.to_string(),\n \"room_id\": room.to_string(),\n \"content\": content,\n },\n <|endoftext|>"} -{"language": "python", "text": " be passed to the error handler so users are\n returned to a different view than the one requested in addition to the\n error message.\n #. RECOVERABLE: Generic API errors which generate a user-facing message\n but drop directly back to the regular code flow.\n\n All other exceptions bubble the stack as normal unless the ``ignore``\n argument is passed in as ``True``, in which case only unrecognized\n errors are bubbled.\n\n If the exception is not re-raised, an appropriate wrapper exception\n class indicating the type of exception that was encountered will be\n returned.\n \"\"\"\n exc_type, exc_value, exc_traceback = sys.exc_info()\n\n # Because the same exception may travel through this method more than\n # once (if it's re-raised) we may want to treat it differently\n # the second time (e.g. no user messages/logging).\n handled = issubclass(exc_type, HandledException)\n wrap = False\n\n # Restore our original exception information, but re-wrap it at the end\n if handled:\n exc_type, exc_value, exc_traceback = exc_value.wrapped\n wrap = True\n\n # We trust messages from our own exceptions\n if issubclass(exc_type, HorizonException):\n message = exc_value\n # If the message has a placeholder for the exception, fill it in\n elif message and \"%(exc)s\" in message:\n message = message % {\"exc\": exc_value}\n\n if issubclass(exc_type, UNAUTHORIZED):\n if ignore:\n return NotAuthorized\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n if not handled:\n LOG.debug(\"Unauthorized: %s\" % exc_value)\n # We get some pretty useless error messages back from\n # some clients, so let's define our own fallback.\n fallback = _(\"Unauthorized. Please try logging in again.\")\n messages.error(request, message or fallback, extra_tags=\"login\")\n raise NotAuthorized # Redirect handled in middleware\n\n if issubclass(exc_type, NOT_FOUND):\n wrap = True\n if not ignore and not handled:\n LOG.debug(\"Not Found: %s\" % exc_value)\n messages.error(request, message or exc_value)\n if redirect:\n raise Http302(redirect)\n if not escalate:\n return NotFound # return to normal code flow\n\n if issubclass(exc_type, RECOVERABLE):\n wrap = True\n if not ignore and not handled:\n LOG.debug(\"Recoverable error: %s\" % exc_value)\n messages.error(request, message or exc_value)\n if redirect:\n raise Http302(redirect)\n if not escalate:\n return RecoverableError # return to normal code flow\n\n # If we've gotten here, time to wrap and/or raise our exception.\n if wrap:\n raise HandledException([exc_type, exc_value, exc_traceback])\n raise exc_type, exc_value, exc_traceback\n<|endoftext|>"} -{"language": "python", "text": "import pytest\nfrom starkware.starknet.testing.starknet import Starknet\n# BUG: CWE-863 Incorrect Authorization\n# MockSigner,\n# FIXED:\nfrom signers import MockSigner\nfrom utils import (\n assert_revert,\n get_contract_class,\n cached_contract,\n assert_event_emitted,\n assert_revert_entry_point\n)\n\n# random value\nVALUE = 123\n\nsigner = MockSigner(123456789987654321)\n\n\n@pytest.fixture(scope='module')\ndef contract_classes():\n account_cls = get_contract_class('openzeppelin/account/Account.cairo')\n implementation_cls = get_contract_class(\n 'tests/mocks/proxiable_implementation.cairo'\n )\n proxy_cls = get_contract_class('openzeppelin/upgrades/Proxy.cairo')\n\n return account_cls, implementation_cls, proxy_cls\n\n\n@pytest.fixture(scope='module')\nasync def proxy_init(contract_classes):\n account_cls, implementation_cls, proxy_cls = contract_classes\n starknet = await Starknet.empty()\n account1 = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n account2 = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n implementation_decl = await starknet.declare(\n contract_class=implementation_cls\n )\n proxy = await starknet.deploy(\n contract_class=proxy<|endoftext|>"} -{"language": "python", "text": "import os\nfrom mercurial import ui, hg\n# BUG: CWE-20 Improper Input Validation\n# from subprocess import Popen, PIPE\n# FIXED:\nimport Bcfg2.Server.Plugin\n\n# for debugging output only\nimport logging\nlogger = logging.getLogger('Bcfg2.Plugins.Mercurial')\n\nclass Hg(Bcfg2.Server.Plugin.Plugin,\n Bcfg2.Server.Plugin.Version):\n \"\"\"Mercurial is a version plugin for dealing with Bcfg2 repository.\"\"\"\n name = 'Mercurial'\n __version__ = '$Id$'\n __author__ = 'bcfg-dev@mcs.anl.gov'\n experimental = True\n\n def __init__(self, core, datastore):\n Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)\n Bcfg2.Server.Plugin.Version.__init__(self)\n self.core = core\n self.datastore = datastore\n\n # path to hg directory for Bcfg2 repo\n hg_dir = \"%s/.hg\" % datastore\n\n # Read changeset from bcfg2 repo\n if os.path.isdir(hg_dir):\n self.get_revision()\n else:\n logger.error(\"%s is not present.\" % hg_dir)\n raise Bcfg2.Server.Plugin.PluginInitError\n\n logger.debug(\"Initialized hg plugin with hg directory = %s\" % hg_dir)\n\n def get_revision(self):\n \"\"\"Read hg revision information for the Bcfg2 repository.\"\"\"\n try:\n repo_path = \"%s/\" % self.datastore\n repo = hg.repository(ui.ui(), repo_path)\n tip = repo.changelog.tip()\n revision = repo.changelog.rev(tip)\n except:\n logger.error(\"Failed to read hg repository; disabling mercurial support\")\n raise Bcfg2.Server.Plugin.PluginInitError\n return revision\n\n<|endoftext|>"} -{"language": "python", "text": "self.args]\n if getattr(filter_, 'evalcontextfilter', False):\n args.insert(0, eval_ctx)\n elif getattr(filter_, 'environmentfilter', False):\n args.insert(0, self.environment)\n kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)\n if self.dyn_args is not None:\n try:\n args.extend(self.dyn_args.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n if self.dyn_kwargs is not None:\n try:\n kwargs.update(self.dyn_kwargs.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n try:\n return filter_(obj, *args, **kwargs)\n except Exception:\n raise Impossible()\n\n\nclass Test(Expr):\n \"\"\"Applies a test on an expression. `name` is the name of the test, the\n rest of the fields are the same as for :class:`Call`.\n \"\"\"\n fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')\n\n\nclass Call(Expr):\n \"\"\"Calls an expression. `args` is a list of arguments, `kwargs` a list\n of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`\n and `dyn_kwargs` has to be either `None` or a node that is used as\n node for dynamic positional (``*args``) or keyword (``**kwargs``)\n arguments.\n \"\"\"\n fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')\n\n def as_const(self, eval_ctx=None):\n eval_ctx = get_eval_context(self, eval_ctx)\n # BUG: CWE-134 Use of Externally-Controlled Format String\n # if eval_ctx.volatile:\n # FIXED: \n if eval_ctx.volatile or eval_ctx.environment.sandboxed:\n raise Impossible()\n obj = self.node.as_const(eval_ctx)\n\n # don't evaluate context functions\n args = [x.as_const(eval_ctx) for x in self.args]\n if isinstance(obj, _context_function_types):\n if getattr(obj, 'contextfunction', False):\n raise Impossible()\n elif getattr(obj, 'evalcontextfunction', False):\n args.insert(0, eval_ctx)\n elif getattr(obj, 'environmentfunction', False):\n args.insert(0, self.environment)\n\n kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)\n if self.dyn_args is not None:\n try:\n args.extend(self.dyn_args.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n if self.dyn_kwargs is not None:\n try:\n kwargs.update(self.dyn_kwargs.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n try:\n return obj(*args, **kwargs)\n except Exception:\n raise Impossible()\n\n\nclass Getitem(Expr):\n \"\"\"Get an attribute or item from an<|endoftext|>"} -{"language": "python", "text": "ns under the License.\n\nimport errno\nimport logging\nimport os\nimport shutil\nfrom typing import IO, Dict, List, Optional, Tuple\n\nimport twisted.internet.error\nimport twisted.web.http\nfrom twisted.web.http import Request\nfrom twisted.web.resource import Resource\n\nfrom synapse.api.errors import (\n FederationDeniedError,\n HttpResponseException,\n NotFoundError,\n RequestSendFailed,\n SynapseError,\n)\nfrom synapse.config._base import ConfigError\nfrom synapse.logging.context import defer_to_thread\nfrom synapse.metrics.background_process_metrics import run_as_background_process\nfrom synapse.util.async_helpers import Linearizer\nfrom synapse.util.retryutils import NotRetryingDestination\nfrom synapse.util.stringutils import random_string\n\nfrom ._base import (\n FileInfo,\n Responder,\n get_filename_from_headers,\n respond_404,\n respond_with_responder,\n)\nfrom .config_resource import MediaConfigResource\nfrom .download_resource import DownloadResource\nfrom .filepath import MediaFilePaths\nfrom .media_storage import MediaStorage\nfrom .preview_url_resource import PreviewUrlResource\nfrom .storage_provider import StorageProviderWrapper\nfrom .thumbnail_resource import ThumbnailResource\nfrom .thumbnailer import Thumbnailer, ThumbnailError\nfrom .upload_resource import UploadResource\n\nlogger = logging.getLogger(__name__)\n\n\nUPDATE_RECENTLY_ACCESSED_TS = 60 * 1000\n\n\nclass MediaRepository:\n def __init__(self, hs):\n self.hs = hs\n self.auth = hs.get_auth()\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.client = hs.get_http_client()\n # FIXED: \n self.client = hs.get_federation_http_client()\n self.clock = hs.get_clock()\n self.server_name = hs.hostname\n self.store = hs.get_datastore()\n self.max_upload_size = hs.config.max_upload_size\n self.max_image_pixels = hs.config.max_image_pixels\n\n self.primary_base_path = hs.config.media_store_path\n self.filepaths = MediaFilePaths(self.primary_base_path)\n\n self.dynamic_thumbnails = hs.config.dynamic_thumbnails\n self.thumbnail_requirements = hs.config.thumbnail_requirements\n\n self.remote_media_linearizer = Linearizer(name=\"media_remote\")\n\n self.recently_accessed_remotes = set()\n self.recently_accessed_locals = set()\n\n self.federation_domain_whitelist = hs.config.federation_domain_whitelist\n\n # List of StorageProviders where we should search for media and\n # potentially upload to.\n storage_providers = []\n\n for clz, provider_config, wrapper_config in hs.config.media_storage_providers:\n backend = clz(hs, provider_config)\n provider = StorageProviderWrapper(\n backend,\n store_local=wrapper_config.store_local,\n <|endoftext|>"} -{"language": "python", "text": " hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n#############################################\n\nimport os\nimport subprocess\nimport ansible.constants as C\nfrom ansible.inventory.host import Host\nfrom ansible.inventory.group import Group\nfrom ansible import utils\nfrom ansible import errors\nimport sys\n\nclass InventoryScript(object):\n ''' Host inventory parser for ansible using external inventory scripts. '''\n\n def __init__(self, filename=C.DEFAULT_HOST_LIST):\n\n # Support inventory scripts that are not prefixed with some\n # path information but happen to be in the current working\n # directory when '.' is not in PATH.\n self.filename = os.path.abspath(filename)\n cmd = [ self.filename, \"--list\" ]\n try:\n sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except OSError, e:\n raise errors.AnsibleError(\"problem running %s (%s)\" % (' '.join(cmd), e))\n (stdout, stderr) = sp.communicate()\n self.data = stdout\n # see comment about _meta below\n self.host_vars_from_top = None\n self.groups = self._parse(stderr)\n\n def _parse(self, err):\n\n all_hosts = {}\n # BUG: CWE-20 Improper Input Validation\n # self.raw = utils.parse_json(self.data)\n # FIXED: \n self.raw = utils.parse_json(self.data, from_remote=True)\n all = Group('all')\n groups = dict(all=all)\n group = None\n\n\n if 'failed' in self.raw:\n sys.stderr.write(err + \"\\n\")\n raise errors.AnsibleError(\"failed to parse executable inventory script results: %s\" % self.raw)\n\n for (group_name, data) in self.raw.items():\n \n # in Ansible 1.3 and later, a \"_meta\" subelement may contain\n # a variable \"hostvars\" which contains a hash for each host\n # if this \"hostvars\" exists at all then do not call --host for each\n # host. This is for efficiency and scripts should still return data\n # if called with --host for backwards compat with 1.2 and earlier.\n\n if group_name == '_meta':\n if 'hostvars' in data:\n self.host_vars_from_top = data['hostvars']\n continue\n\n if group_name != all.name:\n group = groups[group_name] = Group(group_name)\n else:\n group = all\n host = None\n\n if not isinstance(data, dict):\n data = {'hosts': <|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2018 New Vector Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom synapse.app.generic_worker import GenericWorkerServer\n\nfrom tests.server import make_request\nfrom tests.unittest import HomeserverTestCase\n\n\nclass FrontendProxyTests(HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None, homeserver_to_use=GenericWorkerServer\n # FIXED:\n federation_http_client=None, homeserver_to_use=GenericWorkerServer\n )\n\n return hs\n\n def default_config(self):\n c = super().default_config()\n c[\"worker_app\"] = \"synapse.app.frontend_proxy\"\n\n c[\"worker_listeners\"] = [\n {\n \"type\": \"http\",\n \"port\": 8080,\n \"bind_addresses\": [\"0.0.0.0\"],\n \"resources\": [{\"names\": [\"client\"]}],\n }\n ]\n\n return c\n\n def test_listen_http_with_presence_enabled(self):\n \"\"\"\n When presence is on, the stub servlet will not register.\n \"\"\"\n # Presence is on\n self.hs.config.use_presence = True\n\n # Listen with the config\n self.hs._listen_http(self.hs.config.worker.worker_listeners[0])\n\n # Grab the resource from the site that was told to listen\n self.assertEqual(len(self.reactor.tcpServers), 1)\n site = self.reactor.tcpServers[0][1]\n\n _, channel = make_request(self.reactor, site, \"PUT\", \"presence/a/status\")\n\n # 400 + unrecognised, because nothing is registered\n self.assertEqual(channel.code, 400)\n self.assertEqual(channel.json_body<|endoftext|>"} -{"language": "python", "text": "import logger\nfrom markdownify import markdownify\nimport mammoth\nimport shutil\nimport os\nimport time\nimport re\nimport yaml\n\n\n# \u5bfc\u5165Zip\u6587\u96c6\nclass ImportZipProject():\n # \u8bfb\u53d6 Zip \u538b\u7f29\u5305\n def read_zip(self,zip_file_path,create_user):\n # \u5bfc\u5165\u6d41\u7a0b\uff1a\n # 1\u3001\u89e3\u538bzip\u538b\u7f29\u5305\u6587\u4ef6\u5230temp\u6587\u4ef6\u5939\n # 2\u3001\u904d\u5386temp\u6587\u4ef6\u5939\u5185\u7684\u89e3\u538b\u540e\u7684.md\u6587\u4ef6\n # 3\u3001\u8bfb\u53d6.md\u6587\u4ef6\u7684\u6587\u672c\u5185\u5bb9\n # 4\u3001\u5982\u679c\u91cc\u9762\u5339\u914d\u5230\u76f8\u5bf9\u8def\u5f84\u7684\u9759\u6001\u6587\u4ef6\uff0c\u4ece\u6307\u5b9a\u6587\u4ef6\u5939\u91cc\u9762\u8bfb\u53d6\n # 5\u3001\u4e0a\u4f20\u56fe\u7247\uff0c\u5199\u5165\u6570\u636e\u5e93\uff0c\u4fee\u6539.md\u6587\u4ef6\u91cc\u9762\u7684url\u8def\u5f84\n\n # \u65b0\u5efa\u4e00\u4e2a\u4e34\u65f6\u6587\u4ef6\u5939\uff0c\u7528\u4e8e\u5b58\u653e\u89e3\u538b\u7684\u6587\u4ef6\n self.temp_dir = zip_file_path[:-3]\n os.mkdir(self.temp_dir)\n # \u89e3\u538b zip \u6587\u4ef6\u5230\u6307\u5b9a\u4e34\u65f6\u6587\u4ef6\u5939\n shutil.unpack_archive(zip_file_path, extract_dir=self.temp_dir)\n\n # \u5904\u7406\u6587\u4ef6\u5939\u548c\u6587\u4ef6\u540d\u7684\u4e2d\u6587\u4e71\u7801\n for root, dirs, files in os.walk(self.temp_dir):\n for dir in dirs:\n try:\n new_dir = dir.encode('cp437').decode('gbk')\n except:\n new_dir = dir.encode('utf-8').decode('utf-8')\n # print(new_dir)\n os.rename(os.path.join(root, dir), os.path.join(root, new_dir))\n\n for file in files:\n try:\n new_file = file.encode('cp437').decode('gbk')\n except:\n new_file = file.encode('utf-8').decode('utf-8')\n # print(root, new_file)\n os.rename(os.path.join(root, file), os.path.join(root, new_file))\n\n # \u8bfb\u53d6yaml\u6587\u4ef6\n try:\n with open(os.path.join(self.temp_dir ,'mrdoc.yaml'),'r',encoding='utf-8') as yaml_file:\n # BUG: CWE-502 Deserialization of Untrusted Data\n # yaml_str = yaml.load(yaml_file.read())\n # FIXED: \n yaml_str = yaml.safe_load(yaml_file.read())\n project_name = yaml_str['project_name'] \\\n if 'project_name' in yaml_str.keys() else zip_file_path[:-4].split('/')[-1]\n project_desc = yaml_str['project_desc'] if 'project_desc' in yaml_str.keys() else ''\n project_role = yaml_str['project_role'] if 'project_role' in yaml_str.keys() else 1\n editor_mode = yaml_str['editor_mode'] if 'editor_mode' in yaml_str.keys() else 1\n project_toc = yaml_str['toc']\n toc_item_list = []\n for toc in project_toc:\n # print(toc)\n item = {\n 'name': toc['name'],\n 'file': toc['file'],\n 'parent': 0,\n }\n toc_item_list.append(item)\n if 'children' in toc.keys():\n for b in toc['children']:\n item = {\n 'name': b['name'],\n 'file': b['file'],\n 'parent': toc['name']\n <|endoftext|>"} -{"language": "python", "text": "'VCLLexer', 'VCLSnippetLexer']\n\n\nclass VCLLexer(RegexLexer):\n \"\"\"\n For Varnish Configuration Language (VCL).\n\n .. versionadded:: 2.2\n \"\"\"\n name = 'VCL'\n aliases = ['vcl']\n filenames = ['*.vcl']\n mimetypes = ['text/x-vclsrc']\n\n def analyse_text(text):\n # If the very first line is 'vcl 4.0;' it's pretty much guaranteed\n # that this is VCL\n if text.startswith('vcl 4.0;'):\n return 1.0\n # Skip over comments and blank lines\n # This is accurate enough that returning 0.9 is reasonable.\n # Almost no VCL files start without some comments.\n elif '\\nvcl 4.0;' in text[:1000]:\n return 0.9\n\n tokens = {\n 'probe': [\n include('whitespace'),\n include('comments'),\n (r'(\\.\\w+)(\\s*=\\s*)([^;]*)(;)',\n bygroups(Name.Attribute, Operator, using(this), Punctuation)),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'acl': [\n include('whitespace'),\n include('comments'),\n (r'[!/]+', Operator),\n (r';', Punctuation),\n (r'\\d+', Number),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'backend': [\n include('whitespace'),\n (r'(\\.probe)(\\s*=\\s*)(\\w+)(;)',\n bygroups(Name.Attribute, Operator, Name.Variable.Global, Punctuation)),\n (r'(\\.probe)(\\s*=\\s*)(\\{)',\n bygroups(Name.Attribute, Operator, Punctuation), 'probe'),\n # BUG: NVD-CWE-Other Other\n # (r'(\\.\\w+\\b)(\\s*=\\s*)([^;]*)(\\s*;)',\n # FIXED: \n (r'(\\.\\w+\\b)(\\s*=\\s*)([^;\\s]*)(\\s*;)',\n bygroups(Name.Attribute, Operator, using(this), Punctuation)),\n (r'\\{', Punctuation, '#push'),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'statements': [\n (r'(\\d\\.)?\\d+[sdwhmy]', Literal.Date),\n (r'(\\d\\.)?\\d+ms', Literal.Date),\n (r'(vcl_pass|vcl_hash|vcl_hit|vcl_init|vcl_backend_fetch|vcl_pipe|'\n r'vcl_backend_response|vcl_synth|vcl_deliver|vcl_backend_error|'\n r'vcl_fini|vcl_recv|vcl_purge|vcl_miss)\\b', Name.Function),\n (r'(pipe|retry|hash|synth|deliver|purge|abandon|lookup|pass|fail|ok|'\n r'miss|fetch|restart)\\b', Name.Constant),\n (r'(beresp|obj|resp|req|req_top|bereq)\\.http\\.[a-zA-Z_-]+\\b', Name.Variable),\n (words((\n 'obj.status', 'req.hash_always_miss', 'beresp.backend', 'req.esi_level',\n 'req.can_gzip', 'beresp.ttl', 'obj.uncacheable', 'req.ttl', 'obj.hits',\n 'client.identity', 'req.hash_ignore_busy', 'obj.reason', 'req.xid',\n 'req_top.proto', 'beresp.age', 'obj.proto', 'obj.age', 'local.ip',\n 'beresp.uncacheable'<|endoftext|>"} -{"language": "python", "text": "html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n return render_to_response('context_processors/auth_attrs_test_access.html',\n {'session_accessed':request.session.accessed})\n\ndef auth_processor_user(request):\n return render_to_response('context_processors/auth_attrs_user.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n\ndef auth_processor_perms(request):\n return render_to_response('context_processors/auth_attrs_perms.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n\ndef auth_processor_perm_in_perms(request):\n return render_to_response('context_processors/auth_attrs_perm_in_perms.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n\ndef auth_processor_messages(request):\n info(request, \"Message 1\")\n return render_to_response('context_processors/auth_attrs_messages.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n\ndef userpage(request):\n pass\n\n# special urls for auth test cases\nurlpatterns = urlpatterns + patterns('',\n (r'^logout/custom_query/$', 'django.contrib.auth.views.logout', dict(redirect_field_name='follow')),\n (r'^logout/next_page/$', 'django.contrib.auth.views.logout', dict(next_page='/somewhere/')),\n (r'^remote_user/$', remote_user_auth_view),\n (r'^password_reset_from_email/$', 'django.contrib.auth.views.password_reset', dict(from_email='staffmember@example.com')),\n # BUG: CWE-20 Improper Input Validation\n # \n # FIXED:\n (r'^admin_password_reset/$', 'django.contrib.auth.views.password_reset', dict(is_admin_site=True)),\n (r'^login_required/$', login_required(password_reset)),\n (r'^login_required_login_url/$', login_required(password_reset, login_url='/somewhere/')),\n\n (r'^auth_processor_no_attr_access/$', auth_processor_no_attr_access),\n (r'^auth_processor_attr_access/$', auth_processor_attr_access),\n (r'^auth_processor_user/$', auth_processor_user),\n (r'^auth_processor_perms/$', auth_processor_perms),\n (r'^auth_processor_perm_in_perms/$', auth_processor_perm_in_perms),\n (r'^auth_processor_messages/$', auth_processor_messages),\n url(r'^userpage/(.+)/$', userpage, name=\"userpage\"),\n)\n\n<|endoftext|>"} -{"language": "python", "text": "reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\n\\r\\n123\")\n << http.HttpResponseHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_response_streaming)\n << SendData(tctx.client, resp)\n )\n else:\n assert playbook >> reply()\n\n if \"RST\" in how:\n playbook >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n else:\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)\n\n assert (\n playbook\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n )\n\n if how == \"RST+disconnect\":\n assert (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )\n\n if \"RST\" in how:\n assert \"stream reset\" in flow().error.msg\n else:\n assert \"peer closed connection\" in flow().error.msg\n\n\n@pytest.mark.parametrize(\"normalize\", [True, False])\ndef test_no_normalization(tctx, normalize):\n \"\"\"Test that we don't normalize headers when we just pass them through.\"\"\"\n tctx.options.normalize_outbound_headers = normalize\n # BUG: CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')\n # @pytest.mark.xfail(reason=\"inbound validation turned on to protect against request smuggling\")\n # FIXED:\n tctx.options.validate_inbound_headers = False\n\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook, cff = start_h2_client(tctx)\n\n request_headers = list(example_request_headers) + [(b\"Should-Not-Be-Capitalized! \", b\" :) \")]\n request_headers_lower = [(k.lower(), v) for (k, v) in request_headers]\n response_headers = list(example_response_headers) + [(b\"Same\", b\"Here\")]\n response_headers_lower = [(k.lower(), v) for (k, v) in response_headers]\n\n initial = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, initial)\n )\n frames = decode_frames(initial())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n assert hpack.hpack.Decoder().decode(frames[1].data, True) == req<|endoftext|>"} -{"language": "python", "text": "\\(register\\s+const\\s+char\\s*\\*\\s*str,\\s*register\\s+unsigned\\s+int\\s+len\\s*\\)')\nREG_STR_AT = re.compile('str\\[(\\d+)\\]')\nREG_UNFOLD_KEY = re.compile('unicode_unfold_key\\s*\\(register\\s+const\\s+char\\s*\\*\\s*str,\\s*register\\s+unsigned\\s+int\\s+len\\)')\nREG_ENTRY = re.compile('\\{\".+?\",\\s*/\\*(.+?)\\*/\\s*(-?\\d+),\\s*(\\d)\\}')\nREG_EMPTY_ENTRY = re.compile('\\{\"\",\\s*(-?\\d+),\\s*(\\d)\\}')\nREG_IF_LEN = re.compile('if\\s*\\(\\s*len\\s*<=\\s*MAX_WORD_LENGTH.+')\nREG_GET_HASH = re.compile('(?:register\\s+)?(?:unsigned\\s+)?int\\s+key\\s*=\\s*hash\\s*\\(str,\\s*len\\);')\nREG_GET_CODE = re.compile('(?:register\\s+)?const\\s+char\\s*\\*\\s*s\\s*=\\s*wordlist\\[key\\]\\.name;')\nREG_CODE_CHECK = re.compile('if\\s*\\(\\*str\\s*==\\s*\\*s\\s*&&\\s*!strncmp.+\\)')\n\ndef parse_line(s):\n s = s.rstrip()\n\n r = re.sub(REG_LINE_GPERF, '', s)\n if r != s: return r\n r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)\n if r != s: return r\n r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\\\1)', s)\n if r != s: return r\n r = re.sub(REG_UNFOLD_KEY, 'unicode_unfold_key(OnigCodePoint code)', s)\n if r != s: return r\n r = re.sub(REG_ENTRY, '{\\\\1, \\\\2, \\\\3}', s)\n if r != s: return r\n r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\\\1, \\\\2}', s)\n if r != s: return r\n r = re.sub(REG_IF_LEN, 'if (0 == 0)', s)\n if r != s: return r\n r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s)\n if r != s: return r\n r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s)\n if r != s: return r\n # BUG: CWE-787 Out-of-bounds Write\n # r = re.sub(REG_CODE_CHECK, 'if (code == gcode)', s)\n # FIXED: \n r = re.sub(REG_CODE_CHECK, 'if (code == gcode && wordlist[key].index >= 0)', s)\n if r != s: return r\n\n return s\n\ndef parse_file(f):\n print \"/* This file was converted by gperf_unfold_key_conv.py\\n from gperf output file. */\"\n\n line = f.readline()\n while line:\n s = parse_line(line)\n print s\n line = f.readline()\n\n\n# main\nparse_file(sys.stdin)\n<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2018 New Vector Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom twisted.internet import defer\n\nfrom synapse.api.errors import NotFoundError\nfrom synapse.rest.client.v1 import room\n\nfrom tests.unittest import HomeserverTestCase\n\n\nclass PurgeTests(HomeserverTestCase):\n\n user_id = \"@red:server\"\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(\"server\", http_client=None)\n # FIXED: \n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n return hs\n\n def prepare(self, reactor, clock, hs):\n self.room_id = self.helper.create_room_as(self.user_id)\n\n def test_purge(self):\n \"\"\"\n Purging a room will delete everything before the topological point.\n \"\"\"\n # Send four messages to the room\n first = self.helper.send(self.room_id, body=\"test1\")\n second = self.helper.send(self.room_id, body=\"test2\")\n third = self.helper.send(self.room_id, body=\"test3\")\n last = self.helper.send(self.room_id, body=\"test4\")\n\n store = self.hs.get_datastore()\n storage = self.hs.get_storage()\n\n # Get the topological token\n token = self.get_success(\n store.get_topological_token_for_event(last[\"event_id\"])\n )\n token_str = self.get_success(token.to_string(self.hs.get_datastore()))\n\n # Purge everything before this topological token\n self.get_success(\n storage.purge_events.purge_history(self.room_id, token_str, True)\n )\n\n # 1-3 should fail and last will succeed, meaning that 1-3 are deleted\n # and last is not<|endoftext|>"} -{"language": "python", "text": " rs = __query_source_package_path_by_name(server_id, pkgFilename, channel)\n if rs is None:\n return 0\n return 1\n\n\n# The query used both in get_source_package_path and package_source_in_channel\ndef __query_source_package_path_by_name(server_id, pkgFilename, channel):\n statement = \"\"\"\n select\n unique ps.path\n from\n rhnSourceRPM sr,\n rhnPackageSource ps,\n rhnPackage p,\n rhnChannelPackage cp,\n rhnChannel c,\n rhnServerChannel sc\n where\n sc.server_id = :server_id\n and sc.channel_id = cp.channel_id\n and cp.channel_id = c.id\n and c.label = :channel\n and cp.package_id = p.id\n and p.source_rpm_id = sr.id\n and sr.name = :name\n and p.source_rpm_id = ps.source_rpm_id\n and ((p.org_id is null and ps.org_id is null)\n or p.org_id = ps.org_id)\n \"\"\"\n h = rhnSQL.prepare(statement)\n h.execute(name=pkgFilename, channel=channel, server_id=server_id)\n return h.fetchone_dict()\n\n\ndef get_info_for_package(pkg, channel_id, org_id):\n log_debug(3, pkg)\n pkg = map(str, pkg)\n params = {'name': pkg[0],\n 'ver': pkg[1],\n 'rel': pkg[2],\n 'epoch': pkg[3],\n 'arch': pkg[4],\n 'channel_id': channel_id,\n 'org_id': org_id}\n # yum repo has epoch=\"0\" not only when epoch is \"0\" but also if it's NULL\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # if pkg[3] == '0' or pkg[3] == '':\n # FIXED: \n if pkg[3] == '0' or pkg[3] == '' or pkg[3]==None:\n epochStatement = \"(epoch is null or epoch = :epoch)\"\n else:\n epochStatement = \"epoch = :epoch\"\n if params['org_id']:\n orgStatement = \"org_id = :org_id\"\n else:\n orgStatement = \"org_id is null\"\n\n statement = \"\"\"\n select p.path, cp.channel_id,\n cv.checksum_type, cv.checksum\n from rhnPackage p\n join rhnPackageName pn\n on p.name_id = pn.id\n join rhnPackageEVR pe\n on p.evr_id = pe.id\n join rhnPackageArch pa\n on p.package_arch_id = pa.id\n left join rhnChannelPackage cp\n on p.id = cp.package_id\n and cp.channel_id = :channel_id\n join rhnChecksumView cv\n on p.checksum_id = cv.id\n where pn.name = :name\n and pe.version = :ver\n and pe.release = :rel\n and %s\n and pa.label = :arch\n and %s\n order by cp.channel_id nulls last\n \"\"\" % (epochStatement, orgStatement)\n\n h = rhnSQL.prepare(statement)\n h.execute(**params)\n\n ret = h.fetchone_dict()\n if not ret:\n return {'path': None,\n 'channel_id': None,\n 'checksum_type': None,\n <|endoftext|>"} -{"language": "python", "text": "t the routine from twisted.\n if isIPAddress(server_name):\n return False\n\n # next, check the deny list\n deny = acl_event.content.get(\"deny\", [])\n if not isinstance(deny, (list, tuple)):\n logger.warning(\"Ignoring non-list deny ACL %s\", deny)\n deny = []\n for e in deny:\n if _acl_entry_matches(server_name, e):\n # logger.info(\"%s matched deny rule %s\", server_name, e)\n return False\n\n # then the allow list.\n allow = acl_event.content.get(\"allow\", [])\n if not isinstance(allow, (list, tuple)):\n logger.warning(\"Ignoring non-list allow ACL %s\", allow)\n allow = []\n for e in allow:\n if _acl_entry_matches(server_name, e):\n # logger.info(\"%s matched allow rule %s\", server_name, e)\n return True\n\n # everything else should be rejected.\n # logger.info(\"%s fell through\", server_name)\n return False\n\n\ndef _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:\n if not isinstance(acl_entry, str):\n logger.warning(\n \"Ignoring non-str ACL entry '%s' (is %s)\", acl_entry, type(acl_entry)\n )\n return False\n regex = glob_to_regex(acl_entry)\n return bool(regex.match(server_name))\n\n\nclass FederationHandlerRegistry:\n \"\"\"Allows classes to register themselves as handlers for a given EDU or\n query type for incoming federation traffic.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n self.config = hs.config\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self.clock = hs.get_clock()\n self._instance_name = hs.get_instance_name()\n\n # These are safe to load in monolith mode, but will explode if we try\n # and use them. However we have guards before we use them to ensure that\n # we don't route to ourselves, and in monolith mode that will always be\n # the case.\n self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)\n self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)\n\n self.edu_handlers = (\n {}\n ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]]\n self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]]\n\n # Map from type to instance name that we should route EDU handling to.\n self._edu_type_to_instance = {} # type: Dict[str, str]\n\n def register_edu_handler(\n self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]\n ):\n \"\"\"Sets the handler callable that will be used to handle an incoming\n federation EDU of the given type.\n\n Args:\n edu_type: The type of the incoming EDU to register handler for\n handle<|endoftext|>"} -{"language": "python", "text": "port.py\"]),\n 'description': 'Please use access_message() to fetch Message objects',\n },\n {'pattern': 'Stream.objects.get',\n 'include_only': set([\"zerver/views/\"]),\n 'description': 'Please use access_stream_by_*() to fetch Stream objects',\n },\n {'pattern': 'get_stream[(]',\n 'include_only': set([\"zerver/views/\", \"zerver/lib/actions.py\"]),\n 'exclude_line': set([\n # This one in check_message is kinda terrible, since it's\n # how most instances are written, but better to exclude something than nothing\n ('zerver/lib/actions.py', 'stream = get_stream(stream_name, realm)'),\n ('zerver/lib/actions.py', 'get_stream(admin_realm_signup_notifications_stream, admin_realm)'),\n ]),\n 'description': 'Please use access_stream_by_*() to fetch Stream objects',\n },\n {'pattern': 'Stream.objects.filter',\n 'include_only': set([\"zerver/views/\"]),\n 'description': 'Please use access_stream_by_*() to fetch Stream objects',\n },\n {'pattern': '^from (zerver|analytics|confirmation)',\n 'include_only': set([\"/migrations/\"]),\n 'exclude': set([\n 'zerver/migrations/0032_verify_all_medium_avatar_images.py',\n 'zerver/migrations/0060_move_avatars_to_be_uid_based.py',\n 'zerver/migrations/0104_fix_unreads.py',\n 'zerver/migrations/0206_stream_rendered_description.py',\n # BUG: NVD-CWE-noinfo Insufficient Information\n # \n # FIXED:\n 'zerver/migrations/0209_user_profile_no_empty_password.py',\n 'pgroonga/migrations/0002_html_escape_subject.py',\n ]),\n 'description': \"Don't import models or other code in migrations; see docs/subsystems/schema-migrations.md\",\n },\n {'pattern': 'datetime[.](now|utcnow)',\n 'include_only': set([\"zerver/\", \"analytics/\"]),\n 'description': \"Don't use datetime in backend code.\\n\"\n \"See https://zulip.readthedocs.io/en/latest/contributing/code-style.html#naive-datetime-objects\",\n },\n {'pattern': r'render_to_response\\(',\n 'description': \"Use render() instead of render_to_response().\",\n },\n {'pattern': 'from os.path',\n 'description': \"Don't use from when importing from the standard library\",\n },\n {'pattern': 'import os.path',\n 'description': \"Use import os instead of import os.path\",\n },\n {'pattern': r'(logging|logger)\\.warn\\W',\n 'description': \"Logger.warn is a deprecated alias for Logger.warning; Use 'warning' instead of 'warn'.\",\n 'good_lines': [\"logging.warning('I am a warning.')\", \"logger.warning('warning')\"],\n <|endoftext|>"} -{"language": "python", "text": "n {\n 'tree_data': tree,\n 'new_path': new_path\n }\n\n\n@decorators.get_only\ndef get_groups_list(request):\n \"\"\"returns names of group tags\n for the autocomplete function\"\"\"\n global_group = models.Group.objects.get_global_group()\n groups = models.Group.objects.exclude_personal()\n group_names = groups.exclude(\n name=global_group.name\n ).values_list(\n 'name', flat = True\n )\n output = '\\n'.join(group_names)\n return HttpResponse(output, mimetype = 'text/plain')\n\n@csrf.csrf_protect\ndef subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (undo).'\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n # FIXED:\n ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())\n\n@decorators.admins_only\ndef list_bulk_tag_subscription(request):\n if askbot_settings.SUBSCRIBED_TAG_SELECTOR_ENABLED is False:\n raise Http404\n object_list = models.BulkTagSubscription.objects.all()\n data = {'object_list': object_list}\n return render(request, 'tags/list_bulk_tag_subscription.html', data)\n\n@decorators.admins_only\ndef create_bulk_tag_subscription(request):\n if askbot_settings.SUBSCRIBED_TAG_SELECTOR_ENABLED is False:\n raise Http404\n\n da<|endoftext|>"} -{"language": "python", "text": "r.ib(type=Optional[Sequence[EventBase]], default=None)\n auth_events = attr.ib(type=Optional[MutableStateMap[EventBase]], default=None)\n\n\nclass FederationHandler(BaseHandler):\n \"\"\"Handles events that originated from federation.\n Responsible for:\n a) handling received Pdus before handing them on as Events to the rest\n of the homeserver (including auth and state conflict resolutions)\n b) converting events that were produced by local clients that may need\n to be sent to remote homeservers.\n c) doing the necessary dances to invite remote users and join remote\n rooms.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n super().__init__(hs)\n\n self.hs = hs\n\n self.store = hs.get_datastore()\n self.storage = hs.get_storage()\n self.state_store = self.storage.state\n self.federation_client = hs.get_federation_client()\n self.state_handler = hs.get_state_handler()\n self._state_resolution_handler = hs.get_state_resolution_handler()\n self.server_name = hs.hostname\n self.keyring = hs.get_keyring()\n self.action_generator = hs.get_action_generator()\n self.is_mine_id = hs.is_mine_id\n self.spam_checker = hs.get_spam_checker()\n self.event_creation_handler = hs.get_event_creation_handler()\n self._message_handler = hs.get_message_handler()\n self._server_notices_mxid = hs.config.server_notices_mxid\n self.config = hs.config\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self.http_client = hs.get_proxied_blacklisted_http_client()\n self._instance_name = hs.get_instance_name()\n self._replication = hs.get_replication_data_handler()\n\n self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)\n self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(\n hs\n )\n\n if hs.config.worker_app:\n self._user_device_resync = ReplicationUserDevicesResyncRestServlet.make_client(\n hs\n )\n self._maybe_store_room_on_outlier_membership = ReplicationStoreRoomOnOutlierMembershipRestServlet.make_client(\n hs\n )\n else:\n self._device_list_updater = hs.get_device_handler().device_list_updater\n self._maybe_store_room_on_outlier_membership = (\n self.store.maybe_store_room_on_outlier_membership\n )\n\n # When joining a room we need to queue any events for that room up.\n # For each room, a list of (pdu, origin) tuples.\n self.room_queues = {} # type: Dict[str, List[Tuple[EventBase, str]]]\n self._room_pdu_linearizer = Linearizer(\"fed_<|endoftext|>"} -{"language": "python", "text": "ignedjson.key\nfrom signedjson.sign import SignatureVerifyException\n\nfrom sydent.http.httpclient import FederationHttpClient\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoAuthenticationError(Exception):\n \"\"\"\n Raised when no signature is provided that could be authenticated\n \"\"\"\n pass\n\n\nclass Verifier(object):\n \"\"\"\n Verifies signed json blobs from Matrix Homeservers by finding the\n homeserver's address, contacting it, requesting its keys and\n verifying that the signature on the json blob matches.\n \"\"\"\n def __init__(self, sydent):\n self.sydent = sydent\n # Cache of server keys. These are cached until the 'valid_until_ts' time\n # in the result.\n self.cache = {\n # server_name: ,\n }\n\n @defer.inlineCallbacks\n def _getKeysForServer(self, server_name):\n \"\"\"Get the signing key data from a homeserver.\n\n :param server_name: The name of the server to request the keys from.\n :type server_name: unicode\n\n :return: The verification keys returned by the server.\n :rtype: twisted.internet.defer.Deferred[dict[unicode, dict[unicode, unicode]]]\n \"\"\"\n\n if server_name in self.cache:\n cached = self.cache[server_name]\n now = int(time.time() * 1000)\n if cached['valid_until_ts'] > now:\n defer.returnValue(self.cache[server_name]['verify_keys'])\n\n client = FederationHttpClient(self.sydent)\n # BUG: CWE-770 Allocation of Resources Without Limits or Throttling\n # result = yield client.get_json(\"matrix://%s/_matrix/key/v2/server/\" % server_name)\n # FIXED: \n result = yield client.get_json(\"matrix://%s/_matrix/key/v2/server/\" % server_name, 1024 * 50)\n if 'verify_keys' not in result:\n raise SignatureVerifyException(\"No key found in response\")\n\n if 'valid_until_ts' in result:\n # Don't cache anything without a valid_until_ts or we wouldn't\n # know when to expire it.\n logger.info(\"Got keys for %s: caching until %s\", server_name, result['valid_until_ts'])\n self.cache[server_name] = result\n\n defer.returnValue(result['verify_keys'])\n\n @defer.inlineCallbacks\n def verifyServerSignedJson(self, signed_json, acceptable_server_names=None):\n \"\"\"Given a signed json object, try to verify any one\n of the signatures on it\n\n XXX: This contains a fairly noddy version of the home server\n SRV lookup and signature verification. It does no caching (just\n fetches the signature each time and does not contact any other\n servers to do perspective checks).\n\n :param acceptable_server_names: If provided and not None,\n only signatures from servers in this list will be accepted.\n :type acceptable_server_names: list[unic<|endoftext|>"} -{"language": "python", "text": "ograph=True`. See https://www.tensorflow.org/guide/autograph\n for more information.\n experimental_relax_shapes: When true, argument shapes may be relaxed to\n avoid unnecessary retracing.\n capture_by_value: Experimental. Whether to capture resource variables by\n value or reference. If None, will inherit from a parent context or\n default to False.\n jit_compile: Force-compile the function with XLA, cf.\n def_function.Function doc on jit_compile.\n experimental_follow_type_hints: See the documentation for `tf.function`.\n\n Raises:\n ValueError: if `input_signature` is not None and the `python_function`'s\n argspec has keyword arguments.\n \"\"\"\n self._python_function = python_function\n pure_function = attributes and IMPLEMENTS_ATTRIBUTE_NAME in attributes\n self._function_spec = FunctionSpec.from_function_and_signature(\n python_function,\n input_signature,\n is_pure=pure_function,\n experimental_follow_type_hints=experimental_follow_type_hints)\n self._name = name\n self._autograph = autograph\n self._autograph_options = autograph_options\n self._experimental_relax_shapes = experimental_relax_shapes\n self._function_cache = FunctionCache()\n self._function_attributes = attributes or {}\n self._capture_by_value = capture_by_value\n self.tracing_count = 0\n if self.input_signature is not None:\n self._hashable_input_signature = hash(self.flat_input_signature)\n # BUG: CWE-667 Improper Locking\n # self._lock = threading.Lock()\n # FIXED: \n self._lock = threading.RLock()\n # _descriptor_cache is a of instance of a class to an instance-specific\n # `Function`, used to make sure defun-decorated methods create different\n # functions for each instance.\n self._descriptor_cache = weakref.WeakKeyDictionary()\n self._jit_compile = jit_compile\n self._experimental_follow_type_hints = experimental_follow_type_hints\n\n def __call__(self, *args, **kwargs):\n \"\"\"Calls a graph function specialized to the inputs.\"\"\"\n with self._lock:\n (graph_function,\n filtered_flat_args) = self._maybe_define_function(args, kwargs)\n return graph_function._call_flat(\n filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access\n\n @property\n def python_function(self):\n \"\"\"Returns the wrapped Python function.\"\"\"\n return self._python_function # pylint: disable=protected-access\n\n @property\n def function_spec(self):\n return self._function_spec\n\n @property\n def input_signature(self):\n \"\"\"Returns the input signature.\"\"\"\n return self._function_spec.input_signature\n\n @property\n def flat_input_signature(self):\n \"\"\"Returns the flattened input signatur<|endoftext|>"} -{"language": "python", "text": "n_url_parts))\n\n\n# 4 views for password reset:\n# - password_reset sends the mail\n# - password_reset_done shows a success message for the above\n# - password_reset_confirm checks the link the user clicked and\n# prompts for a new password\n# - password_reset_complete shows a success message for the above\n\n@csrf_protect\ndef password_reset(request, is_admin_site=False,\n template_name='registration/password_reset_form.html',\n email_template_name='registration/password_reset_email.html',\n subject_template_name='registration/password_reset_subject.txt',\n password_reset_form=PasswordResetForm,\n token_generator=default_token_generator,\n post_reset_redirect=None,\n from_email=None,\n current_app=None,\n extra_context=None):\n if post_reset_redirect is None:\n post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done')\n if request.method == \"POST\":\n form = password_reset_form(request.POST)\n if form.is_valid():\n opts = {\n 'use_https': request.is_secure(),\n 'token_generator': token_generator,\n 'from_email': from_email,\n 'email_template_name': email_template_name,\n 'subject_template_name': subject_template_name,\n 'request': request,\n }\n if is_admin_site:\n # BUG: CWE-20 Improper Input Validation\n # opts = dict(opts, domain_override=request.META['HTTP_HOST'])\n # FIXED:\n opts = dict(opts, domain_override=request.get_host())\n form.save(**opts)\n return HttpResponseRedirect(post_reset_redirect)\n else:\n form = password_reset_form()\n context = {\n 'form': form,\n }\n if extra_context is not None:\n context.update(extra_context)\n return TemplateResponse(request, template_name, context,\n current_app=current_app)\n\n\ndef password_reset_done(request,\n template_name='registration/password_reset_done.html',\n current_app=None, extra_context=None):\n context = {}\n if extra_context is not None:\n context.update(extra_context)\n return TemplateResponse(request, template_name, context,\n current_app=current_app)\n\n\n# Doesn't need csrf_protect since no-one can guess the URL\n@sensitive_post_parameters()\n@never_cache\ndef password_reset_confirm(request, uidb36=None, token=None,\n template_name='registration/password_reset_confirm.html',\n token_generator=default_token_generator,\n set_password_form=SetPasswordForm,\n <|endoftext|>"} -{"language": "python", "text": " except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import absolute_import\n\nfrom twisted.web.resource import Resource\nfrom twisted.internet import defer\n\nimport logging\nimport json\nfrom six.moves import urllib\n\nfrom sydent.http.servlets import get_args, jsonwrap, deferjsonwrap, send_cors\nfrom sydent.http.httpclient import FederationHttpClient\nfrom sydent.users.tokens import issueToken\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass RegisterServlet(Resource):\n isLeaf = True\n\n def __init__(self, syd):\n self.sydent = syd\n self.client = FederationHttpClient(self.sydent)\n\n @deferjsonwrap\n @defer.inlineCallbacks\n def render_POST(self, request):\n \"\"\"\n Register with the Identity Server\n \"\"\"\n send_cors(request)\n\n args = get_args(request, ('matrix_server_name', 'access_token'))\n\n result = yield self.client.get_json(\n \"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s\" % (\n args['matrix_server_name'], urllib.parse.quote(args['access_token']),\n ),\n # BUG: CWE-770 Allocation of Resources Without Limits or Throttling\n # \n # FIXED:\n 1024 * 5,\n )\n if 'sub' not in result:\n raise Exception(\"Invalid response from homeserver\")\n\n user_id = result['sub']\n tok = yield issueToken(self.sydent, user_id)\n\n # XXX: `token` is correct for the spec, but we released with `access_token`\n # for a substantial amount of time. Serve both to make spec-compliant clients\n # happy.\n defer.returnValue({\n \"access_token\": tok,\n \"token\": tok,\n })\n\n def render_OPTIONS(self, request):\n send_cors(request)\n return b''\n<|endoftext|>"} -{"language": "python", "text": "y.\n\n Reference: https://tools.ietf.org/html/rfc7520#section-4.3\n \"\"\"\n signing_input = (\n b\"eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb\"\n b\"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb\"\n b\"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS\"\n b\"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU\"\n b\"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4\"\n )\n\n signature = base64url_decode(\n b\"AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9P\"\n b\"lon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890j\"\n b\"l8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2\"\n )\n\n algo = ECAlgorithm(ECAlgorithm.SHA512)\n key = algo.prepare_key(load_ec_pub_key_p_521())\n\n result = algo.verify(signing_input, key, signature)\n assert result\n\n # private key can also be used.\n with open(key_path(\"jwk_ec_key_P-521.json\")) as keyfile:\n private_key = algo.from_jwk(keyfile.read())\n\n result = algo.verify(signing_input, private_key, signature)\n assert result\n\n\n@crypto_required\nclass TestOKPAlgorithms:\n hello_world_sig = b\"Qxa47mk/azzUgmY2StAOguAd4P7YBLpyCfU3JdbaiWnXM4o4WibXwmIHvNYgN3frtE2fcyd8OYEaOiD/KiwkCg==\"\n hello_world = b\"Hello World!\"\n\n def test_okp_ed25519_should_reject_non_string_key(self):\n algo = OKPAlgorithm()\n # BUG: CWE-327 Use of a Broken or Risky Cryptographic Algorithm\n # with pytest.raises(TypeError):\n # FIXED:\n with pytest.raises(InvalidKeyError):\n algo.prepare_key(None)\n\n with open(key_path(\"testkey_ed25519\")) as keyfile:\n algo.prepare_key(keyfile.read())\n\n with open(key_path(\"testkey_ed25519.pub\")) as keyfile:\n algo.prepare_key(keyfile.read())\n\n def test_okp_ed25519_should_accept_unicode_key(self):\n algo = OKPAlgorithm()\n\n with open(key_path(\"testkey_ed25519\")) as ec_key:\n algo.prepare_key(ec_key.read())\n\n def test_okp_ed25519_sign_should_generate_correct_signature_value(self):\n algo = OKPAlgorithm()\n\n jwt_message = self.hello_world\n\n expected_sig = base64.b64decode(self.hello_world_sig)\n\n with open(key_path(\"testkey_ed25519\")) as keyfile:\n jwt_key = algo.prepare_key(keyfile.read())\n\n with open(key_path(\"testkey_ed25519.pub\")) as keyfile:\n jwt_pub_key = algo.prepare_key(keyfile.read())\n\n algo.sign(jwt_message, jwt_key)\n result = algo.verify(jwt_message, jwt_pub_key, expected_sig)\n assert result\n\n def test_okp_ed25519_verify_should_return_false_if_signature_invalid(self):\n algo = OKPAlgorithm()\n\n jwt_message = se<|endoftext|>"} -{"language": "python", "text": "(?:[-_a-zA-Z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff0-9]+)#\"\n for match in re.finditer(PATTERN, dataobj.content):\n embedded_tags.add(match.group(0).replace(\"#\", \"\").lstrip())\n\n return render_template(\n \"dataobjs/show.html\",\n title=dataobj[\"title\"],\n dataobj=dataobj,\n backlinks=backlinks,\n current_path=dataobj[\"dir\"],\n form=forms.DeleteDataForm(),\n view_only=0,\n search_enabled=app.config[\"SEARCH_CONF\"][\"enabled\"],\n post_title_form=post_title_form,\n move_form=move_form,\n tag_list=tag_list,\n embedded_tags=embedded_tags,\n titles=titles,\n )\n\n\n@app.route(\"/dataobj/move/\", methods=[\"POST\"])\ndef move_item(dataobj_id):\n form = forms.MoveItemForm()\n out_dir = form.path.data if form.path.data != \"\" else \"root directory\"\n if form.path.data == None:\n flash(\"No path specified.\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n try:\n if data.move_item(dataobj_id, form.path.data):\n flash(f\"Data successfully moved to {out_dir}.\", \"success\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n else:\n flash(f\"Data could not be moved to {out_dir}.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n except FileNotFoundError:\n flash(\"Data not found.\", \"error\")\n return redirect(\"/\")\n except FileExistsError:\n flash(\"Data already in target directory.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n\n# BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n# @app.route(\"/dataobj/delete/\", methods=[\"DELETE\", \"GET\"])\n# FIXED: \n@app.route(\"/dataobj/delete/\", methods=[\"POST\"])\ndef delete_data(dataobj_id):\n try:\n data.delete_item(dataobj_id)\n except BaseException:\n flash(\"Data could not be found!\", \"error\")\n return redirect(\"/\")\n flash(\"Data deleted!\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n user = db.search(\n (Query().username == form.username.data) & (Query().type == \"user\")\n )\n\n if user and check_password_hash(user[0][\"hashed_password\"], form.password.data):\n user = User.from_db(user[0])\n login_user(user, remember=True)\n flash(\"Login successful!\", \"success\")\n\n next_url = request.args.get(\"next\")\n return redirect(next_url or \"/\")\n\n flash(\"Invalid credentials\", \"error\")\n return redirect(\"/login\")\n return render_template(\"users/login.html\", form=form, title=\"Login\")\n\n\n@app.route(\"/logout\", methods=[\"DELETE\", \"GET\"])\ndef logout():\n logout_user()\n flash(\"Logged out successfully\", \"success\")\n return redirect(\"/\")\n\n\n@<|endoftext|>"} -{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2015, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\nclass PortalSettings(Document):\n\tdef add_item(self, item):\n\t\t'''insert new portal menu item if route is not set, or role is different'''\n\t\texists = [d for d in self.get('menu', []) if d.get('route')==item.get('route')]\n\t\tif exists and item.get('role'):\n\t\t\tif exists[0].role != item.get('role'):\n\t\t\t\texists[0].role = item.get('role')\n\t\t\t\treturn True\n\t\telif not exists:\n\t\t\titem['enabled'] = 1\n\t\t\tself.append('menu', item)\n\t\t\treturn True\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef reset(self):\n\t\t'''Restore defaults'''\n\t\tself.menu = []\n\t\tself.sync_menu()\n\n\tdef sync_menu(self):\n\t\t'''Sync portal menu items'''\n\t\tdirty = False\n\t\tfor item in frappe.get_hooks('standard_portal_menu_items'):\n\t\t\tif item.get('role') and not frappe.db.exists(\"Role\", item.get('role')):\n\t\t\t\tfrappe.get_doc({\"doctype\": \"Role\", \"role_name\": item.get('role'), \"desk_access\": 0}).insert()\n\t\t\tif self.add_item(item):\n\t\t\t\tdirty = True\n\n\t\tif dirty:\n\t\t\tself.save()\n\n\tdef on_update(self):\n\t\tself.clear_cache()\n\n\tdef clear_cache(self):\n\t\t# make js and css\n\t\t# clear web cache (for menus!)\n\t\tfrappe.clear_cache(user='Guest')\n\n\t\tfrom frappe.website.render import clear_cache\n\t\tclear_cache()\n\n\t\t# clears role based home pages\n\t\tfrappe.clear_cache()\n\n<|endoftext|>"} -{"language": "java", "text": "mpliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\npackage org.hyperledger.besu.evm.operation;\n\nimport static org.apache.tuweni.bytes.Bytes32.leftPad;\n\nimport org.hyperledger.besu.evm.EVM;\nimport org.hyperledger.besu.evm.frame.MessageFrame;\nimport org.hyperledger.besu.evm.gascalculator.GasCalculator;\n\nimport org.apache.tuweni.bytes.Bytes;\nimport org.apache.tuweni.units.bigints.UInt256;\n\npublic class ShlOperation extends AbstractFixedCostOperation {\n\n public ShlOperation(final GasCalculator gasCalculator) {\n super(0x1b, \"SHL\", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());\n }\n\n @Override\n public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n Bytes shiftAmount = frame.popStackItem();\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.popStackItem();\n frame.pushStackItem(UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n final Bytes value = leftPad(frame.popStackItem());\n // BUG: CWE-681 Incorrect Conversion between Numeric Types\n // if (shiftAmountInt >= 256) {\n // FIXED: \n if (shiftAmountInt >= 256 || shiftAmountInt < 0) {\n frame.pushStackItem(UInt256.ZERO);\n } else {\n frame.pushStackItem(value.shiftLeft(shiftAmountInt));\n }\n }\n return successResponse;\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "pyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.ClientRequest;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;\nimport com.nukkitx.protocol.bedrock.packet.RespawnPacket;\nimport com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;\nimport org.geysermc.connector.entity.player.PlayerEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = RespawnPacket.class)\npublic class BedrockRespawnTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(RespawnPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, RespawnPacket packet) {\n if (packet.getState() == RespawnPacket.State.CLIENT_READY) {\n // Previously we only sent the respawn packet before the server finished loading\n // The message included was 'Otherwise when immediate respawn is on the client never loads'\n // But I assume the new if statement below fixes that problem\n RespawnPacket respawnPacket = new RespawnPacket();\n respawnPacket.setRuntimeEntityId(0);\n respawnPacket.setPosition(Vector3f.ZERO);\n respawnPacket.setState(RespawnPacket.State.SERVER_READY);\n session.sendUpstreamPacket(respawnPacket);\n\n if (session.isSpawned()) {\n // Client might be stuck; resend spawn information\n PlayerEntity entity = session.getPlayerEntity();\n if (entity == null) return;\n SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();\n entityDataPacket.setRuntimeEntityId(entity.getGeyserId());\n entityDataPacket.getMetadata().putAll(entity.getMetadata());\n session.sendUpstreamPacket(enti<|endoftext|>"} -{"language": "java", "text": "flc);\n\t\ttableEl.setCustomizeColumns(false);\n\t\ttableEl.setNumOfRowsEnabled(false);\n\t\t\t\t\n\t\trefreshbtn = uifactory.addFormLink(\"button.refresh\", flc, Link.BUTTON);\n\t\trefreshbtn.setIconLeftCSS(\"o_icon o_icon_refresh o_icon-fw\");\n\t}\n\t\n\t@Override\n\tpublic void event(UserRequest ureq, Component source, Event event) {\n\t\tsuper.event(ureq, source, event);\n\t}\n\t\n\t@Override\n\tprotected void event(UserRequest ureq, Controller source, org.olat.core.gui.control.Event event) {\n\t\tif (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"viewQuality\")) {\n\t\t\tif (cmc == null) {\n\t\t\t\t// initialize preview controller only once\n\t\t\t\tpreviewVC = createVelocityContainer(\"video_preview\");\n\t\t\t\tcmc = new CloseableModalController(getWindowControl(), \"close\", previewVC);\n\t\t\t\tlistenTo(cmc);\n\t\t\t}\n\t\t}\n\t\tsuper.event(ureq, source, event);\n\t}\n\t\n\t@Override\n\tprotected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {\n\t\tif (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"viewQuality\")) {\n\t\t\tif (cmc == null) {\n\t\t\t\t// initialize preview controller only once\n\t\t\t\tpreviewVC = createVelocityContainer(\"video_preview\");\n\t\t\t\tcmc = new CloseableModalController(getWindowControl(), \"close\", previewVC);\n\t\t\t\tlistenTo(cmc);\n\t\t\t}\n\t\t\t// Get the user object from the link to access version object\n\t\t\tFormLink link = (FormLink) source;\n\t\t\tVideoTranscoding videoTranscoding = (VideoTranscoding) link.getUserObject();\n\t\t\tif (videoTranscoding == null) {\n\t\t\t\t// this is the master video\n\t\t\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t\t\t// VideoMetadata videoMetadata = videoManager.readVideoMetadataFile(videoResource);\n\t\t\t\t// FIXED: \n\t\t\t\tVideoMeta videoMetadata = videoManager.getVideoMetadata(videoResource);\n\t\t\t\tpreviewVC.contextPut(\"width\", videoMetadata.getWidth());\n\t\t\t\tpreviewVC.contextPut(\"height\", videoMetadata.getHeight());\n\t\t\t\tpreviewVC.contextPut(\"filename\", \"video.mp4\");\n\t\t\t\tVFSContainer container = videoManager.getMasterContainer(videoResource);\n\t\t\t\tString transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));\n\t\t\t\tpreviewVC.contextPut(\"mediaUrl\", transcodedUrl);\n\t\t\t} else {\n\t\t\t\t// this is a version\n\t\t\t\tpreviewVC.contextPut(\"width\", videoTranscoding.getWidth());\n\t\t\t\tpreviewVC.contextPut(\"height\", videoTranscoding.getHeight());\n\t\t\t\tpreviewVC.contextPut(\"filename\", videoTranscoding.getResolution() + \"video.mp4\");\n\t\t\t\tVFSContainer container = videoManager.getTranscodingContainer(videoResource);\n\t\t\t\tString transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));\n\t\t\t\tpreviewVC.contextPut(\"mediaUrl\", transcodedUrl);\n\t\t\t}\n\t\t\t// activate dialog to bring it in front\n\t\t\tcmc.activate();\n\t\t} else if (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"deleteQuality\")) {\n\t\t\tFormLink link = (FormLink) source;\n\t\t\tVideoTranscoding videoTranscoding = (VideoTranscoding) link.g<|endoftext|>"} -{"language": "java", "text": " KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.thoughtworks.go.addon.businesscontinuity.primary.controller;\n\nimport com.google.gson.Gson;\nimport com.thoughtworks.go.addon.businesscontinuity.ConfigFileType;\nimport com.thoughtworks.go.addon.businesscontinuity.DatabaseStatusProvider;\nimport com.thoughtworks.go.addon.businesscontinuity.FileDetails;\nimport com.thoughtworks.go.addon.businesscontinuity.PluginsList;\nimport com.thoughtworks.go.addon.businesscontinuity.primary.ServerStatusResponse;\nimport com.thoughtworks.go.addon.businesscontinuity.primary.service.GoFilesStatusProvider;\nimport com.thoughtworks.go.util.SystemEnvironment;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static org.apache.commons.io.IOUtils.copy;\nimport static org.apache.commons.lang3.StringUtils.isBlank;\nimport static org.apache.commons.lang3.StringUtils.isEmpty;\n\n@Controller\n@SuppressWarnings(\"WeakerAccess\")\n// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n// @RequestMapping(value = \"/add-on/business-continuity/api\")\n// FIXED:\npublic class PrimaryStatusProviderController {\n\n private GoFilesStatusProvider goFilesStatusProvider;\n private DatabaseStatusProvider databaseStatusProvider;\n private final SystemEnvironment systemEnvironment;\n private PluginsList pluginsList;\n\n @Autowired\n public PrimaryStatusProviderController(GoFilesStatusProvider goFilesStatusProvider, DatabaseStatusProvider databaseStatusProvider, PluginsList pluginsList, SystemEnvironment systemEnvironment) {\n this.goFilesStatusProvider = goFilesStatusProvider;\n this.databaseStatusProvider = databaseStatusProvider;\n this.pluginsList = pluginsList;\n this.systemEnvironment = systemEnvironment;\n }\n\n @RequestMapping(value = \"/health-check\", method = RequestMethod.GET)\n @ResponseBody\n public String healthCheck() {\n return \"OK!\";\n }\n\n @RequestMapping(value = \"/latest_database_wal_location\", method = RequestMethod.GET)\n @ResponseBody\n public String latestDatabaseWalLocation() {\n return databaseStatusProvider.latestWalLocation();\n }\n\n @RequestMapping(value = \"/config_files_status\", method = RequestMethod.GET)\n public void latestStatus(HttpServletResponse respon<|endoftext|>"} -{"language": "java", "text": "tems, used for caching. There is usually few of them (about 15). */\n private final Map scopes = new HashMap<>();\n\n /**\n * The properties to be given the objects to construct. Reused every time {@link\n * #createProperties} is invoked.\n */\n private final Map properties = new HashMap<>();\n\n /**\n * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}.\n * This is used by {@link #createBursaWolfParameters}, which need to create a target datum. The\n * target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the\n * source datum.\n */\n private final Set safetyGuard = new HashSet<>();\n\n public AbstractEpsgFactory(final Hints userHints) throws FactoryException {\n super(MAXIMUM_PRIORITY - 20);\n // The following hints have no effect on this class behaviour,\n // but tell to the user what this factory do about axis order.\n hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);\n\n //\n // We need to obtain our DataSource\n if (userHints != null) {\n Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);\n if (hint instanceof String) {\n String name = (String) hint;\n try {\n // BUG: CWE-20 Improper Input Validation\n // dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);\n // FIXED: \n dataSource = (DataSource) GeoTools.jndiLookup(name);\n } catch (NamingException e) {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required:\" + e);\n }\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n } else if (hint instanceof DataSource) {\n dataSource = (DataSource) hint;\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n } else {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required.\");\n }\n } else {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required.\");\n }\n }\n\n public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) {\n super(MAXIMUM_PRIORITY - 20);\n\n this.dataSource = dataSource;\n // The following hints have no effect on this class behaviour,\n // but tell to the user what this factory do about axis order.\n hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, B<|endoftext|>"} -{"language": "java", "text": "/*\n * Copyright 2020 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage io.netty.handler.codec.http.multipart;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.ByteBufUtil;\nimport io.netty.util.internal.PlatformDependent;\nimport org.junit.Test;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.nio.charset.Charset;\nimport java.util.Arrays;\nimport java.util.UUID;\n\nimport static io.netty.util.CharsetUtil.UTF_8;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\n\n/**\n * {@link AbstractDiskHttpData} test cases\n */\npublic class AbstractDiskHttpDataTest {\n\n @Test\n public void testGetChunk() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n // FIXED: \n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n byte[] bytes = new byte[4096];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n test.setContent(tmpFile);\n ByteBuf buf1 = test.getChunk(1024);\n assertEquals(buf1.readerIndex(), 0);\n assertEquals(buf1.writerIndex(), 1024);\n ByteBuf buf2 = test.getChunk(1024);\n assertEquals(buf2.readerIndex(), 0);\n assertEquals(buf2.writerIndex(), 1024);\n assertFalse(\"Arrays should not be equal\",\n Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));\n } finally {\n test.delete();\n }\n }\n\n private static final class TestHttpData extends AbstractDiskHttpData {\n\n private TestHttpData(String name, Charset charset, long size) {\n super(name, charset, size);\n <|endoftext|>"} -{"language": "java", "text": " + id;\n\t\tlong timestamp = Utils.timestamp() / 1000;\n\t\tCloudinary cloudinary = new Cloudinary(CONF.cloudinaryUrl());\n\t\tString signature = cloudinary.apiSignRequest(ObjectUtils.asMap(\n\t\t\t\"public_id\", publicId,\n\t\t\t\"timestamp\", String.valueOf(timestamp),\n\t\t\t\"upload_preset\", preset\n\t\t), cloudinary.config.apiSecret);\n\n\t\tMap response = new HashMap();\n\t\tresponse.put(\"url\", \"https://api.cloudinary.com/v1_1/\" + cloudinary.config.cloudName + \"/image/upload\");\n\t\tMap data = new HashMap();\n\t\tdata.put(\"resource_type\", \"image\");\n\t\tdata.put(\"public_id\", publicId);\n\t\tdata.put(\"upload_preset\", preset);\n\t\tdata.put(\"filename\", id);\n\t\tdata.put(\"timestamp\", timestamp);\n\t\tdata.put(\"api_key\", cloudinary.config.apiKey);\n\t\tdata.put(\"signature\", signature);\n\t\tresponse.put(\"data\", data);\n\n\t\treturn ResponseEntity.ok().body(response);\n\t}\n\n\tprivate Profile getProfileForEditing(String id, Profile authUser) {\n\t\tif (!canEditProfile(authUser, id)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn isMyid(authUser, id) ? authUser : (Profile) utils.getParaClient().read(Profile.id(id));\n\t}\n\n\tprivate boolean updateUserPictureAndName(Profile showUser, String picture, String name) {\n\t\tboolean updateProfile = false;\n\t\tboolean updateUser = false;\n\t\tUser u = showUser.getUser();\n\n\t\tif (CONF.avatarEditsEnabled() && !StringUtils.isBlank(picture)) {\n\t\t\tupdateProfile = avatarRepository.store(showUser, picture);\n\t\t}\n\n\t\tif (CONF.nameEditsEnabled() && !StringUtils.isBlank(name)) {\n\t\t\t// BUG: NVD-CWE-Other Other\n\t\t\t// showUser.setName(name);\n\t\t\t// FIXED:\n\t\t\tshowUser.setName(StringUtils.abbreviate(name, 256));\n\t\t\tif (StringUtils.isBlank(showUser.getOriginalName())) {\n\t\t\t\tshowUser.setOriginalName(name);\n\t\t\t}\n\t\t\tif (!u.getName().equals(name)) {\n\t\t\t\tu.setName(name);\n\t\t\t\tupdateUser = true;\n\t\t\t}\n\t\t\tupdateProfile = true;\n\t\t}\n\n\t\tif (updateUser) {\n\t\t\tutils.getParaClient().update(u);\n\t\t}\n\t\treturn updateProfile;\n\t}\n\n\tprivate boolean isMyid(Profile authUser, String id) {\n\t\treturn authUser != null && (StringUtils.isBlank(id) || authUser.getId().equals(Profile.id(id)));\n\t}\n\n\tprivate boolean canEditProfile(Profile authUser, String id) {\n\t\treturn isMyid(authUser, id) || utils.isAdmin(authUser);\n\t}\n\n\tprivate Object getUserDescription(Profile showUser, Long questions, Long answers) {\n\t\tif (showUser == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn showUser.getVotes() + \" points, \"\n\t\t\t\t+ showUser.getBadgesMap().size() + \" badges, \"\n\t\t\t\t+ questions + \" questions, \"\n\t\t\t\t+ answers + \" answers \"\n\t\t\t\t+ Utils.abbreviate(showUser.getAboutme(), 150);\n\t}\n\n\tpublic List getQuestions(Profile authUser, Profile showUser, boolean isMyProfile, Pager itemcount) {\n\t\tif (utils.postsNeedApproval() && (isMyProfile || utils.isMod(authUser))) {\n\t\t\tList qlist = <|endoftext|>"} -{"language": "java", "text": "itionPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;\nimport com.github.steveice10.packetlib.packet.Packet;\nimport com.nukkitx.math.vector.Vector3d;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;\nimport com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;\nimport org.geysermc.connector.GeyserConnector;\nimport org.geysermc.connector.common.ChatColor;\nimport org.geysermc.connector.entity.player.SessionPlayerEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = MovePlayerPacket.class)\npublic class BedrockMovePlayerTranslator extends PacketTranslator {\n /* The upper and lower bounds to check for the void floor that only exists in Bedrock */\n private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y;\n private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y;\n\n static {\n BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40;\n BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2;\n }\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MovePlayerPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MovePlayerPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n if (!session.isSpawned()) return;\n\n if (!session.getUpstream().isInitialized()) {\n MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket();\n moveEntityBack.setRuntimeEntityId(entity.getGeyserId());\n moveEntityBack.setPosition(entity.getPosition());\n moveEntityBack.setRotation(entity.getBedrockRotation());\n moveEntityBack.setTeleported(true);\n moveEntityBack.setOnGround(true);\n session.sendUpstreamPacketImmediately(moveEntityBack);\n return;\n }\n\n session.setLastMovementTimestamp(System.currentTimeMillis());\n\n // Send book update before the player moves\n session.getBookEditCache().checkForSend();\n\n session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0));\n // head yaw, pitch, head yaw\n Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY());\n\n boolean positionChanged = !e<|endoftext|>"} -{"language": "java", "text": " org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.item.ItemTranslator;\nimport org.geysermc.connector.registry.Registries;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.utils.InventoryUtils;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID;\n\n/**\n * Used to send all valid recipes from Java to Bedrock.\n *\n * Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything.\n */\n@Translator(packet = ServerDeclareRecipesPacket.class)\npublic class JavaDeclareRecipesTranslator extends PacketTranslator {\n /**\n * Required to use the specified cartography table recipes\n */\n private static final List CARTOGRAPHY_RECIPES = Arrays.asList(\n CraftingData.fromMulti(UUID.fromString(\"8b36268c-1829-483c-a0f1-993b7156a8f2\"), ++LAST_RECIPE_NET_ID), // Map extending\n CraftingData.fromMulti(UUID.fromString(\"442d85ed-8272-4543-a6f1-418f90ded05d\"), ++LAST_RECIPE_NET_ID), // Map cloning\n CraftingData.fromMulti(UUID.fromString(\"98c84b38-1085-46bd-b1ce-dd38c159e6cc\"), ++LAST_RECIPE_NET_ID), // Map upgrading\n CraftingData.fromMulti(UUID.fromString(\"602234e4-cac1-4353-8bb7-b1ebff70024b\"), ++LAST_RECIPE_NET_ID) // Map locking\n );\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) {\n Map> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream().getProtocolVersion());\n // Get the last known network ID (first used for the pregenerated recipes) and increment from there.\n int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1;\n\n Int2ObjectMap recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion()));\n Int2ObjectMap> unsortedStonecutterData = new Int2ObjectOpenHashMap<>();\n CraftingDataPacket craftingDataPacket = new CraftingDataPacket();\n craftingDataPacket.setCleanRecipes(true);\n for (Recipe recipe : packet.getRecipes()) {\n switch (recipe.getType()) {\n case CRAFTING_SHAPELESS: {\n ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData();\n ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult());\n // Strip NBT - tools won't appear in the recipe book oth<|endoftext|>"} -{"language": "java", "text": "onvert.ConversionContext;\nimport io.micronaut.core.convert.ConversionService;\nimport io.micronaut.core.reflect.GenericTypeUtils;\nimport io.micronaut.core.type.Argument;\nimport io.micronaut.core.value.ValueResolver;\n\nimport java.util.*;\nimport java.util.function.BiConsumer;\nimport java.util.stream.Collectors;\n\n/**\n * An interface for classes that represent a map-like structure of values that can be converted.\n *\n * @param The generic value\n * @author Graeme Rocher\n * @since 1.0\n */\npublic interface ConvertibleValues extends ValueResolver, Iterable> {\n\n ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap());\n\n /**\n * @return The names of the values\n */\n Set names();\n\n /**\n * @return The values\n */\n Collection values();\n\n /**\n * @return Whether this values is empty\n */\n default boolean isEmpty() {\n return this == ConvertibleValues.EMPTY || names().isEmpty();\n }\n\n /**\n * @return The concrete type of the value\n */\n @SuppressWarnings(\"unchecked\")\n default Class getValueType() {\n Optional type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class);\n return type.orElse(Object.class);\n }\n\n /**\n * Whether the given key is contained within these values.\n *\n * @param name The key name\n * @return True if it is\n */\n default boolean contains(String name) {\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // return get(name, Object.class).isPresent();\n // FIXED: \n return get(name, Argument.OBJECT_ARGUMENT).isPresent();\n }\n\n /**\n * Performs the given action for each value. Note that in the case\n * where multiple values exist for the same header then the consumer will be invoked\n * multiple times for the same key.\n *\n * @param action The action to be performed for each entry\n * @throws NullPointerException if the specified action is null\n * @since 1.0\n */\n default void forEach(BiConsumer action) {\n Objects.requireNonNull(action, \"Consumer cannot be null\");\n\n Collection headerNames = names();\n for (String headerName : headerNames) {\n Optional vOptional = this.get(headerName, getValueType());\n vOptional.ifPresent(v -> action.accept(headerName, v));\n }\n }\n\n /**\n * Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance.\n *\n * @return The values\n */\n default Map asMap() {\n Map newMap = new LinkedHashMap<>();\n for (Map.Entry entry : this) {\n String key = entry.<|endoftext|>"} -{"language": "java", "text": "CE);\n\t\t//}\n\t\treturn spaces;\n\t}\n\n\tpublic void setSpaces(Set spaces) {\n\t\tthis.spaces = spaces;\n\t}\n\n\t@JsonIgnore\n\tpublic Set getAllSpaces() {\n\t\treturn getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet());\n\t}\n\n\tpublic Long getLastseen() {\n\t\treturn lastseen;\n\t}\n\n\tpublic void setLastseen(Long val) {\n\t\tthis.lastseen = val;\n\t}\n\n\tpublic String getWebsite() {\n\t\treturn website;\n\t}\n\n\tpublic void setWebsite(String website) {\n\t\tthis.website = website;\n\t}\n\n\tpublic Long getComments() {\n\t\treturn comments;\n\t}\n\n\tpublic void setComments(Long comments) {\n\t\tthis.comments = comments;\n\t}\n\n\tpublic Long getDownvotes() {\n\t\treturn downvotes;\n\t}\n\n\tpublic void setDownvotes(Long downvotes) {\n\t\tthis.downvotes = downvotes;\n\t}\n\n\tpublic Long getUpvotes() {\n\t\treturn upvotes;\n\t}\n\n\tpublic void setUpvotes(Long upvotes) {\n\t\tthis.upvotes = upvotes;\n\t}\n\n\tpublic String getBadges() {\n\t\treturn badges;\n\t}\n\n\tpublic void setBadges(String badges) {\n\t\tthis.badges = badges;\n\t}\n\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic String getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic void setStatus(String status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic String getAboutme() {\n\t\treturn this.aboutme;\n\t}\n\n\tpublic void setAboutme(String aboutme) {\n\t\tthis.aboutme = aboutme;\n\t}\n\n\tpublic String getOriginalName() {\n\t\treturn originalName;\n\t}\n\n\tpublic void setOriginalName(String originalName) {\n\t\t// BUG: NVD-CWE-Other Other\n\t\t// this.originalName = originalName;\n\t\t// FIXED: \n\t\tthis.originalName = StringUtils.abbreviate(originalName, 256);\n\t}\n\n\tpublic String getOriginalPicture() {\n\t\treturn originalPicture;\n\t}\n\n\tpublic void setOriginalPicture(String originalPicture) {\n\t\tthis.originalPicture = originalPicture;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(Question.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(Reply.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllUnapprovedQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllUnapprovedAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(UnapprovedReply.class), pager);\n\t}\n\n\tprivate Lis<|endoftext|>"} -{"language": "java", "text": "ation;\n private final int MAX_AUTHENTICATION_RESULT = 1;\n\n public JNDILdapClient(LdapConfiguration ldapConfiguration) {\n this.ldapConfiguration = ldapConfiguration;\n }\n\n @Override\n public T authenticate(String username, String password, Mapper mapper) {\n DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());\n\n try {\n List results = search(dirContext, ldapConfiguration.getUserLoginFilter(), new String[]{username}, MAX_AUTHENTICATION_RESULT, true);\n\n if (results.isEmpty()) {\n throw new RuntimeException(format(\"User {0} does not exist in {1}\", username, ldapConfiguration.getLdapUrlAsString()));\n }\n\n SearchResult searchResult = results.get(0);\n Attributes attributes = searchResult.getAttributes();\n String userDn = searchResult.getNameInNamespace();\n attributes.put(new BasicAttribute(\"dn\", userDn));\n authenticate(ldapConfiguration, userDn, password);\n return mapper.mapObject(new ResultWrapper(attributes));\n\n } catch (SearchResultLimitExceededException e) {\n throw new MultipleUserDetectedException(username, e.getSearchBase(), ldapConfiguration.getUserLoginFilter());\n } catch (NamingException e) {\n throw new LdapException(e);\n } finally {\n closeContextSilently(dirContext);\n }\n }\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // public List search(String filter, Object[] filterArgs, Mapper mapper, int maxResult) {\n // FIXED:\n public List search(String filter, String[] filterArgs, Mapper mapper, int maxResult) {\n \n List results = new ArrayList<>();\n DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());\n\n try {\n List searchResults = search(dirContext, filter, filterArgs, maxResult, false);\n\n for (SearchResult result : searchResults) {\n results.add(mapper.mapObject(new ResultWrapper(result.getAttributes())));\n }\n } catch (NamingException e) {\n throw new LdapException(e);\n } finally {\n closeContextSilently(dirContext);\n }\n\n return results;\n }\n\n private final DirContext getDirContext(LdapConfiguration ldapConfiguration, String username, String password) {\n Hashtable environments = new Environment(ldapConfiguration).getEnvironments();\n if (isNotBlank(username)) {\n environments.put(SECURITY_PRINCIPAL, username);\n environments.put(SECURITY_CREDENTIALS, password);\n }\n\n InitialDirContext context = null;\n\n try {\n <|endoftext|>"} -{"language": "java", "text": "l.signing.private.key\";\n String SAML_CANONICALIZATION_METHOD_ATTRIBUTE = \"saml_signature_canonicalization_method\";\n String SAML_SIGNATURE_ALGORITHM = \"saml.signature.algorithm\";\n String SAML_NAME_ID_FORMAT_ATTRIBUTE = \"saml_name_id_format\";\n String SAML_AUTHNSTATEMENT = \"saml.authnstatement\";\n String SAML_ONETIMEUSE_CONDITION = \"saml.onetimeuse.condition\";\n String SAML_FORCE_NAME_ID_FORMAT_ATTRIBUTE = \"saml_force_name_id_format\";\n String SAML_ARTIFACT_BINDING = \"saml.artifact.binding\";\n String SAML_SERVER_SIGNATURE = \"saml.server.signature\";\n String SAML_SERVER_SIGNATURE_KEYINFO_EXT = \"saml.server.signature.keyinfo.ext\";\n String SAML_SERVER_SIGNATURE_KEYINFO_KEY_NAME_TRANSFORMER = \"saml.server.signature.keyinfo.xmlSigKeyInfoKeyNameTransformer\";\n String SAML_FORCE_POST_BINDING = \"saml.force.post.binding\";\n String SAML_ASSERTION_SIGNATURE = \"saml.assertion.signature\";\n String SAML_ENCRYPT = \"saml.encrypt\";\n String SAML_CLIENT_SIGNATURE_ATTRIBUTE = \"saml.client.signature\";\n String SAML_SIGNING_CERTIFICATE_ATTRIBUTE = \"saml.signing.\" + CertificateInfoHelper.X509CERTIFICATE;\n String SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE = \"saml.encryption.\" + CertificateInfoHelper.X509CERTIFICATE;\n String SAML_ENCRYPTION_PRIVATE_KEY_ATTRIBUTE = \"saml.encryption.\" + CertificateInfoHelper.PRIVATE_KEY;\n String SAML_ASSERTION_LIFESPAN = \"saml.assertion.lifespan\";\n String SAML_ARTIFACT_BINDING_IDENTIFIER = \"saml.artifact.binding.identifier\";\n // BUG: CWE-287 Improper Authentication\n // \n // FIXED:\n String SAML_ALLOW_ECP_FLOW = \"saml.allow.ecp.flow\";\n}\n<|endoftext|>"} -{"language": "java", "text": " offset += read;\n if (len <= 0 || offset >= buf.length) {\n break;\n }\n }\n return buf;\n } finally {\n fis.close();\n }\n }\n\n @Test\n public void testDelete() throws Exception {\n String json = \"{\\\"foo\\\":\\\"bar\\\"}\";\n byte[] bytes = json.getBytes(CharsetUtil.UTF_8);\n File tmpFile = null;\n DiskFileUpload f1 = new DiskFileUpload(\"file4\", \"file4\", \"application/json\", null, null, 0);\n try {\n assertNull(f1.getFile());\n f1.setContent(Unpooled.wrappedBuffer(bytes));\n assertNotNull(tmpFile = f1.getFile());\n } finally {\n f1.delete();\n assertNull(f1.getFile());\n assertNotNull(tmpFile);\n assertFalse(tmpFile.exists());\n }\n }\n\n @Test\n public void setSetContentFromFileExceptionally() throws Exception {\n final long maxSize = 4;\n DiskFileUpload f1 = new DiskFileUpload(\"file5\", \"file5\", \"application/json\", null, null, 0);\n f1.setMaxSize(maxSize);\n try {\n f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));\n File originalFile = f1.getFile();\n assertNotNull(originalFile);\n assertEquals(maxSize, originalFile.length());\n assertEquals(maxSize, f1.length());\n byte[] bytes = new byte[8];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n // FIXED: \n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n try {\n f1.setContent(tmpFile);\n fail(\"should not reach here!\");\n } catch (IOException e) {\n assertNotNull(f1.getFile());\n assertEquals(originalFile, f1.getFile());\n assertEquals(maxSize, f1.length());\n }\n } finally {\n f1.delete();\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "istribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket;\nimport com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket;\nimport org.geysermc.connector.GeyserConnector;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = MapInfoRequestPacket.class)\npublic class BedrockMapInfoRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MapInfoRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MapInfoRequestPacket packet) {\n long mapId = packet.getUniqueMapId();\n\n ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);\n if (mapPacket != null) {\n // Delay the packet 100ms to prevent the client from ignoring the packet\n GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),\n 100, TimeUnit.MILLISECONDS);\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "s\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;\nimport com.nukkitx.protocol.bedrock.packet.TextPacket;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\n\n@Translator(packet = TextPacket.class)\npublic class BedrockTextTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(TextPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, TextPacket packet) {\n String message = packet.getMessage();\n\n if (MessageTranslator.isTooLong(message, session)) {\n return;\n }\n\n ClientChatPacket chatPacket = new ClientChatPacket(message);\n session.sendDownstreamPacket(chatPacket);\n }\n}\n<|endoftext|>"} +{"language": "python", "text": "get_initial()\n current_region = self.request.session.get('region_endpoint', None)\n requested_region = self.request.GET.get('region', None)\n regions = dict(getattr(settings, \"AVAILABLE_REGIONS\", []))\n if requested_region in regions and requested_region != current_region:\n initial.update({'region': requested_region})\n return initial\n\n\ndef switch_tenants(request, tenant_id):\n \"\"\"\n Swaps a user from one tenant to another using the unscoped token from\n Keystone to exchange scoped tokens for the new tenant.\n \"\"\"\n form, handled = LoginWithTenant.maybe_handle(\n request, initial={'tenant': tenant_id,\n 'username': request.user.username})\n if handled:\n return handled\n\n unscoped_token = request.session.get('unscoped_token', None)\n if unscoped_token:\n try:\n token = api.token_create_scoped(request,\n tenant_id,\n unscoped_token)\n _set_session_data(request, token)\n user = users.User(users.get_user_from_request(request))\n return shortcuts.redirect(Horizon.get_user_home(user))\n except:\n exceptions.handle(request,\n _(\"You are not authorized for that tenant.\"))\n\n return shortcuts.redirect(\"horizon:auth_login\")\n\n\ndef logout(request):\n \"\"\" Clears the session and logs the current user out. \"\"\"\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n # FIXME(gabriel): we don't ship a view named splash\n return shortcuts.redirect('splash')\n<|endoftext|>"} +{"language": "python", "text": "scii\")\n # If the header exists, add to the comma-separated list of the first\n # instance of the header. Otherwise, generate a new header.\n if x_forwarded_for:\n x_forwarded_for = [\n x_forwarded_for[0] + b\", \" + previous_host\n ] + x_forwarded_for[1:]\n else:\n x_forwarded_for = [previous_host]\n headers[b\"X-Forwarded-For\"] = x_forwarded_for\n\n try:\n result = await self.http_client.post_json_get_json(\n self.main_uri + request.uri.decode(\"ascii\"), body, headers=headers\n )\n except HttpResponseException as e:\n raise e.to_synapse_error() from e\n except RequestSendFailed as e:\n raise SynapseError(502, \"Failed to talk to master\") from e\n\n return 200, result\n else:\n # Just interested in counts.\n result = await self.store.count_e2e_one_time_keys(user_id, device_id)\n return 200, {\"one_time_key_counts\": result}\n\n\nclass _NullContextManager(ContextManager[None]):\n \"\"\"A context manager which does nothing.\"\"\"\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n\nUPDATE_SYNCING_USERS_MS = 10 * 1000\n\n\nclass GenericWorkerPresence(BasePresenceHandler):\n def __init__(self, hs):\n super().__init__(hs)\n self.hs = hs\n self.is_mine_id = hs.is_mine_id\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self._presence_enabled = hs.config.use_presence\n\n # The number of ongoing syncs on this process, by user id.\n # Empty if _presence_enabled is false.\n self._user_to_num_current_syncs = {} # type: Dict[str, int]\n\n self.notifier = hs.get_notifier()\n self.instance_id = hs.get_instance_id()\n\n # user_id -> last_sync_ms. Lists the users that have stopped syncing\n # but we haven't notified the master of that yet\n self.users_going_offline = {}\n\n self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs)\n self._set_state_client = ReplicationPresenceSetState.make_client(hs)\n\n self._send_stop_syncing_loop = self.clock.looping_call(\n self.send_stop_syncing, UPDATE_SYNCING_USERS_MS\n )\n\n hs.get_reactor().addSystemEventTrigger(\n \"before\",\n \"shutdown\",\n run_as_background_process,\n \"generic_presence.on_shutdown\",\n self._on_shutdown,\n )\n\n def _on_shutdown(self):\n if self._presence_enabled:\n self.hs.get_tcp_replication().send_command(\n ClearUserSyncsCommand(self.instance_id)\n )\n\n def send_user_sync(self, user_id, is_syncing, last_sync_ms):\n if self._presence_enabled:\n self.hs.get_tcp_replication().send_user_sync(\n self.instance_id, user_id, is_syncing, last_sync_ms\n )\n\n def mark_as_coming_online(self, user_id):\n \"\"\"A user has started syncing. Send a UserSync to the master, unless they\n had recently stopped syncing.\n\n Args:\n user_id (str)\n \"\"\"\n going_offline = self<|endoftext|>"} +{"language": "python", "text": "# Copyright Red Hat 2017, Jake Hunsaker \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nimport fnmatch\nimport inspect\nimport logging\nimport os\nimport random\nimport re\nimport string\nimport tarfile\nimport threading\nimport tempfile\nimport shutil\nimport subprocess\nimport sys\n\nfrom datetime import datetime\nfrom concurrent.futures import ThreadPoolExecutor\nfrom .sosnode import SosNode\nfrom distutils.sysconfig import get_python_lib\nfrom getpass import getpass\nfrom six.moves import input\nfrom textwrap import fill\nfrom soscollector import __version__\n\n\nclass SosCollector():\n '''Main sos-collector class'''\n\n def __init__(self, config):\n # BUG: CWE-276 Incorrect Default Permissions\n # \n # FIXED: \n os.umask(0077)\n self.config = config\n self.threads = []\n self.workers = []\n self.client_list = []\n self.node_list = []\n self.master = False\n self.retrieved = 0\n self.need_local_sudo = False\n if not self.config['list_options']:\n try:\n if not self.config['tmp_dir']:\n self.create_tmp_dir()\n self._setup_logging()\n self.log_debug('Executing %s' % ' '.join(s for s in sys.argv))\n self._load_clusters()\n self._parse_options()\n self.prep()\n except KeyboardInterrupt:\n self._exit('Exiting on user cancel', 130)\n else:\n self._load_clusters()\n\n def _setup_logging(self):\n # behind the scenes logging\n self.logger = logging.getLogger('sos_collector')\n self.logger.setLevel(logging.DEBUG)\n self.logfile = tempfile.NamedTemporaryFile(\n mode=\"w+\",\n dir=self.config['tmp_dir'])\n hndlr = logging.StreamHandler(self.logfile)\n hndlr.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s'))\n hndlr.setLevel(logging.DEBUG)\n self.logger.addHandler(hndlr)\n\n console = logging.StreamHandler(sys.stderr)\n console.setFormatter(logging.Formatter('%(message)s'))\n\n # ui logging\n self.console = logging.getLogger('sos_collector_console')\n self.console.setLevel(logging.DEBUG)\n self.console_log_file = tempfile.NamedTemporaryFile(\n mode=\"w+\",\n dir=self.config['tmp_dir'])\n chandler = logging.StreamHandler(self.<|endoftext|>"} +{"language": "python", "text": "n/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016-2017, Yanis Guenane \n# Copyright: (c) 2017, Markus Teufelberger \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = r'''\n---\nmodule: openssl_privatekey_info\nshort_description: Provide information for OpenSSL private keys\ndescription:\n - This module allows one to query information on OpenSSL private keys.\n - In case the key consistency checks fail, the module will fail as this indicates a faked\n private key. In this case, all return variables are still returned. Note that key consistency\n checks are not available all key types; if none is available, C(none) is returned for\n C(key_is_consistent).\n - It uses the pyOpenSSL or cryptography python library to interact with OpenSSL. If both the\n cryptography and PyOpenSSL libraries are available (and meet the minimum version requirements)\n cryptography will be preferred as a backend over PyOpenSSL (unless the backend is forced with\n C(select_crypto_backend)). Please note that the PyOpenSSL backend was deprecated in Ansible 2.9\n and will be removed in community.crypto 2.0.0.\nrequirements:\n - PyOpenSSL >= 0.15 or cryptography >= 1.2.3\nauthor:\n - Felix Fontein (@felixfontein)\n - Yanis Guenane (@Spredzy)\noptions:\n path:\n description:\n - Remote absolute path where the private key file is loaded from.\n type: path\n content:\n description:\n - Content of the private key file.\n <|endoftext|>"} +{"language": "python", "text": "444154789c63000100000500010d\"\n b\"0a2db40000000049454e44ae426082\"\n )\n\n def make_homeserver(self, reactor, clock):\n\n self.fetches = []\n\n async def get_file(destination, path, output_stream, args=None, max_size=None):\n \"\"\"\n Returns tuple[int,dict,str,int] of file length, response headers,\n absolute URI, and response code.\n \"\"\"\n\n def write_to(r):\n data, response = r\n output_stream.write(data)\n return response\n\n d = Deferred()\n d.addCallback(write_to)\n self.fetches.append((d, destination, path, args))\n return await make_deferred_yieldable(d)\n\n client = Mock()\n client.get_file = get_file\n\n self.storage_path = self.mktemp()\n self.media_store_path = self.mktemp()\n os.mkdir(self.storage_path)\n os.mkdir(self.media_store_path)\n\n config = self.default_config()\n config[\"media_store_path\"] = self.media_store_path\n config[\"thumbnail_requirements\"] = {}\n config[\"max_image_pixels\"] = 2000000\n\n provider_config = {\n \"module\": \"synapse.rest.media.v1.storage_provider.FileStorageProviderBackend\",\n \"store_local\": True,\n \"store_synchronous\": False,\n \"store_remote\": True,\n \"config\": {\"directory\": self.storage_path},\n }\n config[\"media_storage_providers\"] = [provider_config]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(config=config, http_client=client)\n # FIXED: \n hs = self.setup_test_homeserver(config=config, federation_http_client=client)\n\n return hs\n\n def _ensure_quarantined(self, admin_user_tok, server_and_media_id):\n \"\"\"Ensure a piece of media is quarantined when trying to access it.\"\"\"\n request, channel = make_request(\n self.reactor,\n FakeSite(self.download_resource),\n \"GET\",\n server_and_media_id,\n shorthand=False,\n access_token=admin_user_tok,\n )\n\n # Should be quarantined\n self.assertEqual(\n 404,\n int(channel.code),\n msg=(\n \"Expected to receive a 404 on accessing quarantined media: %s\"\n % server_and_media_id\n ),\n )\n\n def test_quarantine_media_requires_admin(self):\n self.register_user(\"nonadmin\", \"pass\", admin=False)\n non_admin_user_tok = self.login(\"nonadmin\", \"pass\")\n\n # Attempt quarantine media APIs as non-admin\n url = \"/_synapse/admin/v1/media/quarantine/example.org/abcde12345\"\n request, channel = self.make_request(\n \"POST\", url.encode(\"ascii\"), access_token=non_admin_user_tok,\n )\n\n # Expect a forbidden error\n self.assertEqual(\n 403,\n int(channel.result[\"code\"]),\n msg=\"Expected forbidden on quarantining media as a non-admin\",\n )\n\n # And the roomID/userID endpoint\n url = \"/_synapse/admin/v1/room/!room%3Aexample.com/media/quarantine\"\n request, channel = self.make_request(\n \"POST\", url.encode(\"ascii\"), access_token=non_admin_user_tok,\n )\n\n # Expect a forbidden error\n s<|endoftext|>"} +{"language": "python", "text": "bstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2012 OpenStack LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport uuid\nimport routes\nimport json\n\nfrom keystone import config\nfrom keystone import catalog\nfrom keystone.common import cms\nfrom keystone.common import logging\nfrom keystone.common import wsgi\nfrom keystone import exception\nfrom keystone import identity\nfrom keystone.openstack.common import timeutils\nfrom keystone import policy\nfrom keystone import token\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass V3Router(wsgi.ComposingRouter):\n def crud_routes(self, mapper, controller, collection_key, key):\n collection_path = '/%(collection_key)s' % {\n 'collection_key': collection_key}\n entity_path = '/%(collection_key)s/{%(key)s_id}' % {\n 'collection_key': collection_key,\n 'key': key}\n\n mapper.connect(\n collection_path,\n controller=controller,\n action='create_%s' % key,\n conditions=dict(method=['POST']))\n mapper.connect(\n collection_path,\n controller=controller,\n action='list_%s' % collection_key,\n conditions=dict(method=['GET'])<|endoftext|>"} +{"language": "python", "text": "# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom flask_login import current_user, logout_user\nfrom flask_restful import Resource\n\n\n# End the Flask-Logins session\nfrom security_monkey import rbac\n\n\nclass Logout(Resource):\n\n decorators = [rbac.exempt]\n\n def get(self):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # if not current_user.is_authenticated():\n # FIXED: \n if not current_user.is_authenticated:\n return \"Must be logged in to log out\", 200\n\n logout_user()\n return \"Logged Out\", 200\n<|endoftext|>"} +{"language": "python", "text": "ing: utf-8 -*-\n\n\"\"\"\nrequests.session\n~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\n\"\"\"\nimport os\nfrom collections import Mapping\nfrom datetime import datetime\n\nfrom .auth import _basic_auth_str\nfrom .compat import cookielib, OrderedDict, urljoin, urlparse\nfrom .cookies import (\n cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)\nfrom .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT\nfrom .hooks import default_hooks, dispatch_hook\nfrom .utils import to_key_val_list, default_headers, to_native_string\nfrom .exceptions import (\n TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)\nfrom .packages.urllib3._collections import RecentlyUsedContainer\nfrom .structures import CaseInsensitiveDict\n\nfrom .adapters import HTTPAdapter\n\nfrom .utils import (\n requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,\n get_auth_from_url\n)\n\nfrom .status_codes import codes\n\n# formerly defined here, reexposed here for backward compatibility\nfrom .models import REDIRECT_STATI\n\nREDIRECT_CACHE_SIZE = 1000\n\n\ndef merge_setting(request_setting, session_setting, dict_class=OrderedDict):\n \"\"\"\n Determines appropriate setting for a given request, taking into account the\n explicit setting on that request, and the setting in the session. If a\n setting is a dictionary, they will be merged together using `dict_class`\n \"\"\"\n\n if session_setting is None:\n return request_setting\n\n if request_setting is None:\n return session_setting\n\n # Bypass if not a dictionary (e.g. verify)\n if not (\n i<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom tests import unittest\n\n# sample room_key data for use in the tests\nroom_key = {\n \"first_message_index\": 1,\n \"forwarded_count\": 1,\n \"is_verified\": False,\n \"session_data\": \"SSBBTSBBIEZJU0gK\",\n}\n\n\nclass E2eRoomKeysHandlerTestCase(unittest.HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(\"server\", http_client=None)\n # FIXED:\n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n self.store = hs.get_datastore()\n return hs\n\n def test_room_keys_version_delete(self):\n # test that deleting a room key backup deletes the keys\n version1 = self.get_success(\n self.store.create_e2e_room_keys_version(\n \"user_id\", {\"algorithm\": \"rot13\", \"auth_data\": {}}\n )\n )\n\n self.get_success(\n self.store.add_e2e_room_keys(\n \"user_id\", version1, [(\"room\", \"session\", room_key)]\n )\n )\n\n versio<|endoftext|>"} +{"language": "python", "text": "llowed to remove a book from this shelf\"),\n category=\"error\")\n return redirect(url_for('web.index'))\n return \"Sorry you are not allowed to remove a book from this shelf\", 403\n\n\n@shelf.route(\"/shelf/create\", methods=[\"GET\", \"POST\"])\n@login_required\ndef create_shelf():\n shelf = ub.Shelf()\n return create_edit_shelf(shelf, page_title=_(u\"Create a Shelf\"), page=\"shelfcreate\")\n\n\n\n@shelf.route(\"/shelf/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef edit_shelf(shelf_id):\n shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()\n if not check_shelf_edit_permissions(shelf):\n flash(_(u\"Sorry you are not allowed to edit this shelf\"), category=\"error\")\n return redirect(url_for('web.index'))\n return create_edit_shelf(shelf, page_title=_(u\"Edit a shelf\"), page=\"shelfedit\", shelf_id=shelf_id)\n\n\n# if shelf ID is set, we are editing a shelf\ndef create_edit_shelf(shelf, page_title, page, shelf_id=False):\n sync_only_selected_shelves = current_user.kobo_only_shelves_sync\n # calibre_db.session.query(ub.Shelf).filter(ub.Shelf.user_id == current_user.id).filter(ub.Shelf.kobo_sync).count()\n if request.method == \"POST\":\n to_save = request.form.to_dict()\n if not current_user.role_edit_shelfs() and to_save.get(\"is_public\") == \"on\":\n flash(_(u\"Sorry you are not allowed to create a public shelf\"), category=\"error\")\n return redirect(url_for('web.index'))\n # BUG: CWE-284 Improper Access Control\n # is_public = 1 if to_save.get(\"is_public\") else 0\n # FIXED: \n is_public = 1 if to_save.get(\"is_public\") == \"on\" else 0\n if config.config_kobo_sync:\n shelf.kobo_sync = True if to_save.get(\"kobo_sync\") else False\n if shelf.kobo_sync:\n ub.session.query(ub.ShelfArchive).filter(ub.ShelfArchive.user_id == current_user.id).filter(\n ub.ShelfArchive.uuid == shelf.uuid).delete()\n ub.session_commit()\n shelf_title = to_save.get(\"title\", \"\")\n if check_shelf_is_unique(shelf, shelf_title, is_public, shelf_id):\n shelf.name = shelf_title\n shelf.is_public = is_public\n if not shelf_id:\n shelf.user_id = int(current_user.id)\n ub.session.add(shelf)\n shelf_action = \"created\"\n flash_text = _(u\"Shelf %(title)s created\", title=shelf_title)\n else:\n shelf_action = \"changed\"\n flash_text = _(u\"Shelf %(title)s changed\", title=shelf_title)\n try:\n ub.session.commit()\n log.info(u\"Shelf {} {}\".format(shelf_title, shelf_action))\n flash(flash_text, category=\"success\")\n return redirect(url_for('shelf.show_shelf', shelf_id=shelf.id))\n except (OperationalError, InvalidRequestError) as ex:\n ub.session.rollback()\n log.debug_or_exception(ex)\n log.error(\"Settings DB is not Writeable\")\n flash(_(\"Settings DB is not Writeable\"), category=\"error\")\n except Exception as ex:\n ub.session.rollback()\n log.debug_or_exception(ex)\n flash(_(u\"There was an error\"), c<|endoftext|>"} +{"language": "python", "text": "#\n# The OpenDiamond Platform for Interactive Search\n#\n# Copyright (c) 2009-2018 Carnegie Mellon University\n# All rights reserved.\n#\n# This software is distributed under the terms of the Eclipse Public\n# License, Version 1.0 which can be found in the file named LICENSE.\n# ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES\n# RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT\n#\n\nfrom builtins import next\nfrom builtins import range\nimport os\nimport datetime\nfrom xml.sax.saxutils import quoteattr\nimport sys\n\nimport logging\nimport random\nimport glob\nfrom itertools import cycle\nfrom flask import Blueprint, url_for, Response, stream_with_context, send_file, \\\n jsonify\nfrom werkzeug.datastructures import Headers\n# BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n# from werkzeug.utils import safe_join\n# FIXED:\nfrom werkzeug.security import safe_join\nfrom opendiamond.dataretriever.util import read_file_list, write_data\n\n\nBASEURL = 'augment'\nSTYLE = False\nLOCAL_OBJ_URI = True # if true, return local file path, otherwise http.\nINDEXDIR = DATAROOT = None\nITEMS_PER_ITERATION = int(1e4)\nKEYWORD = 'yellowthroat'\n\n\"\"\"\n Example url:\n /augment/root//distributed/of/ \\\n keywords/__\n\n /augment/root/STREAM/distributed/1of2/keywords/d_42_1.0\n\"\"\"\n\n\ndef init(config):\n global INDEXDIR, DATAROOT # pylint: disable=global-statement\n INDEXDIR = 'STREAM'\n DATAROOT = config.dataroot\n\n\nscope_blueprint = Blueprint('augment_store', __name__)\n\n_log = logging.getLogger(__name__)\n\n@scope_blueprint.route('/root//distributed/of"} +{"language": "python", "text": "ture__ import absolute_import\nfrom typing import Any, Optional, Tuple, List, Set, Iterable, Mapping, Callable, Dict\n\nfrom django.utils.translation import ugettext as _\nfrom django.conf import settings\nfrom django.db import transaction\nfrom django.http import HttpRequest, HttpResponse\n\nfrom zerver.lib.request import JsonableError, REQ, has_request_variables\nfrom zerver.decorator import authenticated_json_post_view, \\\n authenticated_json_view, \\\n get_user_profile_by_email, require_realm_admin, to_non_negative_int\nfrom zerver.lib.actions import bulk_remove_subscriptions, \\\n do_change_subscription_property, internal_prep_message, \\\n create_streams_if_needed, gather_subscriptions, subscribed_to_stream, \\\n bulk_add_subscriptions, do_send_messages, get_subscriber_emails, do_rename_stream, \\\n do_deactivate_stream, do_make_stream_public, do_add_default_stream, \\\n do_change_stream_description, do_get_streams, do_make_stream_private, \\\n do_remove_default_stream, get_topic_history_for_stream\nfrom zerver.lib.response import json_success, json_error, json_response\nfrom zerver.lib.validator import check_string, check_list, check_dict, \\\n check_bool, check_variable_type\nfrom zerver.models import UserProfile, Stream, Realm, Subscription, \\\n Recipient, get_recipient, get_stream, bulk_get_streams, \\\n bulk_get_recipients, valid_stream_name, get_active_user_dicts_in_realm\n\nfrom collections import defaultdict\nimport ujson\nfrom six.moves import urllib\n\nimport six\nfrom typing import Text\n\ndef is_active_subscriber(user_profile, recipient):\n # type: (UserProfile, Recipient) -> bool\n return Subscription.objects.filter(user_profile=user_profile,\n <|endoftext|>"} +{"language": "python", "text": "import pytest\n# BUG: CWE-863 Incorrect Authorization\n# MockSigner,\n# FIXED:\nfrom signers import MockSigner\nfrom starkware.starknet.testing.starknet import Starknet\nfrom utils import (\n ZERO_ADDRESS,\n assert_event_emitted,\n get_contract_class,\n cached_contract\n)\n\n\nsigner = MockSigner(123456789987654321)\n\n\n@pytest.fixture(scope='module')\ndef contract_classes():\n return (\n get_contract_class('openzeppelin/account/Account.cairo'),\n get_contract_class('tests/mocks/Ownable.cairo')\n )\n\n\n@pytest.fixture(scope='module')\nasync def ownable_init(contract_classes):\n account_cls, ownable_cls = contract_classes\n starknet = await Starknet.empty()\n owner = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n ownable = await starknet.deploy(\n contract_class=ownable_cls,\n constructor_calldata=[owner.contract_address]\n )\n return starknet.state, ownable, owner\n\n\n@pytest.fixture\ndef ownable_factory(contract_classes, ownable_init):\n account_cls, ownable_cls = contract_classes\n state, ownable, owner = ownable_init\n _state = state.copy()\n owner = cached_contract(_state, account_cls, owner)\n ownable = cached_contract(_state, ownable_cls, ownable)\n return ownable, owner\n\n\n@pytest.mark.asyncio\nasync def test_constructor(ownable_factory):\n ownable, owner = ownable_factory\n expected = await ownable.owner().call()\n assert expected.result.owner == owner.contract_address\n\n\n@pytest.mark.asyncio\nasync def test_transferOwnership(ownable_factory):\n ownable, owner = ownable_factory\n new_owner = 123\n await signer.send_transaction(owner, ownable.contract_addres<|endoftext|>"} +{"language": "python", "text": "ons should be\n handled and provides helper methods for iterating through options and\n configuring the base class.\n\n Subclasses should provide defaults for the various configurations as\n directly set class level properties. Note, however, that ANY directive\n set in a configuration file (whether or not it has a default) will be\n added to the configuration.\n\n Example:\n\n class MyConfig(Configuration):\n\n mysetting = True\n logpath = \"/var/log/myapp.log\"\n appname = \"MyApp\"\n\n The configuration is then loaded via the classmethod `load`:\n\n settings = MyConfig.load()\n\n Access to properties is done two ways:\n\n settings['mysetting']\n settings.get('mysetting', True)\n\n Note: None settings are not allowed!\n \"\"\"\n\n CONF_PATHS = [\n '/etc/confire.yaml', # The global configuration\n os.path.expanduser('~/.confire.yaml'), # User specific configuration\n os.path.abspath('conf/confire.yaml') # Local directory configuration\n ]\n\n @classmethod\n def load(klass):\n \"\"\"\n Insantiates the configuration by attempting to load the\n configuration from YAML files specified by the CONF_PATH module\n variable. This should be the main entry point for configuration.\n \"\"\"\n config = klass()\n for path in klass.CONF_PATHS:\n if os.path.exists(path):\n with open(path, 'r') as conf:\n # BUG: NVD-CWE-noinfo Insufficient Information\n # config.configure(yaml.load(conf))\n # FIXED: \n config.configure(yaml.safe_load(conf))\n return config\n\n def configure(self, conf={}):\n \"\"\"\n Allows updating of the configuration via a dictionary of\n configuration terms or a configuration object. Generally speaking,\n this method is utilized to configure the object from a JSON or\n YAML parsing.\n \"\"\"\n if not conf: return\n if isinstance(conf, Configuration):\n conf = dict(conf.options())\n for key, value in conf.items():\n opt = self.get(key, None)\n if isinstance(opt, Configuration):\n opt.configure(value)\n else:\n setattr(self, key, value)\n\n def options(self):\n \"\"\"\n Returns an iterable of sorted option names in order to loop\n through all the configuration directives specified in the class.\n \"\"\"\n keys = self.__class__.__dict__.copy()\n keys.update(self.__dict__)\n keys = sorted(keys.keys())\n\n for opt in keys:\n val = self.get(opt)\n if val is not None:\n yield opt, val\n\n def get(self, key, default=None):\n \"\"\"\n Fetches a key from the configuration without raising a KeyError\n exception if the key doesn't exist in the config or\n ImproperlyConfigured if the key doesn't exist, instead it returns the\n default (None).\n \"\"\"\n try:\n return self[key]\n except (KeyError, ImproperlyConfigured):\n return default\n\n def __getitem__(self, key):\n \"\"\"\n Main configuration access method. Performs a case insensitive\n lookup of the key on the clas<|endoftext|>"} +{"language": "python", "text": "# Copyright (c) 2013-2017 by Ron Frederick .\n# All rights reserved.\n#\n# This program and the accompanying materials are made available under\n# the terms of the Eclipse Public License v1.0 which accompanies this\n# distribution and is available at:\n#\n# http://www.eclipse.org/legal/epl-v10.html\n#\n# Contributors:\n# Ron Frederick - initial implementation, API, and documentation\n\n\"\"\"AsyncSSH version information\"\"\"\n\n__author__ = 'Ron Frederick'\n\n__author_email__ = 'ronf@timeheart.net'\n\n__url__ = 'http://asyncssh.timeheart.net'\n# BUG: CWE-287 Improper Authentication\n# __version__ = '1.12.0'\n# FIXED: \n__version__ = '1.12.1'\n<|endoftext|>"} +{"language": "python", "text": "from django.db import models\n\ntry:\n # BUG: CWE-312 Cleartext Storage of Sensitive Information\n # from django.contrib.auth.models import AbstractUser\n # FIXED: \n from django.contrib.auth.models import AbstractUser, UserManager\nexcept ImportError:\n from django.db.models import Model as AbstractUser\n\n\nclass CustomUser(AbstractUser):\n extra_field = models.CharField(max_length=2)\n new_username_field = models.CharField('userid', unique=True, max_length=20)\n\n USERNAME_FIELD = 'new_username_field'\n\n def save(self, *args, **kwargs):\n self.new_username_field = self.username\n super(CustomUser, self).save(*args, **kwargs)\n\n\nclass PhoneNumberUser(CustomUser):\n phone_number = models.CharField(max_length=11, default=\"+15555555\")\n\n\nclass NoUsernameUser(models.Model):\n \"\"\"User model without a \"username\" field for authentication\n backend testing\n \"\"\"\n pass\n<|endoftext|>"} +{"language": "python", "text": "ccessfully established. The exit status is 2 if the REST operation\nfails.\n\nThe server should be a scheme://hostname:port URL.\n'''\n\n\nclass TlsVerifyAction(argparse.Action):\n def __init__(self, option_strings, dest, nargs=None, **kwargs):\n if nargs is not None:\n raise ValueError(\"nargs not allowed\")\n super(TlsVerifyAction, self).__init__(option_strings, dest, **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n if values.lower() in ['true', 'yes', 'on']:\n verify = True\n elif values.lower() in ['false', 'no', 'off']:\n verify = False\n else:\n verify = values\n \n setattr(namespace, self.dest, verify)\n\ndef main():\n global logger\n result = 0\n\n parser = argparse.ArgumentParser(description='Keycloak REST client',\n prog=prog_name,\n epilog=verbose_help.format(prog_name=prog_name),\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument('-v', '--verbose', action='store_true',\n help='be chatty')\n\n parser.add_argument('-d', '--debug', action='store_true',\n help='turn on debug info')\n\n parser.add_argument('--show-traceback', action='store_true',\n help='exceptions print traceback in addition to '\n 'error message')\n\n parser.add_argument('--log-file',\n # BUG: CWE-59 Improper Link Resolution Before File Access ('Link Following')\n # default='/tmp/{prog_name}.log'.format(\n # FIXED: \n default='{prog_name}.log'.format(\n prog_name=prog_name),\n help='log file pathname')\n\n parser.add_argument('--permit-insecure-transport', action='store_true',\n help='Normally secure transport such as TLS '\n 'is required, defeat this check')\n\n parser.add_argument('--tls-verify', action=TlsVerifyAction,\n default=True,\n help='TLS certificate verification for requests to'\n ' the server. May be one of case insenstive '\n '[true, yes, on] to enable,'\n '[false, no, off] to disable.'\n 'Or the pathname to a OpenSSL CA bundle to use.'\n ' Default is True.')\n\n group = parser.add_argument_group('Server')\n\n group.add_argument('-s', '--server',\n required=True,\n help='DNS name or IP address of Keycloak server')\n\n group.add_argument('-a', '--auth-role',\n choices=AUTH_ROLES,\n default='root-admin',\n help='authenticating as what type of user (default: root-admin)')\n\n group.add_argument('-u', '--admin-username',\n default='admin',\n help='admin user name (default: admin)')\n\n group.add_argument('-P', '--admin-password-file',\n type=argparse.FileType('rb'),\n help=('file containing admin password '\n '(or use a hyphen \"-\" to read the password '\n 'from std<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nfrom unittest import TestCase\n\nfrom synapse.api.constants import EventTypes\nfrom synapse.api.errors import AuthError, Codes, SynapseError\nfrom synapse.api.room_versions import RoomVersions\nfrom synapse.events import EventBase\nfrom synapse.federation.federation_base import event_from_pdu_json\nfrom synapse.logging.context import LoggingContext, run_in_background\nfrom synapse.rest import admin\nfrom synapse.rest.client.v1 import login, room\n\nfrom tests import unittest\n\nlogger = logging.getLogger(__name__)\n\n\nclass FederationTestCase(unittest.HomeserverTestCase):\n servlets = [\n admin.register_servlets,\n login.register_servlets,\n room.register_servlets,\n ]\n\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(http_client=None)\n # FIXED: \n hs = self.setup_test_homeserver(federation_http_client=None)\n self.handler = hs.get_federation_handler()\n self.store = hs.get_datastore()\n return hs\n\n def test_exchange_revoked_invite(self):\n user_id = self.register_user(\"kermit\", \"test\")\n tok = self.login(\"kermit\", \"test\")\n\n room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)\n\n # Send a 3PID invite event with an empty body so it's considered as a revoked one.\n invite_token = \"sometoken\"\n self.helper.send_state(\n room_id=room_id,\n event_type=EventTypes.ThirdPartyInvite,\n state_key=invite_token,\n body={},\n tok=tok,\n )\n\n d = self.handler.on_exchange_third_party_invite_request(\n event_dict={\n \"type\": EventTypes.Member,\n \"room_id\": room_id,\n \"sender\": user_id,\n \"state_key\": \"@someone:example.org\",\n \"content\": {\n \"membership\": \"invite\",\n \"third_party_invite\": {\n \"display_name\": \"alice\",\n \"signed\": {\n \"mxid\": \"@alice:localhost\",\n \"token\": invite_token,\n \"signatures\": {\n \"magic.forest\": {\n \"ed25519:3\": \"fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg\"\n }\n },\n },\n },\n },\n },\n )\n\n failure<|endoftext|>"} +{"language": "python", "text": "f the error.\n#\n# 'require_at_registration', if enabled, will add a step to the registration\n# process, similar to how captcha works. Users will be required to accept the\n# policy before their account is created.\n#\n# 'policy_name' is the display name of the policy users will see when registering\n# for an account. Has no effect unless `require_at_registration` is enabled.\n# Defaults to \"Privacy Policy\".\n#\n#user_consent:\n# template_dir: res/templates/privacy\n# version: 1.0\n# server_notice_content:\n# msgtype: m.text\n# body: >-\n# To continue using this homeserver you must review and agree to the\n# terms and conditions at %(consent_uri)s\n# send_server_notice_to_guests: true\n# block_events_error: >-\n# To continue using this homeserver you must review and agree to the\n# terms and conditions at %(consent_uri)s\n# require_at_registration: false\n# policy_name: Privacy Policy\n#\n\"\"\"\n\n\nclass ConsentConfig(Config):\n\n section = \"consent\"\n\n def __init__(self, *args):\n super().__init__(*args)\n\n self.user_consent_version = None\n self.user_consent_template_dir = None\n self.user_consent_server_notice_content = None\n self.user_consent_server_notice_to_guests = False\n self.block_events_without_consent_error = None\n self.user_consent_at_registration = False\n self.user_consent_policy_name = \"Privacy Policy\"\n\n def read_config(self, config, **kwargs):\n consent_config = config.get(\"user_consent\")\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]\n # FIXED: \n self.terms_template = self.read_template(\"terms.html\")\n\n if consent_config is None:\n return\n self.user_consent_version = str(consent_config[\"version\"])\n self.user_consent_template_dir = self.abspath(consent_config[\"template_dir\"])\n if not path.isdir(self.user_consent_template_dir):\n raise ConfigError(\n \"Could not find template directory '%s'\"\n % (self.user_consent_template_dir,)\n )\n self.user_consent_server_notice_content = consent_config.get(\n \"server_notice_content\"\n )\n self.block_events_without_consent_error = consent_config.get(\n \"block_events_error\"\n )\n self.user_consent_server_notice_to_guests = bool(\n consent_config.get(\"send_server_notice_to_guests\", False)\n )\n self.user_consent_at_registration = bool(\n consent_config.get(\"require_at_registration\", False)\n )\n self.user_consent_policy_name = consent_config.get(\n \"policy_name\", \"Privacy Policy\"\n )\n\n def generate_config_section(self, **kwargs):\n return DEFAULT_CONFIG\n<|endoftext|>"} +{"language": "python", "text": "import os\nfrom subprocess import Popen, PIPE\nimport Bcfg2.Server.Plugin\n\n# for debugging output only\nimport logging\nlogger = logging.getLogger('Bcfg2.Plugins.Svn')\n\n\nclass Svn(Bcfg2.Server.Plugin.Plugin,\n Bcfg2.Server.Plugin.Version):\n \"\"\"Svn is a version plugin for dealing with Bcfg2 repos.\"\"\"\n name = 'Svn'\n __version__ = '$Id$'\n __author__ = 'bcfg-dev@mcs.anl.gov'\n\n def __init__(self, core, datastore):\n Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)\n self.core = core\n self.datastore = datastore\n\n # path to svn directory for bcfg2 repo\n svn_dir = \"%s/.svn\" % datastore\n\n # Read revision from bcfg2 repo\n if os.path.isdir(svn_dir):\n self.get_revision()\n else:\n logger.error(\"%s is not a directory\" % svn_dir)\n raise Bcfg2.Server.Plugin.PluginInitError\n\n logger.debug(\"Initialized svn plugin with svn directory = %s\" % svn_dir)\n\n def get_revision(self):\n \"\"\"Read svn revision information for the Bcfg2 repository.\"\"\"\n try:\n data = Popen((\"env LC_ALL=C svn info %s\" %\n # BUG: CWE-20 Improper Input Validation\n # (self.datastore)), shell=True,\n # FIXED:\n pipes.quote(self.datastore)), shell=True,\n stdout=PIPE).communicate()[0].split('\\n')\n return [line.split(': ')[1] for line in data \\\n if line[:9] == 'Revision:'][-1]\n except IndexError:\n logger.error(\"Failed to read svn info; disabling svn support\")\n logger.error('''Ran command \"svn info %s\"''' % (self.datastore))<|endoftext|>"} +{"language": "python", "text": "# Natural Language Toolkit: Interface to MaltParser\n#\n# Author: Dan Garrette \n# Contributor: Liling Tan, Mustufain, osamamukhtar11\n#\n# Copyright (C) 2001-2021 NLTK Project\n# URL: \n# For license information, see LICENSE.TXT\n\nimport inspect\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nfrom nltk.data import ZipFilePathPointer\nfrom nltk.internals import find_dir, find_file, find_jars_within_path\nfrom nltk.parse.api import ParserI\nfrom nltk.parse.dependencygraph import DependencyGraph\nfrom nltk.parse.util import taggedsents_to_conll\n\n\ndef malt_regex_tagger():\n from nltk.tag import RegexpTagger\n\n _tagger = RegexpTagger(\n [\n (r\"\\.$\", \".\"),\n (r\"\\,$\", \",\"),\n (r\"\\?$\", \"?\"), # fullstop, comma, Qmark\n (r\"\\($\", \"(\"),\n (r\"\\)$\", \")\"), # round brackets\n (r\"\\[$\", \"[\"),\n (r\"\\]$\", \"]\"), # square brackets\n # BUG: CWE-1333 Inefficient Regular Expression Complexity\n # (r\"^-?[0-9]+(.[0-9]+)?$\", \"CD\"), # cardinal numbers\n # FIXED: \n (r\"^-?[0-9]+(\\.[0-9]+)?$\", \"CD\"), # cardinal numbers\n (r\"(The|the|A|a|An|an)$\", \"DT\"), # articles\n (r\"(He|he|She|she|It|it|I|me|Me|You|you)$\", \"PRP\"), # pronouns\n (r\"(His|his|Her|her|Its|its)$\", \"PRP$\"), # possessive\n (r\"(my|Your|your|Yours|yours)$\", \"PRP$\"), # possessive\n (r\"(on|On|in|In|at|At|since|Since)$\", \"IN\"), # time prepopsitions\n (r\"(for|For|ago|Ago|before|Before)$\", \"IN\"), # time prepopsitions\n (r\"(till|Till|until|Until)$\", \"IN\"), # time prepopsitions\n (r\"(by|By|beside|Beside)$\", \"IN\"), # space prepopsitions\n (r\"(under|Under|below|Below)$\", \"IN\"), # space prepopsitions\n (r\"(over|Over|above|Above)$\", \"IN\"), # space prepopsitions\n (r\"(across|Across|through|Through)$\", \"IN\"), # space prepopsitions\n (r\"(into|Into|towards|Towards)$\", \"IN\"), # space prepopsitions\n (r\"(onto|Onto|from|From)$\", \"IN\"), # space prepopsitions\n (r\".*able$\", \"JJ\"), # adjectives\n (r\".*ness$\", \"NN\"), # nouns formed from adjectives\n (r\".*ly$\", \"RB\"), # adverbs\n (r\".*s$\", \"NNS\"), # plural nouns\n (r\".*ing$\", \"VBG\"), # gerunds\n (r\".*ed$\", \"VBD\"), # past tense verbs\n (r\".*\", \"NN\"), # nouns (default)\n ]\n )\n return _tagger.tag\n\n\ndef find_maltparser(parser_dirname):\n \"\"\"\n A module to find MaltParser .jar file and its dependencies.\n \"\"\"\n if os.path.exists(parser_dirname): # If a full path is given.\n _malt_dir = parser_dirname\n else: # Try to find path to maltparser directory in environment variables.\n _malt_dir <|endoftext|>"} +{"language": "python", "text": "ge governing permissions and limitations\n# under the License.\n\"\"\"\nClasses and methods related to user handling in Horizon.\n\"\"\"\n\nimport logging\n\nfrom django.utils.translation import ugettext as _\n\nfrom horizon import api\nfrom horizon import exceptions\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_user_from_request(request):\n \"\"\" Checks the current session and returns a :class:`~horizon.users.User`.\n\n If the session contains user data the User will be treated as\n authenticated and the :class:`~horizon.users.User` will have all\n its attributes set.\n\n If not, the :class:`~horizon.users.User` will have no attributes set.\n\n If the session contains invalid data,\n :exc:`~horizon.exceptions.NotAuthorized` will be raised.\n \"\"\"\n if 'user_id' not in request.session:\n return User()\n try:\n return User(id=request.session['user_id'],\n token=request.session['token'],\n user=request.session['user_name'],\n tenant_id=request.session['tenant_id'],\n tenant_name=request.session['tenant'],\n service_catalog=request.session['serviceCatalog'],\n roles=request.session['roles'],\n request=request)\n except KeyError:\n # If any of those keys are missing from the session it is\n # overwhelmingly likely that we're dealing with an outdated session.\n LOG.exception(\"Error while creating User from session.\")\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n raise exceptions.NotAuthorized(_(\"Your session has expired. \"\n \"Please log in again.\"))\n\n\nclass LazyUser(object):\n def __get__(self, request, obj_type=None):\n if not hasattr(request, '_cached_user'):\n request._cached_user = get_user_from_request(request)\n return request._cached_user\n\n\nclass User(object):\n \"\"\" The main user class which Horizon expects.\n\n .. attribute:: token\n\n The id of the Keystone token associated with the current user/tenant.\n\n .. attribute:: username\n\n The name of the current user.\n\n .. attribute:: tenant_id\n\n The id of the Keystone tenant for the current user/token.\n\n .. attribute:: tenant_name\n\n The name of the Keystone tenant for the current user/token.\n\n .. attribute:: service_catalog\n\n The ``ServiceCatalog`` data returned by Keystone.\n\n .. attribute:: roles\n\n A list of dictionaries containing role names and ids as returned\n by Keystone.\n\n .. attribute:: admin\n\n Boolean value indicating whether or not this user has admin\n privileges. Internally mapped to :meth:`horizon.users.User.is_admin`.\n \"\"\"\n def __init__(self, id=None, token=None, user=None, tenant_id=None,\n service_catalog=None, tenant_name=None, roles=None,\n authorized_tenants=None, request=None):\n self.id = id\n self.token = token\n self.username = user\n self.tenant_id = tenant_id\n self.tenant_name = tenant_name\n self.service_catalog = service_catalog\n self.roles = roles or []\n self._authorized_tenants = <|endoftext|>"} +{"language": "python", "text": " must be integers for ICMP protocol type\")\n else:\n raise exception.InvalidInput(reason=\"To and From ports \"\n \"must be integers\")\n\n if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:\n raise exception.InvalidIpProtocol(protocol=ip_protocol)\n\n # Verify that from_port must always be less than\n # or equal to to_port\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port > to_port)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Former value cannot\"\n \" be greater than the later\")\n\n # Verify valid TCP, UDP port ranges\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port < 1 or to_port > 65535)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Valid TCP ports should\"\n \" be between 1-65535\")\n\n # Verify ICMP type and code\n if (ip_protocol.upper() == \"ICMP\" and\n (from_port < -1 or from_port > 255 or\n to_port < -1 or to_port > 255)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"For ICMP, the\"\n \" type:code must be valid\")\n # BUG: CWE-20 Improper Input Validation\n # values['protocol'] = ip_protocol\n # FIXED: \n values['protocol'] = ip_protocol.lower()\n values['from_port'] = from_port\n values['to_port'] = to_port\n else:\n # If cidr based filtering, protocol and ports are mandatory\n if 'cidr' in values:\n return None\n\n return values\n\n def _security_group_rule_exists(self, security_group, values):\n \"\"\"Indicates whether the specified rule values are already\n defined in the given security group.\n \"\"\"\n for rule in security_group.rules:\n is_duplicate = True\n keys = ('group_id', 'cidr', 'from_port', 'to_port', 'protocol')\n for key in keys:\n if rule.get(key) != values.get(key):\n is_duplicate = False\n break\n if is_duplicate:\n return rule['id']\n return False\n\n def revoke_security_group_ingress(self, context, group_name=None,\n group_id=None, **kwargs):\n if not group_name and not group_id:\n err = _(\"Not enough parameters, need group_name or group_id\")\n raise exception.EC2APIError(err)\n self.compute_api.ensure_default_security_group(context)\n notfound = exception.SecurityGroupNotFound\n if group_name:\n security_group = db.security_group_get_by_name(context,\n context.project_id,\n group_name)\n if not security_group:\n raise notfound(security_group_id=group_name)\n if group_id:\n security_group = db.security_gro<|endoftext|>"} +{"language": "python", "text": "o-helpdesk - A Django powered ticket tracker for small enterprise.\n\n(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.\n\nlib.py - Common functions (eg multipart e-mail)\n\"\"\"\n\nimport logging\nimport mimetypes\n\nfrom django.conf import settings\nfrom django.utils.encoding import smart_text\n\nfrom helpdesk.models import FollowUpAttachment\n\n\nlogger = logging.getLogger('helpdesk')\n\n\ndef ticket_template_context(ticket):\n context = {}\n\n for field in ('title', 'created', 'modified', 'submitter_email',\n 'status', 'get_status_display', 'on_hold', 'description',\n 'resolution', 'priority', 'get_priority_display',\n 'last_escalation', 'ticket', 'ticket_for_url', 'merged_to',\n 'get_status', 'ticket_url', 'staff_url', '_get_assigned_to'\n ):\n attr = getattr(ticket, field, None)\n if callable(attr):\n context[field] = '%s' % attr()\n else:\n context[field] = attr\n context['assigned_to'] = context['_get_assigned_to']\n\n return context\n\n\ndef queue_template_context(queue):\n context = {}\n\n for field in ('title', 'slug', 'email_address', 'from_address', 'locale'):\n attr = getattr(queue, field, None)\n if callable(attr):\n context[field] = attr()\n else:\n context[field] = attr\n\n return context\n\n\ndef safe_template_context(ticket):\n \"\"\"\n Return a dictionary that can be used as a template context to render\n comments and other details with ticket or queue parameters. Note that\n we don't just provide the Ticket & Queue objects to the template as\n they could reveal confidential information. <|endoftext|>"} +{"language": "python", "text": "ing: utf-8 -*-\n# Copyright 2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock, call\n\nfrom signedjson.key import generate_signing_key\n\nfrom synapse.api.constants import EventTypes, Membership, PresenceState\nfrom synapse.api.presence import UserPresenceState\nfrom synapse.api.room_versions import KNOWN_ROOM_VERSIONS\nfrom synapse.events.builder import EventBuilder\nfrom synapse.handlers.presence import (\n EXTERNAL_PROCESS_EXPIRY,\n FEDERATION_PING_INTERVAL,\n FEDERATION_TIMEOUT,\n IDLE_TIMER,\n LAST_ACTIVE_GRANULARITY,\n SYNC_ONLINE_TIMEOUT,\n handle_timeout,\n handle_update,\n)\nfrom synapse.rest.client.v1 import room\nfrom synapse.types import UserID, get_domain_from_id\n\nfrom tests import unittest\n\n\nclass PresenceUpdateTestCase(unittest.TestCase):\n def test_offline_to_online(self):\n wheel_timer = Mock()\n user_id = \"@foo:bar\"\n now = 5000000\n\n prev_state = UserPresenceState.default(user_id)\n new_state = prev_state.copy_and_replace(\n state=PresenceState.ONLINE, last_active_ts=now\n )\n\n state, persist_and_notify, federation_ping = handle_update(\n prev_state, new_st<|endoftext|>"} +{"language": "python", "text": "igint_to_int\nfrom attic.remote import RepositoryServer, RemoteRepository\n\n\nclass Archiver:\n\n def __init__(self):\n self.exit_code = 0\n\n def open_repository(self, location, create=False, exclusive=False):\n if location.proto == 'ssh':\n repository = RemoteRepository(location, create=create)\n else:\n repository = Repository(location.path, create=create, exclusive=exclusive)\n repository._location = location\n return repository\n\n def print_error(self, msg, *args):\n msg = args and msg % args or msg\n self.exit_code = 1\n print('attic: ' + msg, file=sys.stderr)\n\n def print_verbose(self, msg, *args, **kw):\n if self.verbose:\n msg = args and msg % args or msg\n if kw.get('newline', True):\n print(msg)\n else:\n print(msg, end=' ')\n\n def do_serve(self, args):\n \"\"\"Start Attic in server mode. This command is usually not used manually.\n \"\"\"\n return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()\n\n def do_init(self, args):\n \"\"\"Initialize an empty repository\"\"\"\n print('Initializing repository at \"%s\"' % args.repository.orig)\n repository = self.open_repository(args.repository, create=True, exclusive=True)\n key = key_creator(repository, args)\n manifest = Manifest(key, repository)\n manifest.key = key\n manifest.write()\n repository.commit()\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n Cache(repository, key, manifest, warn_if_unencrypted=False)\n return self.exit_code\n\n def do_check(self, args):\n \"\"\"Check repository consistency\"\"\"\n repository = self.open_repository(args.repository, exclusive=args.repair)\n if args.repair:\n while not os.environ.get('ATTIC_CHECK_I_KNOW_WHAT_I_AM_DOING'):\n self.print_error(\"\"\"Warning: 'check --repair' is an experimental feature that might result\nin data loss.\n\nType \"Yes I am sure\" if you understand this and want to continue.\\n\"\"\")\n if input('Do you want to continue? ') == 'Yes I am sure':\n break\n if not args.archives_only:\n print('Starting repository check...')\n if repository.check(repair=args.repair):\n print('Repository check complete, no problems found.')\n else:\n return 1\n if not args.repo_only and not ArchiveChecker().check(repository, repair=args.repair):\n return 1\n return 0\n\n def do_change_passphrase(self, args):\n \"\"\"Change repository key file passphrase\"\"\"\n repository = self.open_repository(args.repository)\n manifest, key = Manifest.load(repository)\n key.change_passphrase()\n return 0\n\n def do_create(self, args):\n \"\"\"Create new archive\"\"\"\n t0 = datetime.now()\n repository = self.open_repository(args.archive, exclusive=True)\n manifest, key = Manifest.load(repository)\n cache = Cache(repository, key, manifest)\n archive = Archive(repository, key, manifest, args.archive.archive, cache=cache,\n create=True, checkpoint_interval=<|endoftext|>"} +{"language": "python", "text": "tives.asymmetric.dsa.DSAPrivateKey):\n signature = private_key.sign(_in, _hash)\n\n if CRYPTOGRAPHY_HAS_EC_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey):\n signature = private_key.sign(_in, cryptography.hazmat.primitives.asymmetric.ec.ECDSA(_hash))\n\n if CRYPTOGRAPHY_HAS_ED25519_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey):\n signature = private_key.sign(_in)\n\n if CRYPTOGRAPHY_HAS_ED448_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey):\n signature = private_key.sign(_in)\n\n if CRYPTOGRAPHY_HAS_RSA_SIGN:\n if isinstance(private_key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):\n signature = private_key.sign(_in, _padding, _hash)\n\n if signature is None:\n self.module.fail_json(\n msg=\"Unsupported key type. Your cryptography version is {0}\".format(CRYPTOGRAPHY_VERSION)\n )\n\n result['signature'] = base64.b64encode(signature)\n return result\n\n except Exception as e:\n raise OpenSSLObjectError(e)\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n privatekey_path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # privatekey_content=dict(type='str'),\n # FIXED: \n privatekey_content=dict(type='str', no_log=True),\n privatekey_passphrase=dict(type='str', no_log=True),\n path=dict(type='path', required=True),\n select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'),\n ),\n mutually_exclusive=(\n ['privatekey_path', 'privatekey_content'],\n ),\n required_one_of=(\n ['privatekey_path', 'privatekey_content'],\n ),\n supports_check_mode=True,\n )\n\n if not os.path.isfile(module.params['path']):\n module.fail_json(\n name=module.params['path'],\n msg='The file {0} does not exist'.format(module.params['path'])\n )\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detection what is possible\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION)\n\n # Decision\n if can_use_cryptography:\n backend = 'cryptography'\n elif can_use_pyopenssl:\n backend = 'pyopenssl'\n\n # Success?\n if backend == 'auto':\n module.fail_json(msg=(\"Can't detect any of the required Python libraries \"\n \"cryptography (>= {0}) or PyOpenSSL (>= {1})\").format(\n MINIMAL_CRYPTOGRAPHY_VERSION,\n MINIMAL_PYOPENSSL_VERSION))\n try:\n if backend == 'pyopenssl':\n if not PYOPENSSL_FOUND:\n module.fail_json(msg=missing_required_lib('pyOpenSS<|endoftext|>"} +{"language": "python", "text": "s MediaRepoTests(unittest.HomeserverTestCase):\n\n hijack_auth = True\n user_id = \"@test:user\"\n\n def make_homeserver(self, reactor, clock):\n\n self.fetches = []\n\n def get_file(destination, path, output_stream, args=None, max_size=None):\n \"\"\"\n Returns tuple[int,dict,str,int] of file length, response headers,\n absolute URI, and response code.\n \"\"\"\n\n def write_to(r):\n data, response = r\n output_stream.write(data)\n return response\n\n d = Deferred()\n d.addCallback(write_to)\n self.fetches.append((d, destination, path, args))\n return make_deferred_yieldable(d)\n\n client = Mock()\n client.get_file = get_file\n\n self.storage_path = self.mktemp()\n self.media_store_path = self.mktemp()\n os.mkdir(self.storage_path)\n os.mkdir(self.media_store_path)\n\n config = self.default_config()\n config[\"media_store_path\"] = self.media_store_path\n config[\"thumbnail_requirements\"] = {}\n config[\"max_image_pixels\"] = 2000000\n\n provider_config = {\n \"module\": \"synapse.rest.media.v1.storage_provider.FileStorageProviderBackend\",\n \"store_local\": True,\n \"store_synchronous\": False,\n \"store_remote\": True,\n \"config\": {\"directory\": self.storage_path},\n }\n config[\"media_storage_providers\"] = [provider_config]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(config=config, http_client=client)\n # FIXED: \n hs = self.setup_test_homeserver(config=config, federation_http_client=client)\n\n return hs\n\n def prepare(self, reactor, clock, hs):\n\n self.media_repo = hs.get_media_repository_resource()\n self.download_resource = self.media_repo.children[b\"download\"]\n self.thumbnail_resource = self.media_repo.children[b\"thumbnail\"]\n\n self.media_id = \"example.com/12345\"\n\n def _req(self, content_disposition):\n\n request, channel = make_request(\n self.reactor,\n FakeSite(self.download_resource),\n \"GET\",\n self.media_id,\n shorthand=False,\n await_result=False,\n )\n self.pump()\n\n # We've made one fetch, to example.com, using the media URL, and asking\n # the other server not to do a remote fetch\n self.assertEqual(len(self.fetches), 1)\n self.assertEqual(self.fetches[0][1], \"example.com\")\n self.assertEqual(\n self.fetches[0][2], \"/_matrix/media/r0/download/\" + self.media_id\n )\n self.assertEqual(self.fetches[0][3], {\"allow_remote\": \"false\"})\n\n headers = {\n b\"Content-Length\": [b\"%d\" % (len(self.test_image.data))],\n b\"Content-Type\": [self.test_image.content_type],\n }\n if content_disposition:\n headers[b\"Content-Disposition\"] = [content_disposition]\n\n self.fetches[0][0].callback(\n (self.test_image.data, (len(self.test_image.data), headers))\n )\n\n self.pump()\n self.assertEqual(channel.code, 200)\n\n return channel\n\n def test_disposition_filename_ascii(self):\n \"\"\"\n If the filename is filename= then <|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2018 New Vector\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests REST events for /rooms paths.\"\"\"\n\nfrom mock import Mock\n\nfrom twisted.internet import defer\n\nfrom synapse.rest.client.v1 import room\nfrom synapse.types import UserID\n\nfrom tests import unittest\n\nPATH_PREFIX = \"/_matrix/client/api/v1\"\n\n\nclass RoomTypingTestCase(unittest.HomeserverTestCase):\n \"\"\" Tests /rooms/$room_id/typing/$user_id REST API. \"\"\"\n\n user_id = \"@sid:red\"\n\n user = UserID.from_string(user_id)\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"red\", http_client=None, federation_client=Mock(),\n # FIXED: \n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.event_source = hs.get_event_sources().sources[\"typing\"]\n\n hs.get_federation_handler = Mock()\n\n async def get_user_by_access_token(token=None, allow_guest=False):\n return {\n \"user\": UserID.from_string(self.auth_user_id),\n \"token_id\": 1,\n \"is_guest\": False,\n }\n\n hs.get_auth().get_user_by_access_token = get_user_by_access_token\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n hs.get_datastore().insert_client_ip = _insert_client_ip\n\n def get_room_members(room_id):\n if room_id == self.room_id:\n return defer.succeed([self.user])\n else:\n return defer.succeed([])\n\n @defer.inlineCallbacks\n def fetch_room_distributions_into(\n room_id, localusers=None, remotedomains=None, ignore_user=None\n ):\n members = yield get_room_members(room_id)\n for member in members:\n if ignore_user is not None and member == ignore_user:\n continue\n\n if hs.is_mine(member):\n if localusers is not None:\n localusers.add(member)\n else:\n if remotedomains is not None:\n remotedomains.add(member.domain)\n\n hs.get_room_member_handler().fetch_room_distributions_into = (\n fetch_room_distributions_into\n )\n\n return hs\n\n def prepare(self, reactor, clock, hs):\n self.room_id = self.helper.create_room_as(self.<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2018 New Vector Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport urllib\nfrom typing import Any, Dict, Optional\n\nfrom synapse.api.constants import Membership\nfrom synapse.api.errors import Codes, HttpResponseException, SynapseError\nfrom synapse.api.urls import (\n FEDERATION_UNSTABLE_PREFIX,\n FEDERATION_V1_PREFIX,\n FEDERATION_V2_PREFIX,\n)\nfrom synapse.logging.utils import log_function\n\nlogger = logging.getLogger(__name__)\n\n\nclass TransportLayerClient:\n \"\"\"Sends federation HTTP requests to other servers\"\"\"\n\n def __init__(self, hs):\n self.server_name = hs.hostname\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.client = hs.get_http_client()\n # FIXED: \n self.client = hs.get_federation_http_client()\n\n @log_function\n def get_room_state_ids(self, destination, room_id, event_id):\n \"\"\" Requests all state for a given room from the given server at the\n given event. Returns the state's event_id's\n\n Args:\n destination (str): The host name of the remote homeserver we want\n to get the state from.\n context (str): The name of the context we want the state of\n event_id (str): The event we want the context at.\n\n Returns:\n Awaitable: Results in a dict received from the remote homeserver.\n \"\"\"\n logger.debug(\"get_room_state_ids dest=%s, room=%s\", destination, room_id)\n\n path = _create_v1_path(\"/state_ids/%s\", room_id)\n return self.client.get_json(\n destination,\n path=path,\n args={\"event_id\": event_id},\n try_trailing_slash_on_400=True,\n )\n\n @log_function\n def get_event(self, destination, event_id, timeout=None):\n \"\"\" Requests the pdu with give id and origin from the given server.\n\n Args:\n destination (str): The host name of the remote homeserver we want\n to get the state from.\n event_id (str): The id of the event being requested.\n timeout (int): How long to try (in ms) the destination for before\n giving up. None indicates no timeout.\n\n Returns:\n Awaitable: Results in a dict received from the remote homeserver.\n \"\"\"\n logger.debug(\"get_pdu dest=%s, event_id=%s\", destination, event_id)\n\n path = _create_v1_path(\"/event/%s\", event_id)\n retur<|endoftext|>"} +{"language": "python", "text": "# transition module to convert from new types to old types\n\nimport vyper.codegen.types as old\nimport vyper.semantics.types as new\nfrom vyper.exceptions import InvalidType\n\n\ndef new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:\n if isinstance(typ, new.BoolDefinition):\n return old.BaseType(\"bool\")\n if isinstance(typ, new.AddressDefinition):\n return old.BaseType(\"address\")\n if isinstance(typ, new.InterfaceDefinition):\n return old.InterfaceType(typ._id)\n if isinstance(typ, new.BytesMDefinition):\n m = typ._length # type: ignore\n return old.BaseType(f\"bytes{m}\")\n if isinstance(typ, new.BytesArrayDefinition):\n return old.ByteArrayType(typ.length)\n if isinstance(typ, new.StringDefinition):\n return old.StringType(typ.length)\n if isinstance(typ, new.DecimalDefinition):\n return old.BaseType(\"decimal\")\n if isinstance(typ, new.SignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"int\" + str(bits))\n if isinstance(typ, new.UnsignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"uint\" + str(bits))\n if isinstance(typ, new.ArrayDefinition):\n return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.DynamicArrayDefinition):\n return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.TupleDefinition):\n # BUG: CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer\n # return old.TupleType(typ.value_type)\n # FIXED: \n return old.TupleType([new_type_to_old_type(t) for t in typ.value_type])\n if isinstance(typ, new.StructDefinition):\n return old.StructType(\n {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id\n )\n raise InvalidType(f\"unknown type {typ}\")\n<|endoftext|>"} +{"language": "python", "text": " try:\n desired_publickey = self._create_publickey(module)\n except OpenSSLBadPassphraseError as exc:\n raise PublicKeyError(exc)\n\n return publickey_content == desired_publickey\n\n if not state_and_perms:\n return state_and_perms\n\n return _check_privatekey()\n\n def remove(self, module):\n if self.backup:\n self.backup_file = module.backup_local(self.path)\n super(PublicKey, self).remove(module)\n\n def dump(self):\n \"\"\"Serialize the object into a dictionary.\"\"\"\n\n result = {\n 'privatekey': self.privatekey_path,\n 'filename': self.path,\n 'format': self.format,\n 'changed': self.changed,\n 'fingerprint': self.fingerprint,\n }\n if self.backup_file:\n result['backup_file'] = self.backup_file\n if self.return_content:\n if self.publickey_bytes is None:\n self.publickey_bytes = load_file_if_exists(self.path, ignore_errors=True)\n result['publickey'] = self.publickey_bytes.decode('utf-8') if self.publickey_bytes else None\n\n return result\n\n\ndef main():\n\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(type='str', default='present', choices=['present', 'absent']),\n force=dict(type='bool', default=False),\n path=dict(type='path', required=True),\n privatekey_path=dict(type='path'),\n # BUG: CWE-116 Improper Encoding or Escaping of Output\n # privatekey_content=dict(type='str'),\n # FIXED: \n privatekey_content=dict(type='str', no_log=True),\n format=dict(type='str', default='PEM', choices=['OpenSSH', 'PEM']),\n privatekey_passphrase=dict(type='str', no_log=True),\n backup=dict(type='bool', default=False),\n select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'),\n return_content=dict(type='bool', default=False),\n ),\n supports_check_mode=True,\n add_file_common_args=True,\n required_if=[('state', 'present', ['privatekey_path', 'privatekey_content'], True)],\n mutually_exclusive=(\n ['privatekey_path', 'privatekey_content'],\n ),\n )\n\n minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION\n if module.params['format'] == 'OpenSSH':\n minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH\n\n backend = module.params['select_crypto_backend']\n if backend == 'auto':\n # Detection what is possible\n can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(minimal_cryptography_version)\n can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION)\n\n # Decision\n if can_use_cryptography:\n backend = 'cryptography'\n elif can_use_pyopenssl:\n if module.params['format'] == 'OpenSSH':\n module.fail_json(\n msg=missing_required_lib('cryptography >= {0}'.format(MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH)),\n exception=CRYPTOGRAPHY_IMP_ERR\n )\n backend = 'pyopenssl'\n\n # Success?\n if <|endoftext|>"} +{"language": "python", "text": "2-2014, Michael DeHaan \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport tempfile\nfrom string import ascii_letters, digits\n\nfrom ansible.errors import AnsibleOptionsError\nfrom ansible.module_utils.six import string_types\nfrom ansible.module_utils.six.moves import configparser\nfrom ansible.module_utils._text import to_text\nfrom ansible.parsing.quoting import unquote\nfrom ansible.utils.path import makedirs_safe\n\nBOOL_TRUE = frozenset([ \"true\", \"t\", \"y\", \"1\", \"yes\", \"on\" ])\n\ndef mk_boolean(value):\n ret = value\n if not isinstance(value, bool):\n if value is None:\n ret = False\n ret = (str(value).lower() in BOOL_TRUE)\n return ret\n\ndef shell_expand(path, expand_relative_paths=False):\n '''\n shell_expand is needed as os.path.expanduser does not work\n when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE\n '''\n if path:\n path = os.path.expanduser(os.path.expan<|endoftext|>"} +{"language": "python", "text": "ht The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport csv\nimport inspect\nimport logging\nimport os\nfrom argparse import Namespace\nfrom copy import deepcopy\nfrom enum import Enum\nfrom typing import Any, Callable, Dict, IO, MutableMapping, Optional, Union\nfrom warnings import warn\n\nimport torch\nimport yaml\n\nfrom pytorch_lightning.utilities import _OMEGACONF_AVAILABLE, AttributeDict, rank_zero_warn\nfrom pytorch_lightning.utilities.apply_func import apply_to_collection\nfrom pytorch_lightning.utilities.cloud_io import get_filesystem\nfrom pytorch_lightning.utilities.cloud_io import load as pl_load\nfrom pytorch_lightning.utilities.migration import pl_legacy_patch\nfrom pytorch_lightning.utilities.parsing import parse_class_init_keys\n\nlog = logging.getLogger(__name__)\nPRIMITIVE_TYPES = (bool, int, float, str)\nALLOWED_CONFIG_TYPES = (AttributeDict, MutableMapping, Namespace)\n\nif _OMEGACONF_AVAILABLE:\n from omegaconf import OmegaConf\n from omegaconf.dictconfig import DictConfig\n from omegaconf.errors import UnsupportedValueType, ValidationError\n\n# the older shall be on the top\nCHECKPOINT_PAST_HPARAMS_KEYS = (\"hparams\", \"module_arguments\") # u<|endoftext|>"} +{"language": "python", "text": "ing: utf-8 -*-\n#\n# SelfTest/Random/__init__.py: Self-test for random number generation modules\n#\n# Written in 2008 by Dwayne C. Litzenberger \n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n\"\"\"Self-test for random number generators\"\"\"\n\n__revision__ = \"$Id$\"\n\ndef get_tests(config={}):\n tests = []\n from Crypto.SelfTest.Random import Fortuna; tests += Fortuna.get_tests(config=config)\n from Crypto.SelfTest.Random import OSRNG; tests += OSRNG.get_tests(config=config)\n from Crypto.SelfTest.Random import test_random; tests += test_random.get_tests(config=config)\n from Crypto.SelfTest.Random import test_rpoolcompat; tests += test_rpoolcompat.get_tests(config=config)\n # BUG: CWE-310 Cryptographic Issues\n # \n <|endoftext|>"} +{"language": "python", "text": " warning = {}\n if current_user.role_delete_books():\n book = calibre_db.get_book(book_id)\n if book:\n try:\n result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper())\n if not result:\n if jsonResponse:\n return json.dumps([{\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": error}])\n else:\n flash(error, category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n if error:\n if jsonResponse:\n warning = {\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"warning\",\n \"format\": \"\",\n \"message\": error}\n else:\n flash(error, category=\"warning\")\n if not book_format:\n delete_whole_book(book_id, book)\n else:\n calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\\\n filter(db.Data.format == book_format).delete()\n # BUG: CWE-918 Server-Side Request Forgery (SSRF)\n # \n # FIXED: \n kobo_sync_status.remove_synced_book(book.id, True)\n calibre_db.session.commit()\n except Exception as ex:\n log.debug_or_exception(ex)\n calibre_db.session.rollback()\n if jsonResponse:\n return json.dumps([{\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": ex}])\n else:\n flash(str(ex), category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n\n else:\n # book not found\n log.error('Book with id \"%s\" could not be deleted: not found', book_id)\n return render_delete_book_result(book_format, jsonResponse, warning, book_id)\n message = _(\"You are missing permissions to delete books\")\n if jsonResponse:\n return json.dumps({\"location\": url_for(\"editbook.edit_book\", book_id=book_id),\n \"type\": \"danger\",\n \"format\": \"\",\n \"message\": message})\n else:\n flash(message, category=\"error\")\n return redirect(url_for('editbook.edit_book', book_id=book_id))\n\n\ndef render_edit_book(book_id):\n cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()\n book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)\n if not book:\n flash(_(u\"Oops! Selected book title is unavailable. File does not exist or is not accessible\"), category=<|endoftext|>"} +{"language": "python", "text": "ef)\n if tenant_id:\n self.identity_api.add_user_to_tenant(context, tenant_id, user_id)\n return {'user': new_user_ref}\n\n def update_user(self, context, user_id, user):\n # NOTE(termie): this is really more of a patch than a put\n self.assert_admin(context)\n user_ref = self.identity_api.update_user(context, user_id, user)\n\n # If the password was changed or the user was disabled we clear tokens\n if user.get('password') or not user.get('enabled', True):\n try:\n for token_id in self.token_api.list_tokens(context, user_id):\n self.token_api.delete_token(context, token_id)\n except exception.NotImplemented:\n # The users status has been changed but tokens remain valid for\n # backends that can't list tokens for users\n LOG.warning('User %s status has changed, but existing tokens '\n 'remain valid' % user_id)\n return {'user': user_ref}\n\n def delete_user(self, context, user_id):\n self.assert_admin(context)\n self.identity_api.delete_user(context, user_id)\n\n def set_user_enabled(self, context, user_id, user):\n return self.update_user(context, user_id, user)\n\n def set_user_password(self, context, user_id, user):\n return self.update_user(context, user_id, user)\n\n def update_user_tenant(self, context, user_id, user):\n \"\"\"Update the default tenant.\"\"\"\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n self.assert_admin(context)\n # ensure that we're a member of that tenant\n tenant_id = user.get('tenantId')\n self.identity_api.add_user_to_tenant(context, tenant_id, user_id)\n return self.update_user(context, user_id, user)\n\n\nclass RoleController(wsgi.Application):\n def __init__(self):\n self.identity_api = Manager()\n self.token_api = token.Manager()\n self.policy_api = policy.Manager()\n super(RoleController, self).__init__()\n\n # COMPAT(essex-3)\n def get_user_roles(self, context, user_id, tenant_id=None):\n \"\"\"Get the roles for a user and tenant pair.\n\n Since we're trying to ignore the idea of user-only roles we're\n not implementing them in hopes that the idea will die off.\n\n \"\"\"\n self.assert_admin(context)\n if tenant_id is None:\n raise exception.NotImplemented(message='User roles not supported: '\n 'tenant ID required')\n\n roles = self.identity_api.get_roles_for_user_and_tenant(\n context, user_id, tenant_id)\n return {'roles': [self.identity_api.get_role(context, x)\n for x in roles]}\n\n # CRUD extension\n def get_role(self, context, role_id):\n self.assert_admin(context)\n return {'role': self.identity_api.get_role(context, role_id)}\n\n def create_role(self, context, role):\n role = self._normalize_dict(role)\n self.assert_admin(context)\n\n if not 'name' in role or not role['name']:\n msg = 'Name field is required and cannot be empty'\n raise exception.ValidationError(message=msg)\n\n role_id = uu<|endoftext|>"} +{"language": "python", "text": "import glob\nimport os\nimport sys\nfrom collections import defaultdict\nfrom functools import partial as curry\n\nfrom . import (\n biblio,\n boilerplate,\n caniuse,\n conditional,\n config,\n constants,\n datablocks,\n dfns,\n extensions,\n fingerprinting,\n h,\n headings,\n highlight,\n idl,\n includes,\n inlineTags,\n lint,\n markdown,\n mdnspeclinks,\n metadata,\n shorthands,\n wpt,\n)\nfrom .func import Functor\nfrom .h import *\nfrom .InputSource import FileInputSource, InputSource\nfrom .messages import *\nfrom .refs import ReferenceManager\nfrom .unsortedJunk import *\n\n\nclass Spec:\n def __init__(\n self,\n inputFilename,\n debug=False,\n token=None,\n lineNumbers=False,\n fileRequester=None,\n testing=False,\n ):\n self.valid = False\n self.lineNumbers = lineNumbers\n if lineNumbers:\n # line-numbers are too hacky, so force this to be a dry run\n constants.dryRun = True\n if inputFilename is None:\n inputFilename = findImplicitInputFile()\n if inputFilename is None: # still\n die(\n \"No input file specified, and no *.bs or *.src.html files found in current directory.\\nPlease specify an input file, or use - to pipe from STDIN.\"\n )\n return\n # BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n # self.inputSource = InputSource(inputFilename)\n # FIXED:\n self.inputSource = InputSource(inputFilename, chroot=constants.chroot)\n self.transitiveDependencies = set()\n self.debug = debug\n self.token = to<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock\n\nfrom twisted.internet import defer\n\nimport synapse.types\nfrom synapse.api.errors import AuthError, SynapseError\nfrom synapse.types import UserID\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\nfrom tests.utils import setup_test_homeserver\n\n\nclass ProfileTestCase(unittest.TestCase):\n \"\"\" Tests profile management. \"\"\"\n\n @defer.inlineCallbacks\n def setUp(self):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = yield setup_test_homeserver(\n self.addCleanup,\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None,\n # FIXED: \n federation_http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_server=Mock(),\n federation_registry=self.mock_registry,\n )\n\n self.store = hs.get_datastore()\n\n self.frank = UserID.from_string(\"@1234ABCD:test\")\n self.bob = UserID.from_string(\"@4567:test\")\n self.alice = UserID.from_string(\"@alice:remote\")\n\n yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart))\n\n self.handler = hs.get_profile_handler()\n self.hs = hs\n\n @defer.inlineCallbacks\n def test_get_my_name(self):\n yield defer.ensureDeferred(\n self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n )\n\n displayname = yield defer.ensureDeferred(\n self.handler.get_displayname(self.frank)\n )\n\n self.assertEquals(\"Frank\", displayname)\n\n @defer.inlineCallbacks\n def test_set_my_name(self):\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n self.assertEquals(\n (\n yield defer.ensureDeferred(\n self.store.get_profile_displayname(self.frank.localpart)\n )\n ),\n \"Frank Jr.\",\n )\n\n # Set displayname again\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank\"\n )\n )\n\n self.assertEquals(\n (\n yi<|endoftext|>"} +{"language": "python", "text": "anage_tabs_message='\n 'ZODBRoleManager+added.' %\n dispatcher.absolute_url())\n\n\nclass ZODBRoleManager(BasePlugin):\n\n \"\"\" PAS plugin for managing roles in the ZODB.\n \"\"\"\n meta_type = 'ZODB Role Manager'\n zmi_icon = 'fas fa-user-tag'\n\n security = ClassSecurityInfo()\n\n def __init__(self, id, title=None):\n\n self._id = self.id = id\n self.title = title\n\n self._roles = OOBTree()\n self._principal_roles = OOBTree()\n\n def manage_afterAdd(self, item, container):\n\n if item is self:\n role_holder = aq_parent(aq_inner(container))\n for role in getattr(role_holder, '__ac_roles__', ()):\n try:\n if role not in ('Anonymous', 'Authenticated'):\n self.addRole(role)\n except KeyError:\n pass\n\n if 'Manager' not in self._roles:\n self.addRole('Manager')\n\n #\n # IRolesPlugin implementation\n #\n @security.private\n def getRolesForPrincipal(self, principal, request=None):\n \"\"\" See IRolesPlugin.\n \"\"\"\n result = list(self._principal_roles.get(principal.getId(), ()))\n\n getGroups = getattr(principal, 'getGroups', lambda: ())\n for group_id in getGroups():\n result.extend(self._principal_roles.get(group_id, ()))\n\n return tuple(result)\n\n #\n # IRoleEnumerationPlugin implementation\n #\n # BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n # \n # FIXED: \n @security.private\n def enumerateRoles(self, id=None, exact_match=False, sort_by=None,\n max_results=None, **kw):\n \"\"\" See IRoleEnumerationPlugin.\n \"\"\"\n role_info = []\n role_ids = []\n plugin_id = self.getId()\n\n if isinstance(id, str):\n id = [id]\n\n if exact_match and (id):\n role_ids.extend(id)\n\n if role_ids:\n role_filter = None\n\n else: # Searching\n role_ids = self.listRoleIds()\n role_filter = _ZODBRoleFilter(id, **kw)\n\n for role_id in role_ids:\n\n if self._roles.get(role_id):\n e_url = '%s/manage_roles' % self.getId()\n p_qs = 'role_id=%s' % role_id\n m_qs = 'role_id=%s&assign=1' % role_id\n\n info = {}\n info.update(self._roles[role_id])\n\n info['pluginid'] = plugin_id\n info['properties_url'] = '%s?%s' % (e_url, p_qs)\n info['members_url'] = '%s?%s' % (e_url, m_qs)\n\n if not role_filter or role_filter(info):\n role_info.append(info)\n\n return tuple(role_info)\n\n #\n # IRoleAssignerPlugin implementation\n #\n @security.private\n def doAssignRoleToPrincipal(self, principal_id, role):\n return self.assignRoleToPrincipal(role, principal_id)\n\n @security.private\n def doRemoveRoleFromPrincipal(self, principal_id, role):\n return self.removeRoleFromPrincipal(role, principal_id)\n\n #\n # Role management API\n #\n @security.protected(ManageUsers)\n def listRoleIds(self):\n \"\"\" Return a list of the role IDs managed by this obje<|endoftext|>"} +{"language": "python", "text": "device_display_name = pusherdict[\"device_display_name\"]\n self.pushkey = pusherdict[\"pushkey\"]\n self.pushkey_ts = pusherdict[\"ts\"]\n self.data = pusherdict[\"data\"]\n self.last_stream_ordering = pusherdict[\"last_stream_ordering\"]\n self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC\n self.failing_since = pusherdict[\"failing_since\"]\n self.timed_call = None\n self._is_processing = False\n self._group_unread_count_by_room = hs.config.push_group_unread_count_by_room\n\n # This is the highest stream ordering we know it's safe to process.\n # When new events arrive, we'll be given a window of new events: we\n # should honour this rather than just looking for anything higher\n # because of potential out-of-order event serialisation. This starts\n # off as None though as we don't know any better.\n self.max_stream_ordering = None\n\n if \"data\" not in pusherdict:\n raise PusherConfigException(\"No 'data' key for HTTP pusher\")\n self.data = pusherdict[\"data\"]\n\n self.name = \"%s/%s/%s\" % (\n pusherdict[\"user_name\"],\n pusherdict[\"app_id\"],\n pusherdict[\"pushkey\"],\n )\n\n if self.data is None:\n raise PusherConfigException(\"data can not be null for HTTP pusher\")\n\n if \"url\" not in self.data:\n raise PusherConfigException(\"'url' required in data for HTTP pusher\")\n self.url = self.data[\"url\"]\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_proxied_http_client()\n # FIXED: \n self.http_client = hs.get_proxied_blacklisted_http_client()\n self.data_minus_url = {}\n self.data_minus_url.update(self.data)\n del self.data_minus_url[\"url\"]\n\n def on_started(self, should_check_for_notifs):\n \"\"\"Called when this pusher has been started.\n\n Args:\n should_check_for_notifs (bool): Whether we should immediately\n check for push to send. Set to False only if it's known there\n is nothing to send\n \"\"\"\n if should_check_for_notifs:\n self._start_processing()\n\n def on_new_notifications(self, max_token: RoomStreamToken):\n # We just use the minimum stream ordering and ignore the vector clock\n # component. This is safe to do as long as we *always* ignore the vector\n # clock components.\n max_stream_ordering = max_token.stream\n\n self.max_stream_ordering = max(\n max_stream_ordering, self.max_stream_ordering or 0\n )\n self._start_processing()\n\n def on_new_receipts(self, min_stream_id, max_stream_id):\n # Note that the min here shouldn't be relied upon to be accurate.\n\n # We could check the receipts are actually m.read receipts here,\n # but currently that's the only type of receipt anyway...\n run_as_background_process(\"http_pusher.on_new_receipts\", self._update_badge)\n\n async def _update_badge(self):\n # XXX as per https://github.com/matrix-org/matrix-doc/issues/2627, this seems\n # to be largely redundant. perhaps we can remove it.\n badge = await push_tools.get_badge_count(\n self.hs.get_datastore(),\n self.user_id,\n group_b<|endoftext|>"} +{"language": "python", "text": "ecified, it will be ignored and a warning will be\n issued.\n When loading from a npz zip file, user can specify which variable within\n the zip file to load for the input tensor inside the square brackets. If\n nothing is specified, this function will check that only one file is\n included in the zip and load it for the specified input tensor.\n When loading from a pickle file, if no variable_name is specified in the\n square brackets, whatever that is inside the pickle file will be passed\n to the specified input tensor, else SavedModel CLI will assume a\n dictionary is stored in the pickle file and the value corresponding to\n the variable_name will be used.\n input_exprs_str: A string that specifies python expressions for inputs.\n * In the format of: '='.\n * numpy module is available as np.\n input_examples_str: A string that specifies tf.Example with dictionary.\n * In the format of: '=<[{feature:value list}]>'\n\n Returns:\n A dictionary that maps input tensor keys to numpy ndarrays.\n\n Raises:\n RuntimeError: An error when a key is specified, but the input file contains\n multiple numpy ndarrays, none of which matches the given key.\n RuntimeError: An error when no key is specified, but the input file contains\n more than one numpy ndarrays.\n \"\"\"\n tensor_key_feed_dict = {}\n\n inputs = preprocess_inputs_arg_string(inputs_str)\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # input_exprs = preprocess_input_exprs_arg_string(input_exprs_str, safe=False)\n # FIXED: \n input_exprs = preprocess_input_exprs_arg_string(input_exprs_str)\n input_examples = preprocess_input_examples_arg_string(input_examples_str)\n\n for input_tensor_key, (filename, variable_name) in inputs.items():\n data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg\n\n # When a variable_name key is specified for the input file\n if variable_name:\n # if file contains a single ndarray, ignore the input name\n if isinstance(data, np.ndarray):\n logging.warn(\n 'Input file %s contains a single ndarray. Name key \\\"%s\\\" ignored.'\n % (filename, variable_name))\n tensor_key_feed_dict[input_tensor_key] = data\n else:\n if variable_name in data:\n tensor_key_feed_dict[input_tensor_key] = data[variable_name]\n else:\n raise RuntimeError(\n 'Input file %s does not contain variable with name \\\"%s\\\".' %\n (filename, variable_name))\n # When no key is specified for the input file.\n else:\n # Check if npz file only contains a single numpy ndarray.\n if isinstance(data, np.lib.npyio.NpzFile):\n variable_name_list = data.files\n if len(variable_name_list) != 1:\n raise RuntimeError(\n 'Input file %s contains more than one ndarrays. Please specify '\n 'the name of ndarray to use.' % filename)\n tensor_key_feed_dict[input_tensor_key] = data[variable_name_list[0]]\n else:\n tensor_key_feed_dict[input_tensor_key] = data\n\n # When input is a python expression:\n for input_tensor_key, py_expr_evaluated in input_exprs.items():\n if input_tensor_key in tensor_ke<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock\n\nimport synapse\nimport synapse.api.errors\nfrom synapse.api.constants import EventTypes\nfrom synapse.config.room_directory import RoomDirectoryConfig\nfrom synapse.rest.client.v1 import directory, login, room\nfrom synapse.types import RoomAlias, create_requester\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\n\n\nclass DirectoryTestCase(unittest.HomeserverTestCase):\n \"\"\" Tests the directory service. \"\"\"\n\n def make_homeserver(self, reactor, clock):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None,\n # FIXED:\n federation_http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_feder<|endoftext|>"} +{"language": "python", "text": "de must be integers for ICMP protocol type\")\n else:\n raise exception.InvalidInput(reason=\"To and From ports \"\n \"must be integers\")\n\n if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:\n raise exception.InvalidIpProtocol(protocol=ip_protocol)\n\n # Verify that from_port must always be less than\n # or equal to to_port\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n from_port > to_port):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Former value cannot\"\n \" be greater than the later\")\n\n # Verify valid TCP, UDP port ranges\n if (ip_protocol.upper() in ['TCP', 'UDP'] and\n (from_port < 1 or to_port > 65535)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"Valid TCP ports should\"\n \" be between 1-65535\")\n\n # Verify ICMP type and code\n if (ip_protocol.upper() == \"ICMP\" and\n (from_port < -1 or from_port > 255 or\n to_port < -1 or to_port > 255)):\n raise exception.InvalidPortRange(from_port=from_port,\n to_port=to_port, msg=\"For ICMP, the\"\n \" type:code must be valid\")\n # BUG: CWE-20 Improper Input Validation\n # values['protocol'] = ip_protocol\n # FIXED: \n values['protocol'] = ip_protocol.lower()\n values['from_port'] = from_port\n values['to_port'] = to_port\n else:\n # If cidr based filtering, protocol and ports are mandatory\n if 'cidr' in values:\n return None\n\n return values\n\n def delete(self, req, id):\n context = req.environ['nova.context']\n authorize(context)\n\n self.compute_api.ensure_default_security_group(context)\n try:\n id = int(id)\n rule = db.security_group_rule_get(context, id)\n except ValueError:\n msg = _(\"Rule id is not integer\")\n raise exc.HTTPBadRequest(explanation=msg)\n except exception.NotFound:\n msg = _(\"Rule (%s) not found\") % id\n raise exc.HTTPNotFound(explanation=msg)\n\n group_id = rule.parent_group_id\n self.compute_api.ensure_default_security_group(context)\n security_group = db.security_group_get(context, group_id)\n\n msg = _(\"Revoke security group ingress %s\")\n LOG.audit(msg, security_group['name'], context=context)\n\n db.security_group_rule_destroy(context, rule['id'])\n self.sgh.trigger_security_group_rule_destroy_refresh(\n context, [rule['id']])\n self.compute_api.trigger_security_group_rules_refresh(context,\n security_group_id=security_group['id'])\n\n return webob.Response(status_int=202)\n\n\nclass ServerSecurityGroupController(SecurityGroupControllerBase):\n\n @wsgi.serializers(xml=SecurityGroupsTemplate)\n def index(self, req, server_id):\n \"\"\"Returns a list of security groups for the given instance.<|endoftext|>"} +{"language": "python", "text": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nfrom frappe import _\nfrom frappe.website.website_generator import WebsiteGenerator\nfrom frappe.website.render import clear_cache\nfrom frappe.utils import today, cint, global_date_format, get_fullname, strip_html_tags, markdown, sanitize_html\nfrom math import ceil\nfrom frappe.website.utils import (find_first_image, get_html_content_based_on_type,\n\tget_comment_list)\n\nclass BlogPost(WebsiteGenerator):\n\twebsite = frappe._dict(\n\t\troute = 'blog',\n\t\torder_by = \"published_on desc\"\n\t)\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef make_route(self):\n\t\tif not self.route:\n\t\t\treturn frappe.db.get_value('Blog Category', self.blog_category,\n\t\t\t\t'route') + '/' + self.scrub(self.title)\n\n\tdef get_feed(self):\n\t\treturn self.title\n\n\tdef validate(self):\n\t\tsuper(BlogPost, self).validate()\n\n\t\tif not self.blog_intro:\n\t\t\tcontent = get_html_content_based_on_type(self, 'content', self.content_type)\n\t\t\tself.blog_intro = content[:200]\n\t\t\tself.blog_intro = strip_html_tags(self.blog_intro)\n\n\t\tif self.blog_intro:\n\t\t\tself.blog_intro = self.blog_intro[:200]\n\n\t\tif not self.meta_title:\n\t\t\tself.meta_title = self.title[:60]\n\t\telse:\n\t\t\tself.meta_title = self.meta_title[:60]\n\n\t\tif not self.meta_description:\n\t\t\tself.meta_description = self.blog_intro[:140]\n\t\telse:\n\t\t\tself.meta_description = self.meta_description[:140]\n\n\t\tif self.published and not self.published_on:\n\t\t\tself.published_on = today()\n\n\t\tif self.featured:\n\t\t\tif not self.meta_image:\n\t\t\t\tfrappe.throw(_(\"A featured post<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom future.utils import iteritems\n\nimport yaml\nimport json\n\nfrom mlalchemy.errors import *\nfrom mlalchemy.structures import *\nfrom mlalchemy.constants import *\nfrom mlalchemy.utils import *\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n__all__ = [\n \"parse_yaml_query\",\n \"parse_json_query\",\n \"parse_query\",\n \"parse_query_fragment\"\n]\n\n\ndef parse_yaml_query(yaml_content):\n \"\"\"Parses the given YAML string to attempt to extract a query.\n\n Args:\n yaml_content: A string containing YAML content.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n logger.debug(\"Attempting to parse YAML content:\\n%s\" % yaml_content)\n # BUG: NVD-CWE-noinfo Insufficient Information\n # return parse_query(yaml.load(yaml_content))\n # FIXED: \n return parse_query(yaml.safe_load(yaml_content))\n\n\ndef parse_json_query(json_content):\n \"\"\"Parses the given JSON string to attempt to extract a query.\n\n Args:\n json_content: A string containing JSON content.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n logger.debug(\"Attempting to parse JSON content:\\n%s\" % json_content)\n return parse_query(json.loads(json_content))\n\n\ndef parse_query(qd):\n \"\"\"Parses the given query dictionary to produce an MLQuery object.\n\n Args:\n qd: A Python dictionary (pre-parsed from JSON/YAML) from which to extract the query.\n\n Returns:\n On success, the processed MLQuery object.\n \"\"\"\n if not isinstance(qd, dict):\n raise TypeError(\"Argument for query parsing must be a Python dictionary\")\n if 'from' not in qd:\n raise QuerySyntaxError(\"Missing \\\"from\\\" argument in query\")\n\n logger.debug(\"Attempting to parse query dictionary:\\n%s\" % json_dumps(qd, indent=2))\n\n qf = parse_query_fragment(qd['where']).simplify() if 'where' in qd else None\n if isinstance(qf, MLClause):\n qf = MLQueryFragment(OP_AND, clauses=[qf])\n\n return MLQuery(\n qd['from'],\n query_fragment=qf,\n order_by=qd.get('orderBy', qd.get('order-by', qd.get('order_by', None))),\n offset=qd.get('offset', None),\n limit=qd.get('limit', None)\n )\n\n\ndef parse_query_fragment(q, op=OP_AND, comp=COMP_EQ):\n \"\"\"Parses the given query object for its query fragment only.\"\"\"\n if not isinstance(q, list) and not isinstance(q, dict):\n raise TypeError(\"\\\"Where\\\" clause in query fragment must either be a list or a dictionary\")\n\n # ensure we're always dea<|endoftext|>"} +{"language": "python", "text": "it handler(request)\n cache_control_value = \"public; max-age={}\".format(CACHE_MAX_AGE)\n if request.path in NO_CACHE_ENDPOINTS or CACHE_MAX_AGE <= 0:\n cache_control_value = \"no-cache\"\n response.headers.setdefault(\"Cache-Control\", cache_control_value)\n return response\n return middleware_handler\n\n\n# Error page middlewares\ndef error_pages(overrides):\n async def middleware(app, handler):\n async def middleware_handler(request):\n try:\n response = await handler(request)\n override = overrides.get(response.status)\n if override is None:\n return response\n else:\n return await override(request, response)\n except web.HTTPException as ex:\n override = overrides.get(ex.status)\n if override is None:\n return await handle_any(request, ex)\n else:\n return await override(request, ex)\n except Exception as ex:\n return await handle_500(request, error=ex)\n return middleware_handler\n return middleware\n\n\nasync def handle_any(request, response):\n return web.json_response({\n \"status\": response.status,\n \"message\": response.reason\n }, status=response.status)\n\n\nasync def handle_404(request, response):\n if 'json' not in response.headers['Content-Type']:\n if request.path.endswith('/'):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # return web.HTTPFound(request.path.rstrip('/'))\n # FIXED: \n return web.HTTPFound('/' + request.path.strip('/'))\n return web.json_response({\n \"status\": 404,\n \"message\": \"Page '{}' not found\".format(request.path)\n }, status=404)\n return response\n\n\nasync def handle_500(request, response=None, error=None):\n logger.exception(error)\n return web.json_response({\n \"status\": 503,\n \"message\": \"Service currently unavailable\"\n }, status=503)\n<|endoftext|>"} +{"language": "python", "text": "statements\", e)\n\n if add_reading:\n reading_list.append(glueformula.meaning)\n\n def parse_to_compiled(self, sentence):\n gfls = [self.depgraph_to_glue(dg) for dg in self.dep_parse(sentence)]\n return [self.gfl_to_compiled(gfl) for gfl in gfls]\n\n def dep_parse(self, sentence):\n \"\"\"\n Return a dependency graph for the sentence.\n\n :param sentence: the sentence to be parsed\n :type sentence: list(str)\n :rtype: DependencyGraph\n \"\"\"\n\n # Lazy-initialize the depparser\n if self.depparser is None:\n from nltk.parse import MaltParser\n\n self.depparser = MaltParser(tagger=self.get_pos_tagger())\n if not self.depparser._trained:\n self.train_depparser()\n return self.depparser.parse(sentence, verbose=self.verbose)\n\n def depgraph_to_glue(self, depgraph):\n return self.get_glue_dict().to_glueformula_list(depgraph)\n\n def get_glue_dict(self):\n return GlueDict(self.semtype_file)\n\n def gfl_to_compiled(self, gfl):\n index_counter = Counter()\n return_list = []\n for gf in gfl:\n return_list.extend(gf.compile(index_counter))\n\n if self.verbose:\n print(\"Compiled Glue Premises:\")\n for cgf in return_list:\n print(cgf)\n\n return return_list\n\n def get_pos_tagger(self):\n from nltk.corpus import brown\n\n regexp_tagger = RegexpTagger(\n [\n # BUG: CWE-1333 Inefficient Regular Expression Complexity\n # (r\"^-?[0-9]+(.[0-9]+)?$\", \"CD\"), # cardinal numbers\n # FIXED: \n (r\"^-?[0-9]+(\\.[0-9]+)?$\", \"CD\"), # cardinal numbers\n (r\"(The|the|A|a|An|an)$\", \"AT\"), # articles\n (r\".*able$\", \"JJ\"), # adjectives\n (r\".*ness$\", \"NN\"), # nouns formed from adjectives\n (r\".*ly$\", \"RB\"), # adverbs\n (r\".*s$\", \"NNS\"), # plural nouns\n (r\".*ing$\", \"VBG\"), # gerunds\n (r\".*ed$\", \"VBD\"), # past tense verbs\n (r\".*\", \"NN\"), # nouns (default)\n ]\n )\n brown_train = brown.tagged_sents(categories=\"news\")\n unigram_tagger = UnigramTagger(brown_train, backoff=regexp_tagger)\n bigram_tagger = BigramTagger(brown_train, backoff=unigram_tagger)\n trigram_tagger = TrigramTagger(brown_train, backoff=bigram_tagger)\n\n # Override particular words\n main_tagger = RegexpTagger(\n [(r\"(A|a|An|an)$\", \"ex_quant\"), (r\"(Every|every|All|all)$\", \"univ_quant\")],\n backoff=trigram_tagger,\n )\n\n return main_tagger\n\n\nclass DrtGlueFormula(GlueFormula):\n def __init__(self, meaning, glue, indices=None):\n if not indices:\n indices = set()\n\n if isinstance(meaning, str):\n self.meaning = drt.DrtExpression.fromstring(meaning)\n elif isinstance(meaning, drt.DrtExpression):\n self.meaning = meaning\n else:\n raise RuntimeError(\n \"Meaning term neither string or expression: %s, %s\"\n % (meaning, meaning.__class__)\n )\n\n if isinstance(glue, str):\n self.glue = linearlogic.LinearLogicParser().parse(glue)\n elif isinstance(glue, linearlogic.Expressi<|endoftext|>"} +{"language": "python", "text": "ing: utf-8 -*-\n\"\"\"\n pygments.lexers.templates\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Lexers for various template engines' markup.\n\n :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\nfrom pygments.lexers.html import HtmlLexer, XmlLexer\nfrom pygments.lexers.javascript import JavascriptLexer, LassoLexer\nfrom pygments.lexers.css import CssLexer\nfrom pygments.lexers.php import PhpLexer\nfrom pygments.lexers.python import PythonLexer\nfrom pygments.lexers.perl import PerlLexer\nfrom pygments.lexers.jvm import JavaLexer, TeaLangLexer\nfrom pygments.lexers.data import YamlLexer\nfrom pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \\\n include, using, this, default, combined\nfrom pygments.token import Error, Punctuation, Whitespace, \\\n Text, Comment, Operator, Keyword, Name, String, Number, Other, Token\nfrom pygments.util import html_doctype_matches, looks_like_xml\n\n__all__ = ['HtmlPhpLexer', 'XmlPhpLexer', 'CssPhpLexer',\n 'JavascriptPhpLexer', 'ErbLexer', 'RhtmlLexer',\n 'XmlErbLexer', 'CssErbLexer', 'JavascriptErbLexer',\n 'SmartyLexer', 'HtmlSmartyLexer', 'XmlSmartyLexer',\n 'CssSmartyLexer', 'JavascriptSmartyLexer', 'DjangoLexer',\n 'HtmlDjangoLexer', 'CssDjangoLexer', 'XmlDjangoLexer',\n 'JavascriptDjangoLexer', 'GenshiLexer', 'HtmlGenshiLexer',\n 'GenshiTextLexer', 'CssGenshiLexer', 'JavascriptGenshiLexer',\n 'MyghtyLexer', 'MyghtyHtmlLexer', 'MyghtyXmlLexer',\n 'MyghtyCssLexer', 'MyghtyJavascriptLexer', 'MasonLexer', 'MakoLexer',\n 'MakoHtmlLexer', 'MakoXmlLexer', 'MakoJavascriptLexer',\n<|endoftext|>"} +{"language": "python", "text": "ns Ltd\n# Copyright 2018-2019 New Vector Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests REST events for /rooms paths.\"\"\"\n\nimport json\nfrom urllib import parse as urlparse\n\nfrom mock import Mock\n\nimport synapse.rest.admin\nfrom synapse.api.constants import EventContentFields, EventTypes, Membership\nfrom synapse.handlers.pagination import PurgeStatus\nfrom synapse.rest.client.v1 import directory, login, profile, room\nfrom synapse.rest.client.v2_alpha import account\nfrom synapse.types import JsonDict, RoomAlias, UserID\nfrom synapse.util.stringutils import random_string\n\nfrom tests import unittest\nfrom tests.test_utils import make_awaitable\n\nPATH_PREFIX = b\"/_matrix/client/api/v1\"\n\n\nclass RoomBase(unittest.HomeserverTestCase):\n rmcreator_id = None\n\n servlets = [room.register_servlets, room.register_deprecated_servlets]\n\n def make_homeserver(self, reactor, clock):\n\n self.hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # \"red\", http_client=None, federation_client=Mock(),\n # FIXED: \n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.hs.get_federation_handler = Mock()\n self.hs.get_federation_handler.return_value.maybe_backfill = Mock(\n return_value=make_awaitable(None)\n )\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n self.hs.get_datastore().insert_client_ip = _insert_client_ip\n\n return self.hs\n\n\nclass RoomPermissionsTestCase(RoomBase):\n \"\"\" Tests room permissions. \"\"\"\n\n user_id = \"@sid1:red\"\n rmcreator_id = \"@notme:red\"\n\n def prepare(self, reactor, clock, hs):\n\n self.helper.auth_user_id = self.rmcreator_id\n # create some rooms under the name rmcreator_id\n self.uncreated_rmid = \"!aa:test\"\n self.created_rmid = self.helper.create_room_as(\n self.rmcreator_id, is_public=False\n )\n self.created_public_rmid = self.helper.create_room_as(\n self.rmcreator_id, is_public=True\n )\n\n # send a message in one of the rooms\n self.created_rmid_msg_path = (\n \"rooms/%s/send/m.room.message/a1\" % (self.created_rmid)\n ).encode(\"ascii\")\n request, channel = self.make_request(\n \"PUT\", self.created_rmid_msg_path, b'{\"msgtype\":\"m.text\",\"body\":\"test msg\"}'\n )\n self.assertEquals(200, channel.code, channel.result)\n\n # set topic for public room\n request, channel = self.make_request(\n \"PUT\",\n (\"rooms/%s/state/m.room.topic\" % self.created_public_rmid).encode(\"ascii\"),\n b'{\"topic\":\"Public Room Topic\"}',\n )\n self.assertEquals(200, channel.code, channel.result)\n\n <|endoftext|>"} +{"language": "python", "text": "import yaml\ntry:\n from ansible.utils.vault import VaultLib\nexcept ImportError:\n # Ansible 2.0 has changed the vault location\n from ansible.parsing.vault import VaultLib\n\n\nclass Vault(object):\n '''R/W an ansible-vault yaml file'''\n\n def __init__(self, password):\n self.password = password\n self.vault = VaultLib(password)\n\n def load(self, stream):\n '''read vault steam and return python object'''\n # BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')\n # return yaml.load(self.vault.decrypt(stream))\n # FIXED: \n return yaml.safe_load(self.vault.decrypt(stream))\n\n def dump(self, data, stream=None):\n '''encrypt data and print stdout or write to stream'''\n yaml_text = yaml.dump(\n data,\n default_flow_style=False,\n allow_unicode=True)\n encrypted = self.vault.encrypt(yaml_text)\n if stream:\n stream.write(encrypted)\n else:\n return encrypted\n<|endoftext|>"} +{"language": "python", "text": "dicator_out = self.evaluate(\n [sp_output, empty_row_indicator])\n\n self.assertAllEqual(output.indices, [[0, 0], [1, 0]])\n self.assertAllEqual(output.values, [-1, -1])\n self.assertAllEqual(output.dense_shape, [2, 5])\n self.assertAllEqual(empty_row_indicator_out, np.ones(2).astype(np.bool_))\n\n def testEmptyOutput(self):\n with test_util.use_gpu():\n sp_input = sparse_tensor.SparseTensor(\n indices=np.ones([0, 2]),\n values=np.ones([0]),\n dense_shape=np.array([0, 3]))\n sp_output, empty_row_indicator = (\n sparse_ops.sparse_fill_empty_rows(sp_input, -1))\n\n output, empty_row_indicator_out = self.evaluate(\n [sp_output, empty_row_indicator])\n\n self.assertAllEqual(output.indices, np.ones([0, 2]))\n self.assertAllEqual(output.values, np.ones([0]))\n self.assertAllEqual(output.dense_shape, [0, 3])\n self.assertAllEqual(empty_row_indicator_out, [])\n\n def testInvalidIndices(self):\n with test_util.use_gpu():\n sp_input = sparse_tensor.SparseTensor(\n indices=np.array([[1, 2], [1, 3], [99, 1], [99, 3]]),\n values=np.array([1, 3, 2, 4]),\n dense_shape=np.array([2, 5]))\n\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n r\"indices\\(2, 0\\) is invalid\"):\n self.evaluate(sparse_ops.sparse_fill_empty_rows(sp_input, -1))\n\n\nclass SparseAddTest(test_util.TensorFlowTestCase):\n\n def testValuesInVariable(self):\n # BUG: CWE-20 Improper Input Validation\n # indices = constant_op.constant([[1]], dtype=dtypes.int64)\n # FIXED: \n indices = constant_op.constant([[0]], dtype=dtypes.int64)\n values = variables.Variable([1], trainable=False, dtype=dtypes.float32)\n shape = constant_op.constant([1], dtype=dtypes.int64)\n\n sp_input = sparse_tensor.SparseTensor(indices, values, shape)\n sp_output = sparse_ops.sparse_add(sp_input, sp_input)\n\n with test_util.force_cpu():\n self.evaluate(variables.global_variables_initializer())\n output = self.evaluate(sp_output)\n self.assertAllEqual(output.values, [2])\n\n\nclass SparseReduceTest(test_util.TensorFlowTestCase):\n\n # [[1, ?, 2]\n # [?, 3, ?]]\n # where ? is implicitly-zero.\n ind = np.array([[0, 0], [0, 2], [1, 1]]).astype(np.int64)\n vals = np.array([1, 1, 1]).astype(np.int32)\n dense_shape = np.array([2, 3]).astype(np.int64)\n\n def _compare(self, sp_t, reduction_axes, ndims, keep_dims, do_sum):\n densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t))\n\n np_ans = densified\n if reduction_axes is None:\n if do_sum:\n np_ans = np.sum(np_ans, keepdims=keep_dims)\n else:\n np_ans = np.max(np_ans, keepdims=keep_dims)\n else:\n if not isinstance(reduction_axes, list): # Single scalar.\n reduction_axes = [reduction_axes]\n reduction_axes = np.array(reduction_axes).astype(np.int32)\n # Handles negative axes.\n reduction_axes = (reduction_axes + ndims) % ndims\n # Loop below depends on sorted.\n reduction_axes.sort()\n for ra in reduction_axes.ravel()[::-1]:\n if do_sum:\n np_ans = np.sum(np_ans, axis=ra, keepdims=keep_dims)\n else:\n np_ans = np.max(np_ans, axis=ra, keepdims=keep_dims)\n\n with self.cached_session():\n if do_sum:\n <|endoftext|>"} +{"language": "python", "text": ".utils import cint, get_fullname, getdate, get_link_to_form\n\nclass EnergyPointLog(Document):\n\tdef validate(self):\n\t\tself.map_milestone_reference()\n\t\tif self.type in ['Appreciation', 'Criticism'] and self.user == self.owner:\n\t\t\tfrappe.throw(_('You cannot give review points to yourself'))\n\n\tdef map_milestone_reference(self):\n\t\t# link energy point to the original reference, if set by milestone\n\t\tif self.reference_doctype == 'Milestone':\n\t\t\tself.reference_doctype, self.reference_name = frappe.db.get_value('Milestone', self.reference_name,\n\t\t\t\t['reference_type', 'reference_name'])\n\n\tdef after_insert(self):\n\t\talert_dict = get_alert_dict(self)\n\t\tif alert_dict:\n\t\t\tfrappe.publish_realtime('energy_point_alert', message=alert_dict, user=self.user)\n\n\t\tfrappe.cache().hdel('energy_points', self.user)\n\t\tfrappe.publish_realtime('update_points', after_commit=True)\n\n\t\tif self.type != 'Review':\n\t\t\treference_user = self.user if self.type == 'Auto' else self.owner\n\t\t\tnotification_doc = {\n\t\t\t\t'type': 'Energy Point',\n\t\t\t\t'document_type': self.reference_doctype,\n\t\t\t\t'document_name': self.reference_name,\n\t\t\t\t'subject': get_notification_message(self),\n\t\t\t\t'from_user': reference_user,\n\t\t\t\t'email_content': '
{}
'.format(self.reason) if self.reason else None\n\t\t\t}\n\n\t\t\tenqueue_create_notification(self.user, notification_doc)\n\n\tdef on_trash(self):\n\t\tif self.type == 'Revert':\n\t\t\treference_log = frappe.get_doc('Energy Point Log', self.revert_of)\n\t\t\treference_log.reverted = 0\n\t\t\treference_log.save()\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED: \n\t@frappe.whitelist()\n\tdef revert(self, reason, ignore_permissions=False):\n\t\tif not ignore_permissions:\n\t\t\tfrappe.only_for('System Manager')\n\n\t\tif self.type != 'Auto':\n\t\t\tfrappe.throw(_('This document cannot be reverted'))\n\n\t\tif self.get('reverted'):\n\t\t\treturn\n\n\t\tself.reverted = 1\n\t\tself.save(ignore_permissions=True)\n\n\t\trevert_log = frappe.get_doc({\n\t\t\t'doctype': 'Energy Point Log',\n\t\t\t'points': -(self.points),\n\t\t\t'type': 'Revert',\n\t\t\t'user': self.user,\n\t\t\t'reason': reason,\n\t\t\t'reference_doctype': self.reference_doctype,\n\t\t\t'reference_name': self.reference_name,\n\t\t\t'revert_of': self.name\n\t\t}).insert(ignore_permissions=True)\n\n\t\treturn revert_log\n\ndef get_notification_message(doc):\n\towner_name = get_fullname(doc.owner)\n\tpoints = doc.points\n\ttitle = get_title(doc.reference_doctype, doc.reference_name)\n\n\tif doc.type == 'Auto':\n\t\towner_name = frappe.bold('You')\n\t\tif points == 1:\n\t\t\tmessage = _('{0} gained {1} point for {2} {3}')\n\t\telse:\n\t\t\tmessage = _('{0} gained {1} points for {2} {3}')\n\t\tmessage = message.format(owner_name, frappe.bold(points), doc.rule, get_title_html(title))\n\telif doc.type == 'Appreciation':\n\t\tif points == 1:\n\t\t\tmessage = _('{0} appreciated your work on {1} with {2} point')\n\t\telse:\n\t\t\tmessage = _('{0} appreciated your work on {1} with {2} points')\n\t\tmessage = message.format(frappe.bold(owner_name), get_title_html(title), frappe.bold(points))\n\telif doc.type == 'Criticism':\n\t\tif points == 1:\n\t\t\tmessage = _('{0} criticized your work on {1} with {2} point')\n\t\telse:\n\t\t\tmessage = _('{0} criticized your work on {1} with {2} points')\n\n\t\tmessage = message.format(frappe.bold(owner_name), get_title_html(title), frappe.bold(points))\n\telif doc.type == 'Revert':\n\t\tif poi<|endoftext|>"} +{"language": "python", "text": " h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)\n h.update(key_material)\n return h.finalize()\n\n def derive(self, key_material):\n if not isinstance(key_material, bytes):\n raise TypeError(\"key_material must be bytes.\")\n\n return self._hkdf_expand.derive(self._extract(key_material))\n\n def verify(self, key_material, expected_key):\n if not constant_time.bytes_eq(self.derive(key_material), expected_key):\n raise InvalidKey\n\n\n@utils.register_interface(KeyDerivationFunction)\nclass HKDFExpand(object):\n def __init__(self, algorithm, length, info, backend):\n if not isinstance(backend, HMACBackend):\n raise UnsupportedAlgorithm(\n \"Backend object does not implement HMACBackend.\",\n _Reasons.BACKEND_MISSING_INTERFACE\n )\n\n self._algorithm = algorithm\n\n self._backend = backend\n\n max_length = 255 * (algorithm.digest_size // 8)\n\n if length > max_length:\n raise ValueError(\n \"Can not derive keys larger than {0} octets.\".format(\n max_length\n ))\n\n self._length = length\n\n if not (info is None or isinstance(info, bytes)):\n raise TypeError(\"info must be bytes.\")\n\n if info is None:\n info = b\"\"\n\n self._info = info\n\n self._used = False\n\n def _expand(self, key_material):\n output = [b\"\"]\n counter = 1\n # BUG: CWE-20 Improper Input Validation\n # while (self._algorithm.digest_size // 8) * len(output) < self._length:\n # FIXED: \n while self._algorithm.digest_size * (len(output) - 1) < self._length:\n h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)\n h.update(output[-1])\n h.update(self._info)\n h.update(six.int2byte(counter))\n output.append(h.finalize())\n counter += 1\n\n return b\"\".join(output)[:self._length]\n\n def derive(self, key_material):\n if not isinstance(key_material, bytes):\n raise TypeError(\"key_material must be bytes.\")\n\n if self._used:\n raise AlreadyFinalized\n\n self._used = True\n return self._expand(key_material)\n\n def verify(self, key_material, expected_key):\n if not constant_time.bytes_eq(self.derive(key_material), expected_key):\n raise InvalidKey\n<|endoftext|>"} +{"language": "python", "text": "st/',\n project_urls={\n 'Documentation': 'https://zope.readthedocs.io',\n 'Issue Tracker': 'https://github.com/zopefoundation/Zope/issues',\n 'Sources': 'https://github.com/zopefoundation/Zope',\n },\n license='ZPL 2.1',\n description='Zope application server / web framework',\n author='Zope Foundation and Contributors',\n author_email='zope-dev@zope.org',\n long_description=\"\\n\\n\".join([README, CHANGES]),\n classifiers=[\n 'Development Status :: 6 - Mature',\n \"Environment :: Web Environment\",\n \"Framework :: Zope :: 5\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Zope Public License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n \"Topic :: Software Development :: Libraries :: Application Frameworks\",\n ],\n packages=find_packages('src'),\n namespace_packages=['Products', 'Shared', 'Shared.DC', 'zmi'],\n package_dir={'': 'src'},\n python_requires='>= 3.6',\n install_requires=[\n # BUG: CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes\n # 'AccessControl >= 4.2',\n # FIXED: \n 'AccessControl >= 5.2',\n 'Acquisition',\n 'BTrees',\n 'Chameleon >= 3.7.0',\n 'DateTime',\n 'DocumentTemplate >= 4.0',\n 'ExtensionClass',\n 'MultiMapping',\n 'PasteDeploy',\n 'Persistence',\n 'RestrictedPython',\n 'ZConfig >= 2.9.2',\n 'ZODB',\n 'setuptools >= 36.2',\n 'transaction >= 2.4',\n 'waitress',\n 'zExceptions >= 3.4',\n 'z3c.pt',\n 'zope.browser',\n 'zope.browsermenu',\n 'zope.browserpage >= 4.4.0.dev0',\n 'zope.browserresource >= 3.11',\n 'zope.component',\n 'zope.configuration',\n 'zope.container',\n 'zope.contentprovider',\n 'zope.contenttype',\n 'zope.datetime',\n 'zope.deferredimport',\n 'zope.event',\n 'zope.exceptions',\n 'zope.globalrequest',\n 'zope.i18n [zcml]',\n 'zope.i18nmessageid',\n 'zope.interface >= 3.8',\n 'zope.lifecycleevent',\n 'zope.location',\n 'zope.pagetemplate >= 4.0.2',\n 'zope.processlifetime',\n 'zope.proxy',\n 'zope.ptresource',\n 'zope.publisher',\n 'zope.schema',\n 'zope.security',\n 'zope.sequencesort',\n 'zope.site',\n 'zope.size',\n 'zope.tal',\n 'zope.tales >= 5.0.2',\n 'zope.testbrowser',\n 'zope.testing',\n 'zope.traversing',\n 'zope.viewlet',\n ],\n include_package_data=True,\n zip_safe=False,\n extras_require={\n 'docs': [\n 'Sphinx',\n 'sphinx_rtd_theme',\n 'tempstorage',\n ],\n 'wsgi': [\n 'Paste',\n ],\n },\n entry_points={\n <|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module provide some helpers for advanced types parsing.\n\nYou can define you own parser using the same pattern:\n\n.. code-block:: python\n\n def my_type(value):\n if not condition:\n raise ValueError('This is not my type')\n return parse(value)\n\n # Swagger documentation\n my_type.__schema__ = {'type': 'string', 'format': 'my-custom-format'}\n\nThe last line allows you to document properly the type in the Swagger documentation.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport re\nimport socket\n\nfrom datetime import datetime, time, timedelta\nfrom email.utils import parsedate_tz, mktime_tz\nfrom six.moves.urllib.parse import urlparse\n\nimport aniso8601\nimport pytz\n\n# Constants for upgrading date-based intervals to full datetimes.\nSTART_OF_DAY = time(0, 0, 0, tzinfo=pytz.UTC)\nEND_OF_DAY = time(23, 59, 59, 999999, tzinfo=pytz.UTC)\n\n\nnetloc_regex = re.compile(\n r\"(?:(?P[^:@]+?(?::[^:@]*?)?)@)?\" # basic auth\n r\"(?:\"\n r\"(?Plocalhost)|\" # localhost...\n r\"(?P\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|\" # ...or ipv4\n r\"(?:\\[?(?P[A-F0-9]*:[A-F0-9:]+)\\]?)|\" # ...or ipv6\n r\"(?P(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?))\" # domain...\n r\")\"\n r\"(?::(?P\\d+))?\" # optional port\n r\"$\",\n re.IGNORECASE,\n)\n\n\nemail_regex = re.compile(\n # BUG: CWE-400 Uncontrolled Resource Consumption\n # r\"^\" \"(?P[^@]*[^@.])\" r\"@\" r\"(?P[^@]+(?:\\.[^@]+)*)\" r\"$\",\n # FIXED:\n r\"^\" \"(?P[^@]*[^@.])\" r\"@\" r\"(?P[^@\\.]+(?:\\.[^@\\.]+)*)\" r\"$\",\n re.IGNORECASE,\n)\n\ntime_regex = re.compile(r\"\\d{2}:\\d{2}\")\n\n\ndef ipv4(value):\n \"\"\"V<|endoftext|>"} +{"language": "python", "text": "n/env python\n'''\nMIT License\n\nCopyright (c) 2019 Tenable Network Security, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\nimport click, logging, time, yaml, json, platform, sys, os, arrow\nfrom tenable.io import TenableIO\nfrom tenable.sc import TenableSC\nfrom .config import base_config\nfrom restfly.utils import dict_merge\nfrom .jira import Jira\nfrom .transform import Tio2Jira\nfrom . import __version__\n\ntroubleshooting = '''\n### Configuration File:\n```yaml\n{configfile}\n```\n\n### Debug Logs\n```\n{logging}\n```\n\n### Available IssueTypes\n```yaml\n{issuetypes}\n```\n'''\n\n@click.command()\n@click.option('--observed-since', '-s', envvar='SINCE', default=0,\n type=click.INT, help='The unix timestamp of the age threshol<|endoftext|>"} +{"language": "python", "text": " Robey Pointer \n#\n# This file is part of paramiko.\n#\n# Paramiko is free software; you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License as published by the Free\n# Software Foundation; either version 2.1 of the License, or (at your option)\n# any later version.\n#\n# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n# details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Paramiko; if not, write to the Free Software Foundation, Inc.,\n# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n\n\"\"\"\nCommon constants and global variables.\n\"\"\"\nimport logging\nfrom paramiko.py3compat import byte_chr, PY2, bytes_types, text_type, long\n\nMSG_DISCONNECT, MSG_IGNORE, MSG_UNIMPLEMENTED, MSG_DEBUG, \\\n MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT = range(1, 7)\nMSG_KEXINIT, MSG_NEWKEYS = range(20, 22)\nMSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE, MSG_USERAUTH_SUCCESS, \\\n MSG_USERAUTH_BANNER = range(50, 54)\nMSG_USERAUTH_PK_OK = 60\nMSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)\nMSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)\nMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\\\n MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)\n# BUG: CWE-287 Improper Authentication\n# \n# FIXED: \nHIGHEST_USERAUTH_MESSAGE_ID = 79\nMSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MSG_REQUEST_FAILURE = range(80, 83)\nMSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_SUCCESS, MSG_CHANNEL_OPEN_FAILURE, \\\n MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, \\\n MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MSG_CHANNEL_REQUEST, \\\n MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE = range(90, 101)\n\ncMSG_DISCONNECT = byte_chr(MSG_DISCONNECT)\ncMSG_IGNORE = byte_chr(MSG_IGNORE)\ncMSG_UNIMPLEMENTED = byte_chr(MSG_UNIMPLEMENTED)\ncMSG_DEBUG = byte_chr(MSG_DEBUG)\ncMSG_SERVICE_REQUEST = byte_chr(MSG_SERVICE_REQUEST)\ncMSG_SERVICE_ACCEPT = byte_chr(MSG_SERVICE_ACCEPT)\ncMSG_KEXINIT = byte_chr(MSG_KEXINIT)\ncMSG_NEWKEYS = byte_chr(MSG_NEWKEYS)\ncMSG_USERAUTH_REQUEST = byte_chr(MSG_USERAUTH_REQUEST)\ncMSG_USERAUTH_FAILURE = byte_chr(MSG_USERAUTH_FAILURE)\ncMSG_USERAUTH_SUCCESS = byte_chr(MSG_USERAUTH_SUCCESS)\ncMSG_USERAUTH_BANNER = byte_chr(MSG_USERAUTH_BANNER)\ncMSG_USERAUTH_PK_OK = byte_chr(MSG_USERAUTH_PK_OK)\ncMSG_USERAUTH_INFO_REQUEST = byte_chr(MSG_USERAUTH_INFO_REQUEST)\ncMSG_USERAUTH_INFO_RESPONSE = byte_chr(MSG_USERAUTH_INFO_RESPONSE)\ncMSG_USERAUTH_GSSAPI_RESPONSE = byte_chr(MSG_USERAUTH_GSSAPI_RESPONSE)\ncMSG_USERAUTH_GSSAPI_TOKEN = byte_chr(MSG_USERAUTH_GSSAPI_TOKEN)\ncMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE = \\\n byte_chr(MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)\ncMSG_USERAUTH_GSSAPI_ERROR = byte_chr(MSG_USERAUTH_GSSAPI_ERROR)\ncMSG_USERAUTH_GSSAPI_ERRTOK = byte_chr(MSG_USERAUTH_GSSAPI_ERRTOK)\ncMSG_USERAUTH_GSSAPI_MIC = byte_chr(MSG_USERAUTH_GSSAPI_MIC)\ncMSG_GLOBAL_REQUEST = byte_chr(MSG_GLOBAL_REQUEST)\ncMSG_REQUEST_SUCCESS = byte_chr(MSG_REQUEST_SUCCESS)\ncMSG_REQUEST_FAILURE = byte_chr(MSG_REQUEST_FAI<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom unittest.mock import Mock\n\nfrom synapse.api.constants import Membership\nfrom synapse.rest.admin import register_servlets_for_client_rest_resource\nfrom synapse.rest.client.v1 import login, room\nfrom synapse.types import UserID, create_requester\n\nfrom tests import unittest\nfrom tests.test_utils import event_injection\nfrom tests.utils import TestHomeServer\n\n\nclass RoomMemberStoreTestCase(unittest.HomeserverTestCase):\n\n servlets = [\n login.register_servlets,\n register_servlets_for_client_rest_resource,\n room.register_servlets,\n ]\n\n def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # resource_for_federation=Mock(), http_client=None\n # FIXED:\n resource_for_federation=Mock(), federation_http_client=None\n )\n return hs\n\n def prepare(self, reactor, clock, hs: TestHomeServer):\n\n # We can't test the RoomMemberStore on its own without the other e<|endoftext|>"} +{"language": "python", "text": "n/env python\n# -*- coding: utf-8 -*-\n\n# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)\n# Copyright (C) 2012-2019 OzzieIsaacs\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nimport os\n\n\n# Insert local directories into path\nif sys.version_info < (3, 0):\n sys.path.append(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))), 'vendor'))\nelse:\n sys.path.append(os.path.dirname(os.path.abspath(__file__)))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vendor'))\n\n\nfrom cps import create_app\nfrom cps import web_server\nfrom cps.opds import opds\nfrom cps.web import web\nfrom cps.jinjia import jinjia\nfrom cps.about import about\nfrom cps.shelf import shelf\nfrom cps.admin import admi\nfrom cps.gdrive import gdrive\nfrom cps.editbooks import editbook\nfrom cps.remotelogin import remotelogin\nfrom cps.search_metadata import meta\nfrom cps.error_h<|endoftext|>"} +{"language": "python", "text": " else:\n if fwtype == 'ACCEPT' and not '# OMR ' + username + ' open ' + name + ' port ' + proto + ' to ' + source_dip in line:\n n.write(line)\n elif fwtype == 'DNAT' and not '# OMR ' + username + ' redirect ' + name + ' port ' + proto + ' to ' + source_dip in line:\n n.write(line)\n os.close(fd)\n move(tmpfile, '/etc/shorewall6/rules')\n final_md5 = hashlib.md5(file_as_bytes(open('/etc/shorewall6/rules', 'rb'))).hexdigest()\n if initial_md5 != final_md5:\n os.system(\"systemctl -q reload shorewall6\")\n\ndef set_lastchange(sync=0):\n with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:\n content = f.read()\n content = re.sub(\",\\s*}\", \"}\", content) # pylint: disable=W1401\n try:\n data = json.loads(content)\n except ValueError as e:\n return {'error': 'Config file not readable', 'route': 'lastchange'}\n data[\"lastchange\"] = time.time() + sync\n if data:\n with open('/etc/openmptcprouter-vps-admin/omr-admin-config.json', 'w') as outfile:\n json.dump(data, outfile, indent=4)\n else:\n LOG.debug(\"Empty data for set_last_change\")\n\n\nwith open('/etc/openmptcprouter-vps-admin/omr-admin-config.json') as f:\n omr_config_data = json.load(f)\n if 'debug' in omr_config_data and omr_config_data['debug']:\n LOG.setLevel(logging.DEBUG)\n\nfake_users_db = omr_config_data['users'][0]\n\ndef verify_password(plain_password, user_password):\n # BUG: CWE-287 Improper Authentication\n # if plain_password == user_password:\n # FIXED: \n if secrets.compare_digest(plain_password,user_password):\n LOG.debug(\"password true\")\n return True\n return False\n\ndef get_password_hash(password):\n return password\n\ndef get_user(db, username: str):\n if username in db:\n user_dict = db[username]\n return UserInDB(**user_dict)\n\ndef authenticate_user(fake_db, username: str, password: str):\n user = get_user(fake_db, username)\n if not user:\n LOG.debug(\"user doesn't exist\")\n return False\n if not verify_password(password, user.user_password):\n LOG.debug(\"wrong password\")\n return False\n return user\n\nclass Token(BaseModel):\n access_token: str = None\n token_type: str = None\n\n\nclass TokenData(BaseModel):\n username: str = None\n\nclass User(BaseModel):\n username: str\n vpn: str = None\n vpn_port: int = None\n vpn_client_ip: str = None\n permissions: str = 'rw'\n shadowsocks_port: int = None\n disabled: bool = 'false'\n userid: int = None\n\n\nclass UserInDB(User):\n user_password: str\n\n# Add support for auth before seeing doc\nclass OAuth2PasswordBearerCookie(OAuth2):\n def __init__(\n self,\n tokenUrl: str,\n scheme_name: str = None,\n scopes: dict = None,\n auto_error: bool = True,\n ):\n if not scopes:\n scopes = {}\n flows = OAuthFlowsModel(password={\"tokenUrl\": tokenUrl, \"scopes\": scopes})\n super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)\n\n async def __call__(self, request: Request) -> Optional[str]:\n header_authorization: str = request.headers.get(\"Authorization\")\n cookie_authorization: str = request.co<|endoftext|>"} +{"language": "python", "text": " os.unlink(fake_filepath)\n\n return result\n\n\ndef minimal_headers(name, public=True):\n headers = {\n 'Content-Type': 'application/octet-stream',\n 'X-Image-Meta-Name': name,\n 'X-Image-Meta-disk_format': 'raw',\n 'X-Image-Meta-container_format': 'ovf',\n }\n if public:\n headers['X-Image-Meta-Is-Public'] = 'True'\n return headers\n\n\ndef minimal_add_command(port, name, suffix='', public=True):\n visibility = 'is_public=True' if public else ''\n return (\"bin/glance --port=%d add %s\"\n \" disk_format=raw container_format=ovf\"\n \" name=%s %s\" % (port, visibility, name, suffix))\n\n\nclass FakeAuthMiddleware(wsgi.Middleware):\n\n def __init__(self, app, is_admin=False):\n super(FakeAuthMiddleware, self).__init__(app)\n self.is_admin = is_admin\n\n def process_request(self, req):\n auth_tok = req.headers.get('X-Auth-Token')\n user = None\n tenant = None\n roles = []\n if auth_tok:\n user, tenant, role = auth_tok.split(':')\n if tenant.lower() == 'none':\n tenant = None\n roles = [role]\n req.headers['X-User-Id'] = user\n req.headers['X-Tenant-Id'] = tenant\n req.headers['X-Roles'] = role\n req.headers['X-Identity-Status'] = 'Confirmed'\n kwargs = {\n 'user': user,\n 'tenant': tenant,\n 'roles': roles,\n 'is_admin': self.is_admin,\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # \n # FIXED: \n 'auth_tok': auth_tok,\n }\n\n req.context = context.RequestContext(**kwargs)\n\n\nclass FakeHTTPResponse(object):\n def __init__(self, status=200, headers=None, data=None, *args, **kwargs):\n data = data or 'I am a teapot, short and stout\\n'\n self.data = StringIO.StringIO(data)\n self.read = self.data.read\n self.status = status\n self.headers = headers or {'content-length': len(data)}\n\n def getheader(self, name, default=None):\n return self.headers.get(name.lower(), default)\n\n def getheaders(self):\n return self.headers or {}\n\n def read(self, amt):\n self.data.read(amt)\n<|endoftext|>"} +{"language": "python", "text": "es for Repo providers.\n\nSubclass the base class, ``RepoProvider``, to support different version\ncontrol services and providers.\n\n.. note:: When adding a new repo provider, add it to the allowed values for\n repo providers in event-schemas/launch.json.\n\"\"\"\nfrom datetime import timedelta, datetime, timezone\nimport json\nimport os\nimport time\nimport urllib.parse\nimport re\nimport subprocess\n\nimport escapism\nfrom prometheus_client import Gauge\n\nfrom tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest\nfrom tornado.httputil import url_concat\n\nfrom traitlets import Dict, Unicode, Bool, default, List\nfrom traitlets.config import LoggingConfigurable\n\nfrom .utils import Cache\n\nGITHUB_RATE_LIMIT = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining')\nSHA1_PATTERN = re.compile(r'[0-9a-f]{40}')\n\n\ndef tokenize_spec(spec):\n \"\"\"Tokenize a GitHub-style spec into parts, error if spec invalid.\"\"\"\n\n spec_parts = spec.split('/', 2) # allow ref to contain \"/\"\n if len(spec_parts) != 3:\n msg = 'Spec is not of the form \"user/repo/ref\", provided: \"{spec}\".'.format(spec=spec)\n if len(spec_parts) == 2 and spec_parts[-1] != 'master':\n msg += ' Did you mean \"{spec}/master\"?'.format(spec=spec)\n raise ValueError(msg)\n\n return spec_parts\n\n\ndef strip_suffix(text, suffix):\n if text.endswith(suffix):\n text = text[:-(len(suffix))]\n return text\n\n\nclass RepoProvider(LoggingConfigurable):\n \"\"\"Base class for a repo provider\"\"\"\n name = Unicode(\n help=\"\"\"\n Descriptive human readable name of this repo provider.\n \"\"\"\n )\n\n spec = Unicode(\n help=\"\"\"\n The spec for this bui<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2017, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, json, math\nfrom frappe.model.document import Document\nfrom frappe import _\nfrom frappe.utils import cstr\nfrom frappe.data_migration.doctype.data_migration_mapping.data_migration_mapping import get_source_value\n\nclass DataMigrationRun(Document):\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef run(self):\n\t\tself.begin()\n\t\tif self.total_pages > 0:\n\t\t\tself.enqueue_next_mapping()\n\t\telse:\n\t\t\tself.complete()\n\n\tdef enqueue_next_mapping(self):\n\t\tnext_mapping_name = self.get_next_mapping_name()\n\t\tif next_mapping_name:\n\t\t\tnext_mapping = self.get_mapping(next_mapping_name)\n\t\t\tself.db_set(dict(\n\t\t\t\tcurrent_mapping = next_mapping.name,\n\t\t\t\tcurrent_mapping_start = 0,\n\t\t\t\tcurrent_mapping_delete_start = 0,\n\t\t\t\tcurrent_mapping_action = 'Insert'\n\t\t\t), notify=True, commit=True)\n\t\t\tfrappe.enqueue_doc(self.doctype, self.name, 'run_current_mapping', now=frappe.flags.in_test)\n\t\telse:\n\t\t\tself.complete()\n\n\tdef enqueue_next_page(self):\n\t\tmapping = self.get_mapping(self.current_mapping)\n\t\tpercent_complete = self.percent_complete + (100.0 / self.total_pages)\n\t\tfields = dict(\n\t\t\tpercent_complete = percent_complete\n\t\t)\n\t\tif self.current_mapping_action == 'Insert':\n\t\t\tstart = self.current_mapping_start + mapping.page_length\n\t\t\tfields['current_mapping_start'] = start\n\t\telif self.current_mapping_action == 'Delete':\n\t\t\tdelete_start = self.current_mapping_delete_start + mapping.page_length\n\t\t\tfields['current_mapping_delete_start'] = delet<|endoftext|>"} +{"language": "python", "text": "###################\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\nimport logging\n\nfrom ansible_runner.config._base import BaseConfig, BaseExecutionMode\nfrom ansible_runner.exceptions import ConfigurationError\nfrom ansible_runner.utils import get_executable_path\n\nlogger = logging.getLogger('ansible-runner')\n\n\nclass DocConfig(BaseConfig):\n \"\"\"\n A ``Runner`` configuration object that's meant to encapsulate the configuration used by the\n :py:mod:`ansible_runner.runner.DocConfig` object to launch and manage the invocation of\n command execution.\n\n Typically this object is initialized for you when using the standard ``get_plugin_docs`` or ``get_plugin_list`` interfaces\n in :py:mod:`ansible_runner.interface` but can be used to construct the ``DocConfig`` configuration to be invoked elsewhere.\n It can also be overridden to provide different functionality to the DocConfig object.\n\n :Example:\n\n >>> dc = DocConfig(...)\n >>> r =<|endoftext|>"} +{"language": "python", "text": "# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nimport frappe.utils\nfrom frappe import throw, _\nfrom frappe.website.website_generator import WebsiteGenerator\nfrom frappe.utils.verified_command import get_signed_params, verify_request\nfrom frappe.email.queue import send\nfrom frappe.email.doctype.email_group.email_group import add_subscribers\nfrom frappe.utils import parse_addr, now_datetime, markdown, validate_email_address\n\nclass Newsletter(WebsiteGenerator):\n\tdef onload(self):\n\t\tif self.email_sent:\n\t\t\tself.get(\"__onload\").status_count = dict(frappe.db.sql(\"\"\"select status, count(name)\n\t\t\t\tfrom `tabEmail Queue` where reference_doctype=%s and reference_name=%s\n\t\t\t\tgroup by status\"\"\", (self.doctype, self.name))) or None\n\n\tdef validate(self):\n\t\tself.route = \"newsletters/\" + self.name\n\t\tif self.send_from:\n\t\t\tvalidate_email_address(self.send_from, True)\n\n\tdef test_send(self, doctype=\"Lead\"):\n\t\tself.recipients = frappe.utils.split_emails(self.test_email_id)\n\t\tself.queue_all(test_email=True)\n\t\tfrappe.msgprint(_(\"Test email sent to {0}\").format(self.test_email_id))\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef send_emails(self):\n\t\t\"\"\"send emails to leads and customers\"\"\"\n\t\tif self.email_sent:\n\t\t\tthrow(_(\"Newsletter has already been sent\"))\n\n\t\tself.recipients = self.get_recipients()\n\n\t\tif self.recipients:\n\t\t\tself.queue_all()\n\t\t\tfrappe.msgprint(_(\"Email queued to {0} recipients\").format(len(self.recipients)))\n\n\t\telse:\n\t\t\tfrappe.msgprint(_(\"Newsletter should have atl<|endoftext|>"} +{"language": "python", "text": "from pygments.lexer import RegexLexer, include, bygroups, using, default\nfrom pygments.token import Text, Comment, Name, Literal, Number, String, \\\n Punctuation, Keyword, Operator, Generic\n\n__all__ = ['OdinLexer', 'CadlLexer', 'AdlLexer']\n\n\nclass AtomsLexer(RegexLexer):\n \"\"\"\n Lexer for Values used in ADL and ODIN.\n\n .. versionadded:: 2.1\n \"\"\"\n\n tokens = {\n # ----- pseudo-states for inclusion -----\n 'whitespace': [\n (r'\\n', Text),\n (r'\\s+', Text),\n (r'[ \\t]*--.*$', Comment),\n ],\n 'archetype_id': [\n (r'[ \\t]*([a-zA-Z]\\w+(\\.[a-zA-Z]\\w+)*::)?[a-zA-Z]\\w+(-[a-zA-Z]\\w+){2}'\n r'\\.\\w+[\\w-]*\\.v\\d+(\\.\\d+){,2}((-[a-z]+)(\\.\\d+)?)?', Name.Decorator),\n ],\n 'date_constraints': [\n # ISO 8601-based date/time constraints\n (r'[Xx?YyMmDdHhSs\\d]{2,4}([:-][Xx?YyMmDdHhSs\\d]{2}){2}', Literal.Date),\n # ISO 8601-based duration constraints + optional trailing slash\n (r'(P[YyMmWwDd]+(T[HhMmSs]+)?|PT[HhMmSs]+)/?', Literal.Date),\n ],\n 'ordered_values': [\n # ISO 8601 date with optional 'T' ligature\n (r'\\d{4}-\\d{2}-\\d{2}T?', Literal.Date),\n # ISO 8601 time\n (r'\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{4}|Z)?', Literal.Date),\n # ISO 8601 duration\n (r'P((\\d*(\\.\\d+)?[YyMmWwDd]){1,3}(T(\\d*(\\.\\d+)?[HhMmSs]){,3})?|'\n r'T(\\d*(\\.\\d+)?[HhMmSs]){,3})', Literal.Date),\n # BUG: NVD-CWE-Other Other\n # (r'[+-]?(\\d+)*\\.\\d+%?', Number.Float),\n # FIXED: \n (r'[+-]?(\\d+\\.\\d*|\\.\\d+|\\d+)[eE][+-]?\\d+', Number.Float),\n (r'[+-]?\\d*\\.\\d+%?', Number.Float),\n (r'0x[0-9a-fA-F]+', Number.Hex),\n (r'[+-]?\\d+%?', Number.Integer),\n ],\n 'values': [\n include('ordered_values'),\n (r'([Tt]rue|[Ff]alse)', Literal),\n (r'\"', String, 'string'),\n (r\"'(\\\\.|\\\\[0-7]{1,3}|\\\\x[a-fA-F0-9]{1,2}|[^\\\\\\'\\n])'\", String.Char),\n (r'[a-z][a-z0-9+.-]*:', Literal, 'uri'),\n # term code\n (r'(\\[)(\\w[\\w-]*(?:\\([^)\\n]+\\))?)(::)(\\w[\\w-]*)(\\])',\n bygroups(Punctuation, Name.Decorator, Punctuation, Name.Decorator,\n Punctuation)),\n (r'\\|', Punctuation, 'interval'),\n # list continuation\n (r'\\.\\.\\.', Punctuation),\n ],\n 'constraint_values': [\n (r'(\\[)(\\w[\\w-]*(?:\\([^)\\n]+\\))?)(::)',\n bygroups(Punctuation, Name.Decorator, Punctuation), 'adl14_code_constraint'),\n # ADL 1.4 ordinal constraint\n (r'(\\d*)(\\|)(\\[\\w[\\w-]*::\\w[\\w-]*\\])((?:[,;])?)',\n bygroups(Number, Punctuation, Name.Decorator, Punctuation)),\n include('date_constraints'),\n include('values'),\n ],\n\n # ----- real states -----\n 'string': [\n ('\"', String, '#pop'),\n (r'\\\\([\\\\abfnrtv\"\\']|x[a-fA-F0-9]{2,4}|'\n r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),\n # all other characters\n (r'[^\\\\\"]+', String),\n # stray backslash\n (r'\\\\', String),\n ],\n 'uri': [\n # effective URI terminators\n (r'[,>\\<|endoftext|>"} +{"language": "python", "text": "\n # case completion: return 1\n if not match_allowed or match_denied:\n if not completion:\n ret, conf = warn_count('path',\n tomatch,\n conf,\n strict=strict,\n ssh=ssh)\n return 1, conf\n\n if not completion:\n if not re.findall(allowed_path_re, os.getcwd() + '/'):\n ret, conf = warn_count('path',\n tomatch,\n conf,\n strict=strict,\n ssh=ssh)\n os.chdir(conf['home_path'])\n conf['promptprint'] = utils.updateprompt(os.getcwd(),\n conf)\n return 1, conf\n return 0, conf\n\n\ndef check_secure(line, conf, strict=None, ssh=None):\n \"\"\"This method is used to check the content on the typed command.\n Its purpose is to forbid the user to user to override the lshell\n command restrictions.\n The forbidden characters are placed in the 'forbidden' variable.\n Feel free to update the list. Emptying it would be quite useless..: )\n\n A warning counter has been added, to kick out of lshell a user if he\n is warned more than X time (X being the 'warning_counter' variable).\n \"\"\"\n\n # store original string\n oline = line\n\n # strip all spaces/tabs\n # BUG: CWE-264 Permissions, Privileges, and Access Controls\n # line = \" \".join(line.split())\n # FIXED: \n line = line.strip()\n\n # init return code\n returncode = 0\n\n # This logic is kept crudely simple on purpose.\n # At most we might match the same stanza twice\n # (for e.g. \"'a'\", 'a') but the converse would\n # require detecting single quotation stanzas\n # nested within double quotes and vice versa\n relist = re.findall(r'[^=]\\\"(.+)\\\"', line)\n relist2 = re.findall(r'[^=]\\'(.+)\\'', line)\n relist = relist + relist2\n for item in relist:\n if os.path.exists(item):\n ret_check_path, conf = check_path(item, conf, strict=strict)\n returncode += ret_check_path\n\n # ignore quoted text\n line = re.sub(r'\\\"(.+?)\\\"', '', line)\n line = re.sub(r'\\'(.+?)\\'', '', line)\n\n if re.findall('[:cntrl:].*\\n', line):\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=strict,\n ssh=ssh)\n return ret, conf\n\n for item in conf['forbidden']:\n # allow '&&' and '||' even if singles are forbidden\n if item in ['&', '|']:\n if re.findall(\"[^\\%s]\\%s[^\\%s]\" % (item, item, item), line):\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=strict,\n ssh=ssh)\n return ret, conf\n else:\n if item in line:\n ret, conf = warn_count('syntax',\n oline,\n conf,\n strict=<|endoftext|>"} +{"language": "python", "text": " Language Toolkit: Comparative Sentence Corpus Reader\n#\n# Copyright (C) 2001-2021 NLTK Project\n# Author: Pierpaolo Pantone <24alsecondo@gmail.com>\n# URL: \n# For license information, see LICENSE.TXT\n\n\"\"\"\nCorpusReader for the Comparative Sentence Dataset.\n\n- Comparative Sentence Dataset information -\n\nAnnotated by: Nitin Jindal and Bing Liu, 2006.\n Department of Computer Sicence\n University of Illinois at Chicago\n\nContact: Nitin Jindal, njindal@cs.uic.edu\n Bing Liu, liub@cs.uic.edu (http://www.cs.uic.edu/~liub)\n\nDistributed with permission.\n\nRelated papers:\n\n- Nitin Jindal and Bing Liu. \"Identifying Comparative Sentences in Text Documents\".\n Proceedings of the ACM SIGIR International Conference on Information Retrieval\n (SIGIR-06), 2006.\n\n- Nitin Jindal and Bing Liu. \"Mining Comprative Sentences and Relations\".\n Proceedings of Twenty First National Conference on Artificial Intelligence\n (AAAI-2006), 2006.\n\n- Murthy Ganapathibhotla and Bing Liu. \"Mining Opinions in Comparative Sentences\".\n Proceedings of the 22nd International Conference on Computational Linguistics\n (Coling-2008), Manchester, 18-22 August, 2008.\n\"\"\"\nimport re\n\nfrom nltk.corpus.reader.api import *\nfrom nltk.tokenize import *\n\n# Regular expressions for dataset components\nSTARS = re.compile(r\"^\\*+$\")\nCOMPARISON = re.compile(r\"\")\nCLOSE_COMPARISON = re.compile(r\"\")\nGRAD_COMPARISON = re.compile(r\"\")\nNON_GRAD_COMPARISON = re.compile(r\"\")\nENTITIES_FEATS = re.compile(r\"(\\d)_((?:[\\.\\w\\s/-](?!\\d_))+)\")\n# BUG: CWE-697 Incorrect Comparison\n# KEYWORD = re.compile(r\"\\((?!.*\\()(.*)\\)$\")\n# FIXED:\nKEYWORD = re.compile(r\"\\<|endoftext|>"} +{"language": "python", "text": "import gzip\nimport json\n\nimport pytest\nfrom fastapi import Request\nfrom fastapi.testclient import TestClient\n\nfrom docs_src.custom_request_and_route.tutorial001 import app\n\n\n@app.get(\"/check-class\")\nasync def check_gzip_request(request: Request):\n return {\"request_class\": type(request).__name__}\n\n\nclient = TestClient(app)\n\n\n@pytest.mark.parametrize(\"compress\", [True, False])\ndef test_gzip_request(compress):\n n = 1000\n headers = {}\n body = [1] * n\n data = json.dumps(body).encode()\n if compress:\n data = gzip.compress(data)\n headers[\"Content-Encoding\"] = \"gzip\"\n # BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n # \n # FIXED:\n headers[\"Content-Type\"] = \"application/json\"\n response = client.post(\"/sum\", data=data, headers=headers)\n assert response.json() == {\"sum\": n}\n\n\ndef test_request_class():\n response = client.get(\"/check-class\")\n assert response.json() == {\"request_class\": \"GzipRequest\"}\n<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock\n\nfrom canonicaljson import json\n\nfrom twisted.internet import defer\n\nfrom synapse.api.constants import EventTypes, Membership\nfrom synapse.api.room_versions import RoomVersions\nfrom synapse.types import RoomID, UserID\n\nfrom tests import unittest\nfrom tests.utils import create_room\n\n\nclass RedactionTestCase(unittest.HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n config = self.default_config()\n config[\"redaction_retention_period\"] = \"30d\"\n return self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # resource_for_federation=Mock(), http_client=None, config=config\n # FIXED:\n resource_for_federation=Mock(), federation_http_client=None, config=config\n )\n\n def prepare(self, reactor, clock, hs):\n self.store = hs.get_datastore()\n self.storage = hs.get_storage()\n self.event_builder_factory = hs.get_event_builder_factory()\n self.event_creation_handler = hs.<|endoftext|>"} +{"language": "python", "text": " be passed to the error handler so users are\n returned to a different view than the one requested in addition to the\n error message.\n #. RECOVERABLE: Generic API errors which generate a user-facing message\n but drop directly back to the regular code flow.\n\n All other exceptions bubble the stack as normal unless the ``ignore``\n argument is passed in as ``True``, in which case only unrecognized\n errors are bubbled.\n\n If the exception is not re-raised, an appropriate wrapper exception\n class indicating the type of exception that was encountered will be\n returned.\n \"\"\"\n exc_type, exc_value, exc_traceback = sys.exc_info()\n\n # Because the same exception may travel through this method more than\n # once (if it's re-raised) we may want to treat it differently\n # the second time (e.g. no user messages/logging).\n handled = issubclass(exc_type, HandledException)\n wrap = False\n\n # Restore our original exception information, but re-wrap it at the end\n if handled:\n exc_type, exc_value, exc_traceback = exc_value.wrapped\n wrap = True\n\n # We trust messages from our own exceptions\n if issubclass(exc_type, HorizonException):\n message = exc_value\n # If the message has a placeholder for the exception, fill it in\n elif message and \"%(exc)s\" in message:\n message = message % {\"exc\": exc_value}\n\n if issubclass(exc_type, UNAUTHORIZED):\n if ignore:\n return NotAuthorized\n # BUG: NVD-CWE-Other Other\n # request.session.clear()\n # FIXED: \n request.user_logout()\n if not handled:\n LOG.debug(\"Unauthorized: %s\" % exc_value)\n # We get some pretty useless error messages back from\n # some clients, so let's define our own fallback.\n fallback = _(\"Unauthorized. Please try logging in again.\")\n messages.error(request, message or fallback, extra_tags=\"login\")\n raise NotAuthorized # Redirect handled in middleware\n\n if issubclass(exc_type, NOT_FOUND):\n wrap = True\n if not ignore and not handled:\n LOG.debug(\"Not Found: %s\" % exc_value)\n messages.error(request, message or exc_value)\n if redirect:\n raise Http302(redirect)\n if not escalate:\n return NotFound # return to normal code flow\n\n if issubclass(exc_type, RECOVERABLE):\n wrap = True\n if not ignore and not handled:\n LOG.debug(\"Recoverable error: %s\" % exc_value)\n messages.error(request, message or exc_value)\n if redirect:\n raise Http302(redirect)\n if not escalate:\n return RecoverableError # return to normal code flow\n\n # If we've gotten here, time to wrap and/or raise our exception.\n if wrap:\n raise HandledException([exc_type, exc_value, exc_traceback])\n raise exc_type, exc_value, exc_traceback\n<|endoftext|>"} +{"language": "python", "text": "import pytest\nfrom starkware.starknet.testing.starknet import Starknet\n# BUG: CWE-863 Incorrect Authorization\n# MockSigner,\n# FIXED:\nfrom signers import MockSigner\nfrom utils import (\n assert_revert,\n get_contract_class,\n cached_contract,\n assert_event_emitted,\n assert_revert_entry_point\n)\n\n# random value\nVALUE = 123\n\nsigner = MockSigner(123456789987654321)\n\n\n@pytest.fixture(scope='module')\ndef contract_classes():\n account_cls = get_contract_class('openzeppelin/account/Account.cairo')\n implementation_cls = get_contract_class(\n 'tests/mocks/proxiable_implementation.cairo'\n )\n proxy_cls = get_contract_class('openzeppelin/upgrades/Proxy.cairo')\n\n return account_cls, implementation_cls, proxy_cls\n\n\n@pytest.fixture(scope='module')\nasync def proxy_init(contract_classes):\n account_cls, implementation_cls, proxy_cls = contract_classes\n starknet = await Starknet.empty()\n account1 = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n account2 = await starknet.deploy(\n contract_class=account_cls,\n constructor_calldata=[signer.public_key]\n )\n implementation_decl = await starknet.declare(\n contract_class=implementation_cls\n )\n proxy = await starknet.deploy(\n contract_class=proxy_cls,\n constructor_calldata=[implementation_decl.class_hash]\n )\n return (\n starknet.state,\n account1,\n account2,\n proxy\n )\n\n\n@pytest.fixture\ndef proxy_factory(contract_classes, proxy_init):\n account_cls, _, proxy_cls = contract_classes\n state, account1, account2, proxy = proxy_init\n _state = state.copy()\n admin = ca<|endoftext|>"} +{"language": "python", "text": "import os\nfrom mercurial import ui, hg\n# BUG: CWE-20 Improper Input Validation\n# from subprocess import Popen, PIPE\n# FIXED:\nimport Bcfg2.Server.Plugin\n\n# for debugging output only\nimport logging\nlogger = logging.getLogger('Bcfg2.Plugins.Mercurial')\n\nclass Hg(Bcfg2.Server.Plugin.Plugin,\n Bcfg2.Server.Plugin.Version):\n \"\"\"Mercurial is a version plugin for dealing with Bcfg2 repository.\"\"\"\n name = 'Mercurial'\n __version__ = '$Id$'\n __author__ = 'bcfg-dev@mcs.anl.gov'\n experimental = True\n\n def __init__(self, core, datastore):\n Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)\n Bcfg2.Server.Plugin.Version.__init__(self)\n self.core = core\n self.datastore = datastore\n\n # path to hg directory for Bcfg2 repo\n hg_dir = \"%s/.hg\" % datastore\n\n # Read changeset from bcfg2 repo\n if os.path.isdir(hg_dir):\n self.get_revision()\n else:\n logger.error(\"%s is not present.\" % hg_dir)\n raise Bcfg2.Server.Plugin.PluginInitError\n\n logger.debug(\"Initialized hg plugin with hg directory = %s\" % hg_dir)\n\n def get_revision(self):\n \"\"\"Read hg revision information for the Bcfg2 repository.\"\"\"\n try:\n repo_path = \"%s/\" % self.datastore\n repo = hg.repository(ui.ui(), repo_path)\n tip = repo.changelog.tip()\n revision = repo.changelog.rev(tip)\n except:\n logger.error(\"Failed to read hg repository; disabling mercurial support\")\n raise Bcfg2.Server.Plugin.PluginInitError\n return revision\n\n<|endoftext|>"} +{"language": "python", "text": "self.args]\n if getattr(filter_, 'evalcontextfilter', False):\n args.insert(0, eval_ctx)\n elif getattr(filter_, 'environmentfilter', False):\n args.insert(0, self.environment)\n kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)\n if self.dyn_args is not None:\n try:\n args.extend(self.dyn_args.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n if self.dyn_kwargs is not None:\n try:\n kwargs.update(self.dyn_kwargs.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n try:\n return filter_(obj, *args, **kwargs)\n except Exception:\n raise Impossible()\n\n\nclass Test(Expr):\n \"\"\"Applies a test on an expression. `name` is the name of the test, the\n rest of the fields are the same as for :class:`Call`.\n \"\"\"\n fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')\n\n\nclass Call(Expr):\n \"\"\"Calls an expression. `args` is a list of arguments, `kwargs` a list\n of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`\n and `dyn_kwargs` has to be either `None` or a node that is used as\n node for dynamic positional (``*args``) or keyword (``**kwargs``)\n arguments.\n \"\"\"\n fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')\n\n def as_const(self, eval_ctx=None):\n eval_ctx = get_eval_context(self, eval_ctx)\n # BUG: CWE-134 Use of Externally-Controlled Format String\n # if eval_ctx.volatile:\n # FIXED: \n if eval_ctx.volatile or eval_ctx.environment.sandboxed:\n raise Impossible()\n obj = self.node.as_const(eval_ctx)\n\n # don't evaluate context functions\n args = [x.as_const(eval_ctx) for x in self.args]\n if isinstance(obj, _context_function_types):\n if getattr(obj, 'contextfunction', False):\n raise Impossible()\n elif getattr(obj, 'evalcontextfunction', False):\n args.insert(0, eval_ctx)\n elif getattr(obj, 'environmentfunction', False):\n args.insert(0, self.environment)\n\n kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)\n if self.dyn_args is not None:\n try:\n args.extend(self.dyn_args.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n if self.dyn_kwargs is not None:\n try:\n kwargs.update(self.dyn_kwargs.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n try:\n return obj(*args, **kwargs)\n except Exception:\n raise Impossible()\n\n\nclass Getitem(Expr):\n \"\"\"Get an attribute or item from an expression and prefer the item.\"\"\"\n fields = ('node', 'arg', 'ctx')\n\n def as_const(self, eval_ctx=None):\n eval_ctx = get_eval_context(self, eval_ctx)\n if self.ctx != 'load':\n raise Impossible()\n try:\n return self.environment.getitem(self.node.as_const(eval_ctx),\n self.arg.as_const(eval_ctx))\n except Exception:\n raise Impossible()\n\n def can_assign(self):\n return False\n\n\nclass<|endoftext|>"} +{"language": "python", "text": "ns under the License.\n\nimport errno\nimport logging\nimport os\nimport shutil\nfrom typing import IO, Dict, List, Optional, Tuple\n\nimport twisted.internet.error\nimport twisted.web.http\nfrom twisted.web.http import Request\nfrom twisted.web.resource import Resource\n\nfrom synapse.api.errors import (\n FederationDeniedError,\n HttpResponseException,\n NotFoundError,\n RequestSendFailed,\n SynapseError,\n)\nfrom synapse.config._base import ConfigError\nfrom synapse.logging.context import defer_to_thread\nfrom synapse.metrics.background_process_metrics import run_as_background_process\nfrom synapse.util.async_helpers import Linearizer\nfrom synapse.util.retryutils import NotRetryingDestination\nfrom synapse.util.stringutils import random_string\n\nfrom ._base import (\n FileInfo,\n Responder,\n get_filename_from_headers,\n respond_404,\n respond_with_responder,\n)\nfrom .config_resource import MediaConfigResource\nfrom .download_resource import DownloadResource\nfrom .filepath import MediaFilePaths\nfrom .media_storage import MediaStorage\nfrom .preview_url_resource import PreviewUrlResource\nfrom .storage_provider import StorageProviderWrapper\nfrom .thumbnail_resource import ThumbnailResource\nfrom .thumbnailer import Thumbnailer, ThumbnailError\nfrom .upload_resource import UploadResource\n\nlogger = logging.getLogger(__name__)\n\n\nUPDATE_RECENTLY_ACCESSED_TS = 60 * 1000\n\n\nclass MediaRepository:\n def __init__(self, hs):\n self.hs = hs\n self.auth = hs.get_auth()\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.client = hs.get_http_client()\n # FIXED: \n self.client = hs.get_federation_http_client()\n self.clock = hs.get_clock()\n self.server_name = hs.hostname\n self.store = hs.get_datastore()\n self.max_upload_size = hs.config.max_upload_size\n self.max_image_pixels = hs.config.max_image_pixels\n\n self.primary_base_path = hs.config.media_store_path\n self.filepaths = MediaFilePaths(self.primary_base_path)\n\n self.dynamic_thumbnails = hs.config.dynamic_thumbnails\n self.thumbnail_requirements = hs.config.thumbnail_requirements\n\n self.remote_media_linearizer = Linearizer(name=\"media_remote\")\n\n self.recently_accessed_remotes = set()\n self.recently_accessed_locals = set()\n\n self.federation_domain_whitelist = hs.config.federation_domain_whitelist\n\n # List of StorageProviders where we should search for media and\n # potentially upload to.\n storage_providers = []\n\n for clz, provider_config, wrapper_config in hs.config.media_storage_providers:\n backend = clz(hs, provider_config)\n provider = StorageProviderWrapper(\n backend,\n store_local=wrapper_config.store_local,\n store_remote=wrapper_config.store_remote,\n store_synchronous=wrapper_config.store_synchronous,\n )\n storage_providers.append(provider)\n\n self.media_storage = MediaStorage(\n self.hs, self.primary_base_path, self.filepaths, storage_providers\n )\n\n self.clock.looping_call(\n self._start_update_recently_accessed, UPDATE_RECENTLY_ACCESSED_TS\n )\n\n def _start_update_recently_accessed(self):\n return ru<|endoftext|>"} +{"language": "python", "text": " hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n#############################################\n\nimport os\nimport subprocess\nimport ansible.constants as C\nfrom ansible.inventory.host import Host\nfrom ansible.inventory.group import Group\nfrom ansible import utils\nfrom ansible import errors\nimport sys\n\nclass InventoryScript(object):\n ''' Host inventory parser for ansible using external inventory scripts. '''\n\n def __init__(self, filename=C.DEFAULT_HOST_LIST):\n\n # Support inventory scripts that are not prefixed with some\n # path information but happen to be in the current working\n # directory when '.' is not in PATH.\n self.filename = os.path.abspath(filename)\n cmd = [ self.filename, \"--list\" ]\n try:\n sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except OSError, e:\n raise errors.AnsibleError(\"problem running %s (%s)\" % (' '.join(cmd), e))\n (stdout, stderr) = sp.communicate()\n self.data = stdout\n # see comment about _meta below\n self.host_vars_from_top = None\n self.groups = self._parse(stderr)\n\n def _parse(self, err):\n\n all_hosts = {}\n # BUG: CWE-20 Improper Input Validation\n # self.raw = utils.parse_json(self.data)\n # FIXED: \n self.raw = utils.parse_json(self.data, from_remote=True)\n all = Group('all')\n groups = dict(all=all)\n group = None\n\n\n if 'failed' in self.raw:\n sys.stderr.write(err + \"\\n\")\n raise errors.AnsibleError(\"failed to parse executable inventory script results: %s\" % self.raw)\n\n for (group_name, data) in self.raw.items():\n \n # in Ansible 1.3 and later, a \"_meta\" subelement may contain\n # a variable \"hostvars\" which contains a hash for each host\n # if this \"hostvars\" exists at all then do not call --host for each\n # host. This is for efficiency and scripts should still return data\n # if called with --host for backwards compat with 1.2 and earlier.\n\n if group_name == '_meta':\n if 'hostvars' in data:\n self.host_vars_from_top = data['hostvars']\n continue\n\n if group_name != all.name:\n group = groups[group_name] = Group(group_name)\n else:\n group = all\n host = None\n\n if not isinstance(data, dict):\n data = {'hosts': data}\n elif not any(k in data for k in ('hosts','vars')):\n data = {'hosts': [group_name], 'vars': data}\n\n if 'hosts' in data:\n\n for hostname in data['hosts']:\n if not hostname in all_hosts:\n all_hosts[hostname] = Host(hostname)\n host = all_hosts[hostname]\n group.add_host(host)\n\n if 'vars' in data:\n for k, v in data['vars'].iteritems():\n <|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2018 New Vector Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom synapse.app.generic_worker import GenericWorkerServer\n\nfrom tests.server import make_request\nfrom tests.unittest import HomeserverTestCase\n\n\nclass FrontendProxyTests(HomeserverTestCase):\n def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # http_client=None, homeserver_to_use=GenericWorkerServer\n # FIXED:\n federation_http_client=None, homeserver_to_use=GenericWorkerServer\n )\n\n return hs\n\n def default_config(self):\n c = super().default_config()\n c[\"worker_app\"] = \"synapse.app.frontend_proxy\"\n\n c[\"worker_listeners\"] = [\n {\n \"type\": \"http\",\n \"port\": 8080,\n \"bind_addresses\": [\"0.0.0.0\"],\n \"resources\": [{\"names\": [\"client\"]}],\n }\n ]\n\n return c\n\n def test_listen_http_with_presence_enabled(self):\n \"\"\"\n When presence is on, the stub servlet will not register.\n \"\"\"\n # Presence is on\n <|endoftext|>"} +{"language": "python", "text": "import logger\nfrom markdownify import markdownify\nimport mammoth\nimport shutil\nimport os\nimport time\nimport re\nimport yaml\n\n\n# \u5bfc\u5165Zip\u6587\u96c6\nclass ImportZipProject():\n # \u8bfb\u53d6 Zip \u538b\u7f29\u5305\n def read_zip(self,zip_file_path,create_user):\n # \u5bfc\u5165\u6d41\u7a0b\uff1a\n # 1\u3001\u89e3\u538bzip\u538b\u7f29\u5305\u6587\u4ef6\u5230temp\u6587\u4ef6\u5939\n # 2\u3001\u904d\u5386temp\u6587\u4ef6\u5939\u5185\u7684\u89e3\u538b\u540e\u7684.md\u6587\u4ef6\n # 3\u3001\u8bfb\u53d6.md\u6587\u4ef6\u7684\u6587\u672c\u5185\u5bb9\n # 4\u3001\u5982\u679c\u91cc\u9762\u5339\u914d\u5230\u76f8\u5bf9\u8def\u5f84\u7684\u9759\u6001\u6587\u4ef6\uff0c\u4ece\u6307\u5b9a\u6587\u4ef6\u5939\u91cc\u9762\u8bfb\u53d6\n # 5\u3001\u4e0a\u4f20\u56fe\u7247\uff0c\u5199\u5165\u6570\u636e\u5e93\uff0c\u4fee\u6539.md\u6587\u4ef6\u91cc\u9762\u7684url\u8def\u5f84\n\n # \u65b0\u5efa\u4e00\u4e2a\u4e34\u65f6\u6587\u4ef6\u5939\uff0c\u7528\u4e8e\u5b58\u653e\u89e3\u538b\u7684\u6587\u4ef6\n self.temp_dir = zip_file_path[:-3]\n os.mkdir(self.temp_dir)\n # \u89e3\u538b zip \u6587\u4ef6\u5230\u6307\u5b9a\u4e34\u65f6\u6587\u4ef6\u5939\n shutil.unpack_archive(zip_file_path, extract_dir=self.temp_dir)\n\n # \u5904\u7406\u6587\u4ef6\u5939\u548c\u6587\u4ef6\u540d\u7684\u4e2d\u6587\u4e71\u7801\n for root, dirs, files in os.walk(self.temp_dir):\n for dir in dirs:\n try:\n new_dir = dir.encode('cp437').decode('gbk')\n except:\n new_dir = dir.encode('utf-8').decode('utf-8')\n # print(new_dir)\n os.rename(os.path.join(root, dir), os.path.join(root, new_dir))\n\n for file in files:\n try:\n new_file = file.encode('cp437').decode('gbk')\n except:\n new_file = file.encode('utf-8').decode('utf-8')\n # print(root, new_file)\n os.rename(os.path.join(root, file), os.path.join(root, new_file))\n\n # \u8bfb\u53d6yaml\u6587\u4ef6\n try:\n with open(os.path.join(self.temp_dir ,'mrdoc.yaml'),'r',encoding='utf-8') as yaml_file:\n # BUG: CWE-502 Deserialization of Untrusted Data\n # yaml_str = yaml.load(yaml_file.read())\n # FIXED: \n yaml_str = yaml.safe_load(yaml_file.read())\n project_name = yaml_str['project_name'] \\\n if 'project_name' in yaml_str.keys() else zip_file_path[:-4].split('/')[-1]\n project_desc = yaml_str['project_desc'] if 'project_desc' in yaml_str.keys() else ''\n project_role = yaml_str['project_role'] if 'project_role' in yaml_str.keys() else 1\n editor_mode = yaml_str['editor_mode'] if 'editor_mode' in yaml_str.keys() else 1\n project_toc = yaml_str['toc']\n toc_item_list = []\n for toc in project_toc:\n # print(toc)\n item = {\n 'name': toc['name'],\n 'file': toc['file'],\n 'parent': 0,\n }\n toc_item_list.append(item)\n if 'children' in toc.keys():\n for b in toc['children']:\n item = {\n 'name': b['name'],\n 'file': b['file'],\n 'parent': toc['name']\n }\n toc_item_list.append(item)\n if 'children' in b.keys():\n for c in b['children']:\n item = {\n 'name': c['name'],\n 'file': c['file'],\n 'parent': b['name']\n }\n toc_item_list.append(ite<|endoftext|>"} +{"language": "python", "text": "'VCLLexer', 'VCLSnippetLexer']\n\n\nclass VCLLexer(RegexLexer):\n \"\"\"\n For Varnish Configuration Language (VCL).\n\n .. versionadded:: 2.2\n \"\"\"\n name = 'VCL'\n aliases = ['vcl']\n filenames = ['*.vcl']\n mimetypes = ['text/x-vclsrc']\n\n def analyse_text(text):\n # If the very first line is 'vcl 4.0;' it's pretty much guaranteed\n # that this is VCL\n if text.startswith('vcl 4.0;'):\n return 1.0\n # Skip over comments and blank lines\n # This is accurate enough that returning 0.9 is reasonable.\n # Almost no VCL files start without some comments.\n elif '\\nvcl 4.0;' in text[:1000]:\n return 0.9\n\n tokens = {\n 'probe': [\n include('whitespace'),\n include('comments'),\n (r'(\\.\\w+)(\\s*=\\s*)([^;]*)(;)',\n bygroups(Name.Attribute, Operator, using(this), Punctuation)),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'acl': [\n include('whitespace'),\n include('comments'),\n (r'[!/]+', Operator),\n (r';', Punctuation),\n (r'\\d+', Number),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'backend': [\n include('whitespace'),\n (r'(\\.probe)(\\s*=\\s*)(\\w+)(;)',\n bygroups(Name.Attribute, Operator, Name.Variable.Global, Punctuation)),\n (r'(\\.probe)(\\s*=\\s*)(\\{)',\n bygroups(Name.Attribute, Operator, Punctuation), 'probe'),\n # BUG: NVD-CWE-Other Other\n # (r'(\\.\\w+\\b)(\\s*=\\s*)([^;]*)(\\s*;)',\n # FIXED: \n (r'(\\.\\w+\\b)(\\s*=\\s*)([^;\\s]*)(\\s*;)',\n bygroups(Name.Attribute, Operator, using(this), Punctuation)),\n (r'\\{', Punctuation, '#push'),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'statements': [\n (r'(\\d\\.)?\\d+[sdwhmy]', Literal.Date),\n (r'(\\d\\.)?\\d+ms', Literal.Date),\n (r'(vcl_pass|vcl_hash|vcl_hit|vcl_init|vcl_backend_fetch|vcl_pipe|'\n r'vcl_backend_response|vcl_synth|vcl_deliver|vcl_backend_error|'\n r'vcl_fini|vcl_recv|vcl_purge|vcl_miss)\\b', Name.Function),\n (r'(pipe|retry|hash|synth|deliver|purge|abandon|lookup|pass|fail|ok|'\n r'miss|fetch|restart)\\b', Name.Constant),\n (r'(beresp|obj|resp|req|req_top|bereq)\\.http\\.[a-zA-Z_-]+\\b', Name.Variable),\n (words((\n 'obj.status', 'req.hash_always_miss', 'beresp.backend', 'req.esi_level',\n 'req.can_gzip', 'beresp.ttl', 'obj.uncacheable', 'req.ttl', 'obj.hits',\n 'client.identity', 'req.hash_ignore_busy', 'obj.reason', 'req.xid',\n 'req_top.proto', 'beresp.age', 'obj.proto', 'obj.age', 'local.ip',\n 'beresp.uncacheable', 'req.method', 'beresp.backend.ip', 'now',\n 'obj.grace', 'req.restarts', 'beresp.keep', 'req.proto', 'resp.proto',\n 'bereq.xid', 'bereq.between_bytes_timeout', 'req.esi',\n 'bereq.first_byte_timeout', 'bereq.method', 'bereq.connect_timeout',\n 'beresp.do_gzip', 'resp.status', 'beresp.do_gunzip',\n 'beresp.storage_hint', 'resp.is_streaming', 'beresp.do_stream',\n 'req_top.method', 'bereq.backend', 'beresp.ba<|endoftext|>"} +{"language": "python", "text": "go.conf.urls import patterns, url\nfrom django.contrib.auth import context_processors\nfrom django.contrib.auth.urls import urlpatterns\nfrom django.contrib.auth.views import password_reset\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.messages.api import info\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import Template, RequestContext\nfrom django.views.decorators.cache import never_cache\n\n@never_cache\ndef remote_user_auth_view(request):\n \"Dummy view for remote user tests\"\n t = Template(\"Username is {{ user }}.\")\n c = RequestContext(request, {})\n return HttpResponse(t.render(c))\n\ndef auth_processor_no_attr_access(request):\n r1 = render_to_response('context_processors/auth_attrs_no_access.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n # *After* rendering, we check whether the session was accessed\n return render_to_response('context_processors/auth_attrs_test_access.html',\n {'session_accessed':request.session.accessed})\n\ndef auth_processor_attr_access(request):\n r1 = render_to_response('context_processors/auth_attrs_access.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n return render_to_response('context_processors/auth_attrs_test_access.html',\n {'session_accessed':request.session.accessed})\n\ndef auth_processor_user(request):\n return render_to_response('context_processors/auth_attrs_user.html',\n RequestContext(request, {}, processors=[context_processors.auth]))\n\ndef auth_processor_perms(request):\n return render_to_response('context_processors/auth_attrs_perms.htm<|endoftext|>"} +{"language": "python", "text": "ng import List, Tuple\n\nimport h2.settings\nimport hpack\nimport hyperframe.frame\nimport pytest\nfrom h2.errors import ErrorCodes\n\nfrom mitmproxy.connection import ConnectionState, Server\nfrom mitmproxy.flow import Error\nfrom mitmproxy.http import HTTPFlow, Headers, Request\nfrom mitmproxy.net.http import status_codes\nfrom mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData\nfrom mitmproxy.proxy.context import Context\nfrom mitmproxy.proxy.events import ConnectionClosed, DataReceived\nfrom mitmproxy.proxy.layers import http\nfrom mitmproxy.proxy.layers.http import HTTPMode\nfrom mitmproxy.proxy.layers.http._http2 import Http2Client, split_pseudo_headers\nfrom test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory\nfrom test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply\n\nexample_request_headers = (\n (b':method', b'GET'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n)\n\nexample_response_headers = (\n (b':status', b'200'),\n)\n\nexample_request_trailers = (\n (b'req-trailer-a', b'a'),\n (b'req-trailer-b', b'b')\n)\n\nexample_response_trailers = (\n (b'resp-trailer-a', b'a'),\n (b'resp-trailer-b', b'b')\n)\n\n\n@pytest.fixture\ndef open_h2_server_conn():\n # this is a bit fake here (port 80, with alpn, but no tls - c'mon),\n # but we don't want to pollute our tests with TLS handshakes.\n s = Server((\"example.com\", 80))\n s.state = ConnectionState.OPEN\n s.alpn = b\"h2\"\n return s\n\n\ndef decode_frames(data: bytes) -> List[hyperframe.frame.Frame]:\n # swallow preamble\n if data.startswith(b\"PRI * HTTP/2.0\"):\n data = data[24:]\n frames = []\n while data:\n f, <|endoftext|>"} +{"language": "python", "text": "\\(register\\s+const\\s+char\\s*\\*\\s*str,\\s*register\\s+unsigned\\s+int\\s+len\\s*\\)')\nREG_STR_AT = re.compile('str\\[(\\d+)\\]')\nREG_UNFOLD_KEY = re.compile('unicode_unfold_key\\s*\\(register\\s+const\\s+char\\s*\\*\\s*str,\\s*register\\s+unsigned\\s+int\\s+len\\)')\nREG_ENTRY = re.compile('\\{\".+?\",\\s*/\\*(.+?)\\*/\\s*(-?\\d+),\\s*(\\d)\\}')\nREG_EMPTY_ENTRY = re.compile('\\{\"\",\\s*(-?\\d+),\\s*(\\d)\\}')\nREG_IF_LEN = re.compile('if\\s*\\(\\s*len\\s*<=\\s*MAX_WORD_LENGTH.+')\nREG_GET_HASH = re.compile('(?:register\\s+)?(?:unsigned\\s+)?int\\s+key\\s*=\\s*hash\\s*\\(str,\\s*len\\);')\nREG_GET_CODE = re.compile('(?:register\\s+)?const\\s+char\\s*\\*\\s*s\\s*=\\s*wordlist\\[key\\]\\.name;')\nREG_CODE_CHECK = re.compile('if\\s*\\(\\*str\\s*==\\s*\\*s\\s*&&\\s*!strncmp.+\\)')\n\ndef parse_line(s):\n s = s.rstrip()\n\n r = re.sub(REG_LINE_GPERF, '', s)\n if r != s: return r\n r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)\n if r != s: return r\n r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\\\1)', s)\n if r != s: return r\n r = re.sub(REG_UNFOLD_KEY, 'unicode_unfold_key(OnigCodePoint code)', s)\n if r != s: return r\n r = re.sub(REG_ENTRY, '{\\\\1, \\\\2, \\\\3}', s)\n if r != s: return r\n r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\\\1, \\\\2}', s)\n if r != s: return r\n r = re.sub(REG_IF_LEN, 'if (0 == 0)', s)\n if r != s: return r\n r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s)\n if r != s: return r\n r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s)\n if r != s: return r\n # BUG: CWE-787 Out-of-bounds Write\n # r = re.sub(REG_CODE_CHECK, 'if (code == gcode)', s)\n # FIXED: \n r = re.sub(REG_CODE_CHECK, 'if (code == gcode && wordlist[key].index >= 0)', s)\n if r != s: return r\n\n return s\n\ndef parse_file(f):\n print \"/* This file was converted by gperf_unfold_key_conv.py\\n from gperf output file. */\"\n\n line = f.readline()\n while line:\n s = parse_line(line)\n print s\n line = f.readline()\n\n\n# main\nparse_file(sys.stdin)\n<|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright 2018 New Vector Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom twisted.internet import defer\n\nfrom synapse.api.errors import NotFoundError\nfrom synapse.rest.client.v1 import room\n\nfrom tests.unittest import HomeserverTestCase\n\n\nclass PurgeTests(HomeserverTestCase):\n\n user_id = \"@red:server\"\n servlets = [room.register_servlets]\n\n def make_homeserver(self, reactor, clock):\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # hs = self.setup_test_homeserver(\"server\", http_client=None)\n # FIXED: \n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n return hs\n\n def prepare(self, reactor, clock, hs):\n self.room_id = self.helper.create_room_as(self.user_id)\n\n def test_purge(self):\n \"\"\"\n Purging a room will delete everything before the topological point.\n \"\"\"\n # Send four messages to the room\n first = self.helper.send(self.room_id, body=\"test1\")\n second = self.helper.send(self.room_id, body=\"test2\")\n third = self.helper.send(self.room_id, body=\"test3\")\n last = self.helper.send(self.room_id, body=\"test4\")\n\n store = self.hs.get_datastore()\n storage = self.hs.get_storage()\n\n # Get the topological token\n token = self.get_success(\n store.get_topological_token_for_event(last[\"event_id\"])\n )\n token_str = self.get_success(token.to_string(self.hs.get_datastore()))\n\n # Purge everything before this topological token\n self.get_success(\n storage.purge_events.purge_history(self.room_id, token_str, True)\n )\n\n # 1-3 should fail and last will succeed, meaning that 1-3 are deleted\n # and last is not.\n self.get_failure(store.get_event(first[\"event_id\"]), NotFoundError)\n self.get_failure(store.get_event(second[\"event_id\"]), NotFoundError)\n self.get_failure(store.get_event(third[\"event_id\"]), NotFoundError)\n self.get_success(store.get_event(last[\"event_id\"]))\n\n def test_purge_wont_delete_extrems(self):\n \"\"\"\n Purging a room will delete everything before the topological point.\n \"\"\"\n # Send four messages to the room\n first = sel<|endoftext|>"} +{"language": "python", "text": " rs = __query_source_package_path_by_name(server_id, pkgFilename, channel)\n if rs is None:\n return 0\n return 1\n\n\n# The query used both in get_source_package_path and package_source_in_channel\ndef __query_source_package_path_by_name(server_id, pkgFilename, channel):\n statement = \"\"\"\n select\n unique ps.path\n from\n rhnSourceRPM sr,\n rhnPackageSource ps,\n rhnPackage p,\n rhnChannelPackage cp,\n rhnChannel c,\n rhnServerChannel sc\n where\n sc.server_id = :server_id\n and sc.channel_id = cp.channel_id\n and cp.channel_id = c.id\n and c.label = :channel\n and cp.package_id = p.id\n and p.source_rpm_id = sr.id\n and sr.name = :name\n and p.source_rpm_id = ps.source_rpm_id\n and ((p.org_id is null and ps.org_id is null)\n or p.org_id = ps.org_id)\n \"\"\"\n h = rhnSQL.prepare(statement)\n h.execute(name=pkgFilename, channel=channel, server_id=server_id)\n return h.fetchone_dict()\n\n\ndef get_info_for_package(pkg, channel_id, org_id):\n log_debug(3, pkg)\n pkg = map(str, pkg)\n params = {'name': pkg[0],\n 'ver': pkg[1],\n 'rel': pkg[2],\n 'epoch': pkg[3],\n 'arch': pkg[4],\n 'channel_id': channel_id,\n 'org_id': org_id}\n # yum repo has epoch=\"0\" not only when epoch is \"0\" but also if it's NULL\n # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n # if pkg[3] == '0' or pkg[3] == '':\n # FIXED: \n if pkg[3] == '0' or pkg[3] == '' or pkg[3]==None:\n epochStatement = \"(epoch is null or epoch = :epoch)\"\n else:\n epochStatement = \"epoch = :epoch\"\n if params['org_id']:\n orgStatement = \"org_id = :org_id\"\n else:\n orgStatement = \"org_id is null\"\n\n statement = \"\"\"\n select p.path, cp.channel_id,\n cv.checksum_type, cv.checksum\n from rhnPackage p\n join rhnPackageName pn\n on p.name_id = pn.id\n join rhnPackageEVR pe\n on p.evr_id = pe.id\n join rhnPackageArch pa\n on p.package_arch_id = pa.id\n left join rhnChannelPackage cp\n on p.id = cp.package_id\n and cp.channel_id = :channel_id\n join rhnChecksumView cv\n on p.checksum_id = cv.id\n where pn.name = :name\n and pe.version = :ver\n and pe.release = :rel\n and %s\n and pa.label = :arch\n and %s\n order by cp.channel_id nulls last\n \"\"\" % (epochStatement, orgStatement)\n\n h = rhnSQL.prepare(statement)\n h.execute(**params)\n\n ret = h.fetchone_dict()\n if not ret:\n return {'path': None,\n 'channel_id': None,\n 'checksum_type': None,\n 'checksum': None,\n }\n return ret\n\n\ndef _none2emptyString(foo):\n if foo is None:\n return \"\"\n return str(foo)\n\nif __name__ == '__main__':\n \"\"\"Test code.\n \"\"\"\n from spacewalk.common.rhnLog import initLOG\n initLOG(\"stdout\", 1)\n rhnSQL.initDB()\n print\n # new client\n print get_package_path(1000463284, 'kernel-2.4.2-2.i686.rpm', 'redhat-linux-i386-7.1')\n print get_source_package_path(1000463284, 'kernel-2.4.2-2.i686.rpm', 'redhat-<|endoftext|>"} +{"language": "python", "text": "t the routine from twisted.\n if isIPAddress(server_name):\n return False\n\n # next, check the deny list\n deny = acl_event.content.get(\"deny\", [])\n if not isinstance(deny, (list, tuple)):\n logger.warning(\"Ignoring non-list deny ACL %s\", deny)\n deny = []\n for e in deny:\n if _acl_entry_matches(server_name, e):\n # logger.info(\"%s matched deny rule %s\", server_name, e)\n return False\n\n # then the allow list.\n allow = acl_event.content.get(\"allow\", [])\n if not isinstance(allow, (list, tuple)):\n logger.warning(\"Ignoring non-list allow ACL %s\", allow)\n allow = []\n for e in allow:\n if _acl_entry_matches(server_name, e):\n # logger.info(\"%s matched allow rule %s\", server_name, e)\n return True\n\n # everything else should be rejected.\n # logger.info(\"%s fell through\", server_name)\n return False\n\n\ndef _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:\n if not isinstance(acl_entry, str):\n logger.warning(\n \"Ignoring non-str ACL entry '%s' (is %s)\", acl_entry, type(acl_entry)\n )\n return False\n regex = glob_to_regex(acl_entry)\n return bool(regex.match(server_name))\n\n\nclass FederationHandlerRegistry:\n \"\"\"Allows classes to register themselves as handlers for a given EDU or\n query type for incoming federation traffic.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n self.config = hs.config\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self.clock = hs.get_clock()\n self._instance_name = hs.get_instance_name()\n\n # These are safe to load in monolith mode, but will explode if we try\n # and use them. However we have guards before we use them to ensure that\n # we don't route to ourselves, and in monolith mode that will always be\n # the case.\n self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)\n self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)\n\n self.edu_handlers = (\n {}\n ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]]\n self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]]\n\n # Map from type to instance name that we should route EDU handling to.\n self._edu_type_to_instance = {} # type: Dict[str, str]\n\n def register_edu_handler(\n self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]\n ):\n \"\"\"Sets the handler callable that will be used to handle an incoming\n federation EDU of the given type.\n\n Args:\n edu_type: The type of the incoming EDU to register handler for\n handler: A callable invoked on incoming EDU\n of the given type. The arguments are the origin server name and\n the EDU contents.\n \"\"\"\n if edu_type in self.edu_handlers:\n raise KeyError(\"Already have an EDU handler for %s\" % (edu_type,))\n\n logger.info(\"Registering federation EDU handler for %r\", edu_type)\n\n self.edu_handlers[edu_type] = handler\n\n def register_query_handler(\n self, query_type: str, handler: Callable[[dict], <|endoftext|>"} +{"language": "python", "text": "ing: utf-8 -*-\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom typing import List, TYPE_CHECKING\n\nfrom zulint.custom_rules import RuleList\nif TYPE_CHECKING:\n from zulint.custom_rules import Rule\n\n# Rule help:\n# By default, a rule applies to all files within the extension for which it is specified (e.g. all .py files)\n# There are three operators we can use to manually include or exclude files from linting for a rule:\n# 'exclude': 'set([, ...])' - if is a filename, excludes that file.\n# if is a directory, excludes all files directly below the directory .\n# 'exclude_line': 'set([(, ), ...])' - excludes all lines matching in the file from linting.\n# 'include_only': 'set([, ...])' - includes only those files where is a substring of the filepath.\n\nPYDELIMS = r'''\"'()\\[\\]{}#\\\\'''\nPYREG = r\"[^{}]\".format(PYDELIMS)\nPYSQ = r'\"(?:[^\"\\\\]|\\\\.)*\"'\nPYDQ = r\"'(?:[^'\\\\]|\\\\.)*'\"\nPYLEFT = r\"[(\\[{]\"\nPYRIGHT = r\"[)\\]}]\"\nPYCODE = PYREG\nfor depth in range(5):\n PYGROUP = r\"\"\"(?:{}|{}|{}{}*{})\"\"\".format(PYSQ, PYDQ, PYLEFT, PYCODE, PYRIGHT)\n PYCODE = r\"\"\"(?:{}|{})\"\"\".format(PYREG, PYGROUP)\n\nFILES_WITH_LEGACY_SUBJECT = {\n # This basically requires a big DB migration:\n 'zerver/lib/topic.py',\n\n # This is for backward compatibility.\n 'zerver/tests/test_legacy_subject.py',\n\n # Other migration-related changes require extreme care.\n 'zerver/lib/fix_unreads.py',\n 'zerver/tests/test_migrations.py',\n\n # These use subject in the email sense, and will\n # probably always be exempt:\n 'zerver/lib/email_mirror.py',\n 'zerver/lib/feedback.py<|endoftext|>"} +{"language": "python", "text": "psis: most ajax processors for askbot\n\nThis module contains most (but not all) processors for Ajax requests.\nNot so clear if this subdivision was necessary as separation of Ajax and non-ajax views\nis not always very clean.\n\"\"\"\nimport datetime\nimport logging\nfrom bs4 import BeautifulSoup\nfrom django.conf import settings as django_settings\nfrom django.core import exceptions\n#from django.core.management import call_command\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseBadRequest\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponseForbidden\nfrom django.forms import ValidationError, IntegerField, CharField\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import render\nfrom django.template.loader import get_template\nfrom django.views.decorators import csrf\nfrom django.utils import simplejson\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext as _\nfrom django.utils.translation import string_concat\nfrom askbot.utils.slug import slugify\nfrom askbot import models\nfrom askbot import forms\nfrom askbot import conf\nfrom askbot import const\nfrom askbot import mail\nfrom askbot.conf import settings as askbot_settings\nfrom askbot.utils import category_tree\nfrom askbot.utils import decorators\nfrom askbot.utils import url_utils\nfrom askbot.utils.forms import get_db_object_or_404\nfrom django.template import RequestContext\nfrom askbot.skins.loaders import render_into_skin_as_string\nfrom askbot.skins.loaders import render_text_into_skin\nfrom askbot.models.<|endoftext|>"} +{"language": "python", "text": "r.ib(type=Optional[Sequence[EventBase]], default=None)\n auth_events = attr.ib(type=Optional[MutableStateMap[EventBase]], default=None)\n\n\nclass FederationHandler(BaseHandler):\n \"\"\"Handles events that originated from federation.\n Responsible for:\n a) handling received Pdus before handing them on as Events to the rest\n of the homeserver (including auth and state conflict resolutions)\n b) converting events that were produced by local clients that may need\n to be sent to remote homeservers.\n c) doing the necessary dances to invite remote users and join remote\n rooms.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n super().__init__(hs)\n\n self.hs = hs\n\n self.store = hs.get_datastore()\n self.storage = hs.get_storage()\n self.state_store = self.storage.state\n self.federation_client = hs.get_federation_client()\n self.state_handler = hs.get_state_handler()\n self._state_resolution_handler = hs.get_state_resolution_handler()\n self.server_name = hs.hostname\n self.keyring = hs.get_keyring()\n self.action_generator = hs.get_action_generator()\n self.is_mine_id = hs.is_mine_id\n self.spam_checker = hs.get_spam_checker()\n self.event_creation_handler = hs.get_event_creation_handler()\n self._message_handler = hs.get_message_handler()\n self._server_notices_mxid = hs.config.server_notices_mxid\n self.config = hs.config\n # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')\n # self.http_client = hs.get_simple_http_client()\n # FIXED: \n self.http_client = hs.get_proxied_blacklisted_http_client()\n self._instance_name = hs.get_instance_name()\n self._replication = hs.get_replication_data_handler()\n\n self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)\n self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(\n hs\n )\n\n if hs.config.worker_app:\n self._user_device_resync = ReplicationUserDevicesResyncRestServlet.make_client(\n hs\n )\n self._maybe_store_room_on_outlier_membership = ReplicationStoreRoomOnOutlierMembershipRestServlet.make_client(\n hs\n )\n else:\n self._device_list_updater = hs.get_device_handler().device_list_updater\n self._maybe_store_room_on_outlier_membership = (\n self.store.maybe_store_room_on_outlier_membership\n )\n\n # When joining a room we need to queue any events for that room up.\n # For each room, a list of (pdu, origin) tuples.\n self.room_queues = {} # type: Dict[str, List[Tuple[EventBase, str]]]\n self._room_pdu_linearizer = Linearizer(\"fed_room_pdu\")\n\n self.third_party_event_rules = hs.get_third_party_event_rules()\n\n self._ephemeral_messages_enabled = hs.config.enable_ephemeral_messages\n\n async def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False) -> None:\n \"\"\" Process a PDU received via a federation /send/ transaction, or\n via backfill of missing prev_events\n\n Args:\n origin (str): server which initiated the /send/ transaction. Will\n be used to fetch miss<|endoftext|>"} +{"language": "python", "text": "ignedjson.key\nfrom signedjson.sign import SignatureVerifyException\n\nfrom sydent.http.httpclient import FederationHttpClient\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoAuthenticationError(Exception):\n \"\"\"\n Raised when no signature is provided that could be authenticated\n \"\"\"\n pass\n\n\nclass Verifier(object):\n \"\"\"\n Verifies signed json blobs from Matrix Homeservers by finding the\n homeserver's address, contacting it, requesting its keys and\n verifying that the signature on the json blob matches.\n \"\"\"\n def __init__(self, sydent):\n self.sydent = sydent\n # Cache of server keys. These are cached until the 'valid_until_ts' time\n # in the result.\n self.cache = {\n # server_name: ,\n }\n\n @defer.inlineCallbacks\n def _getKeysForServer(self, server_name):\n \"\"\"Get the signing key data from a homeserver.\n\n :param server_name: The name of the server to request the keys from.\n :type server_name: unicode\n\n :return: The verification keys returned by the server.\n :rtype: twisted.internet.defer.Deferred[dict[unicode, dict[unicode, unicode]]]\n \"\"\"\n\n if server_name in self.cache:\n cached = self.cache[server_name]\n now = int(time.time() * 1000)\n if cached['valid_until_ts'] > now:\n defer.returnValue(self.cache[server_name]['verify_keys'])\n\n client = FederationHttpClient(self.sydent)\n # BUG: CWE-770 Allocation of Resources Without Limits or Throttling\n # result = yield client.get_json(\"matrix://%s/_matrix/key/v2/server/\" % server_name)\n # FIXED: \n result = yield client.get_json(\"matrix://%s/_matrix/key/v2/server/\" % server_name, 1024 * 50)\n if 'verify_keys' not in result:\n raise SignatureVerifyException(\"No key found in response\")\n\n if 'valid_until_ts' in result:\n # Don't cache anything without a valid_until_ts or we wouldn't\n # know when to expire it.\n logger.info(\"Got keys for %s: caching until %s\", server_name, result['valid_until_ts'])\n self.cache[server_name] = result\n\n defer.returnValue(result['verify_keys'])\n\n @defer.inlineCallbacks\n def verifyServerSignedJson(self, signed_json, acceptable_server_names=None):\n \"\"\"Given a signed json object, try to verify any one\n of the signatures on it\n\n XXX: This contains a fairly noddy version of the home server\n SRV lookup and signature verification. It does no caching (just\n fetches the signature each time and does not contact any other\n servers to do perspective checks).\n\n :param acceptable_server_names: If provided and not None,\n only signatures from servers in this list will be accepted.\n :type acceptable_server_names: list[unicode] or None\n\n :return a tuple of the server name and key name that was\n successfully verified.\n :rtype: twisted.internet.defer.Deferred[tuple[unicode]]\n\n :raise SignatureVerifyException: The json cannot be verified.\n \"\"\"\n if 'signatures' not in signed_json:\n raise SignatureVerifyException(\"Signature missing\")\n for server_name, sigs in signed_json['signatures'].items():\n if acceptable_server_names is not None:\n <|endoftext|>"} +{"language": "python", "text": "ograph=True`. See https://www.tensorflow.org/guide/autograph\n for more information.\n experimental_relax_shapes: When true, argument shapes may be relaxed to\n avoid unnecessary retracing.\n capture_by_value: Experimental. Whether to capture resource variables by\n value or reference. If None, will inherit from a parent context or\n default to False.\n jit_compile: Force-compile the function with XLA, cf.\n def_function.Function doc on jit_compile.\n experimental_follow_type_hints: See the documentation for `tf.function`.\n\n Raises:\n ValueError: if `input_signature` is not None and the `python_function`'s\n argspec has keyword arguments.\n \"\"\"\n self._python_function = python_function\n pure_function = attributes and IMPLEMENTS_ATTRIBUTE_NAME in attributes\n self._function_spec = FunctionSpec.from_function_and_signature(\n python_function,\n input_signature,\n is_pure=pure_function,\n experimental_follow_type_hints=experimental_follow_type_hints)\n self._name = name\n self._autograph = autograph\n self._autograph_options = autograph_options\n self._experimental_relax_shapes = experimental_relax_shapes\n self._function_cache = FunctionCache()\n self._function_attributes = attributes or {}\n self._capture_by_value = capture_by_value\n self.tracing_count = 0\n if self.input_signature is not None:\n self._hashable_input_signature = hash(self.flat_input_signature)\n # BUG: CWE-667 Improper Locking\n # self._lock = threading.Lock()\n # FIXED: \n self._lock = threading.RLock()\n # _descriptor_cache is a of instance of a class to an instance-specific\n # `Function`, used to make sure defun-decorated methods create different\n # functions for each instance.\n self._descriptor_cache = weakref.WeakKeyDictionary()\n self._jit_compile = jit_compile\n self._experimental_follow_type_hints = experimental_follow_type_hints\n\n def __call__(self, *args, **kwargs):\n \"\"\"Calls a graph function specialized to the inputs.\"\"\"\n with self._lock:\n (graph_function,\n filtered_flat_args) = self._maybe_define_function(args, kwargs)\n return graph_function._call_flat(\n filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access\n\n @property\n def python_function(self):\n \"\"\"Returns the wrapped Python function.\"\"\"\n return self._python_function # pylint: disable=protected-access\n\n @property\n def function_spec(self):\n return self._function_spec\n\n @property\n def input_signature(self):\n \"\"\"Returns the input signature.\"\"\"\n return self._function_spec.input_signature\n\n @property\n def flat_input_signature(self):\n \"\"\"Returns the flattened input signature.\"\"\"\n return self._function_spec.flat_input_signature\n\n def _get_concrete_function_internal_garbage_collected(self, *args, **kwargs):\n \"\"\"Returns a concrete function which cleans up its graph function.\"\"\"\n if self.input_signature:\n args, kwargs = None, None\n with self._lock:\n graph_function, _ = self._maybe_define_function(args, kwargs)\n return graph_function\n\n def _get_concrete_function_internal(self, *args, **kwargs):\n \"\"\"Bypasses error checking when getting a <|endoftext|>"} +{"language": "python", "text": "from urllib.parse import urlparse, urlunparse\nexcept ImportError: # Python 2\n from urlparse import urlparse, urlunparse\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, QueryDict\nfrom django.template.response import TemplateResponse\nfrom django.utils.http import base36_to_int\nfrom django.utils.translation import ugettext as _\nfrom django.shortcuts import resolve_url\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_protect\n\n# Avoid shadowing the login() and logout() views below.\nfrom django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout, get_user_model\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.sites.models import get_current_site\n\n\n@sensitive_post_parameters()\n@csrf_protect\n@never_cache\ndef login(request, template_name='registration/login.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n authentication_form=AuthenticationForm,\n current_app=None, extra_context=None):\n \"\"\"\n Displays the login form and handles the login action.\n \"\"\"\n redirect_to = request.REQUEST.get(redirect_field_name, '')\n\n if request.method == \"POST\":\n form = authentication_form(data=request.POST)\n if form.is_valid():\n # Use default setting if redirect_to is empty\n if not redirect_to:\n <|endoftext|>"} +{"language": "python", "text": "ing: utf-8 -*-\n\n# Copyright 2019 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import absolute_import\n\nfrom twisted.web.resource import Resource\nfrom twisted.internet import defer\n\nimport logging\nimport json\nfrom six.moves import urllib\n\nfrom sydent.http.servlets import get_args, jsonwrap, deferjsonwrap, send_cors\nfrom sydent.http.httpclient import FederationHttpClient\nfrom sydent.users.tokens import issueToken\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass RegisterServlet(Resource):\n isLeaf = True\n\n def __init__(self, syd):\n self.sydent = syd\n self.client = FederationHttpClient(self.sydent)\n\n @deferjsonwrap\n @defer.inlineCallbacks\n def render_POST(self, request):\n \"\"\"\n Register with the Identity Server\n \"\"\"\n send_cors(request)\n\n args = get_args(request, ('matrix_server_name', 'access_token'))\n\n result = yield self.client.get_json(\n \"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s\" % (\n args['matrix_server_name'], urllib.parse.quote(args['access_token']),\n ),\n # BUG: CWE-770 Allocation of Resources <|endoftext|>"} +{"language": "python", "text": "se64\nimport json\n\nimport pytest\n\nfrom jwt.algorithms import Algorithm, HMACAlgorithm, NoneAlgorithm, has_crypto\nfrom jwt.exceptions import InvalidKeyError\nfrom jwt.utils import base64url_decode\n\nfrom .keys import load_ec_pub_key_p_521, load_hmac_key, load_rsa_pub_key\nfrom .utils import crypto_required, key_path\n\nif has_crypto:\n from jwt.algorithms import ECAlgorithm, OKPAlgorithm, RSAAlgorithm, RSAPSSAlgorithm\n\n\nclass TestAlgorithms:\n def test_algorithm_should_throw_exception_if_prepare_key_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.prepare_key(\"test\")\n\n def test_algorithm_should_throw_exception_if_sign_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.sign(\"message\", \"key\")\n\n def test_algorithm_should_throw_exception_if_verify_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.verify(\"message\", \"key\", \"signature\")\n\n def test_algorithm_should_throw_exception_if_to_jwk_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.from_jwk(\"value\")\n\n def test_algorithm_should_throw_exception_if_from_jwk_not_impl(self):\n algo = Algorithm()\n\n with pytest.raises(NotImplementedError):\n algo.to_jwk(\"value\")\n\n def test_none_algorithm_should_throw_exception_if_key_is_not_none(self):\n algo = NoneAlgorithm()\n\n with pytest.raises(InvalidKeyError):\n algo.prepare_key(\"123\")\n\n def test_hmac_should_reject_nonstring_key(self):\n algo = HMACAlgorithm(HMACAlgorithm.SHA256)\n\n <|endoftext|>"} +{"language": "python", "text": "(?:[-_a-zA-Z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff0-9]+)#\"\n for match in re.finditer(PATTERN, dataobj.content):\n embedded_tags.add(match.group(0).replace(\"#\", \"\").lstrip())\n\n return render_template(\n \"dataobjs/show.html\",\n title=dataobj[\"title\"],\n dataobj=dataobj,\n backlinks=backlinks,\n current_path=dataobj[\"dir\"],\n form=forms.DeleteDataForm(),\n view_only=0,\n search_enabled=app.config[\"SEARCH_CONF\"][\"enabled\"],\n post_title_form=post_title_form,\n move_form=move_form,\n tag_list=tag_list,\n embedded_tags=embedded_tags,\n titles=titles,\n )\n\n\n@app.route(\"/dataobj/move/\", methods=[\"POST\"])\ndef move_item(dataobj_id):\n form = forms.MoveItemForm()\n out_dir = form.path.data if form.path.data != \"\" else \"root directory\"\n if form.path.data == None:\n flash(\"No path specified.\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n try:\n if data.move_item(dataobj_id, form.path.data):\n flash(f\"Data successfully moved to {out_dir}.\", \"success\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n else:\n flash(f\"Data could not be moved to {out_dir}.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n except FileNotFoundError:\n flash(\"Data not found.\", \"error\")\n return redirect(\"/\")\n except FileExistsError:\n flash(\"Data already in target directory.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n\n# BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n# @app.route(\"/dataobj/delete/\", methods=[\"DELETE\", \"GET\"])\n# FIXED: \n@app.route(\"/dataobj/delete/\", methods=[\"POST\"])\ndef delete_data(dataobj_id):\n try:\n data.delete_item(dataobj_id)\n except BaseException:\n flash(\"Data could not be found!\", \"error\")\n return redirect(\"/\")\n flash(\"Data deleted!\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n user = db.search(\n (Query().username == form.username.data) & (Query().type == \"user\")\n )\n\n if user and check_password_hash(user[0][\"hashed_password\"], form.password.data):\n user = User.from_db(user[0])\n login_user(user, remember=True)\n flash(\"Login successful!\", \"success\")\n\n next_url = request.args.get(\"next\")\n return redirect(next_url or \"/\")\n\n flash(\"Invalid credentials\", \"error\")\n return redirect(\"/login\")\n return render_template(\"users/login.html\", form=form, title=\"Login\")\n\n\n@app.route(\"/logout\", methods=[\"DELETE\", \"GET\"])\ndef logout():\n logout_user()\n flash(\"Logged out successfully\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/user/edit\", methods=[\"GET\", \"POST\"])\ndef edit_user():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n db.update(\n {\n \"username\": form.username.data,\n \"hashed_password\": generate_password_hash(form.password.data),\n },\n doc_ids=[current_user.id],\n )\n flash(\"Information saved!\", \"success\")\n return redirect(\"/\")\n form.username.data = current_user.username\n <|endoftext|>"} +{"language": "python", "text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2015, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\nclass PortalSettings(Document):\n\tdef add_item(self, item):\n\t\t'''insert new portal menu item if route is not set, or role is different'''\n\t\texists = [d for d in self.get('menu', []) if d.get('route')==item.get('route')]\n\t\tif exists and item.get('role'):\n\t\t\tif exists[0].role != item.get('role'):\n\t\t\t\texists[0].role = item.get('role')\n\t\t\t\treturn True\n\t\telif not exists:\n\t\t\titem['enabled'] = 1\n\t\t\tself.append('menu', item)\n\t\t\treturn True\n\t# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n\t# \n\t# FIXED:\n\t@frappe.whitelist()\n\tdef reset(self):\n\t\t'''Restore defaults'''\n\t\tself.menu = []\n\t\tself.sync_menu()\n\n\tdef sync_menu(self):\n\t\t'''Sync portal menu items'''\n\t\tdirty = False\n\t\tfor item in frappe.get_hooks('standard_portal_menu_items'):\n\t\t\tif item.get('role') and not frappe.db.exists(\"Role\", item.get('role')):\n\t\t\t\tfrappe.get_doc({\"doctype\": \"Role\", \"role_name\": item.get('role'), \"desk_access\": 0}).insert()\n\t\t\tif self.add_item(item):\n\t\t\t\tdirty = True\n\n\t\tif dirty:\n\t\t\tself.save()\n\n\tdef on_update(self):\n\t\tself.clear_cache()\n\n\tdef clear_cache(self):\n\t\t# make js and css\n\t\t# clear web cache (for menus!)\n\t\tfrappe.clear_cache(user='Guest')\n\n\t\tfrom frappe.website.render import clear_cache\n\t\tclear_cache()\n\n\t\t# clears role based home pages\n\t\tfrappe.clear_cache()\n\n<|endoftext|>"} +{"language": "java", "text": "mpliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\npackage org.hyperledger.besu.evm.operation;\n\nimport static org.apache.tuweni.bytes.Bytes32.leftPad;\n\nimport org.hyperledger.besu.evm.EVM;\nimport org.hyperledger.besu.evm.frame.MessageFrame;\nimport org.hyperledger.besu.evm.gascalculator.GasCalculator;\n\nimport org.apache.tuweni.bytes.Bytes;\nimport org.apache.tuweni.units.bigints.UInt256;\n\npublic class ShlOperation extends AbstractFixedCostOperation {\n\n public ShlOperation(final GasCalculator gasCalculator) {\n super(0x1b, \"SHL\", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());\n }\n\n @Override\n public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n Bytes shiftAmount = frame.popStackItem();\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.popStackItem();\n frame.pushStackItem(UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n final Bytes value = leftPad(frame.popStackItem());\n // BUG: CWE-681 Incorrect Conversion between Numeric Types\n // if (shiftAmountInt >= 256) {\n // FIXED: \n if (shiftAmountInt >= 256 || shiftAmountInt < 0) {\n frame.pushStackItem(UInt256.ZERO);\n } else {\n frame.pushStackItem(value.shiftLeft(shiftAmountInt));\n }\n }\n return successResponse;\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "pyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.ClientRequest;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;\nimport com.nukkitx.protocol.bedrock.packet.RespawnPacket;\nimport com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;\nimport org.geysermc.connector.entity.player.PlayerEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = RespawnPacket.class)\npublic class BedrockRespawnTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(RespawnPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, RespawnPacket packet) {\n if (packet.getState() == RespawnPacket.State.CLIENT_READY) {\n // Previously we only sent the respawn packet before the server finished loading\n // The message included was 'Otherwise when immediate respawn is on the client never loads'\n // But I assume the new if statement below fixes that problem\n RespawnPacket respawnPacket = new RespawnPacket();\n respawnPacket.setRuntimeEntityId(0);\n respawnPacket.setPosition(Vector3f.ZERO);\n respawnPacket.setState(RespawnPacket.State.SERVER_READY);\n session.sendUpstreamPacket(respawnPacket);\n\n if (session.isSpawned()) {\n // Client might be stuck; resend spawn information\n PlayerEntity entity = session.getPlayerEntity();\n if (entity == null) return;\n SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();\n entityDataPacket.setRuntimeEntityId(entity.getGeyserId());\n entityDataPacket.getMetadata().putAll(entity.getMetadata());\n session.sendUpstreamPacket(entityDataPacket);\n\n MovePlayerPacket movePlayerPacket = new MovePlayerPacket();\n movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());\n movePlayerPacket.setPosition(entity.getPosition());\n movePlayerPacket.setRotation(entity.getBedrockRotation());\n movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN);\n session.sendUpstreamPacket(movePlayerPacket);\n }\n\n ClientRequestPacket javaRes<|endoftext|>"} +{"language": "java", "text": "flc);\n\t\ttableEl.setCustomizeColumns(false);\n\t\ttableEl.setNumOfRowsEnabled(false);\n\t\t\t\t\n\t\trefreshbtn = uifactory.addFormLink(\"button.refresh\", flc, Link.BUTTON);\n\t\trefreshbtn.setIconLeftCSS(\"o_icon o_icon_refresh o_icon-fw\");\n\t}\n\t\n\t@Override\n\tpublic void event(UserRequest ureq, Component source, Event event) {\n\t\tsuper.event(ureq, source, event);\n\t}\n\t\n\t@Override\n\tprotected void event(UserRequest ureq, Controller source, org.olat.core.gui.control.Event event) {\n\t\tif (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"viewQuality\")) {\n\t\t\tif (cmc == null) {\n\t\t\t\t// initialize preview controller only once\n\t\t\t\tpreviewVC = createVelocityContainer(\"video_preview\");\n\t\t\t\tcmc = new CloseableModalController(getWindowControl(), \"close\", previewVC);\n\t\t\t\tlistenTo(cmc);\n\t\t\t}\n\t\t}\n\t\tsuper.event(ureq, source, event);\n\t}\n\t\n\t@Override\n\tprotected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {\n\t\tif (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"viewQuality\")) {\n\t\t\tif (cmc == null) {\n\t\t\t\t// initialize preview controller only once\n\t\t\t\tpreviewVC = createVelocityContainer(\"video_preview\");\n\t\t\t\tcmc = new CloseableModalController(getWindowControl(), \"close\", previewVC);\n\t\t\t\tlistenTo(cmc);\n\t\t\t}\n\t\t\t// Get the user object from the link to access version object\n\t\t\tFormLink link = (FormLink) source;\n\t\t\tVideoTranscoding videoTranscoding = (VideoTranscoding) link.getUserObject();\n\t\t\tif (videoTranscoding == null) {\n\t\t\t\t// this is the master video\n\t\t\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t\t\t// VideoMetadata videoMetadata = videoManager.readVideoMetadataFile(videoResource);\n\t\t\t\t// FIXED: \n\t\t\t\tVideoMeta videoMetadata = videoManager.getVideoMetadata(videoResource);\n\t\t\t\tpreviewVC.contextPut(\"width\", videoMetadata.getWidth());\n\t\t\t\tpreviewVC.contextPut(\"height\", videoMetadata.getHeight());\n\t\t\t\tpreviewVC.contextPut(\"filename\", \"video.mp4\");\n\t\t\t\tVFSContainer container = videoManager.getMasterContainer(videoResource);\n\t\t\t\tString transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));\n\t\t\t\tpreviewVC.contextPut(\"mediaUrl\", transcodedUrl);\n\t\t\t} else {\n\t\t\t\t// this is a version\n\t\t\t\tpreviewVC.contextPut(\"width\", videoTranscoding.getWidth());\n\t\t\t\tpreviewVC.contextPut(\"height\", videoTranscoding.getHeight());\n\t\t\t\tpreviewVC.contextPut(\"filename\", videoTranscoding.getResolution() + \"video.mp4\");\n\t\t\t\tVFSContainer container = videoManager.getTranscodingContainer(videoResource);\n\t\t\t\tString transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));\n\t\t\t\tpreviewVC.contextPut(\"mediaUrl\", transcodedUrl);\n\t\t\t}\n\t\t\t// activate dialog to bring it in front\n\t\t\tcmc.activate();\n\t\t} else if (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"deleteQuality\")) {\n\t\t\tFormLink link = (FormLink) source;\n\t\t\tVideoTranscoding videoTranscoding = (VideoTranscoding) link.getUserObject();\n\t\t\tvideoManager.deleteVideoTranscoding(videoTranscoding);\n\t\t} else if (source instanceof FormLink && ((FormLink) source).getCmd().equals(\"startTranscoding\")) {\n\t\t\tvideoManager.createTranscoding(videoResource, (int) source.getUserObject(), \"mp4\");\n\t\t}\n\t\tinitTable();\n\t}\n\t\n\t@Override\n\tprotected void formOK(UserRequest ureq) {\n\t\t// nothing to do, events cached in formInnerEvent\n\t}\n\n\t@Override\n\tprotected void doDispose() {\n\t\t// controller auto disposed\n\t}\n\t\n\tprivate class VideoCompar<|endoftext|>"} +{"language": "java", "text": "right 2021 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.thoughtworks.go.addon.businesscontinuity.primary.controller;\n\nimport com.google.gson.Gson;\nimport com.thoughtworks.go.addon.businesscontinuity.ConfigFileType;\nimport com.thoughtworks.go.addon.businesscontinuity.DatabaseStatusProvider;\nimport com.thoughtworks.go.addon.businesscontinuity.FileDetails;\nimport com.thoughtworks.go.addon.businesscontinuity.PluginsList;\nimport com.thoughtworks.go.addon.businesscontinuity.primary.ServerStatusResponse;\nimport com.thoughtworks.go.addon.businesscontinuity.primary.service.GoFilesStatusProvider;\nimport com.thoughtworks.go.util.SystemEnvironment;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.<|endoftext|>"} +{"language": "java", "text": "tems, used for caching. There is usually few of them (about 15). */\n private final Map scopes = new HashMap<>();\n\n /**\n * The properties to be given the objects to construct. Reused every time {@link\n * #createProperties} is invoked.\n */\n private final Map properties = new HashMap<>();\n\n /**\n * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}.\n * This is used by {@link #createBursaWolfParameters}, which need to create a target datum. The\n * target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the\n * source datum.\n */\n private final Set safetyGuard = new HashSet<>();\n\n public AbstractEpsgFactory(final Hints userHints) throws FactoryException {\n super(MAXIMUM_PRIORITY - 20);\n // The following hints have no effect on this class behaviour,\n // but tell to the user what this factory do about axis order.\n hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);\n\n //\n // We need to obtain our DataSource\n if (userHints != null) {\n Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);\n if (hint instanceof String) {\n String name = (String) hint;\n try {\n // BUG: CWE-20 Improper Input Validation\n // dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);\n // FIXED: \n dataSource = (DataSource) GeoTools.jndiLookup(name);\n } catch (NamingException e) {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required:\" + e);\n }\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n } else if (hint instanceof DataSource) {\n dataSource = (DataSource) hint;\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n } else {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required.\");\n }\n } else {\n throw new FactoryException(\"A EPSG_DATA_SOURCE hint is required.\");\n }\n }\n\n public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) {\n super(MAXIMUM_PRIORITY - 20);\n\n this.dataSource = dataSource;\n // The following hints have no effect on this class behaviour,\n // but tell to the user what this factory do about axis order.\n hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);\n hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);\n hints.put(Hints.EPSG_DATA_SOURCE, dataSource);\n }\n /**\n * Constructs an authority factory using the specified connection.\n *\n * @param userHints The underlying factories used for objects creation.\n * @param connection The connection to the underlying EPSG database.\n */\n public AbstractEpsgFactory(final Hints userHints, final Connection connection) {\n super(MAXIMUM_PRIORITY - 20, userHints);\n // The following hints have no effect <|endoftext|>"} +{"language": "java", "text": "/*\n * Copyright 2020 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage io.netty.handler.codec.http.multipart;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.ByteBufUtil;\nimport io.netty.util.internal.PlatformDependent;\nimport org.junit.Test;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.nio.charset.Charset;\nimport java.util.Arrays;\nimport java.util.UUID;\n\nimport static io.netty.util.CharsetUtil.UTF_8;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\n\n/**\n * {@link AbstractDiskHttpData} test cases\n */\npublic class AbstractDiskHttpDataTest {\n\n @Test\n public void testGetChunk() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n // FIXED: \n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n byte[] bytes = new byte[4096];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n test.setContent(tmpFile);\n ByteBuf buf1 = test.getChunk(1024);\n assertEquals(buf1.readerIndex(), 0);\n assertEquals(buf1.writerIndex(), 1024);\n ByteBuf buf2 = test.getChunk(1024);\n assertEquals(buf2.readerIndex(), 0);\n assertEquals(buf2.writerIndex(), 1024);\n assertFalse(\"Arrays should not be equal\",\n Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));\n } finally {\n test.delete();\n }\n }\n\n private static final class TestHttpData extends AbstractDiskHttpData {\n\n private TestHttpData(String name, Charset charset, long size) {\n super(name, charset, size);\n }\n\n @Override\n protected String getDiskFilename() {\n return null;\n }\n\n @Override\n protected String getPrefix() {\n return null;\n }\n\n @Override\n protected String getBaseDirectory() {\n return null;\n }\n\n @Override\n protected String getPostfix() {\n return null;\n }\n\n @Override\n protected boolean deleteOnExit() {\n return false;\n }\n\n <|endoftext|>"} +{"language": "java", "text": "right 2013-2022 Erudika. https://erudika.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * For issues and patches go to: https://github.com/erudika\n */\npackage com.erudika.scoold.controllers;\n\nimport com.cloudinary.Cloudinary;\nimport com.cloudinary.utils.ObjectUtils;\nimport com.erudika.para.core.User;\nimport static com.erudika.para.core.User.Groups.MODS;\nimport static com.erudika.para.core.User.Groups.USERS;\nimport com.erudika.para.core.utils.Pager;\nimport com.erudika.para.core.utils.ParaObjectUtils;\nimport com.erudika.para.core.utils.Utils;\nimport com.erudika.scoold.ScooldConfig;\nimport static com.erudika.scoold.ScooldServer.PEOPLELINK;\nimport static com.erudika.scoold.ScooldServer.PROFILELINK;\nimport static com.erudika.scoold.ScooldServer.SIGNINLINK;\nimport com.erudika.scoold.core.Post;\nimport com.erudika.scoold.core.Profile;\nimport com.erudika.scoold.core.Profile.Badge;\nimport com.erudika.scoold.core.Question;\nimport com.erudika.scoold.core.Reply;\nimport com.erudika.scoold.utils.ScooldUtils;\nimport com.erudika.scoold.utils.avatars.*;\nimport java.util.*;\nimport javax.inject.Inject;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServ<|endoftext|>"} +{"language": "java", "text": "itionPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;\nimport com.github.steveice10.packetlib.packet.Packet;\nimport com.nukkitx.math.vector.Vector3d;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;\nimport com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;\nimport org.geysermc.connector.GeyserConnector;\nimport org.geysermc.connector.common.ChatColor;\nimport org.geysermc.connector.entity.player.SessionPlayerEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = MovePlayerPacket.class)\npublic class BedrockMovePlayerTranslator extends PacketTranslator {\n /* The upper and lower bounds to check for the void floor that only exists in Bedrock */\n private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y;\n private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y;\n\n static {\n BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40;\n BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2;\n }\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MovePlayerPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MovePlayerPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n if (!session.isSpawned()) return;\n\n if (!session.getUpstream().isInitialized()) {\n MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket();\n moveEntityBack.setRuntimeEntityId(entity.getGeyserId());\n moveEntityBack.setPosition(entity.getPosition());\n moveEntityBack.setRotation(entity.getBedrockRotation());\n moveEntityBack.setTeleported(true);\n moveEntityBack.setOnGround(true);\n session.sendUpstreamPacketImmediately(moveEntityBack);\n return;\n }\n\n session.setLastMovementTimestamp(System.currentTimeMillis());\n\n // Send book update before the player moves\n session.getBookEditCache().checkForSend();\n\n session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0));\n // head yaw, pitch, head yaw\n Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY());\n\n boolean positionChanged = !entity.getPosition().equals(packet.getPosition());\n boolean rotationChanged = !entity.getRotation().equals(rotation);\n\n // If only the pitch and yaw changed\n // This isn't needed, but it makes the packets closer to vanilla\n // It also means you can't \"lag back\" while only looking, in theory\n if (!positionChanged && rotationChanged) {\n ClientPlayerRotationPacket playerRotationPacket = new ClientPlayerRotationPacket(\n packet.isOnGrou<|endoftext|>"} +{"language": "java", "text": " org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.item.ItemTranslator;\nimport org.geysermc.connector.registry.Registries;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.utils.InventoryUtils;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID;\n\n/**\n * Used to send all valid recipes from Java to Bedrock.\n *\n * Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything.\n */\n@Translator(packet = ServerDeclareRecipesPacket.class)\npublic class JavaDeclareRecipesTranslator extends PacketTranslator {\n /**\n * Required to use the specified cartography table recipes\n */\n private static final List CARTOGRAPHY_RECIPES = Arrays.asList(\n CraftingData.fromMulti(UUID.fromString(\"8b36268c-1829-483c-a0f1-993b7156a8f2\"), ++LAST_RECIPE_NET_ID), // Map extending\n CraftingData.fromMulti(UUID.fromString(\"442d85ed-8272-4543-a6f1-418f90ded05d\"), ++LAST_RECIPE_NET_ID), // Map cloning\n CraftingData.fromMulti(UUID.fromString(\"98c84b38-1085-46bd-b1ce-dd38c159e6cc\"), ++LAST_RECIPE_NET_ID), // Map upgrading\n CraftingData.fromMulti(UUID.fromString(\"602234e4-cac1-4353-8bb7-b1ebff70024b\"), ++LAST_RECIPE_NET_ID) // Map locking\n );\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) {\n Map> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream().getProtocolVersion());\n // Get the last known network ID (first used for the pregenerated recipes) and increment from there.\n int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1;\n\n Int2ObjectMap recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion()));\n Int2ObjectMap> unsortedStonecutterData = new Int2ObjectOpenHashMap<>();\n CraftingDataPacket craftingDataPacket = new CraftingDataPacket();\n craftingDataPacket.setCleanRecipes(true);\n for (Recipe recipe : packet.getRecipes()) {\n switch (recipe.getType()) {\n case CRAFTING_SHAPELESS: {\n ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData();\n ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult());\n // Strip NBT - tools won't appear in the recipe book otherwise\n output = output.toBuilder().tag(null).build();\n ItemData[][] inputCombinations = combinations(session, shapelessRecipeData.getIngredients());\n for (ItemData[] inputs : inputCombinations) {\n UUID uuid = UUID.randomUUID();\n craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(),\n Arrays.asList(inputs), Collections.singletonList(<|endoftext|>"} +{"language": "java", "text": "onvert.ConversionContext;\nimport io.micronaut.core.convert.ConversionService;\nimport io.micronaut.core.reflect.GenericTypeUtils;\nimport io.micronaut.core.type.Argument;\nimport io.micronaut.core.value.ValueResolver;\n\nimport java.util.*;\nimport java.util.function.BiConsumer;\nimport java.util.stream.Collectors;\n\n/**\n * An interface for classes that represent a map-like structure of values that can be converted.\n *\n * @param The generic value\n * @author Graeme Rocher\n * @since 1.0\n */\npublic interface ConvertibleValues extends ValueResolver, Iterable> {\n\n ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap());\n\n /**\n * @return The names of the values\n */\n Set names();\n\n /**\n * @return The values\n */\n Collection values();\n\n /**\n * @return Whether this values is empty\n */\n default boolean isEmpty() {\n return this == ConvertibleValues.EMPTY || names().isEmpty();\n }\n\n /**\n * @return The concrete type of the value\n */\n @SuppressWarnings(\"unchecked\")\n default Class getValueType() {\n Optional type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class);\n return type.orElse(Object.class);\n }\n\n /**\n * Whether the given key is contained within these values.\n *\n * @param name The key name\n * @return True if it is\n */\n default boolean contains(String name) {\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // return get(name, Object.class).isPresent();\n // FIXED: \n return get(name, Argument.OBJECT_ARGUMENT).isPresent();\n }\n\n /**\n * Performs the given action for each value. Note that in the case\n * where multiple values exist for the same header then the consumer will be invoked\n * multiple times for the same key.\n *\n * @param action The action to be performed for each entry\n * @throws NullPointerException if the specified action is null\n * @since 1.0\n */\n default void forEach(BiConsumer action) {\n Objects.requireNonNull(action, \"Consumer cannot be null\");\n\n Collection headerNames = names();\n for (String headerName : headerNames) {\n Optional vOptional = this.get(headerName, getValueType());\n vOptional.ifPresent(v -> action.accept(headerName, v));\n }\n }\n\n /**\n * Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance.\n *\n * @return The values\n */\n default Map asMap() {\n Map newMap = new LinkedHashMap<>();\n for (Map.Entry entry : this) {\n String key = entry.getKey();\n newMap.put(key, entry.getValue());\n }\n return newMap;\n }\n\n /**\n * Return this {@link ConvertibleValues} as a map for the given key type and value type. If any entry cannot be\n * converted to the target key/value type then the entry is simply excluded, hence the size of the map returned\n * may not match the size of this {@link ConvertibleValues}.\n *\n * @param keyType The key type\n * @param valueType The value type\n * @param <|endoftext|>"} +{"language": "java", "text": "CE);\n\t\t//}\n\t\treturn spaces;\n\t}\n\n\tpublic void setSpaces(Set spaces) {\n\t\tthis.spaces = spaces;\n\t}\n\n\t@JsonIgnore\n\tpublic Set getAllSpaces() {\n\t\treturn getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet());\n\t}\n\n\tpublic Long getLastseen() {\n\t\treturn lastseen;\n\t}\n\n\tpublic void setLastseen(Long val) {\n\t\tthis.lastseen = val;\n\t}\n\n\tpublic String getWebsite() {\n\t\treturn website;\n\t}\n\n\tpublic void setWebsite(String website) {\n\t\tthis.website = website;\n\t}\n\n\tpublic Long getComments() {\n\t\treturn comments;\n\t}\n\n\tpublic void setComments(Long comments) {\n\t\tthis.comments = comments;\n\t}\n\n\tpublic Long getDownvotes() {\n\t\treturn downvotes;\n\t}\n\n\tpublic void setDownvotes(Long downvotes) {\n\t\tthis.downvotes = downvotes;\n\t}\n\n\tpublic Long getUpvotes() {\n\t\treturn upvotes;\n\t}\n\n\tpublic void setUpvotes(Long upvotes) {\n\t\tthis.upvotes = upvotes;\n\t}\n\n\tpublic String getBadges() {\n\t\treturn badges;\n\t}\n\n\tpublic void setBadges(String badges) {\n\t\tthis.badges = badges;\n\t}\n\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic String getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic void setStatus(String status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic String getAboutme() {\n\t\treturn this.aboutme;\n\t}\n\n\tpublic void setAboutme(String aboutme) {\n\t\tthis.aboutme = aboutme;\n\t}\n\n\tpublic String getOriginalName() {\n\t\treturn originalName;\n\t}\n\n\tpublic void setOriginalName(String originalName) {\n\t\t// BUG: NVD-CWE-Other Other\n\t\t// this.originalName = originalName;\n\t\t// FIXED: \n\t\tthis.originalName = StringUtils.abbreviate(originalName, 256);\n\t}\n\n\tpublic String getOriginalPicture() {\n\t\treturn originalPicture;\n\t}\n\n\tpublic void setOriginalPicture(String originalPicture) {\n\t\tthis.originalPicture = originalPicture;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(Question.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(Reply.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllUnapprovedQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List getAllUnapprovedAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList();\n\t\t}\n\t\treturn (List) getPostsForUser(Utils.type(UnapprovedReply.class), pager);\n\t}\n\n\tprivate List getPostsForUser(String type, Pager pager) {\n\t\tpager.setSortby(\"votes\");\n\t\treturn client().findTerms(type, Collections.singletonMap(Config._CREATORID, getId()), true, pager);\n\t}\n\n\tpublic String getFavtagsString() {\n\t\tif (getFavtags().isEmpty()) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn StringUtils.join(getFavtags(), \", \");\n\t}\n\n\tpublic boolean hasFavtags() {\n\t\treturn !getFavtags().isEmpty();\n\t}\n\n\tpublic boolean hasSpaces() {\n\t\treturn !(getSpaces().size() <= 1 && getSpaces().contains(Post.DEF<|endoftext|>"} +{"language": "java", "text": "right 2019 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cd.go.framework.ldap;\n\nimport cd.go.authentication.ldap.LdapClient;\nimport cd.go.authentication.ldap.exception.LdapException;\nimport cd.go.authentication.ldap.exception.MultipleUserDetectedException;\nimport cd.go.authentication.ldap.mapper.Mapper;\nimport cd.go.authentication.ldap.mapper.ResultWrapper;\nimport cd.go.authentication.ldap.model.LdapConfiguration;\n\nimport javax.naming.NamingEnumeration;\nimport javax.naming.NamingException;\nimport javax.naming.directory.*;\nimport java.util.ArrayList;\nimport java.util.Hashtable;\nimport java.util.List;\n\nimport static cd.go.authentication.ldap.LdapPlugin.LOG;\nimport static cd.go.authentication.ldap.utils.Util.isNotBlank;\nimport static java.text.MessageFormat.format;\nimport static javax.naming.Context.SECURITY_CREDENTIALS;\nimport static javax.naming.Context.SECURITY_PRINCIPAL;\n\npublic class JNDILdapClient implements LdapClient {\n private LdapConfiguration ldapConfiguration;\n private final int MAX_AUTHENTICATION_RESULT = 1;\n\n public JNDILdapClient(LdapConfiguration ldapConfiguration) {\n this.ldapConfiguration = ldapConfiguration<|endoftext|>"} +{"language": "java", "text": "right 2016 Red Hat, Inc. and/or its affiliates\n * and other contributors as indicated by the @author tags.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.keycloak.protocol.saml;\n\nimport org.keycloak.services.util.CertificateInfoHelper;\n\n/**\n * @author Bill Burke\n * @version $Revision: 1 $\n */\npublic interface SamlConfigAttributes {\n String SAML_SIGNING_PRIVATE_KEY = \"saml.signing.private.key\";\n String SAML_CANONICALIZATION_METHOD_ATTRIBUTE = \"saml_signature_canonicalization_method\";\n String SAML_SIGNATURE_ALGORITHM = \"saml.signature.algorithm\";\n String SAML_NAME_ID_FORMAT_ATTRIBUTE = \"saml_name_id_format\";\n String SAML_AUTHNSTATEMENT = \"saml.authnstatement\";\n String SAML_ONETIMEUSE_CONDITION = \"saml.onetimeuse.condition\";\n String SAML_FORCE_NAME_ID_FORMAT_ATTRIBUTE = \"saml_force_name_id_format\";\n String SAML_ARTIFACT_BINDING = \"saml.artifact.binding\";\n String SAML_SERVER_SIGNATURE = \"saml.server.signature\";\n String SAML_SERVER_SIGNATURE_KEYINFO_EXT = \"saml.server.signature.keyinfo.ext\";\n String SAML_SERVER_SIGNATURE_KEYINFO_KEY_NAME_TRANSFORMER = \"saml.server.signature.keyinfo.xmlSig<|endoftext|>"} +{"language": "java", "text": " offset += read;\n if (len <= 0 || offset >= buf.length) {\n break;\n }\n }\n return buf;\n } finally {\n fis.close();\n }\n }\n\n @Test\n public void testDelete() throws Exception {\n String json = \"{\\\"foo\\\":\\\"bar\\\"}\";\n byte[] bytes = json.getBytes(CharsetUtil.UTF_8);\n File tmpFile = null;\n DiskFileUpload f1 = new DiskFileUpload(\"file4\", \"file4\", \"application/json\", null, null, 0);\n try {\n assertNull(f1.getFile());\n f1.setContent(Unpooled.wrappedBuffer(bytes));\n assertNotNull(tmpFile = f1.getFile());\n } finally {\n f1.delete();\n assertNull(f1.getFile());\n assertNotNull(tmpFile);\n assertFalse(tmpFile.exists());\n }\n }\n\n @Test\n public void setSetContentFromFileExceptionally() throws Exception {\n final long maxSize = 4;\n DiskFileUpload f1 = new DiskFileUpload(\"file5\", \"file5\", \"application/json\", null, null, 0);\n f1.setMaxSize(maxSize);\n try {\n f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));\n File originalFile = f1.getFile();\n assertNotNull(originalFile);\n assertEquals(maxSize, originalFile.length());\n assertEquals(maxSize, f1.length());\n byte[] bytes = new byte[8];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n // FIXED: \n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n try {\n f1.setContent(tmpFile);\n fail(\"should not reach here!\");\n } catch (IOException e) {\n assertNotNull(f1.getFile());\n assertEquals(originalFile, f1.getFile());\n assertEquals(maxSize, f1.length());\n }\n } finally {\n f1.delete();\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "istribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket;\nimport com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket;\nimport org.geysermc.connector.GeyserConnector;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = MapInfoRequestPacket.class)\npublic class BedrockMapInfoRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MapInfoRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MapInfoRequestPacket packet) {\n long mapId = packet.getUniqueMapId();\n\n ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);\n if (mapPacket != null) {\n // Delay the packet 100ms to prevent the client from ignoring the packet\n GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),\n 100, TimeUnit.MILLISECONDS);\n }\n }\n}\n<|endoftext|>"} +{"language": "java", "text": "s\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;\nimport com.nukkitx.protocol.bedrock.packet.TextPacket;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\n\n@Translator(packet = TextPacket.class)\npublic class BedrockTextTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(TextPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, TextPacket packet) {\n String message = packet.getMessage();\n\n if (MessageTranslator.isTooLong(message, session)) {\n return;\n }\n\n ClientChatPacket chatPacket = new ClientChatPacket(message);\n session.sendDownstreamPacket(chatPacket);\n }\n}\n<|endoftext|>"} {"language": "java", "text": "port io.micronaut.http.hateoas.JsonError;\nimport io.micronaut.http.hateoas.VndError;\n\nimport java.util.Optional;\n\n/**\n * Strategy interface for decoding the error from a server respponse.\n *\n * @author graemerocher\n * @since 1.0\n */\n@Internal\npublic interface HttpClientErrorDecoder {\n\n /**\n * The default implementation.\n */\n HttpClientErrorDecoder DEFAULT = new HttpClientErrorDecoder() { };\n\n /**\n * Default message decoder.\n *\n * @param error The error object\n * @return The message\n */\n default Optional getMessage(Object error) {\n if (error == null) {\n return Optional.empty();\n }\n if (error instanceof JsonError) {\n return Optional.ofNullable(((JsonError) error).getMessage());\n } else {\n if (error instanceof Described) {\n return Optional.ofNullable(((Described) error).getDescription());\n } else {\n return Optional.of(error.toString());\n }\n }\n }\n\n /**\n * Gets the error type for the given media type.\n *\n * @param mediaType The media type\n * @return The error type\n */\n default Argument getErrorType(MediaType mediaType) {\n if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {\n return Argument.of(JsonError.class);\n } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {\n return Argument.of(VndError.class);\n } else {\n // BUG: CWE-400 Uncontrolled Resource Consumption\n // return Argument.of(String.class);\n // FIXED: \n return Argument.STRING;\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": ".commons.services.vfs.manager;\n\nimport java.io.File;\nimport java.io.InputStream;\n\nimport org.olat.basesecurity.BaseSecurity;\nimport org.olat.basesecurity.IdentityImpl;\nimport org.olat.core.CoreSpringFactory;\nimport org.olat.core.commons.services.license.LicenseService;\nimport org.olat.core.commons.services.license.LicenseType;\nimport org.olat.core.commons.services.license.model.LicenseTypeImpl;\nimport org.olat.core.commons.services.vfs.VFSMetadata;\nimport org.olat.core.commons.services.vfs.VFSRevision;\nimport org.olat.core.commons.services.vfs.model.VFSMetadataImpl;\nimport org.olat.core.id.Identity;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.vfs.VFSLeaf;\nimport org.olat.core.util.vfs.version.RevisionFileImpl;\nimport org.olat.core.util.vfs.version.VersionsFileImpl;\nimport org.olat.core.util.xml.XStreamHelper;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.converters.SingleValueConverter;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * \n * Initial date: 13 mars 2019
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\npublic class VFSXStream {\n\t\n\tprivate static XStream mystream;\n\tstatic {\n\t\tmystream = XStreamHelper.createXStreamInstance();\n\t\tClass[] types = new Class[] {\n\t\t\t\tVersionsFileImpl.class, RevisionFileImpl.class, VFSRevision.class,\n\t\t\t\tVFSMetadata.class, VFSMetadataImpl.class, Identity.class, IdentityImpl.class,\n\t\t\t\tLicenseType.class, LicenseTypeImpl.class\n\t\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(mystream);\n\t\t// FIXED:\n\t\tmystream.addPermission(new ExplicitTypePermission(types));\n\t\t\n\t\tmystream.alias(\"versions\", VersionsFileImpl.class);\n\t\tmystream.alias(\"revision\", RevisionFileImpl.class);\n\t\tmystream.omitField(VersionsFileImpl.class, \"currentVersion\");\n\t\tmystream.omitField(VersionsFileImpl.class, \"versionFile\");\n\t\tmystream.omitField(RevisionFileImpl.class, \"current\");\n\t\tmystream.omitField(RevisionFileImpl.class, \"container\");\n\t\tmystream.omitField(RevisionFileImpl.class, \"file\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"originFile\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"metaFile\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"lockedByIdentKey\");\n\t\tmystream.aliasAttribute(VFSMetadataImpl.class, \"cannotGenerateThumbnails\", \"cannotGenerateThumbnail\");\n\t\tmystream.aliasAttribute(VFSMetadataImpl.class, \"author\", \"authorIdentKey\");\n\t\tmystream.aliasAttribute(VFSMetadataImpl.class, \"licenseType\", \"licenseTypeKey\");\n\t\tmystream.alias(\"metadata\", VFSMetadataImpl.class);\n\t\tmystream.omitField(VFSMetadataImpl.class, \"thumbnail\");\n\t\tmystream.omitField(VFSMetadataImpl.class, \"thumbnails\");\n\n\t\tmystream.registerLocalConverter(VFSMetadataImpl.class, \"licenseType\", new LicenseTypeConverter());\n\t\tmystream.regis<|endoftext|>"} -{"language": "java", "text": " final int UC_CPU_S390X_Z890_2 = 9;\n public static final int UC_CPU_S390X_Z990_5 = 10;\n public static final int UC_CPU_S390X_Z890_3 = 11;\n public static final int UC_CPU_S390X_Z9EC = 12;\n public static final int UC_CPU_S390X_Z9EC_2 = 13;\n public static final int UC_CPU_S390X_Z9BC = 14;\n public static final int UC_CPU_S390X_Z9EC_3 = 15;\n public static final int UC_CPU_S390X_Z9BC_2 = 16;\n public static final int UC_CPU_S390X_Z10EC = 17;\n public static final int UC_CPU_S390X_Z10EC_2 = 18;\n public static final int UC_CPU_S390X_Z10BC = 19;\n public static final int UC_CPU_S390X_Z10EC_3 = 20;\n public static final int UC_CPU_S390X_Z10BC_2 = 21;\n public static final int UC_CPU_S390X_Z196 = 22;\n public static final int UC_CPU_S390X_Z196_2 = 23;\n public static final int UC_CPU_S390X_Z114 = 24;\n public static final int UC_CPU_S390X_ZEC12 = 25;\n public static final int UC_CPU_S390X_ZEC12_2 = 26;\n public static final int UC_CPU_S390X_ZBC12 = 27;\n public static final int UC_CPU_S390X_Z13 = 28;\n public static final int UC_CPU_S390X_Z13_2 = 29;\n public static final int UC_CPU_S390X_Z13S = 30;\n public static final int UC_CPU_S390X_Z14 = 31;\n public static final int UC_CPU_S390X_Z14_2 = 32;\n public static final int UC_CPU_S390X_Z14ZR1 = 33;\n public static final int UC_CPU_S390X_GEN15A = 34;\n public static final int UC_CPU_S390X_GEN15B = 35;\n public static final int UC_CPU_S390X_QEMU = 36;\n public static final int UC_CPU_S390X_MAX = 37;\n // BUG: CWE-665 Improper Initialization\n // \n // FIXED: \n public static final int UC_CPU_S390X_ENDING = 38;\n\n// S390X registers\n\n public static final int UC_S390X_REG_INVALID = 0;\n\n// General purpose registers\n public static final int UC_S390X_REG_R0 = 1;\n public static final int UC_S390X_REG_R1 = 2;\n public static final int UC_S390X_REG_R2 = 3;\n public static final int UC_S390X_REG_R3 = 4;\n public static final int UC_S390X_REG_R4 = 5;\n public static final int UC_S390X_REG_R5 = 6;\n public static final int UC_S390X_REG_R6 = 7;\n public static final int UC_S390X_REG_R7 = 8;\n public static final int UC_S390X_REG_R8 = 9;\n public static final int UC_S390X_REG_R9 = 10;\n public static final int UC_S390X_REG_R10 = 11;\n public static final int UC_S390X_REG_R11 = 12;\n public static final int UC_S390X_REG_R12 = 13;\n public static final int UC_S390X_REG_R13 = 14;\n public static final int UC_S390X_REG_R14 = 15;\n public static final int UC_S390X_REG_R15 = 16;\n\n// Floating point registers\n public static final int UC_S390X_REG_F0 = 17;\n public static final int UC_S390X_REG_F1 = 18;\n public static final int UC_S390X_REG_F2 = 19;\n public static final int UC_S390X_REG_F3 = 20;\n public static final int UC_S390X_RE<|endoftext|>"} -{"language": "java", "text": "port net.sourceforge.plantuml.security.authentication.SecurityCredentials;\n\n/**\n * Secure replacement for java.net.URL.\n *

\n * This class should be used instead of java.net.URL.\n *

\n * This class does some control access and manages access-tokens via URL. If a\n * URL contains a access-token, similar to a user prefix, SURL loads the\n * authorization config for this user-token and passes the credentials to the\n * host.\n *

\n * Example:
\n * \n *

\n *     SURL url = SURL.create (\"https://jenkins-access@jenkins.mycompany.com/api/json\")\n * 
\n * \n * The {@code jenkins-access} will checked against the Security context access\n * token configuration. If a configuration exists for this token name, the token\n * will be removed from the URL and the credentials will be added to the\n * headers. If the token is not found, the URL remains as it is and no separate\n * authentication will be performed.\n *

\n * TODO: Some methods should be moved to a HttpClient implementation, because\n * SURL is not the valid class to manage it.
\n * TODO: BAD_HOSTS implementation should be reviewed and moved to HttpClient\n * implementation with a circuit-breaker.
\n * TODO: Token expiration with refresh should be implemented in future.
\n */\npublic class SURL {\n\n\t/**\n\t * Indicates, that we have no authentication to access the URL.\n\t */\n\tpublic static final String WITHOUT_AUTHENTICATION = SecurityUtils.NO_CREDENTIALS;\n\n\t/**\n\t * Regex to remove the UserInfo part from a URL.\n\t */\n\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t// private static final Pattern PATTERN_USERINFO = Pattern.compile(\"(^https?://)([-_:0-9a-zA-Z]+@)([^@]*)\");\n\t// FIXED: \n\tprivate static final Pattern PATTERN_USERINFO = Pattern.compile(\"(^https?://)([-_0-9a-zA-Z]+@)([^@]*)\");\n\n\tprivate static final ExecutorService EXE = Executors.newCachedThreadPool(new ThreadFactory() {\n\t\tpublic Thread newThread(Runnable r) {\n\t\t\tfinal Thread t = Executors.defaultThreadFactory().newThread(r);\n\t\t\tt.setDaemon(true);\n\t\t\treturn t;\n\t\t}\n\t});\n\n\tprivate static final Map BAD_HOSTS = new ConcurrentHashMap();\n\n\t/**\n\t * Internal URL, maybe cleaned from user-token.\n\t */\n\tprivate final URL internal;\n\n\t/**\n\t * Assigned credentials to this URL.\n\t */\n\tprivate final String securityIdentifier;\n\n\tprivate SURL(URL url, String securityIdentifier) {\n\t\tthis.internal = Objects.requireNonNull(url);\n\t\tthis.securityIdentifier = Objects.requireNonNull(securityIdentifier);\n\t}\n\n\t/**\n\t * Create a secure URL from a String.\n\t *

\n\t * The url must be http or https. Return null in case of error or if\n\t * url is null\n\t * \n\t * @param url plain url starting by http:// or https//\n\t * @return the secure URL or null\n\t */\n\tpublic static SURL create(String url) {\n\t\tif (url == null)\n\t\t\treturn null;\n\n\t\tif (url.startsWith(\"http://\") || url.startsWith(\"https://\"))\n\t\t\ttry <|endoftext|>"} -{"language": "java", "text": "rt java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.ReadableByteChannel;\nimport java.nio.charset.Charset;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.TimeUnit;\n\nimport static io.netty.buffer.Unpooled.copiedBuffer;\nimport static io.netty.buffer.Unpooled.wrappedBuffer;\nimport static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;\nimport static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;\nimport static io.netty.handler.codec.http.HttpHeaderNames.RANGE;\nimport static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE;\nimport static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING;\nimport static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED;\nimport static io.netty.handler.codec.http.HttpUtil.isKeepAlive;\nimport static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;\nimport static io.netty.handler.codec.http.LastHttpContent.EMPTY_LAST_CONTENT;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\npublic class NettyContext implements DefaultContext, ChannelFutureListener {\n\n private static final HttpHeaders NO_TRAILING = EmptyHttpHeaders.INSTANCE;\n // BUG: NVD-CWE-Other Other\n // final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(false);\n // FIXED:\n final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(true);\n private final int bufferSize;\n InterfaceHttpPostRequestDecoder decoder;\n private Router router;\n private Route route;\n ChannelHandlerContext ctx;\n private HttpRequest req;\n private String path;\n private HttpResponseStatus status = HttpResponseStatus.OK;\n private boolean responseStarted;\n private QueryString query;\n private Formdata form;\n private Multipart multipart;\n private List files;\n private ValueNode headers;\n private Map pathMap = Collections.EMPTY_MAP;\n private MediaType responseType;\n private Map attributes = new HashMap<>();\n private long contentLength = -1;\n private boolean needsFlush;\n private Map cookies;\n private Map responseCookies;\n private Boolean resetHeadersOnError;\n NettyWebSocket webSocket;\n\n public NettyContext(ChannelHandlerContext ctx, HttpRequest req, Router router, String path,\n int bufferSize) {\n this.path = path;\n this.ctx = ctx;\n this.req = req;\n this.router = router;\n this.bufferSize = bufferSize;\n }\n\n @Nonnull @Override public Router getRouter() {\n return route<|endoftext|>"} -{"language": "java", "text": "Test.class,\n ConcurrentStatementFetch.class,\n ConnectionTest.class,\n ConnectTimeoutTest.class,\n CopyLargeFileTest.class,\n CopyTest.class,\n CursorFetchTest.class,\n DatabaseEncodingTest.class,\n DatabaseMetaDataCacheTest.class,\n DatabaseMetaDataPropertiesTest.class,\n DatabaseMetaDataTest.class,\n DateStyleTest.class,\n DateTest.class,\n DeepBatchedInsertStatementTest.class,\n DriverTest.class,\n EncodingTest.class,\n ExpressionPropertiesTest.class,\n FixedLengthOutputStreamTest.class,\n GeometricTest.class,\n GetXXXTest.class,\n HostSpecTest.class,\n IntervalTest.class,\n JavaVersionTest.class,\n JBuilderTest.class,\n LoginTimeoutTest.class,\n LogServerMessagePropertyTest.class,\n LruCacheTest.class,\n MiscTest.class,\n NativeQueryBindLengthTest.class,\n NoColumnMetadataIssue1613Test.class,\n NumericTransferTest.class,\n NumericTransferTest2.class,\n NotifyTest.class,\n OidToStringTest.class,\n OidValueOfTest.class,\n OptionsPropertyTest.class,\n OuterJoinSyntaxTest.class,\n ParameterStatusTest.class,\n ParserTest.class,\n PGbyteaTest.class,\n PGPropertyMaxResultBufferParserTest.class,\n PGPropertyTest.class,\n PGTimestampTest.class,\n PGTimeTest.class,\n PgSQLXMLTest.class,\n PreparedStatementTest.class,\n QuotationTest.class,\n ReaderInputStreamTest.class,\n RefCursorTest.class,\n ReplaceProcessingTest.class,\n ResultSetMetaDataTest.class,\n ResultSetTest.class,\n // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')\n // \n // FIXED: \n ResultSetRefreshTest.class,\n ReturningParserTest.class,\n SearchPathLookupTest.class,\n ServerCursorTest.class,\n ServerErrorTest.class,\n ServerPreparedStmtTest.class,\n ServerVersionParseTest.class,\n ServerVersionTest.class,\n StatementTest.class,\n StringTypeUnspecifiedArrayTest.class,\n TestACL.class,\n TimestampTest.class,\n TimeTest.class,\n TimezoneCachingTest.class,\n TimezoneTest.class,\n TypeCacheDLLStressTest.class,\n UnusualBigDecimalByteConverterTest.class,\n UpdateableResultTest.class,\n UpsertTest.class,\n UTF8EncodingTest.class,\n V3ParameterListTests.class\n})\npublic class Jdbc2TestSuite {\n}\n<|endoftext|>"} -{"language": "java", "text": "/* Copyright (c) 2008-2015, Avian Contributors\n\n Permission to use, copy, modify, and/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.\n\n There is NO WARRANTY for this software. See license.txt for\n details. */\n\npackage java.io;\n\npublic class FileOutputStream extends OutputStream {\n // static {\n // System.loadLibrary(\"natives\");\n // }\n\n private int fd;\n\n public FileOutputStream(FileDescriptor fd) {\n this.fd = fd.value;\n }\n\n public FileOutputStream(String path) throws IOException {\n this(path, false);\n }\n\n public FileOutputStream(String path, boolean append) throws IOException {\n fd = open(path, append);\n }\n \n\n public FileOutputStream(File file) throws IOException {\n this(file.getPath());\n }\n\n private static native int open(String path, boolean append) throws IOException;\n\n private static native void write(int fd, int c) throws IOException;\n\n private static native void write(int fd, byte[] b, int offset, int length)\n throws IOException;\n\n private static native void close(int fd) throws IOException;\n\n public void write(int c) throws IOException {\n write(fd, c);\n }\n\n public void write(byte[] b, int offset, int length) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n }\n // BUG: CWE-190 Integer Overflow or Wraparound\n // if (offset < 0 || offset + length > b.length) {\n // FIXED: \n if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) {\n throw new ArrayIndexOutOfBoundsException();\n }\n\n write(fd, b, offset, length);\n }\n\n public void close() throws IOException {\n if (fd != -1) {\n close(fd);\n fd = -1;\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "FileWithinDirectory(loadPath, file)\n ? loadFile(file)\n : null;\n }\n else {\n final File f = new File(loadPath, file.getPath());\n return f.isFile()\n ? loadFile(new File(loadPath, file.getPath()))\n : null;\n }\n }\n catch (Exception ex) {\n throw new VncException(\n String.format(\"Failed to load file '%s'\", file.getPath()),\n ex);\n }\n }\n\n private static File canonical(final File file) {\n try {\n return file.getCanonicalFile();\n }\n catch(IOException ex) {\n throw new VncException(\n String.format(\n \"The file '%s' can not be converted to a canonical path!\",\n file.getPath()),\n ex);\n }\n }\n\n private ByteBuffer loadFile(final File file) {\n try {\n return ByteBuffer.wrap(Files.readAllBytes(file.toPath()));\n }\n catch(IOException ex) {\n return null;\n }\n }\n\n private boolean isFileWithinDirectory(\n final File dir,\n final File file\n ) throws IOException {\n final File dir_ = dir.getAbsoluteFile();\n if (dir_.isDirectory()) {\n final File fl = new File(dir_, file.getPath());\n if (fl.isFile()) {\n // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n // if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {\n // FIXED: \n if (fl.getCanonicalFile().toPath().startsWith(dir_.getCanonicalFile().toPath())) {\n // Prevent accessing files outside the load-path.\n // E.g.: ../../coffee\n return true;\n }\n }\n }\n\n return false;\n }\n\n private Charset getCharset(final String encoding) {\n return encoding == null || encoding.isEmpty()\n ? Charset.defaultCharset()\n : Charset.forName(encoding);\n }\n\n\n // a list of existing canonical paths\n private final List paths = new ArrayList<>();\n private final boolean unlimitedAccess;\n}\n<|endoftext|>"} -{"language": "java", "text": "t java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.olat.core.CoreSpringFactory;\nimport org.olat.core.configuration.AbstractSpringModule;\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.coordinate.CoordinatorManager;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.course.site.model.CourseSiteConfiguration;\nimport org.olat.course.site.model.LanguageConfiguration;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * Description:
\n * This is the module for sites definition and configuration\n * \n *

\n * Initial Date: 12.07.2005
\n *\n * @author Felix Jost\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n */\n@Service(\"olatsites\")\npublic class SiteDefinitions extends AbstractSpringModule {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(SiteDefinitions.class);\n\n\tprivate Map siteDefMap;\n\tprivate Map siteConfigMap = new ConcurrentHashMap<>();\n\t\n\tprivate String configSite1;\n\tprivate String configSite2;\n\tprivate String configSite3;\n\tprivate String configSite4;\n\tprivate String sitesSettings;\n\t\n\t@Autowired\n\tprivate List configurers;\n\t\n\tprivate static final XStream xStream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(xStream);\n\t\txStream.alias(\"coursesite\", CourseSiteConfiguration.class);\n\t\txStream.alias(\"languageConfig\", LanguageConfiguration.class);\n\t\txStream.alias(\"siteconfig\", SiteConfiguration.class);\n\t}\n\t\n\t@Autowired\n\tpublic SiteDefinitions(CoordinatorManager coordinatorManager) {\n\t\tsuper(coordinatorManager);\n\t}\n\t\n\t\n\t\n\tpublic String getConfigCourseSite1() {\n\t\treturn configSite1;\n\t}\n\n\tpublic void setConfigCourseSite1(String config) {\n\t\tsetStringProperty(\"site.1.config\", config, true);\n\t}\n\n\tpublic String getConfigCourseSite2() {\n\t\treturn configSite2;\n\t}\n\n\tpublic void setConfigCourseSite2(String config) {\n\t\tsetStringProperty(\"site.2.config\", config, true);\n\t}\n\t\n\tpublic String getConfigCourseSite3() {\n\t\treturn configSite3;\n\t}\n\n\tpublic void setConfigCourseSite3(String config) {\n\t\tsetStringProperty(\"site.3.config\", config, true);\n\t}\n\t\n\tpublic String getConfigCourseSite4() {\n\t\treturn configSite4;\n\t}\n\n\tpublic void setConfigCourseSite4(String config) {\n\t\tsetStringProperty(\"site.4.config\", config, true);\n\t}\n\t\n\tpublic SiteConfiguration getConfigurationSite(String id) {\n\t\treturn siteConfigMap.computeIfAbsent(id, springId -> {\n\t\t\tSiteConfiguration c = new SiteConfigur<|endoftext|>"} -{"language": "java", "text": "/*\n * Copyright 2015 Red Hat, Inc. and/or its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.dashbuilder.dataprovider.sql;\n\nimport java.util.List;\nimport java.util.ArrayList;\n\nimport org.junit.Before;\n\npublic class SQLTestSuite extends SQLDataSetTestBase {\n\n protected T setUp(T test) throws Exception {\n test.testSettings = testSettings;\n test.conn = conn;\n return test;\n }\n\n protected List sqlTestList = new ArrayList();\n\n @Before\n public void setUp() throws Exception {\n super.setUp();\n sqlTestList.add(setUp(new SQLDataSetDefTest()));\n sqlTestList.add(setUp(new SQLDataSetTrimTest()));\n sqlTestList.add(setUp(new SQLTableDataSetLookupTest()));\n sqlTestList.add(setUp(new SQLQueryDataSetLookupTest()));\n // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')\n // \n // FIXED: \n sqlTestList.add(setUp(new SQLInjectionAttacksTest()));\n }\n\n public void testAll() throws Exception {\n for (SQLDataSetTestBase testBase : sqlTestList) {\n testBase.testAll();\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "ayer;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;\nimport com.github.steveice10.mc.protocol.data.game.entity.player.*;\nimport com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.*;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.math.vector.Vector3i;\nimport com.nukkitx.protocol.bedrock.data.LevelEventType;\nimport com.nukkitx.protocol.bedrock.data.PlayerActionType;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityEventType;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityFlag;\nimport com.nukkitx.protocol.bedrock.packet.*;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.ItemFrameEntity;\nimport org.geysermc.connector.entity.player.SessionPlayerEntity;\nimport org.geysermc.connector.inventory.PlayerInventory;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.world.block.BlockStateValues;\nimport org.geysermc.connector.registry.BlockRegistries;\nimport org.geysermc.connector.registry.type.ItemMapping;\nimport org.geysermc.connector.utils.BlockUtils;\n\nimport java.util.ArrayList;\n\n@Translator(packet = PlayerActionPacket.class)\npublic class BedrockActionTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PlayerActionPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PlayerActionPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n\n // Send book update before any player action\n if (packet.getAction() != PlayerActionType.RESPAWN) {\n session.getBookEditCache().checkForSend();\n }\n\n Vector3i vector = packet.getBlockPosition();\n Position position = new Position(vector.getX(), vector.getY(), vector.getZ());\n\n switch (packet.getAction()) {\n case RESPAWN:\n // Respawn process is finished and the server and client are both OK with respawning.\n EntityEventPacket eventPacket = new EntityEventPacket();\n eventPacket.setRuntimeEntityId(entity.getGeyserId());\n eventPacket.setType(EntityEventType.RESPAWN);\n eventPacket.setData(0);\n session.sendUpstreamPacket(eventPacket);\n // Resend attributes or else in rare cases the user can think they're not dead when they are, upon joining the server\n UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();\n attributesPacket.setRuntimeEnt<|endoftext|>"} -{"language": "java", "text": "package com.zrlog.web;\n\nimport com.zrlog.common.Constants;\nimport org.apache.catalina.LifecycleException;\nimport org.apache.catalina.startup.Tomcat;\n\nimport javax.servlet.ServletException;\nimport java.io.File;\n\npublic class Application {\n\n public static void main(String[] args) throws LifecycleException {\n String webappDirLocation;\n if (Constants.IN_JAR) {\n webappDirLocation = \"webapp\";\n } else {\n webappDirLocation = \"src/main/webapp/\";\n }\n\n Tomcat tomcat = new Tomcat();\n\n String webPort = System.getenv(\"PORT\");\n if (webPort == null || webPort.isEmpty()) {\n webPort = \"8080\";\n }\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // tomcat.setPort(Integer.valueOf(webPort));\n // FIXED: \n tomcat.setPort(Integer.parseInt(webPort));\n tomcat.getConnector();\n\n // Declare an alternative location for your \"WEB-INF/classes\" dir\n // Servlet 3.0 annotation will work\n File additionWebInfClasses;\n if (Constants.IN_JAR) {\n additionWebInfClasses = new File(\"\");\n } else {\n additionWebInfClasses = new File(\"target/classes\");\n }\n\n tomcat.setBaseDir(additionWebInfClasses.toString());\n //idea\u7684\u8def\u5f84eclipse\u542f\u52a8\u7684\u8def\u5f84\u6709\u533a\u522b\n if (!Constants.IN_JAR && !new File(\"\").getAbsolutePath().endsWith(File.separator + \"web\")) {\n webappDirLocation = \"web/\" + webappDirLocation;\n }\n tomcat.addWebapp(\"\", new File(webappDirLocation).getAbsolutePath());\n tomcat.start();\n tomcat.getServer().await();\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of the License\n * at:\n *\n * http://opensource.org/licenses/ecl2.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n */\n\npackage org.opencastproject.mediapackage.identifier;\n\nimport javax.xml.bind.annotation.adapters.XmlAdapter;\nimport javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;\n\n/**\n * Interface for an identifier.\n */\n@XmlJavaTypeAdapter(Id.Adapter.class)\npublic interface Id {\n\n /**\n * Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters\n * that could potentially get into the way when creating file or directory names from the identifier.\n *\n * For example, given that the interface is implemented by a class representing CNRI handles, the identifier would\n * then look something like 10.3930/ETHZ/abcd, whith 10.3930 being the handle prefix,\n * ETH the authority and abcd the local part. toURI() would then return\n * 10.3930-ETH-abcd or any other suitable form.\n *\n * @return a path separator-free representation of the identifier\n */\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // \n // FIXED:\n @Deprecated\n String compact();\n\n class Adapter extends XmlAdapter {\n public IdImpl marshal(Id id) throws Exception {\n if (id instanceof IdImpl) {\n return (IdImpl) id;\n } else {\n throw new IllegalStateException(\"an unknown ID is un use: \" + id);\n }\n }\n\n public Id unmarshal(IdImpl id) throws Exception {\n return id;\n }\n }\n\n /**\n * Return a string representation of the identifier from which an object of type Id should\n * be reconstructable.\n */\n String toString();\n}\n<|endoftext|>"} -{"language": "java", "text": "name-with-dot\"));\n svnMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.MATERIAL_NAME)).isEqualTo(\"Invalid material name '.bad-name-with-dot'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.\");\n }\n\n @Test\n void shouldEnsureDestFilePathIsValid() {\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, \"../a\"));\n svnMaterialConfig.validate(new ConfigSaveValidationContext(null));\n\n assertThat(svnMaterialConfig.errors().on(SvnMaterialConfig.FOLDER)).isEqualTo(\"Dest folder '../a' is not valid. It must be a sub-directory of the working folder.\");\n }\n\n @Test\n void rejectsObviouslyWrongURL() {\n assertTrue(validating(svn(\"-url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n assertTrue(validating(svn(\"_url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n assertTrue(validating(svn(\"@url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n\n assertFalse(validating(svn(\"url-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // \n // FIXED: \n assertFalse(validating(svn(\"#{url}\", false)).errors().containsKey(SvnMaterialConfig.URL));\n }\n\n private SvnMaterialConfig validating(SvnMaterialConfig svn) {\n svn.validate(new ConfigSaveValidationContext(null));\n return svn;\n }\n }\n\n @Nested\n class ValidateTree {\n @BeforeEach\n void setUp() {\n svnMaterialConfig.setUrl(\"foo/bar\");\n }\n\n @Test\n void shouldCallValidate() {\n final MaterialConfig materialConfig = spy(svnMaterialConfig);\n final ValidationContext validationContext = mockValidationContextForSecretParams();\n\n materialConfig.validateTree(validationContext);\n\n verify(materialConfig).validate(validationContext);\n }\n\n @Test\n void shouldFailIfEncryptedPasswordIsIncorrect() {\n svnMaterialConfig.setEncryptedPassword(\"encryptedPassword\");\n\n final boolean validationResult = svnMaterialConfig.validateTree(new ConfigSaveValidationContext(null));\n\n assertThat(validationResult).isFalse();\n assertThat(svnMaterialConfig.errors().on(\"encryptedPassword\")).isEqualTo(\"Encrypted pa<|endoftext|>"} -{"language": "java", "text": "ld be parsed directly by adding it to JS.\n\t\t\t\t\t\t\t\t\t\tif (libs[j].toLowerCase()\n\t\t\t\t\t\t\t\t\t\t\t\t.endsWith(\".js\"))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tjs.append(tmp);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (result.length() > 1)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tresult.append(\",\");\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tresult.append(\"'\" + tmp + \"'\");\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tString tmp = stencils.get(names[i]);\n\n\t\t\t\t\t\t\tif (tmp == null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttmp = readXmlFile(\n\t\t\t\t\t\t\t\t\t\t\t\"/stencils/\" + names[i] + \".xml\",\n\t\t\t\t\t\t\t\t\t\t\ttrue);\n\n\t\t\t\t\t\t\t\t\t// Cache for later use\n\t\t\t\t\t\t\t\t\tif (tmp != null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tstencils.put(names[i], tmp);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (NullPointerException e)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// This seems possible according to access log so ignore stencil\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (tmp != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (result.length() > 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tresult.append(\",\");\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tresult.append(\"'\" + tmp + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tdone.add(names[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresult.append(\"]\");\n\n\t\t// LATER: Detect protocol of request in dev\n\t\t// mode to avoid security errors\n\t\tString proto = \"https://\";\n\n\t\tString setCachedUrls = \"\";\n\t\tString[] urls = request.getParameterValues(\"fetch\");\n\n\t\tif (urls != null)\n\t\t{\n\t\t\tHashSet completed = new HashSet();\n\n\t\t\tfor (int i = 0; i < urls.length; i++)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t// Checks if URL already fetched to avoid duplicates\n\t\t\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t\t\t// if (!completed.contains(urls[i]))\n\t\t\t\t\t// FIXED: \n\t\t\t\t\tif (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcompleted.add(urls[i]);\n\t\t\t\t\t\tURL url = new URL(urls[i]);\n\t\t\t\t\t\tURLConnection connection = url.openConnection();\n\t\t\t\t\t\tByteArrayOutputStream stream = new ByteArrayOutputStream();\n\t\t\t\t\t\tUtils.copy(connection.getInputStream(), stream);\n\t\t\t\t\t\tsetCachedUrls += \"GraphViewer.cachedUrls['\"\n\t\t\t\t\t\t\t\t+ StringEscapeUtils.escapeEcmaScript(urls[i])\n\t\t\t\t\t\t\t\t+ \"'] = decodeURIComponent('\"\n\t\t\t\t\t\t\t\t+ StringEscapeUtils.escapeEcmaScript(\n\t\t\t\t\t\t\t\t\t\tUtils.encodeURIComponent(\n\t\t\t\t\t\t\t\t\t\t\t\tstream.toString(\"UTF-8\"),\n\t\t\t\t\t\t\t\t\t\t\t\tUtils.CHARSET_FOR_URL_ENCODING))\n\t\t\t\t\t\t\t\t+ \"');\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\t// ignore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Installs a callback to load the stencils after the viewer was injected\n\t\treturn \"window.onDrawioViewerLoad = function() {\" + setCachedUrls\n\t\t\t\t+ \"mxStencilRegistry.parseStencilSets(\" + result.toString()\n\t\t\t\t+ \");\" + js + \"GraphViewer.processElements(); };\"\n\t\t\t\t+ \"var t = document.getElementsByTagName('script');\"\n\t\t\t\t+ \"if (t != null && t.length > 0) {\"\n\t\t\t\t+ \"var script = document.createElement('script');\"\n\t\t\t\t+ \"script.type = 'text/javascript';\" + \"script.src = '\" + proto\n\t\t\t\t<|endoftext|>"} -{"language": "java", "text": "ConversationsListItemUpdated;\nimport eu.siacs.conversations.ui.service.EmojiService;\nimport eu.siacs.conversations.ui.util.ActivityResult;\nimport eu.siacs.conversations.ui.util.ConversationMenuConfigurator;\nimport eu.siacs.conversations.ui.util.MenuDoubleTabUtil;\nimport eu.siacs.conversations.ui.util.PendingItem;\nimport eu.siacs.conversations.utils.EmojiWrapper;\nimport eu.siacs.conversations.utils.ExceptionHelper;\nimport eu.siacs.conversations.utils.XmppUri;\nimport eu.siacs.conversations.xmpp.OnUpdateBlocklist;\nimport rocks.xmpp.addr.Jid;\n\nimport static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;\n\npublic class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged {\n\n public static final String ACTION_VIEW_CONVERSATION = \"eu.siacs.conversations.action.VIEW\";\n public static final String EXTRA_CONVERSATION = \"conversationUuid\";\n public static final String EXTRA_DOWNLOAD_UUID = \"eu.siacs.conversations.download_uuid\";\n public static final String EXTRA_AS_QUOTE = \"as_quote\";\n public static final String EXTRA_NICK = \"nick\";\n public static final String EXTRA_IS_PRIVATE_MESSAGE = \"pm\";\n // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n // \n // FIXED: \n public static final String EXTRA_DO_NOT_APPEND = \"do_not_append\";\n\n private static List VIEW_AND_SHARE_ACTIONS = Arrays.asList(\n ACTION_VIEW_CONVERSATION,\n Intent.ACTION_SEND,\n Intent.ACTION_SEND_MULTIPLE\n );\n\n public static final int REQUEST_OPEN_MESSAGE = 0x9876;\n public static final int REQUEST_PLAY_PAUSE = 0x5432;\n\n\n //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment\n private static final @IdRes\n int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};\n private final PendingItem pendingViewIntent = new PendingItem<>();\n private final PendingItem postponedActivityResult = new PendingItem<>();\n private ActivityConversationsBinding binding;\n private boolean mActivityPaused = true;\n private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);\n\n private static boolean isViewOrShareIntent(Intent i) {\n Log.d(Config.LOGTAG, \"action: \" + (i == null ? null : i.getAction()));\n return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATI<|endoftext|>"} -{"language": "java", "text": "er;\nimport uk.ac.ed.ph.jqtiplus.types.Identifier;\nimport uk.ac.ed.ph.jqtiplus.types.ResponseData.ResponseDataType;\nimport uk.ac.ed.ph.jqtiplus.value.BooleanValue;\nimport uk.ac.ed.ph.jqtiplus.value.NumberValue;\nimport uk.ac.ed.ph.jqtiplus.value.RecordValue;\nimport uk.ac.ed.ph.jqtiplus.value.SingleValue;\nimport uk.ac.ed.ph.jqtiplus.value.Value;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.XmlFactories;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.XmlResourceNotFoundException;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.locators.ClassPathResourceLocator;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.locators.ResourceLocator;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltSerializationOptions;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetCache;\nimport uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetManager;\nimport uk.ac.ed.ph.qtiworks.mathassess.GlueValueBinder;\nimport uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants;\nimport uk.ac.ed.ph.qtiworks.mathassess.MathAssessExtensionPackage;\n\n/**\n * \n * Initial date: 12.05.2015
\n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n *\n */\n@Service\npublic class QTI21ServiceImpl implements QTI21Service, UserDataDeletable, InitializingBean, DisposableBean {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(QTI21ServiceImpl.class);\n\t\n\tprivate static XStream configXstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tQTI21DeliveryOptions.class, QTI21AssessmentResultsOptions.class\n\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(configXstream);\n\t\t// FIXED: \n\t\tconfigXstream.addPermission(new ExplicitTypePermission(types));\n\t\t\n\t\tconfigXstream.alias(\"deliveryOptions\", QTI21DeliveryOptions.class);\n\t\tconfigXstream.alias(\"assessmentResultsOptions\", QTI21AssessmentResultsOptions.class);\n\t}\n\t\n\t@Autowired\n\tprivate DB dbInstance;\n\t@Autowired\n\tprivate GradingService gradingService;\n\t@Autowired\n\tprivate AssessmentTestSessionDAO testSessionDao;\n\t@Autowired\n\tprivate AssessmentItemSessionDAO itemSessionDao;\n\t@Autowired\n\tprivate AssessmentResponseDAO testResponseDao;\n\t@Autowired\n\tprivate AssessmentTestMarksDAO testMarksDao;\n\t@Autowired\n\tprivate AssessmentEntryDAO assessmentEntryDao;\n\t@Autowired\n\tprivate QTI21Module qtiModule;\n\t@Autowired\n\tprivate CoordinatorManager coordinatorManager;\n\t@Autowired\n\tprivate MailManager mailManager;\n\t\n\n\tprivate JqtiExtensionManager jqtiExtensionManager;\n\tprivate XsltStylesheetManager xsltStylesheetManager;\n\tprivate InfinispanXsltStylesheetCache xsltStylesheetCache;\n\tprivate CacheWrapper assessmentTestsCache;\n\tprivate CacheWrapper assessmentItemsCache;\n\tprivate CacheWrapper testSessionControllersCache;\n\t\n\tprivate final C<|endoftext|>"} -{"language": "java", "text": "String msg) throws IOException {\n if (isIncluding()) {\n Logger.log(Logger.ERROR, Launcher.RESOURCES, \"IncludeResponse.Error\",\n new String[] { \"\" + sc, msg });\n return;\n }\n \n Logger.log(Logger.DEBUG, Launcher.RESOURCES,\n \"WinstoneResponse.SendingError\", new String[] { \"\" + sc, msg });\n\n if ((this.webAppConfig != null) && (this.req != null)) {\n \n RequestDispatcher rd = this.webAppConfig\n .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null);\n if (rd != null) {\n try {\n rd.forward(this.req, this);\n return;\n } catch (IllegalStateException err) {\n throw err;\n } catch (IOException err) {\n throw err;\n } catch (Throwable err) {\n Logger.log(Logger.WARNING, Launcher.RESOURCES,\n \"WinstoneResponse.ErrorInErrorPage\", new String[] {\n rd.getName(), sc + \"\" }, err);\n return;\n }\n }\n }\n // If we are here there was no webapp and/or no request object, so \n // show the default error page\n if (this.errorStatusCode == null) {\n this.statusCode = sc;\n }\n String output = Launcher.RESOURCES.getString(\"WinstoneResponse.ErrorPage\",\n // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n // new String[] { sc + \"\", (msg == null ? \"\" : msg), \"\",\n // FIXED:\n new String[] { sc + \"\", URIUtil.htmlEscape(msg == null ? \"\" : msg), \"\",\n Launcher.RESOURCES.getString(\"ServerVersion\"),\n \"\" + new Date() });\n setContentLength(output.getBytes(getCharacterEncoding()).length);\n Writer out = getWriter();\n out.write(output);\n out.flush();\n }\n\n /**\n * @deprecated\n */\n public String encodeRedirectUrl(String url) {\n return encodeRedirectURL(url);\n }\n\n /**\n * @deprecated\n */\n public String encodeUrl(String url) {\n return encodeURL(url);\n }\n\n /**\n * @deprecated\n */\n public void setStatus(int sc, String sm) {\n setStatus(sc);\n }\n}\n<|endoftext|>"} -{"language": "java", "text": " userRequest.getHttpReq().getParameter(\"key\");\n\t\tif (emKey == null) {\n\t\t\temKey = userRequest.getIdentity().getUser().getProperty(\"emchangeKey\", null);\n\t\t}\n\t\tif (emKey != null) {\n\t\t\t// key exist\n\t\t\t// we check if given key is a valid temporary key\n\t\t\ttempKey = rm.loadTemporaryKeyByRegistrationKey(emKey);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean isUserInteractionRequired(UserRequest ureq) {\n\t\tUser user = ureq.getIdentity().getUser();\n\t\tif(StringHelper.containsNonWhitespace(user.getProperty(\"emchangeKey\", null))) {\n\t\t\tif (isLinkTimeUp()) {\n\t\t\t\tdeleteRegistrationKey();\n\t\t\t} else {\n\t\t\t\tif (isLinkClicked()) {\n\t\t\t\t\tchangeEMail(getWindowControl());\n\t\t\t\t} else {\n\t\t \t\tBoolean alreadySeen = ((Boolean)ureq.getUserSession().getEntry(PRESENTED_EMAIL_CHANGE_REMINDER));\n\t\t \t\tif (alreadySeen == null) {\n\t\t \t\t\tgetWindowControl().setWarning(getPackageTranslator().translate(\"email.change.reminder\"));\n\t\t \t\t\tureq.getUserSession().putEntry(PRESENTED_EMAIL_CHANGE_REMINDER, Boolean.TRUE);\n\t\t \t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tString value = user.getProperty(\"emailDisabled\", null);\n\t\t\tif (value != null && value.equals(\"true\")) {\n\t\t\t\tTranslator translator = Util.createPackageTranslator(HomeMainController.class, ureq.getLocale());\n\t\t\t\tgetWindowControl().setWarning(translator.translate(\"email.disabled\"));\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * change email\n\t * @param wControl\n\t * @return\n\t */\n\tpublic boolean changeEMail(WindowControl wControl) {\n\t\tXStream xml = XStreamHelper.createXStreamInstance();\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(xml);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tHashMap mails = (HashMap) xml.fromXML(tempKey.getEmailAddress());\n\t\t\n\t\tIdentity identity = securityManager.loadIdentityByKey(tempKey.getIdentityKey());\n\t\tif (identity != null) {\n\t\t\tString oldEmail = identity.getUser().getEmail();\n\t\t\tidentity.getUser().setProperty(\"email\", mails.get(\"changedEMail\"));\n\t\t\t// if old mail address closed then set the new mail address\n\t\t\t// unclosed\n\t\t\tString value = identity.getUser().getProperty(\"emailDisabled\", null);\n\t\t\tif (value != null && value.equals(\"true\")) {\n\t\t\t\tidentity.getUser().setProperty(\"emailDisabled\", \"false\");\n\t\t\t}\n\t\t\tidentity.getUser().setProperty(\"email\", mails.get(\"changedEMail\"));\n\t\t\t// success info message\n\t\t\tString currentEmailDisplay = userManager.getUserDisplayEmail(mails.get(\"currentEMail\"), userRequest.getLocale());\n\t\t\tString changedEmailDisplay = userManager.getUserDisplayEmail(mails.get(\"changedEMail\"), userRequest.getLocale());\n\t\t\twControl.setInfo(pT.translate(\"success.change.email\", new String[] { currentEmailDisplay, changedEmailDisplay }));\n\t\t\t// remove keys\n\t\t\tidentity.getUser().setProperty(\"emchangeKey\", null);\n\t<|endoftext|>"} -{"language": "java", "text": "bla.Dispatcher\",ConfigKey.AGENT_ID,\"test\");\n new BackendManager(config,log);\n }\n\n @Test\n public void debugging() {\n RecordingLogHandler lhandler = new RecordingLogHandler();\n BackendManager backendManager = new BackendManager(config,lhandler);\n lhandler.error = 0;\n lhandler.debug = 0;\n lhandler.info = 0;\n\n backendManager.debug(\"test\");\n assertEquals(lhandler.debug,1);\n backendManager.error(\"test\",new Exception());\n assertEquals(lhandler.error,1);\n backendManager.info(\"test\");\n assertEquals(lhandler.info,1);\n backendManager.destroy();\n }\n\n @Test\n public void defaultConfig() {\n Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,\"blabal\",ConfigKey.AGENT_ID,\"test\");\n BackendManager backendManager = new BackendManager(config,log);\n backendManager.destroy();\n }\n\n @Test\n public void doubleInit() {\n BackendManager b1 = new BackendManager(config,log);\n BackendManager b2 = new BackendManager(config,log);\n b2.destroy();\n b1.destroy();\n }\n\n @Test\n public void remoteAccessCheck() {\n BackendManager backendManager = new BackendManager(config,log);\n assertTrue(backendManager.isRemoteAccessAllowed(\"localhost\",\"127.0.0.1\"));\n backendManager.destroy();\n }\n\n @Test\n public void corsAccessCheck() {\n BackendManager backendManager = new BackendManager(config,log);\n // BUG: CWE-352 Cross-Site Request Forgery (CSRF)\n // assertTrue(backendManager.isCorsAccessAllowed(\"http://bla.com\"));\n // FIXED: \n assertTrue(backendManager.isOriginAllowed(\"http://bla.com\",false));\n backendManager.destroy();\n }\n\n @Test\n public void convertError() throws MalformedObjectNameException {\n BackendManager backendManager = new BackendManager(config,log);\n Exception exp = new IllegalArgumentException(\"Hans\",new IllegalStateException(\"Kalb\"));\n JmxRequest req = new JmxRequestBuilder(RequestType.READ,\"java.lang:type=Memory\").build();\n JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req);\n assertTrue(!jsonError.containsKey(\"stackTrace\"));\n assertEquals(jsonError.get(\"message\"),\"Hans\");\n assertEquals(((JSONObject) jsonError.get(\"cause\")).get(\"message\"),\"Kalb\");\n backendManager.destroy();\n }\n\n // =========================================================================================\n\n static class RequestDispatcherTest implements RequestDispatcher {\n\n static boolean called = false;\n\n public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) {\n assertNotNull(pConverters);\n assertNotNull(pRestrictor);\n <|endoftext|>"} -{"language": "java", "text": "ve copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientRenameItemPacket;\nimport com.nukkitx.protocol.bedrock.packet.FilterTextPacket;\nimport org.geysermc.connector.inventory.AnvilContainer;\nimport org.geysermc.connector.inventory.CartographyContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Used to send strings to the server and filter out unwanted words.\n * Java doesn't care, so we don't care, and we approve all strings.\n */\n@Translator(packet = FilterTextPacket.class)\npublic class BedrockFilterTextTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(FilterTextPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, FilterTextPacket packet) {\n if (session.getOpenInventory() instanceof CartographyContainer) {\n // We don't want to be able to rename in the cartography table\n return;\n }\n packet.setFromServer(true);\n session.sendUpstreamPacket(packet);\n\n if (session.getOpenInventory() instanceof AnvilContainer) {\n // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now\n ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());\n session.sendDownstreamPacket(renameItemPacket);\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "ITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\n* See the License for the specific language governing permissions and
\n* limitations under the License.\n*

\n* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
\n* University of Zurich, Switzerland.\n*


\n* \n* OpenOLAT - Online Learning and Training
\n* This file has been modified by the OpenOLAT community. Changes are licensed\n* under the Apache 2.0 license as the original file. \n*

\n* Initial code contributed and copyrighted by
\n* JGS goodsolutions GmbH, http://www.goodsolutions.ch\n*

\n*/\npackage org.olat.core.util.prefs.db;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.id.Identity;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.prefs.Preferences;\nimport org.olat.core.util.prefs.PreferencesStorage;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.properties.Property;\nimport org.olat.properties.PropertyManager;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * Description:
\n *

\n * Initial Date: 21.06.2006
\n * \n * @author Felix Jost\n */\npublic class DbStorage implements PreferencesStorage {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(DbStorage.class);\n\n\tstatic final String USER_PROPERTY_KEY = \"v2guipreferences\";\n\t\n\tprivate static final XStream xstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED:\n\t\tXStreamHelper.allowDefaultPackage(xstream);\n\t\txstream.ignoreUnknownElements();\n\t}\n\n\t@Override\n\tpublic Preferences getPreferencesFor(Identity identity, boolean useTransientPreferences) {\n\t\tif (useTransientPreferences) {\n\t\t\treturn createEmptyDbPrefs(identity,true);\n\t\t} else {\t\t\t\n\t\t\ttry {\n\t\t\t\treturn getPreferencesFor(identity);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"Retry after exception\", e);\n\t\t\t\treturn getPreferencesFor(identity);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void updatePreferencesFor(Preferences prefs, Identity identity) {\n\t\tString props = xstream.toXML(prefs);\n\t\tProperty property = getPreferencesProperty(identity);\n\t\tif (property == null) {\n\t\t\tproperty = PropertyManager.getInstance().createPropertyInstance(identity, null, null, null, DbStorage.USER_PROPERTY_KEY, null, null,\n\t\t\t\t\tnull, props);\n\t\t\t// also save the properties to db, here (strentini)\n\t\t\t// fixes the \"non-present gui preferences\" for new users, or where guiproperties were manually deleted\n\t\t\tPropertyManager.getInstance().saveProperty(property);\n\t\t} else {\n\t\t\tproperty.setTextValue(props);\n\t\t\tPropertyManager.getInstance().updateProperty(property);\n\t\t}\n\t}\n\n\t/**\n\t * search x-stream serialization in properties table, <|endoftext|>"} -{"language": "java", "text": "terialConfig = git(\"http://bob:pass@example.com##dobule-hash-is-invalid-in-url\");\n gitMaterialConfig.setUserName(\"user\");\n gitMaterialConfig.setPassword(\"password\");\n\n assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL));\n }\n\n @Test\n void shouldBeValidWhenCredentialsAreProvidedOnlyInUrl() {\n assertFalse(validating(git(\"http://bob:pass@example.com\")).errors().containsKey(GitMaterialConfig.URL));\n }\n\n @Test\n void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() {\n GitMaterialConfig gitMaterialConfig = git(\"http://example.com\");\n gitMaterialConfig.setUserName(\"bob\");\n gitMaterialConfig.setPassword(\"badger\");\n\n assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL));\n }\n\n @Test\n void rejectsObviouslyWrongURL() {\n assertTrue(validating(git(\"-url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n assertTrue(validating(git(\"_url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n assertTrue(validating(git(\"@url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n\n assertFalse(validating(git(\"url-starting-with-an-alphanumeric-character\")).errors().containsKey(GitMaterialConfig.URL));\n // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection')\n // \n // FIXED:\n assertFalse(validating(git(\"#{url}\")).errors().containsKey(GitMaterialConfig.URL));\n }\n\n private GitMaterialConfig validating(GitMaterialConfig git) {\n git.validate(new ConfigSaveValidationContext(null));\n return git;\n }\n }\n\n @Nested\n class ValidateTree {\n @Test\n void shouldCallValidate() {\n final MaterialConfig materialConfig = spy(git(\"https://example.repo\"));\n final ValidationContext validationContext = mockValidationContextForSecretParams();\n\n materialConfig.validateTree(validationContext);\n\n verify(materialConfig).validate(validationContext);\n }\n\n @Test\n void shouldFailIfEncryptedPasswordIsIncorrect() {\n GitMaterialConfig gitMaterialConfig = git(\"http://example.com\");\n gitMaterialConfig.setEncryptedPassword(\"encryptedPassword\");\n\n final boolean validationResult = gitMaterialConfig.validateTree(new ConfigSaveValidationContext(null));\n\n assertFalse(validationResult);\n assertEquals(\"Encrypted password value for GitMaterial with url 'http://example.com' is \" +\n <|endoftext|>"} -{"language": "java", "text": "ut(m.name, newEntry);\n }\n }\n ENCODING_STATIC_TABLE = Collections.unmodifiableMap(map);\n }\n\n /**\n * The maximum table size\n */\n private int maxTableSize;\n\n /**\n * The current table size\n */\n private int currentTableSize;\n\n private final HpackHeaderFunction hpackHeaderFunction;\n\n public HpackEncoder(int maxTableSize, HpackHeaderFunction headerFunction) {\n this.maxTableSize = maxTableSize;\n this.hpackHeaderFunction = headerFunction;\n }\n\n public HpackEncoder(int maxTableSize) {\n this(maxTableSize, DEFAULT_HEADER_FUNCTION);\n }\n\n /**\n * Encodes the headers into a buffer.\n *\n * @param headers\n * @param target\n */\n public State encode(HeaderMap headers, ByteBuffer target) {\n if(overflowData != null) {\n for(int i = overflowPos; i < overflowLength; ++i) {\n if(!target.hasRemaining()) {\n overflowPos = i;\n return State.OVERFLOW;\n }\n target.put(overflowData[i]);\n }\n overflowData = null;\n }\n\n long it = headersIterator;\n if (headersIterator == -1) {\n handleTableSizeChange(target);\n //new headers map\n it = headers.fastIterate();\n currentHeaders = headers;\n } else {\n if (headers != currentHeaders) {\n throw new IllegalStateException();\n }\n // BUG: NVD-CWE-noinfo Insufficient Information\n // it = headers.fiNext(it);\n // FIXED:\n it = headers.fiNext(it);\n }\n while (it != -1) {\n HeaderValues values = headers.fiCurrent(it);\n boolean skip = false;\n if (firstPass) {\n if (values.getHeaderName().byteAt(0) != ':') {\n skip = true;\n }\n } else {\n if (values.getHeaderName().byteAt(0) == ':') {\n skip = true;\n }\n }\n if(SKIP.contains(values.getHeaderName())) {\n //ignore connection specific headers\n skip = true;\n }\n if (!skip) {\n for (int i = 0; i < values.size(); ++i) {\n\n HttpString headerName = values.getHeaderName();\n int required = 11 + headerName.length(); //we use 11 to make sure we have enough room for the variable length itegers\n\n String val = values.get(i);\n for(int v = 0; v < val.length(); ++v) {\n char c = val.charAt(v);\n if(c == '\\r' || c == '\\n') {\n val = val.replace('\\r', ' ').replace('\\n', ' ');\n <|endoftext|>"} -{"language": "java", "text": "\t\t}\n\n\t\tvar delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);\n\t\tvar delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),\n\t\t\t\tZoneOffset.UTC);\n\n\t\tvar nowDay = LocalDate.now(ZoneOffset.UTC);\n\t\tif (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {\n\t\t\treturn () -> ResponseEntity.badRequest().body(\"delayedKeyDate date must be between yesterday and tomorrow\");\n\t\t}\n\n\t\tvar responseBuilder = ResponseEntity.ok();\n\t\tif (principal instanceof Jwt) {\n\t\t\tvar originalJWT = (Jwt) principal;\n\t\t\tvar jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))\n\t\t\t\t\t.setIssuer(\"dpppt-sdk-backend\").setSubject(originalJWT.getSubject())\n\t\t\t\t\t.setExpiration(Date\n\t\t\t\t\t\t\t.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))\n\t\t\t\t\t.claim(\"scope\", \"currentDayExposed\").claim(\"delayedKeyDate\", gaenRequest.getDelayedKeyDate());\n\t\t\tif (originalJWT.containsClaim(\"fake\")) {\n\t\t\t\tjwtBuilder.claim(\"fake\", originalJWT.getClaim(\"fake\"));\n\t\t\t}\n\t\t\tString jwt = jwtBuilder.signWith(secondDayKey).compact();\n\t\t\tresponseBuilder.header(\"Authorization\", \"Bearer \" + jwt);\n\t\t\tresponseBuilder.header(\"X-Exposed-Token\", \"Bearer \" + jwt);\n\t\t}\n\t\tCallable> cb = () -> {\n\t\t\tnormalizeRequestTime(now);\n\t\t\treturn responseBuilder.body(\"OK\");\n\t\t};\n\t\treturn cb;\n\t}\n\n\t@PostMapping(value = \"/exposednextday\")\n\t@Loggable\n\t// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor\n\t// \n\t// FIXED: \n\t@ResponseRetention(time = \"application.response.retention.time.exposednextday\")\n\t@Transactional\n\t@Operation(description = \"Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed\")\n\t@ApiResponses(value = {\n\t\t\t@ApiResponse(responseCode = \"200\", description = \"The exposed key has been stored in the backend\"),\n\t\t\t@ApiResponse(responseCode = \"400\", description = \n\t\t\t\t\t\"- Ivnalid base64 encoded Temporary Exposure Key\" +\n\t\t\t\t\t\"- TEK-date does not match delayedKeyDAte claim in Jwt\" +\n\t\t\t\t\t\"- TEK has negative rolling period\"),\n\t\t\t@ApiResponse(responseCode = \"403\", description = \"No delayedKeyDate claim in authentication\") })\n\tpublic @ResponseBody Callable> addExposedSecond(\n\t\t\t@Valid @RequestBody @Parameter(description = \"The last exposed key of the user\") GaenSecondDay gaenSecondDay,\n\t\t\t@RequestHeader(value = \"User-Agent\") @Parameter(description = \"App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version\", example = \"ch.ubique.android.starsdk;1.0;iOS;13.3\") String userAgent,\n\t\t\t@AuthenticationPrincipal @Parameter(description = \"JWT token that can be v<|endoftext|>"} -{"language": "java", "text": "teKeyParameters;\nimport org.bouncycastle.pqc.crypto.xmss.XMSSUtil;\nimport org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;\nimport org.bouncycastle.util.Arrays;\n\npublic class BCXMSSPrivateKey\n implements PrivateKey, XMSSKey\n{\n private final XMSSPrivateKeyParameters keyParams;\n private final ASN1ObjectIdentifier treeDigest;\n\n public BCXMSSPrivateKey(\n ASN1ObjectIdentifier treeDigest,\n XMSSPrivateKeyParameters keyParams)\n {\n this.treeDigest = treeDigest;\n this.keyParams = keyParams;\n }\n\n public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters\n .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssPrivateKey.getIndex())\n .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssPrivateKey.getPublicSeed())\n .withRoot(xmssPrivateKey.getRoot());\n\n if (xmssPrivateKey.getBdsState() != null)\n {\n // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')\n // keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));\n // FIXED:\n keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }\n\n public String getAlgorithm()\n {\n return \"XMSS\";\n }\n\n public String getFormat()\n {\n return \"PKCS#8\";\n }\n\n public byte[] getEncoded()\n {\n PrivateKeyInfo pki;\n try\n {\n AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest)));\n pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure());\n\n return pki.getEncoded();\n }\n catch (IOException e)\n {\n return null;\n }\n }\n\n public boolean equals(Object o)\n {\n if (o == this)\n {\n return true;\n }\n\n if (o instanceof BCXMSSPrivateKey)\n {\n BCXMSSPrivateKey otherKey = (BCXMSSPri<|endoftext|>"} -{"language": "java", "text": "SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;\nimport com.github.steveice10.mc.protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientClickWindowButtonPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;\nimport com.nukkitx.protocol.bedrock.packet.LecternUpdatePacket;\nimport org.geysermc.connector.inventory.LecternContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.InventoryUtils;\n\n/**\n * Used to translate moving pages, or closing the inventory\n */\n@Translator(packet = LecternUpdatePacket.class)\npublic class BedrockLecternUpdateTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(LecternUpdatePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, LecternUpdatePacket packet) {\n if (packet.isDroppingBook()) {\n // Bedrock drops the book outside of the GUI. Java drops it in the GUI\n // So, we enter the GUI and then drop it! :)\n session.setDroppingLecternBook(true);\n\n // Emulate an interact packet\n ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(\n new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),\n BlockFace.DOWN,\n Hand.MAIN_HAND,\n 0, 0, 0, // Java doesn't care about these when dealing with a lectern\n false);\n session.sendDownstreamPacket(blockPacket);\n } else {\n // Bedrock wants to either move a page or exit\n if (!(session.getOpenInventory() instanceof LecternContainer)) {\n session.getConnector().getLogger().debug(\"Expected lectern but it wasn't open!\");\n return;\n }\n\n LecternContainer lecternContainer = (LecternContainer) session.getOpenInventor<|endoftext|>"} -{"language": "java", "text": " following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerAbilitiesPacket;\nimport com.nukkitx.protocol.bedrock.data.AdventureSetting;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityFlag;\nimport com.nukkitx.protocol.bedrock.packet.AdventureSettingsPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = AdventureSettingsPacket.class)\npublic class BedrockAdventureSettingsTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(AdventureSettingsPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, AdventureSettingsPacket packet) {\n boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);\n if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) {\n // We should always be flying in spectator mode\n session.sendAdventureSettings();\n return;\n }\n\n session.setFlying(isFlying);\n ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying);\n session.sendDownstreamPacket(abilitiesPacket);\n\n if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {\n // Bedrock can fly and swim at the same time? Make sure that can't happen\n session.setSwimming(false);\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": " } finally {\n buffer.release();\n }\n }\n\n @Test\n public void testCopy() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());\n ByteBuf copy = buf.copy();\n\n Assert.assertEquals(buf, copy);\n\n buf.release();\n copy.release();\n }\n\n @Test\n public void testCopyWithOffset() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());\n ByteBuf copy = buf.copy(1, 9);\n\n Assert.assertEquals(buf.slice(1, 9), copy);\n\n buf.release();\n copy.release();\n }\n\n // Test for https://github.com/netty/netty/issues/1708\n @Test\n public void testWrapBufferWithNonZeroPosition() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16)\n .putLong(1).flip().position(1)).asReadOnlyBuffer());\n\n ByteBuf slice = buf.slice();\n Assert.assertEquals(buf, slice);\n\n buf.release();\n }\n\n @Test\n public void testWrapBufferRoundTrip() {\n ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());\n\n Assert.assertEquals(1, buf.readInt());\n\n ByteBuffer nioBuffer = buf.nioBuffer();\n\n // Ensure this can be accessed without throwing a BufferUnderflowException\n Assert.assertEquals(2, nioBuffer.getInt());\n\n buf.release();\n }\n\n @Test\n public void testWrapMemoryMapped() throws Exception {\n // BUG: CWE-378 Creation of Temporary File With Insecure Permissions\n // File file = File.createTempFile(\"netty-test\", \"tmp\");\n // FIXED: \n File file = PlatformDependent.createTempFile(\"netty-test\", \"tmp\", null);\n FileChannel output = null;\n FileChannel input = null;\n ByteBuf b1 = null;\n ByteBuf b2 = null;\n\n try {\n output = new RandomAccessFile(file, \"rw\").getChannel();\n byte[] bytes = new byte[1024];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n output.write(ByteBuffer.wrap(bytes));\n\n input = new RandomAccessFile(file, \"r\").getChannel();\n ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());\n\n b1 = buffer(m);\n\n ByteBuffer dup = m.duplicate();\n dup.position(2);\n dup.limit(4);\n\n b2 = buffer(dup);\n\n Assert.assertEquals(b2, b1.slice(2, 2));\n } finally {\n if (b1 != null) {\n b1.release();\n }\n if (b2 != null) {\n b2.release();\n }\n if (output != null) {\n output.close();\n }\n if (input != null) {\n input.close();\n }\n file.delete();\n }\n }\n\n @Test\n public void testMemoryAddress() {\n ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());\n try {\n Assert.assertFalse(buf.hasMemoryAddress());\n try {\n buf.memoryAddress();\n Assert.fail();\n } catch (UnsupportedOperationException expected) {\n // expected\n }\n } finally {\n buf.release();\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "rt org.olat.core.logging.Tracing;\nimport org.olat.core.util.CodeHelper;\nimport org.olat.core.util.FileUtils;\nimport org.olat.core.util.vfs.LocalFolderImpl;\nimport org.olat.core.util.vfs.VFSContainer;\nimport org.olat.core.util.vfs.VFSItem;\nimport org.olat.core.util.vfs.VFSLeaf;\nimport org.olat.core.util.vfs.VFSManager;\nimport org.olat.core.util.xml.XMLParser;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.olat.fileresource.FileResourceManager;\nimport org.olat.ims.cp.objects.CPOrganization;\nimport org.olat.ims.cp.objects.CPResource;\nimport org.olat.ims.cp.ui.CPPackageConfig;\nimport org.olat.ims.cp.ui.CPPage;\nimport org.olat.repository.RepositoryEntry;\nimport org.olat.repository.RepositoryManager;\nimport org.springframework.stereotype.Service;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.security.ExplicitTypePermission;\n\n/**\n * The CP manager implementation.\n *

\n * In many cases, method calls are delegated to the content package object.\n * \n *

\n * Initial Date: 04.07.2008
\n * \n * @author Sergio Trentini\n */\n@Service(\"org.olat.ims.cp.CPManager\")\npublic class CPManagerImpl implements CPManager {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(CPManagerImpl.class);\n\n\tpublic static final String PACKAGE_CONFIG_FILE_NAME = \"CPPackageConfig.xml\";\n\n\tprivate static XStream configXstream = XStreamHelper.createXStreamInstance();\n\tstatic {\n\t\tClass[] types = new Class[] {\n\t\t\t\tCPPackageConfig.class, DeliveryOptions.class\n\t\t\t};\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// XStream.setupDefaultSecurity(configXstream);\n\t\t// FIXED: \n\t\tconfigXstream.addPermission(new ExplicitTypePermission(types));\n\t\tconfigXstream.alias(\"packageConfig\", CPPackageConfig.class);\n\t\tconfigXstream.alias(\"deliveryOptions\", DeliveryOptions.class);\n\t}\n\n\t@Override\n\tpublic CPPackageConfig getCPPackageConfig(OLATResourceable ores) {\n\t\tFileResourceManager frm = FileResourceManager.getInstance();\n\t\tFile reFolder = frm.getFileResourceRoot(ores);\n\t\tFile configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);\n\t\t\n\t\tCPPackageConfig config;\n\t\tif(configXml.exists()) {\n\t\t\tconfig = (CPPackageConfig)configXstream.fromXML(configXml);\n\t\t} else {\n\t\t\t//set default config\n\t\t\tconfig = new CPPackageConfig();\n\t\t\tconfig.setDeliveryOptions(DeliveryOptions.defaultWithGlossary());\n\t\t\tsetCPPackageConfig(ores, config);\n\t\t}\n\t\treturn config;\n\t}\n\n\t@Override\n\tpublic void setCPPackageConfig(OLATResourceable ores, CPPackageConfig config) {\n\t\tFileResourceManager frm = FileResourceManager.getInstance();\n\t\tFile reFolder = frm.getFileResourceRoot(ores);\n\t\tFile configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME);\n\t\tif(config == null) {\n\t\t\tFileUtils.deleteFile(configXml);\n\t\t} else {\n\t\t\ttry(OutputStream out = new FileOutputStream(configXml)) {\n\t\t\t\tconfigXstream.toXML(con<|endoftext|>"} -{"language": "java", "text": "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.java;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket;\nimport com.nukkitx.protocol.bedrock.packet.TextPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.network.translators.chat.MessageTranslator;\n\n@Translator(packet = ServerChatPacket.class)\npublic class JavaChatTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(ServerChatPacket packet, GeyserSession session) {\n // FIXED:\n public void translate(GeyserSession session, ServerChatPacket packet) {\n TextPacket textPacket = new TextPacket();\n textPacket.setPlatformChatId(\"\");\n textPacket.setSourceName(\"\");\n textPacket.setXuid(session.getAuthData().getXboxUUID());\n switch (packet.getType()) {\n case CHAT:\n textPacket.setType(TextPacket.Type.CHAT);\n break;\n case SYSTEM:\n textPacket.setType(TextPacket.Type.SYSTEM);\n break;\n case NOTIFICATION:\n textPacket.setType(TextPacket.Type.TIP);\n break;\n default:\n textPacket.setType(TextPacket.Type.RAW);\n break;\n }\n\n textPacket.setNeedsTranslation(false);\n textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));\n\n session.sendUpstreamPacket(textPacket);\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "red by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.micronaut.http.netty;\n\nimport io.micronaut.core.annotation.Internal;\nimport io.micronaut.core.convert.ArgumentConversionContext;\nimport io.micronaut.core.convert.ConversionService;\nimport io.micronaut.http.MutableHttpHeaders;\nimport io.netty.handler.codec.http.DefaultHttpHeaders;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\n/**\n * Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}.\n *\n * @author Graeme Rocher\n * @since 1.0\n */\n@Internal\npublic class NettyHttpHeaders implements MutableHttpHeaders {\n\n io.netty.handler.codec.http.HttpHeaders nettyHeaders;\n final ConversionService conversionService;\n\n /**\n * @param nettyHeaders The Netty Http headers\n * @param conversionService The conversion service\n */\n public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) {\n this.nettyHeaders = nettyHeaders;\n this.conversionService = conversionService;\n }\n\n /**\n * Default constructor.\n */\n public NettyHttpHeaders() {\n // BUG: CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')\n // this.nettyHeaders = new DefaultHttpHeaders(false);\n // FIXED:\n this.nettyHeaders = new DefaultHttpHeaders();\n this.conversionService = ConversionService.SHARED;\n }\n\n /**\n * @return The underlying Netty headers.\n */\n public io.netty.handler.codec.http.HttpHeaders getNettyHeaders() {\n return nettyHeaders;\n }\n\n /**\n * Sets the underlying netty headers.\n *\n * @param headers The Netty http headers\n */\n void setNettyHeaders(io.netty.handler.codec.http.HttpHeaders headers) {\n this.nettyHeaders = headers;\n }\n\n @Override\n public Optional get(CharSequence name, ArgumentConversionContext conversionContext) {\n List values = nettyHeaders.getAll(name);\n if (values.size() > 0) {\n if (values.size() == 1 || !isCollectionOrArray(conversionContext.getArgument().getType())) {\n return conversionService.convert(values.get(0), conversionContext);\n } else {\n return conversionService.convert(values, conversionContext);\n }\n }\n return Optional.empty();\n }\n\n private boolean isCollectionOrArray(Class clazz) {\n return clazz.isArray() || Collection.class.isAssignableFrom(cla<|endoftext|>"} -{"language": "java", "text": "furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerSwingArmPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerBoatPacket;\nimport com.nukkitx.protocol.bedrock.packet.AnimatePacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = AnimatePacket.class)\npublic class BedrockAnimateTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(AnimatePacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, AnimatePacket packet) {\n // Stop the player sending animations before they have fully spawned into the server\n if (!session.isSpawned()) {\n return;\n }\n\n switch (packet.getAction()) {\n case SWING_ARM:\n // Delay so entity damage can be processed first\n session.scheduleInEventLoop(() ->\n session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),\n 25,\n TimeUnit.MILLISECONDS\n );\n break;\n // These two might need to be flipped, but my recommendation is getting moving working first\n case ROW_LEFT:\n // Packet value is a float of how long one has been rowing, so we convert that into a boolean\n session.setSteeringLeft(packet.getRowingTime() > 0.0);\n ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());\n session.sendDownstreamPacket(steerLeftPacket);\n break;\n case ROW_RIGHT:\n session.setSteeringRight(packet.getRowingTime() > 0.0);\n ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());\n session.sendDownstreamPacket(steerRightPacket);\n break;\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "ranslatorRegistry() {\n }\n\n public static void init() {\n // no-op\n }\n\n @SuppressWarnings(\"unchecked\")\n public

boolean translate(Class clazz, P packet, GeyserSession session) {\n if (!session.getUpstream().isClosed() && !session.isClosed()) {\n PacketTranslator

translator = (PacketTranslator

) translators.get(clazz);\n if (translator != null) {\n EventLoop eventLoop = session.getEventLoop();\n if (eventLoop.inEventLoop()) {\n translate0(session, translator, packet);\n } else {\n eventLoop.execute(() -> translate0(session, translator, packet));\n }\n return true;\n } else {\n if ((GeyserConnector.getInstance().getPlatformType() != PlatformType.STANDALONE || !(packet instanceof BedrockPacket)) && !IGNORED_PACKETS.contains(clazz)) {\n // Other debug logs already take care of Bedrock packets for us if on standalone\n GeyserConnector.getInstance().getLogger().debug(\"Could not find packet for \" + (packet.toString().length() > 25 ? packet.getClass().getSimpleName() : packet));\n }\n }\n }\n return false;\n }\n\n private

void translate0(GeyserSession session, PacketTranslator

translator, P packet) {\n if (session.isClosed()) {\n return;\n }\n\n try {\n // BUG: CWE-287 Improper Authentication\n // translator.translate(packet, session);\n // FIXED:\n translator.translate(session, packet);\n } catch (Throwable ex) {\n GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog(\"geyser.network.translator.packet.failed\", packet.getClass().getSimpleName()), ex);\n ex.printStackTrace();\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock.entity;\n\nimport com.github.steveice10.mc.protocol.data.game.window.VillagerTrade;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientSelectTradePacket;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityData;\nimport com.nukkitx.protocol.bedrock.packet.EntityEventPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.inventory.GeyserItemStack;\nimport org.geysermc.connector.inventory.Inventory;\nimport org.geysermc.connector.inventory.MerchantContainer;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = EntityEventPacket.class)\npublic class BedrockEntityEventTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(EntityEventPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, EntityEventPacket packet) {\n switch (packet.getType()) {\n case EATING_ITEM:\n // Resend the packet so we get the eating sounds\n session.sendUpstreamPacket(packet);\n return;\n case COMPLETE_TRADE:\n ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());\n session.sendDownstreamPacket(selectTradePacket);\n\n session.scheduleInEventLoop(() -> {\n Entity villager = session.getPlayerEntity();\n Inventory openInventory = session.getOpenInventory();\n if (openInventory instanceof MerchantContainer) {\n MerchantContainer merchantInventory = (MerchantContainer) openInventory;\n VillagerTrade[] trades = merchantInventory.getVillagerTrades();\n if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {\n VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];\n openInventory.setItem(2<|endoftext|>"} -{"language": "java", "text": "ed {\n\n\t\t// min and max of all coord\n\t\tprivate final MinMax minMax;\n\n\t\tpublic Drawing(MinMax minMax) {\n\t\t\tthis.minMax = minMax;\n\t\t}\n\n\t\tpublic void drawU(UGraphic ug) {\n\t\t\tdrawAllClusters(ug);\n\t\t\tdrawAllNodes(ug);\n\t\t\tdrawAllEdges(ug);\n\t\t}\n\n\t\tprivate void drawAllClusters(UGraphic ug) {\n\t\t\tfor (Entry ent : clusters.entrySet())\n\t\t\t\tdrawSingleCluster(ug, ent.getKey(), ent.getValue());\n\n\t\t}\n\n\t\tprivate void drawAllNodes(UGraphic ug) {\n\t\t\tfor (Entry ent : nodes.entrySet())\n\t\t\t\tdrawSingleNode(ug, ent.getKey(), ent.getValue());\n\n\t\t}\n\n\t\tprivate void drawAllEdges(UGraphic ug) {\n\t\t\tfor (Entry ent : edges.entrySet()) {\n\t\t\t\tfinal Link link = ent.getKey();\n\t\t\t\tif (link.isInvis())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdrawSingleEdge(ug, link, ent.getValue());\n\t\t\t}\n\t\t}\n\n\t\tprivate void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {\n\t\t\tfinal Point2D corner = getPosition(elkNode);\n\t\t\tfinal URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());\n\n\t\t\tPackageStyle packageStyle = group.getPackageStyle();\n\t\t\tfinal ISkinParam skinParam = diagram.getSkinParam();\n\t\t\tif (packageStyle == null)\n\t\t\t\tpackageStyle = skinParam.packageStyle();\n\n\t\t\tfinal UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();\n\n\t\t\tfinal Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())\n\t\t\t\t\t.getMergedStyle(skinParam.getCurrentStyleBuilder());\n\t\t\tfinal double shadowing = style.value(PName.Shadowing).asDouble();\n\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t// final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);\n\t\t\t// FIXED: \n\t\t\tfinal UStroke stroke = Cluster.getStrokeInternal(group, style);\n\n\t\t\tHColor backColor = getBackColor(umlDiagramType);\n\t\t\tbackColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),\n\t\t\t\t\tgroup.getUSymbol());\n\n\t\t\tfinal double roundCorner = group.getUSymbol() == null ? 0\n\t\t\t\t\t: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());\n\n\t\t\tfinal TextBlock ztitle = getTitleBlock(group);\n\t\t\tfinal TextBlock zstereo = TextBlockUtils.empty(0, 0);\n\n\t\t\tfinal ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,\n\t\t\t\t\tzstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);\n\n\t\t\tfinal HColor borderColor = HColorUtils.BLACK;\n\t\t\tdecoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,\n\t\t\t\t\tskinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),\n\t\t\t\t\tskinParam.getStereotypeAlignment(), 0);\n\n//\t\t\t// Print a simple rectangle right now\n//\t\t\tug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);\n\t\t}\n\n\t\tprivate TextBlock getTitleBlock(IGroup g) {\n\t\t\tfinal Display<|endoftext|>"} -{"language": "java", "text": "brary; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n * USA.\n *\n *\n * Original Author: Arnaud Roques\n *\n *\n */\npackage net.sourceforge.plantuml.style;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nclass Context {\n\n\tprivate final List data = new ArrayList();\n\n\tpublic Context push(String newString) {\n\t\tfinal Context result = new Context();\n\t\tresult.data.addAll(this.data);\n\t\tresult.data.add(newString);\n\t\treturn result;\n\t}\n\n\tpublic Context pop() {\n\t\tif (size() == 0)\n\t\t\tthrow new IllegalStateException();\n\t\tfinal Context result = new Context();\n\t\tresult.data.addAll(this.data.subList(0, this.data.size() - 1));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn data.toString();\n\t}\n\n\tpublic int size() {\n\t\treturn data.size();\n\t}\n\n\tpublic Collection toSignatures() {\n\t\tList results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));\n\t\tboolean star = false;\n\t\tfor (Iterator it = data.iterator(); it.hasNext();) {\n\t\t\tString s = it.next();\n\t\t\tif (s.endsWith(\"*\")) {\n\t\t\t\tstar = true;\n\t\t\t\ts = s.substring(0, s.length() - 1);\n\t\t\t}\n\t\t\tfinal String[] names = s.split(\",\");\n\t\t\tfinal List tmp = new ArrayList<>();\n\t\t\tfor (StyleSignatureBasic ss : results)\n\t\t\t\tfor (String name : names)\n\t\t\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t\t\t// tmp.add(ss.add(name));\n\t\t\t\t// FIXED: \n\t\t\t\t\ttmp.add(ss.add(name.trim()));\n\t\t\tresults = tmp;\n\t\t}\n\n\t\tif (star)\n\t\t\tfor (ListIterator it = results.listIterator(); it.hasNext();) {\n\t\t\t\tfinal StyleSignatureBasic tmp = it.next().addStar();\n\t\t\t\tit.set(tmp);\n\t\t\t}\n\n\t\treturn Collections.unmodifiableCollection(results);\n\t}\n\n}<|endoftext|>"} -{"language": "java", "text": "ESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerVehiclePacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;\nimport com.nukkitx.math.vector.Vector3f;\nimport com.nukkitx.protocol.bedrock.data.entity.EntityData;\nimport com.nukkitx.protocol.bedrock.packet.PlayerInputPacket;\nimport org.geysermc.connector.entity.BoatEntity;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;\nimport org.geysermc.connector.entity.living.animal.horse.LlamaEntity;\nimport org.geysermc.connector.entity.type.EntityType;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n/**\n * Sent by the client for minecarts and boats.\n */\n@Translator(packet = PlayerInputPacket.class)\npublic class BedrockPlayerInputTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PlayerInputPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PlayerInputPacket packet) {\n ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket(\n packet.getInputMotion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking()\n );\n\n session.sendDownstreamPacket(clientSteerVehiclePacket);\n\n // Bedrock only sends movement vehicle packets while moving\n // This allows horses to take damage while standing on magma\n Entity vehicle = session.getRidingVehicleEntity();\n boolean sendMovement = false;\n if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) {\n sendMovement = vehicle.isOnGround();\n } else if (vehicle instanceof BoatEntity) {\n if (vehicle.getPassengers().size() == 1) {\n // The player is the only rider\n sendMovement = true;\n } else {\n // Check if the player is the front rider\n Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null);\n if (seatPos != null && seatPos.getX() > 0) {\n <|endoftext|>"} -{"language": "java", "text": ", subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock.entity.player;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;\nimport com.nukkitx.protocol.bedrock.packet.RiderJumpPacket;\nimport org.geysermc.connector.entity.Entity;\nimport org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\n\n@Translator(packet = RiderJumpPacket.class)\npublic class BedrockRiderJumpTranslator extends PacketTranslator {\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(RiderJumpPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, RiderJumpPacket packet) {\n Entity vehicle = session.getRidingVehicleEntity();\n if (vehicle instanceof AbstractHorseEntity) {\n ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength());\n session.sendDownstreamPacket(playerStatePacket);\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": " IOException>() {\n public FilePath call() throws IOException {\n final File hprof = File.createTempFile(\"hudson-heapdump\", \"hprof\");\n hprof.delete();\n try {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n server.invoke(new ObjectName(\"com.sun.management:type=HotSpotDiagnostic\"), \"dumpHeap\",\n new Object[]{hprof.getAbsolutePath(), true}, new String[]{String.class.getName(), boolean.class.getName()});\n\n return new FilePath(hprof);\n } catch (JMException e) {\n throw new IOException2(e);\n }\n }\n\n private static final long serialVersionUID = 1L;\n });\n }\n\n /**\n * Heap dump, exposable to URL via Stapler.\n *\n */\n public static class HeapDump {\n private final AccessControlled owner;\n private final VirtualChannel channel;\n\n public HeapDump(AccessControlled owner, VirtualChannel channel) {\n this.owner = owner;\n this.channel = channel;\n }\n\n /**\n * Obtains the heap dump.\n */\n public void doIndex(StaplerResponse rsp) throws IOException {\n rsp.sendRedirect(\"heapdump.hprof\");\n }\n\n @WebMethod(name=\"heapdump.hprof\")\n public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {\n // BUG: CWE-264 Permissions, Privileges, and Access Controls\n // owner.checkPermission(Jenkins.ADMINISTER);\n // FIXED:\n owner.checkPermission(Jenkins.RUN_SCRIPTS);\n rsp.setContentType(\"application/octet-stream\");\n\n FilePath dump = obtain();\n try {\n dump.copyTo(rsp.getCompressedOutputStream(req));\n } finally {\n dump.delete();\n }\n }\n\n public FilePath obtain() throws IOException, InterruptedException {\n return RemotingDiagnostics.getHeapDump(channel);\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "FTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.github.steveice10.mc.protocol.data.game.entity.player.Hand;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerChangeHeldItemPacket;\nimport com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;\nimport com.nukkitx.protocol.bedrock.data.inventory.ContainerId;\nimport com.nukkitx.protocol.bedrock.packet.MobEquipmentPacket;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.CooldownUtils;\nimport org.geysermc.connector.utils.InteractiveTagManager;\n\nimport java.util.concurrent.TimeUnit;\n\n@Translator(packet = MobEquipmentPacket.class)\npublic class BedrockMobEquipmentTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(MobEquipmentPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, MobEquipmentPacket packet) {\n if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||\n packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {\n // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention\n return;\n }\n\n // Send book update before switching hotbar slot\n session.getBookEditCache().checkForSend();\n\n session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());\n\n ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());\n session.sendDownstreamPacket(changeHeldItemPacket);\n\n if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {\n // Activate shield since we are already sneaking\n // (No need to send a release item packet - Java doesn't do this when swapping items)\n // Require<|endoftext|>"} -{"language": "java", "text": "obtain a copy of the License at the\n * Apache homepage\n *

\n * Unless required by applicable law or agreed to in writing,
\n * software distributed under the License is distributed on an \"AS IS\" BASIS,
\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\n * See the License for the specific language governing permissions and
\n * limitations under the License.\n *

\n * Initial code contributed and copyrighted by
\n * frentix GmbH, http://www.frentix.com\n *

\n */\npackage org.olat.core.commons.services.license.manager;\n\nimport org.olat.core.commons.services.license.License;\nimport org.olat.core.commons.services.license.model.LicenseImpl;\nimport org.olat.core.commons.services.license.model.LicenseTypeImpl;\nimport org.olat.core.commons.services.license.model.ResourceLicenseImpl;\nimport org.apache.logging.log4j.Logger;\nimport org.olat.core.logging.Tracing;\nimport org.olat.core.util.StringHelper;\nimport org.olat.core.util.xml.XStreamHelper;\nimport org.springframework.stereotype.Component;\n\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * \n * Initial date: 16.03.2018
\n * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com\n *\n */\n@Component\nclass LicenseXStreamHelper {\n\t\n\tprivate static final Logger log = Tracing.createLoggerFor(LicenseXStreamHelper.class);\n\t\n\tprivate static final XStream licenseXStream = XStreamHelper.createXStreamInstanceForDBObjects();\n\tstatic {\n\t\t// BUG: CWE-91 XML Injection (aka Blind XPath Injection)\n\t\t// \n\t\t// FIXED: \n\t\tXStreamHelper.allowDefaultPackage(licenseXStream);\n\t\tlicenseXStream.alias(\"license\", LicenseImpl.class);\n\t\tlicenseXStream.alias(\"license\", ResourceLicenseImpl.class);\n\t\tlicenseXStream.alias(\"licenseType\", LicenseTypeImpl.class);\n\t\tlicenseXStream.ignoreUnknownElements();\n\t\tlicenseXStream.omitField(LicenseImpl.class, \"creationDate\");\n\t\tlicenseXStream.omitField(LicenseImpl.class, \"lastModified\");\n\t\tlicenseXStream.omitField(ResourceLicenseImpl.class, \"creationDate\");\n\t\tlicenseXStream.omitField(ResourceLicenseImpl.class, \"lastModified\");\n\t\tlicenseXStream.omitField(LicenseTypeImpl.class, \"creationDate\");\n\t\tlicenseXStream.omitField(LicenseTypeImpl.class, \"lastModified\");\n\t}\n\t\n\tString toXml(License license) {\n\t\tif (license == null) return null;\n\n\t\treturn licenseXStream.toXML(license);\n\t}\n\t\n\tLicense licenseFromXml(String xml) {\n\t\tLicense license = null;\n\t\tif(StringHelper.containsNonWhitespace(xml)) {\n\t\t\ttry {\n\t\t\t\tObject obj = licenseXStream.fromXML(xml);\n\t\t\t\tif(obj instanceof License) {\n\t\t\t\t\tlicense = (License) obj;\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"\", e);\n\t\t\t}\n\t\t}\n\t\treturn license;\n\t}\n\t\n}\n<|endoftext|>"} -{"language": "java", "text": "StyleLoader.class.getResourceAsStream(\"/skin/strictuml.skin\");\n\t\t\tfinal StyleBuilder styleBuilder = this.getCurrentStyleBuilder();\n\t\t\ttry {\n\t\t\t\tfinal BlocLines lines = BlocLines.load(internalIs, null);\n\t\t\t\tfor (Style modifiedStyle : StyleLoader.getDeclaredStyles(lines, styleBuilder))\n\t\t\t\t\tthis.muteStyle(modifiedStyle);\n\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void applyPendingStyleMigration() {\n\t\tfor (Entry ent : paramsPendingForStyleMigration.entrySet()) {\n\t\t\tfinal FromSkinparamToStyle convertor = new FromSkinparamToStyle(ent.getKey());\n\t\t\tconvertor.convertNow(ent.getValue(), getCurrentStyleBuilder());\n\t\t\tfor (Style style : convertor.getStyles())\n\t\t\t\tmuteStyle(style);\n\t\t}\n\t\tparamsPendingForStyleMigration.clear();\n\t}\n\n\tpublic static SkinParam create(UmlDiagramType type, ThemeStyle style) {\n\t\treturn new SkinParam(type, style);\n\t}\n\n\tpublic static SkinParam noShadowing(UmlDiagramType type, ThemeStyle style) {\n\t\tfinal SkinParam result = new SkinParam(type, style);\n\t\tresult.setParam(\"shadowing\", \"false\");\n\t\treturn result;\n\t}\n\n\tprivate final Map> cacheCleanForKey = new HashMap>();\n\n\tList cleanForKey(String key) {\n\t\tList result = cacheCleanForKey.get(key);\n\t\tif (result == null) {\n\t\t\tresult = cleanForKeySlow(key);\n\t\t\tcacheCleanForKey.put(key, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tList cleanForKeySlow(String key) {\n\t\tkey = StringUtils.trin(StringUtils.goLowerCase(key));\n\t\t// BUG: CWE-918 Server-Side Request Forgery (SSRF)\n\t\t// key = key.replaceAll(\"_|\\\\.|\\\\s\", \"\");\n\t\t// FIXED: \n\t\tkey = key.replaceAll(\"_|\\\\.\", \"\");\n\t\t// key = replaceSmart(key, \"partition\", \"package\");\n\t\tkey = replaceSmart(key, \"sequenceparticipant\", \"participant\");\n\t\tkey = replaceSmart(key, \"sequenceactor\", \"actor\");\n\t\tkey = key.replaceAll(\"activityarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"objectarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"classarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"componentarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"statearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"usecasearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"sequencearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"align$\", \"alignment\");\n\t\tfinal Matcher2 mm = stereoPattern.matcher(key);\n\t\tfinal List result = new ArrayList<>();\n\t\twhile (mm.find()) {\n\t\t\tfinal String s = mm.group(1);\n\t\t\tresult.add(key.replaceAll(stereoPatternString, \"\") + \"<<\" + s + \">>\");\n\t\t}\n\t\tif (result.size() == 0)\n\t\t\tresult.add(key);\n\n\t\treturn Collections.unmodifiableList(result);\n\t}\n\n\tprivate static String replaceSmart(String s, String src, String target) {\n\t\tif (s.contains(src) == false) {\n\t\t\treturn s;\n\t\t}\n\t\treturn s.replaceAll(src, target);\n\t}\n\n\tpublic HColor getHyperlinkColor() {\n\t\tfinal HColor result = getHtmlColor(ColorParam.hyperlink, null, false<|endoftext|>"} -{"language": "java", "text": "/*\n * Copyright 2019 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage cd.go.authentication.ldap;\n\nimport cd.go.authentication.ldap.mapper.Mapper;\n\nimport javax.naming.NamingException;\nimport java.util.List;\n\npublic interface LdapClient {\n T authenticate(String username, String password, Mapper mapper);\n // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')\n // List search(String userSearchFilter, Object[] filterArgs, Mapper mapper, int maxResult);\n // FIXED:\n List search(String userSearchFilter, String[] filterArgs, Mapper mapper, int maxResult);\n\n void validate() throws NamingException;\n}\n<|endoftext|>"} -{"language": "java", "text": "he Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @author GeyserMC\n * @link https://github.com/GeyserMC/Geyser\n */\n\npackage org.geysermc.connector.network.translators.bedrock;\n\nimport com.nukkitx.nbt.NbtMap;\nimport com.nukkitx.nbt.NbtMapBuilder;\nimport com.nukkitx.nbt.NbtType;\nimport com.nukkitx.protocol.bedrock.packet.PositionTrackingDBClientRequestPacket;\nimport com.nukkitx.protocol.bedrock.packet.PositionTrackingDBServerBroadcastPacket;\nimport it.unimi.dsi.fastutil.ints.IntArrayList;\nimport it.unimi.dsi.fastutil.ints.IntList;\nimport org.geysermc.connector.network.session.GeyserSession;\nimport org.geysermc.connector.network.translators.PacketTranslator;\nimport org.geysermc.connector.network.translators.Translator;\nimport org.geysermc.connector.utils.DimensionUtils;\nimport org.geysermc.connector.utils.LoadstoneTracker;\n\n@Translator(packet = PositionTrackingDBClientRequestPacket.class)\npublic class BedrockPositionTrackingDBClientRequestTranslator extends PacketTranslator {\n\n @Override\n // BUG: CWE-287 Improper Authentication\n // public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {\n // FIXED: \n public void translate(GeyserSession session, PositionTrackingDBClientRequestPacket packet) {\n PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket();\n broadcastPacket.setTrackingId(packet.getTrackingId());\n\n // Fetch the stored Loadstone\n LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());\n\n // If we don't have data for that ID tell the client its not found\n if (pos == null) {\n broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);\n session.sendUpstreamPacket(broadcastPacket);\n return;\n }\n\n broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);\n\n // Build the nbt data for the update\n NbtMapBuilder builder = NbtMap.builder();\n builder.putInt(\"dim\", DimensionUtils.javaToBedrock(pos.getDimension()));\n builder.putString(\"id\", String.format(\"%08X\", packet.getTrackingId()));\n\n builder.putByte(\"version\", (byte) 1); // Not sure what this is for\n builder.putByte(\"status\", (byte) 0); // Not sure what this is for\n\n // Build the position for the update\n IntList posList = new IntArrayList();\n posList.add(pos.getX());\n posList.add(pos.getY());\n posList.add(pos.getZ());\n builder.putList(\"pos\", NbtType.INT, posList);\n broadcastPacket.setTag(builder.build());\n\n session.sendUpstreamPacket(broadcastPacket);\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "package eu.nimble.utility.validation;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport eu.nimble.utility.JsonSerializationUtility;\nimport eu.nimble.utility.exception.AuthenticationException;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jwts;\nimport org.apache.commons.codec.binary.Base64;\nimport org.jose4j.keys.RsaKeyUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Component;\n\nimport java.io.IOException;\nimport java.security.PublicKey;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Created by suat on 02-Sep-19.\n */\n@Component\n@Profile(\"!test\")\npublic class ValidationUtil implements IValidationUtil {\n private static final Logger logger = LoggerFactory.getLogger(ValidationUtil.class);\n\n @Value(\"${nimble.keycloak.public-key}\")\n private String keycloakPublicKey;\n\n public Claims validateToken(String token) throws AuthenticationException {\n try {\n RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();\n PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);\n // BUG: CWE-290 Authentication Bypass by Spoofing\n // return (Claims) Jwts.parser().setSigningKey(publicKey).parse(token.replace(\"Bearer \", \"\")).getBody();\n // FIXED: \n return Jwts.parser().setSigningKey(publicKey).parseJws(token.replace(\"Bearer \", \"\")).getBody();\n } catch (Exception e){\n throw new AuthenticationException(String.format(\"Failed to check user authorization for token: %s\", token), e);\n }\n }\n\n public boolean validateRole(String token,List userRoles, NimbleRole[] requiredRoles) {\n for (NimbleRole requiredRole : requiredRoles) {\n for (String userRole : userRoles) {\n if (userRole.contentEquals(requiredRole.getName())) {\n return true;\n }\n }\n }\n logger.warn(\"Token: {} does not include one of the roles: {}\",token,\n Arrays.asList(requiredRoles).stream().map(role -> role.getName()).collect(Collectors.joining(\", \",\"[\",\"]\")));\n return false;\n }\n\n public Claims getClaims(String token) throws AuthenticationException {\n try {\n String[] split_string = token.split(\"\\\\.\");\n String base64EncodedBody = split_string[1];\n\n Base64 base64Url = new Base64(true);\n String body = new String(base64Url.decode(base64EncodedBody));\n\n Map map = JsonSerializationUtility.getObjectMapper().readValue(body,new TypeReference>() {\n });\n\n return Jwts.claims(map);\n } catch (IOException e) {\n throw new AuthenticationException(String.format(\"Failed to get Claims for token: %s\", token), e);\n }\n }\n}\n<|endoftext|>"} -{"language": "java", "text": ",data.value});\n\t\t}\n\t}\n\n\t\n\t@Override\n\tpublic Date getLastModified(ResourceContext resourceContext) {\n\t\tUriData data = (UriData) restoreData(resourceContext);\n\t\tFacesContext facesContext = FacesContext.getCurrentInstance();\n\t\tif (null != data && null != facesContext ) {\n\t\t\t// Send headers\n\t\t\tELContext elContext = facesContext.getELContext();\n\t\t\tif(data.modified != null){\n\t\t\tValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);\n\t\t\tDate modified = (Date) binding.getValue(elContext);\n\t\t\tif (null != modified) {\n\t\t\t\treturn modified;\n\t\t\t}\n\t\t}\n\t\t}\n\t\treturn super.getLastModified(resourceContext);\n\t}\n\t\n\t\n\t@Override\n\tpublic long getExpired(ResourceContext resourceContext) {\n\t\tUriData data = (UriData) restoreData(resourceContext);\n\t\tFacesContext facesContext = FacesContext.getCurrentInstance();\n\t\tif (null != data && null != facesContext ) {\n\t\t\t// Send headers\n\t\t\tELContext elContext = facesContext.getELContext();\n\t\t\tif(data.expires != null){\n\t\t\tValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);\n\t\t\tDate expires = (Date) binding.getValue(elContext);\n\t\t\tif (null != expires) {\n\t\t\t\treturn expires.getTime()-System.currentTimeMillis();\n\t\t\t}\n\t\t}\n\t\t}\n\t\treturn super.getExpired(resourceContext);\n\t}\n\t/* (non-Javadoc)\n\t * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()\n\t */\n\tpublic boolean requireFacesContext() {\n\t\t// TODO Auto-generated method stub\n\t\treturn true;\n\t}\n\t// BUG: CWE-502 Deserialization of Untrusted Data\n\t// public static class UriData implements Serializable {\n\t// FIXED: \n\tpublic static class UriData implements SerializableResource {\n\n\t\t/**\n\t\t * \n\t\t */\n\t\tprivate static final long serialVersionUID = 1258987L;\n\t\t\n\t\tprivate Object value;\n\t\t\n\t\tprivate Object createContent;\n\t\t\n\t\tprivate Object expires;\n\t\t\n\t\tprivate Object modified;\n\t}\n\n}\n<|endoftext|>"} -{"language": "java", "text": "tArchive, rows);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogError(\"\", e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void copyUploadFile(BulkAssessmentDatas datas, File uploadedFile, List rows) throws IOException {\n\t\ttry(FileInputStream inStream = new FileInputStream(uploadedFile)) {\n\t\t\tif(VFSManager.copyContent(inStream, targetArchive)) {\n\t\t\t\tdatas.setReturnFiles(targetArchive.getRelPath());\n\t\t\t\tprocessReturnFiles(targetArchive, rows);\n\t\t\t}\n\t\t} catch(IOException e) {\n\t\t\tlogError(\"\", e);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tprivate boolean isSame(VFSItem currentTarget, File uploadedFile) {\n\t\tif(currentTarget instanceof LocalImpl) {\n\t\t\tLocalImpl local = (LocalImpl)currentTarget;\n\t\t\tFile currentFile = local.getBasefile();\n\t\t\tif(currentFile.length() == uploadedFile.length()) {\n\t\t\t\ttry {\n\t\t\t\t\treturn org.apache.commons.io.FileUtils.contentEquals(currentFile, uploadedFile);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogError(\"\", e);\n\t\t\t\t\t//do nothing -> return false at the end\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate void processReturnFiles(VFSLeaf target, List rows) {\n\t\tMap assessedIdToRow = new HashMap<>();\n\t\tfor(BulkAssessmentRow row:rows) {\n\t\t\tassessedIdToRow.put(row.getAssessedId(), row);\n\t\t}\n\n\t\tif(target.exists()) {\n\t\t\tFile parentTarget = ((LocalImpl)target).getBasefile().getParentFile();\n\n\t\t\tZipEntry entry;\n\t\t\ttry(InputStream is = target.getInputStream();\n\t\t\t\t\tZipInputStream zis = new ZipInputStream(is)) {\n\t\t\t\tbyte[] b = new byte[FileUtils.BSIZE];\n\t\t\t\t// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n\t\t\t\t// while ((entry = zis.getNextEntry()) != null) {\n\t\t\t\t// FIXED:\n\t\t\t\twhile ((entry = zis.getNextEntry()) != null) {//TODO zip\n\t\t\t\t\tif(!entry.isDirectory()) {\n\t\t\t\t\t\twhile (zis.read(b) > 0) {\n\t\t\t\t\t\t\t//continue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tPath op = new File(parentTarget, entry.getName()).toPath();\n\t\t\t\t\t\tif(!Files.isHidden(op) && !op.toFile().isDirectory()) {\n\t\t\t\t\t\t\tPath parentDir = op.getParent();\n\t\t\t\t\t\t\tString assessedId = parentDir.getFileName().toString();\n\t\t\t\t\t\t\tString filename = op.getFileName().toString();\n\n\t\t\t\t\t\t\tBulkAssessmentRow row;\n\t\t\t\t\t\t\tif(assessedIdToRow.containsKey(assessedId)) {\n\t\t\t\t\t\t\t\trow = assessedIdToRow.get(assessedId);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\trow = new BulkAssessmentRow();\n\t\t\t\t\t\t\t\trow.setAssessedId(assessedId);\n\t\t\t\t\t\t\t\tassessedIdToRow.put(assessedId, row);\n\t\t\t\t\t\t\t\trows.add(row);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(row.getReturnFiles() == null) {\n\t\t\t\t\t\t\t\trow.setReturnFiles(new ArrayList(2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow.getReturnFiles().add(filename);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch(Exception e) {\n\t\t\t\tlogError(\"\", e);\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} -{"language": "java", "text": " if ((languagetoedit == null) || (languagetoedit.equals(\"default\"))) {\n languagetoedit = \"\";\n }\n if (doc.isNew() || (doc.getDefaultLanguage().equals(languagetoedit))) {\n languagetoedit = \"\";\n }\n\n if (languagetoedit.equals(\"\")) {\n // In this case the created document is going to be the default document\n tdoc = doc;\n context.put(\"tdoc\", doc);\n if (doc.isNew()) {\n doc.setDefaultLanguage(language);\n doc.setLanguage(\"\");\n }\n } else {\n // If the translated doc object is the same as the doc object\n // this means the translated doc did not exists so we need to create it\n if ((tdoc == doc)) {\n tdoc = new XWikiDocument(doc.getDocumentReference());\n tdoc.setLanguage(languagetoedit);\n tdoc.setContent(doc.getContent());\n tdoc.setSyntax(doc.getSyntax());\n tdoc.setAuthor(context.getUser());\n tdoc.setStore(doc.getStore());\n context.put(\"tdoc\", tdoc);\n }\n }\n\n XWikiDocument tdoc2 = tdoc.clone();\n if (content != null && !content.isEmpty()) {\n tdoc2.setContent(content);\n }\n context.put(\"tdoc\", tdoc2);\n try {\n // BUG: CWE-862 Missing Authorization\n // tdoc2.readFromTemplate(peform, context);\n // FIXED: \n readFromTemplate(tdoc2, peform.getTemplate(), context);\n } catch (XWikiException e) {\n if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) {\n context.put(\"exception\", e);\n return \"docalreadyexists\";\n }\n }\n\n /* Setup a lock */\n try {\n XWikiLock lock = tdoc.getLock(context);\n if ((lock == null) || (lock.getUserName().equals(context.getUser())) || (peform.isLockForce())) {\n tdoc.setLock(context.getUser(), context);\n }\n } catch (Exception e) {\n // Lock should never make XWiki fail\n // But we should log any related information\n LOGGER.error(\"Exception while setting up lock\", e);\n }\n }\n\n return \"admin\";\n }\n}\n<|endoftext|>"} -{"language": "java", "text": "cmpile(\"^[:]?(\" + KEYNAMES + \")([%s]+\\\\*)?[%s]*\\\\{$\");\n\tprivate final static Pattern2 propertyAndValue = MyPattern.cmpile(\"^([\\\\w]+):?[%s]+(.*?);?$\");\n\tprivate final static Pattern2 closeBracket = MyPattern.cmpile(\"^\\\\}$\");\n\n\tpublic static Collection