code
stringlengths
23
2.05k
label_name
stringlengths
6
7
label
int64
0
37
def setup_logging(): """Configure the python logging appropriately for the tests. (Logs will end up in _trial_temp.) """ root_logger = logging.getLogger() log_format = ( "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s" " - %(message)s" ) handler = ToTwistedHandler() ...
CWE-20
0
def auth_role_public(self): return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
CWE-287
4
def process_response(self, request, response, spider): if ( request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', []) or response.status in request.meta.get('handle_httpstatus_list', []) or request.meta.get('h...
CWE-863
11
def test_magic_response2(): # check 'body' handling and another 'headers' format mw = _get_mw() req = SplashRequest('http://example.com/', magic_response=True, headers={'foo': 'bar'}, dont_send_headers=True) req = mw.process_request(req, None) assert 'headers' not in req.meta...
CWE-200
10
def test_basic_two_credentials(): # Test Basic Authentication with multiple sets of credentials http = httplib2.Http() password1 = tests.gen_password() password2 = tests.gen_password() allowed = [("joe", password1)] # exploit shared mutable list handler = tests.http_reflect_with_auth( a...
CWE-400
2
def _checkPolkitPrivilege(self, sender, conn, privilege): # from jockey """ Verify that sender has a given PolicyKit privilege. sender is the sender's (private) D-BUS name, such as ":1:42" (sender_keyword in @dbus.service.methods). conn is the dbus.Connection object ...
CWE-362
18
def test_open_with_filename(self): tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] del fp os.unlink(tmpname)
CWE-20
0
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = ( "Basic " + base64.b64encode("%s:%s" % self.credentials).strip() )
CWE-400
2
def auth_role_admin(self): return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
CWE-287
4
def _on_ssl_errors(self, error): self._has_ssl_errors = True url = error.url() log.webview.debug("Certificate error: {}".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abort_questio...
CWE-684
35
def CreateAuthenticator(): """Create a packet autenticator. All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm. This function returns a suitable random string that can be used as an...
CWE-330
12
def parse_json(raw_data): ''' this version for module return data only ''' orig_data = raw_data # ignore stuff like tcgetattr spewage or other warnings data = filter_leading_non_json_lines(raw_data) try: return json.loads(data) except: # not JSON, but try "Baby JSON" which all...
CWE-20
0
def to_xml(self, data, options=None): """ Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, ...
CWE-20
0
def auth_ldap_use_tls(self): return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"]
CWE-287
4
async def on_exchange_third_party_invite_request( self, room_id: str, event_dict: JsonDict
CWE-400
2
def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. m = re.search(r'((\r\n|\r|\n)+) *$', token.value) if m is not None: return sql.Token(T.Whitespace.New...
CWE-400
2
def read_requirements(name): project_root = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(project_root, name), 'rb') as f: # remove whitespace and comments g = (line.decode('utf-8').lstrip().split('#', 1)[0].rstrip() for line in f) return [l for l in g if l]
CWE-400
2
def delete(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: # We request the manifest for the object. If one exists, # that means the object was uploaded in chunks/segm...
CWE-200
10
def _decompressContent(response, new_content): content = new_content try: encoding = response.get("content-encoding", None) if encoding in ["gzip", "deflate"]: if encoding == "gzip": content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read() if...
CWE-400
2
def readBodyToFile( response: IResponse, stream: BinaryIO, max_size: Optional[int]
CWE-400
2
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IRnode]: ret = [] # the type of the calldata base_args_t = TupleType([arg.typ for arg in sig.base_args]) # tuple with the abi_encoded args if sig.is_init_func: base_args_ofst = IRnode(0, location=DATA, typ=base_a...
CWE-119
26
def MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt)
CWE-327
3
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType: if isinstance(typ, new.BoolDefinition): return old.BaseType("bool") if isinstance(typ, new.AddressDefinition): return old.BaseType("address") if isinstance(typ, new.InterfaceDefinition): return old.InterfaceType(typ._i...
CWE-119
26
def is_writable(dir): """Determine whether a given directory is writable in a portable manner. Parameters ---------- dir : str A string represeting a path to a directory on the filesystem. Returns ------- res : bool True or False. """ if not os.path.isdir(dir): ...
CWE-269
6
def _handle_carbon_received(self, msg): self.xmpp.event('carbon_received', msg)
CWE-346
16
def test_basic_lua(settings): class LuaScriptSpider(ResponseSpider): """ Make a request using a Lua script similar to the one from README """ def start_requests(self): yield SplashRequest(self.url + "#foo", endpoint='execute', args={'lua_source': DEFA...
CWE-200
10
def test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(TypeError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile: algo.prepare_key(keyfile.read()) with open(key_path("testkey_ed25519.pub"...
CWE-327
3
def get_ipcache_entry(self, client): """Build a cache of dns results.""" if client in self.ipcache: if self.ipcache[client]: return self.ipcache[client] else: raise socket.gaierror else: # need to add entry try: ...
CWE-20
0
def __init__( self, *, resource_group: str, location: str, application_name: str, owner: str, client_id: Optional[str], client_secret: Optional[str], app_zip: str, tools: str, instance_specific: str, third_party: str, ...
CWE-346
16
def serialize(self, bundle, format='application/json', options={}): """ Given some data and a format, calls the correct method to serialize the data and returns the result. """ desired_format = None for short_format, long_format in self.content_types.items():...
CWE-20
0
def cookies(self, jar: RequestsCookieJar): # <https://docs.python.org/3/library/cookielib.html#cookie-objects> stored_attrs = ['value', 'path', 'secure', 'expires'] self['cookies'] = {} for cookie in jar: self['cookies'][cookie.name] = { attname: getattr(c...
CWE-200
10
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """ if isinstance...
CWE-20
0
def test_slot_policy_scrapy_default(): mw = _get_mw() req = scrapy.Request("http://example.com", meta = {'splash': { 'slot_policy': scrapy_splash.SlotPolicy.SCRAPY_DEFAULT }}) req = mw.process_request(req, None) assert 'download_slot' not in req.meta
CWE-200
10
def stream_exists_backend(request, user_profile, stream_id, autosubscribe): # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse try: stream = get_and_validate_stream_by_id(stream_id, user_profile.realm) except JsonableError: stream = None result = {"exists": bool(stream)} i...
CWE-863
11
def test_basic(settings): items, url, crawler = yield crawl_items(ResponseSpider, HelloWorld, settings) assert len(items) == 1 resp = items[0]['response'] assert resp.url == url assert resp.css('body::text').extract_first().strip() == "hello world!"
CWE-200
10
async def on_GET(self, origin, content, query, context, user_id): content = await self.handler.on_make_leave_request(origin, context, user_id) return 200, content
CWE-400
2
def test_urlsplit_normalization(self): # Certain characters should never occur in the netloc, # including under normalization. # Ensure that ALL of them are detected and cause an error illegal_chars = '/:#?@' hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars} ...
CWE-522
19
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False): ''' return a configuration variable with casting ''' value = _get_config(p, section, key, env_var, default) if boolean: return mk_boolean(value) if value and integer: return int(value) if...
CWE-74
1
def delete_scans(request): context = {} if request.method == "POST": list_of_scan_id = [] for key, value in request.POST.items(): if key != "scan_history_table_length" and key != "csrfmiddlewaretoken": ScanHistory.objects.filter(id=value).delete() messages.ad...
CWE-330
12
def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): TITLE = 'original title' PROFILE_ID = u'snapshot-testing' site = self._makeSite(TITLE) tool = self._makeOne('setup_tool').__of__(site) registry = tool.getImportStepRegistry() registry.registerSt...
CWE-200
10
def test_create_catalog(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'c') assert_(cat is not None) cat.close() self.remove_dir(pardir)
CWE-269
6
def _expand_user_properties(self, template): # Make sure username and servername match the restrictions for DNS labels # Note: '-' is not in safe_chars, as it is being used as escape character safe_chars = set(string.ascii_lowercase + string.digits) # Set servername based on whether...
CWE-863
11
def _on_ssl_errors(self): self._has_ssl_errors = True
CWE-684
35
def auth_username_ci(self): return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
CWE-287
4
async def on_PUT(self, origin, content, query, context, event_id): # TODO(paul): assert that context/event_id parsed from path actually # match those given in content content = await self.handler.on_send_join_request(origin, content, context) return 200, (200, content)
CWE-400
2
def analyze(self, avc): import commands if avc.has_any_access_in(['execmod']): # MATCH if (commands.getstatusoutput("eu-readelf -d %s | fgrep -q TEXTREL" % avc.tpath)[0] == 1): return self.report(("unsafe")) mcon = selinux.matchpathcon(avc.tpath.s...
CWE-77
14
def get_mime_for_format(self, format): """ Given a format, attempts to determine the correct MIME type. If not available on the current ``Serializer``, returns ``application/json`` by default. """ try: return self.content_types[format] exc...
CWE-20
0
def to_html(self, data, options=None): """ Reserved for future usage. The desire is to provide HTML output of a resource, making an API available to a browser. This is on the TODO list but not currently implemented. """ options = options or {} ...
CWE-20
0
def read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False,
CWE-74
1
def CreateID(self): """Create a packet ID. All RADIUS requests have a ID which is used to identify a request. This is used to detect retries and replay attacks. This function returns a suitable random number that can be used as ID. :return: ID number :rtype: integer ...
CWE-330
12
def format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level (``datetime_formatting``) or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``). Default is ``iso-8601``, which looks like...
CWE-20
0
def _parse_www_authenticate(headers, headername="www-authenticate"): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headername in headers: try: authenticate = headers[headername].strip() www_auth = ( USE_WWW_AUTH_STRIC...
CWE-400
2
def verify(self, password, encoded): algorithm, data = encoded.split('$', 1) assert algorithm == self.algorithm bcrypt = self._load_library() # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None...
CWE-200
10
def make_sydent(test_config={}): """Create a new sydent Args: test_config (dict): any configuration variables for overriding the default sydent config """ # Use an in-memory SQLite database. Note that the database isn't cleaned up between # tests, so by default the same database...
CWE-20
0
def from_html(self, content): """ Reserved for future usage. The desire is to handle form-based (maybe Javascript?) input, making an API available to a browser. This is on the TODO list but not currently implemented. """ pass
CWE-20
0
def from_yaml(self, content): """ Given some YAML data, returns a Python dictionary of the decoded data. """ if yaml is None: raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.") return yaml.load(content)
CWE-20
0
async def send_transactions(self, account, calls, nonce=None, max_fee=0): if nonce is None: execution_info = await account.get_nonce().call() nonce, = execution_info.result build_calls = [] for call in calls: build_call = list(call) build_call...
CWE-863
11
def test_file_position_after_fromfile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') ...
CWE-20
0
def host_passes(self, host_state, filter_properties): context = filter_properties['context'] scheduler_hints = filter_properties.get('scheduler_hints') or {} me = host_state.host affinity_uuids = scheduler_hints.get('different_host', []) if isinstance(affinity_uuids, basestr...
CWE-20
0
def remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
CWE-200
10
def is_gae_instance(): server_software = os.environ.get('SERVER_SOFTWARE', '') if (server_software.startswith('Google App Engine/') or server_software.startswith('Development/') or server_software.startswith('testutil/')): return True return False
CWE-400
2
def _bind_write_headers(msg): def _write_headers(self): # Self refers to the Generator object. for h, v in msg.items(): print("%s:" % h, end=" ", file=self._fp) if isinstance(v, header.Header): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) ...
CWE-400
2
def testInvalidSparseTensor(self): with test_util.force_cpu(): shape = [2, 2] val = [0] dense = constant_op.constant(np.zeros(shape, dtype=np.int32)) for bad_idx in [ [[-1, 0]], # -1 is invalid. [[1, 3]], # ...so is 3. ]: sparse = sparse_tensor.SparseTe...
CWE-20
0
def test_unicode_url(): mw = _get_mw() req = SplashRequest( # note unicode URL u"http://example.com/", endpoint='execute') req2 = mw.process_request(req, None) res = {'html': '<html><body>Hello</body></html>'} res_body = json.dumps(res) response = TextResponse("http://mysplash.ex...
CWE-200
10
def deserialize(self, content, format='application/json'): """ Given some data and a format, calls the correct method to deserialize the data and returns the result. """ desired_format = None format = format.split(';')[0] for short_format, long_format in sel...
CWE-20
0
def get_by_name(self, name, project): return ( Person.query.filter(Person.name == name) .filter(Project.id == project.id) .one() )
CWE-863
11
def get(self, request, name=None): if name is None: if request.user.is_staff: return FormattedResponse(config.get_all()) return FormattedResponse(config.get_all_non_sensitive()) return FormattedResponse(config.get(name))
CWE-200
10
def __init__( self, cache, safe=safename
CWE-400
2
def get_type_string(data): """ Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float: return 'float' elif data_type == bool: return 'boolean' elif data_type in (lis...
CWE-20
0
def _iterate_over_text( tree: "etree.Element", *tags_to_ignore: Union[str, "etree.Comment"]
CWE-674
28
def is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: str :return: Whether the client_secret is valid :rtype: bool """ return client_secret_rege...
CWE-20
0
def verify_password(plain_password, user_password): if plain_password == user_password: LOG.debug("password true") return True return False
CWE-287
4
async def on_context_state_request( self, origin: str, room_id: str, event_id: str
CWE-400
2
async def message(self, ctx, *, message: str): """Set the message that is shown at the start of each ticket channel.\n\nUse ``{user.mention}`` to mention the person who created the ticket.""" try: message.format(user=ctx.author) await self.config.guild(ctx.guild).message.set(...
CWE-74
1
def test_nonexistent_catalog_is_none(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'r') self.remove_dir(pardir) assert_(cat is None)
CWE-269
6
def from_plist(self, content): """ Given some binary plist data, returns a Python dictionary of the decoded data. """ if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.readPlistFromString(content...
CWE-20
0
def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey,
CWE-400
2
def get(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: resp_headers, resp_body = connection.get_object( container=location.container, obj=location.obj, ...
CWE-200
10
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
CWE-400
2
def build_key(self, filename, entry, metadata): """ generates a new key according the the specification """ type = self.key_specs[entry.get('name')]['type'] bits = self.key_specs[entry.get('name')]['bits'] if type == 'rsa': cmd = "openssl genrsa %s " % bit...
CWE-20
0
def __init__(self, sydent): self.sydent = sydent # The default endpoint factory in Twisted 14.0.0 (which we require) uses the # BrowserLikePolicyForHTTPS context factory which will do regular cert validation # 'like a browser' self.agent = Agent( self.sydent.react...
CWE-20
0
def __init__(self, formats=None, content_types=None, datetime_formatting=None): self.supported_formats = [] self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601') if formats is not None: self.formats = formats if content...
CWE-20
0
def command(self): res = self._gnupg().list_secret_keys() return self._success("Searched for secret keys", res)
CWE-287
4
def test_is_valid_hostname(self): """Tests that the is_valid_hostname function accepts only valid hostnames (or domain names), with optional port number. """ self.assertTrue(is_valid_hostname("example.com")) self.assertTrue(is_valid_hostname("EXAMPLE.COM")) self.asse...
CWE-20
0
def _cnonce(): dig = _md5( ( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).encode("utf-8") ).hexdigest() return dig[:16]
CWE-400
2
async def on_PUT(self, origin, content, query, room_id): content = await self.handler.on_exchange_third_party_invite_request( room_id, content ) return 200, content
CWE-400
2
def test_change_response_class_to_json_binary(): mw = _get_mw() # We set magic_response to False, because it's not a kind of data we would # expect from splash: we just return binary data. # If we set magic_response to True, the middleware will fail, # but this is ok because magic_response presumes ...
CWE-200
10
def prepare_context(self, request, context, *args, **kwargs): """ Hook for adding additional data to the context dict """ pass
CWE-200
10
def test_manage_pools(self) -> None: user1 = uuid4() user2 = uuid4() # by default, any can modify self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=True), UserInfo() ) ) # with oid, but no ad...
CWE-346
16
def test_exchange_revoked_invite(self): user_id = self.register_user("kermit", "test") tok = self.login("kermit", "test") room_id = self.helper.create_room_as(room_creator=user_id, tok=tok) # Send a 3PID invite event with an empty body so it's considered as a revoked one. i...
CWE-400
2
def CreateAuthenticator(): """Create a packet autenticator. All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm. This function returns a suitable random string that can be used as an...
CWE-330
12
def test_patch_bot_role(self) -> None: self.login("desdemona") email = "default-bot@zulip.com" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) resu...
CWE-863
11
def _build_ssl_context( disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None, maximum_version=None, minimum_version=None, key_password=None,
CWE-400
2
def skip(self, type): if type == TType.STOP: return elif type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte() elif type == TType.I16: self.readI16() elif type == TType.I32: self.readI32() ...
CWE-755
21
def _on_load_started(self) -> None: self._progress = 0 self._has_ssl_errors = False self.data.viewing_source = False self._set_load_status(usertypes.LoadStatus.loading) self.load_started.emit()
CWE-684
35
def is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: unicode :return: Whether the client_secret is valid :rtype: bool """ return client_secret_...
CWE-20
0
def validate_request(self, request): """If configured for webhook basic auth, validate request has correct auth.""" if self.basic_auth: basic_auth = get_request_basic_auth(request) if basic_auth is None or basic_auth not in self.basic_auth: # noinspection PyUn...
CWE-200
10
def verify_cert_against_ca(self, filename, entry): """ check that a certificate validates against the ca cert, and that it has not expired. """ chaincert = self.CAs[self.cert_specs[entry.get('name')]['ca']].get('chaincert') cert = self.data + filename cmd = "o...
CWE-20
0
def format_date(self, data): """ A hook to control how dates are formatted. Can be overridden at the ``Serializer`` level (``datetime_formatting``) or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``). Default is ``iso-8601``, which looks like "2010-1...
CWE-20
0
def __init__(self, *args, **kwargs): super(BasketShareForm, self).__init__(*args, **kwargs) try: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], initial=kwargs["initial"]["selected"], widget=form...
CWE-200
10