code
stringlengths
23
2.05k
label_name
stringlengths
6
7
label
int64
0
37
def parse_jwt_token(request: func.HttpRequest) -> Result[UserInfo]: """Obtains the Access Token from the Authorization Header""" token_str = get_auth_token(request) if token_str is None: return Error( code=ErrorCode.INVALID_REQUEST, errors=["unable to find authorization token...
CWE-285
23
def _handle_carbon_sent(self, msg): self.xmpp.event('carbon_sent', msg)
CWE-20
0
def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode( _sha("%s%s%s" % (cnonce, iso_now, password)).digest() ).strip()
CWE-400
2
def start_requests(self): yield SplashRequest(self.url, endpoint='execute', args={'lua_source': DEFAULT_SCRIPT})
CWE-200
10
def test_modify_config(self) -> None: user1 = uuid4() user2 = uuid4() # no admins set self.assertTrue(can_modify_config_impl(InstanceConfig(), UserInfo())) # with oid, but no admin self.assertTrue( can_modify_config_impl(InstanceConfig(), UserInfo(object...
CWE-346
16
async def on_PUT(self, origin, content, query, room_id, event_id): content = await self.handler.on_send_leave_request(origin, content, room_id) return 200, (200, content)
CWE-400
2
def __init__(self, private_key): self.signer = Signer(private_key) self.public_key = self.signer.public_key
CWE-863
11
def _ssl_wrap_socket( sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
CWE-400
2
def get_release_file(root, request): session = DBSession() f = ReleaseFile.by_id(session, int(request.matchdict['file_id'])) rv = {'id': f.id, 'url': f.url, 'filename': f.filename, } f.downloads += 1 f.release.downloads += 1 f.release.package.downloads += 1 ses...
CWE-20
0
def try_ldap_login(login, password): """ Connect to a LDAP directory to verify user login/passwords""" result = "Wrong login/password" s = Server(config.LDAPURI, port=config.LDAPPORT, use_ssl=False, get_info=ALL) # 1. connection with service account to find the user uid uid = useruid(...
CWE-74
1
def test_digest_object_stale(): credentials = ("joe", "password") host = None request_uri = "/digest/stale/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true' ) ...
CWE-400
2
def is_valid_hostname(string: str) -> bool: """Validate that a given string is a valid hostname or domain name, with an optional port number. For domain names, this only validates that the form is right (for instance, it doesn't check that the TLD is valid). If a port is specified, it has to be a v...
CWE-20
0
def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None }
CWE-200
10
def test_can_read_token_from_headers(self): """Tests that Sydent correct extracts an auth token from request headers""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details" ) request.requestHeaders.addRawHea...
CWE-20
0
def to_plist(self, data, options=None): """ Given some Python data, produces binary plist output. """ options = options or {} if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.wr...
CWE-20
0
def get(self, id, project=None): if not project: project = g.project return ( Person.query.filter(Person.id == id) .filter(Project.id == project.id) .one() )
CWE-863
11
def start_requests(self): yield SplashRequest(self.url)
CWE-200
10
def _checknetloc(netloc): if not netloc or netloc.isascii(): return # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.rpartition('@')[2] # ignore anything to the left of '@' n = n.replace(':',...
CWE-522
19
def refresh(self): """ Security endpoint for the refresh token, so we can obtain a new token without forcing the user to login again --- post: description: >- Use the refresh token to get a new JWT access token responses: 20...
CWE-287
4
def test_captcha_validate_value(self): captcha = FlaskSessionCaptcha(self.app) _default_routes(captcha, self.app) with self.app.test_request_context('/'): captcha.generate() answer = captcha.get_answer() assert not captcha.validate(value="wrong") ...
CWE-754
31
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 test_tofile_sep(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.0,3.51,4.0') os.unlink(self.filenam...
CWE-20
0
def runTest(self): for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP): encryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv) ciphertext = encryption_cipher.encrypt(self.plaintext) ...
CWE-119
26
def _slices_from_text(self, text): last_break = 0 for match in self._lang_vars.period_context_re().finditer(text): context = match.group() + match.group("after_tok") if self.text_contains_sentbreak(context): yield slice(last_break, match.end()) ...
CWE-400
2
def delete_scan(request, id): obj = get_object_or_404(ScanHistory, id=id) if request.method == "POST": delete_dir = obj.domain.name + '_' + \ str(datetime.datetime.strftime(obj.start_scan_date, '%Y_%m_%d_%H_%M_%S')) delete_path = settings.TOOL_LOCATION + 'scan_results/' + delete_dir ...
CWE-330
12
def __init__( self, credentials, host, request_uri, headers, response, content, http
CWE-400
2
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-20
0
def debug_decisions(self, text): """ Classifies candidate periods as sentence breaks, yielding a dict for each that may be used to understand why the decision was made. See format_debug_decision() to help make this output readable. """ for match in self._lang_vars.p...
CWE-400
2
def _handle_carbon_received(self, msg): self.xmpp.event('carbon_received', msg)
CWE-20
0
def test_basic_for_domain(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=4) as uri: respo...
CWE-400
2
def render_POST(self, request): """ Register with the Identity Server """ send_cors(request) args = get_args(request, ('matrix_server_name', 'access_token')) result = yield self.client.get_json( "matrix://%s/_matrix/federation/v1/openid/userinfo?access_t...
CWE-20
0
def prepare_key(self, key): key = force_bytes(key) invalid_strings = [ b"-----BEGIN PUBLIC KEY-----", b"-----BEGIN CERTIFICATE-----", b"-----BEGIN RSA PUBLIC KEY-----", b"ssh-rsa", ] if any(string_value in key for string_value in inva...
CWE-327
3
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback( SynapseError( 502, "Requested file is too la...
CWE-400
2
def connectionMade(self): method = getattr(self.factory, 'method', b'GET') self.sendCommand(method, self.factory.path) if self.factory.scheme == b'http' and self.factory.port != 80: host = self.factory.host + b':' + intToBytes(self.factory.port) elif self.factory.scheme =...
CWE-74
1
def load_module(name): if os.path.exists(name) and os.path.splitext(name)[1] == '.py': sys.path.insert(0, os.path.dirname(os.path.abspath(name))) try: m = os.path.splitext(os.path.basename(name))[0] module = importlib.import_module(m) finally: sys.path.pop...
CWE-20
0
def generate_subparsers(root, parent_parser, definitions): action_dest = '_'.join(parent_parser.prog.split()[1:] + ['action']) actions = parent_parser.add_subparsers( dest=action_dest ) for command, properties in definitions.items(): is_subparser = isinstance(properties, dict) de...
CWE-200
10
def event_from_pdu_json(pdu_json, outlier=False): """Construct a FrozenEvent from an event json received over federation Args: pdu_json (object): pdu as received over federation outlier (bool): True to mark this event as an outlier Returns: FrozenEvent Raises: SynapseE...
CWE-20
0
def parse_html_description(tree: "etree.Element") -> Optional[str]: """ Calculate a text description based on an HTML document. Grabs any text nodes which are inside the <body/> tag, unless they are within an HTML5 semantic markup tag (<header/>, <nav/>, <aside/>, <footer/>), or if they are within ...
CWE-674
28
def _handle_carbon_sent(self, msg): self.xmpp.event('carbon_sent', msg)
CWE-346
16
def verify_cert_against_key(self, filename, key_filename): """ check that a certificate validates against its private key. """ cert = self.data + filename key = self.data + key_filename cmd = "openssl x509 -noout -modulus -in %s | openssl md5" % cert cert_md5 ...
CWE-20
0
def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name) if not os.path.exists(path): os.makedirs(path,...
CWE-269
6
async def account_register_post( request: Request, U: str = Form(default=str()), # Username E: str = Form(default=str()), # Email H: str = Form(default=False), # Hide Email BE: str = Form(default=None), # Backup Email R: str = Form(default=""), # Real Name HP: str = Form(default=None), ...
CWE-200
10
def __init__( self, cache, safe=safename
CWE-400
2
def remove_dir(self,d): import distutils.dir_util distutils.dir_util.remove_tree(d)
CWE-269
6
def auth_user_registration_role(self): return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"]
CWE-287
4
def auth_user_registration(self): return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION"]
CWE-287
4
def save(self): self['__meta__'] = { 'httpie': __version__ } if self.helpurl: self['__meta__']['help'] = self.helpurl if self.about: self['__meta__']['about'] = self.about self.ensure_directory() json_string = json.dumps( ...
CWE-200
10
def _writeHeaders(self, transport, TEorCL): hosts = self.headers.getRawHeaders(b'host', ()) if len(hosts) != 1: raise BadHeaders(u"Exactly one Host header required") # In the future, having the protocol version be a parameter to this # method would probably be good. It ...
CWE-74
1
def load(self): config_type = type(self).__name__.lower() try: with self.path.open(encoding=UTF8) as f: try: data = json.load(f) except ValueError as e: raise ConfigFileError( f'invalid {confi...
CWE-200
10
def parse(self, response): yield {'response': response}
CWE-200
10
def is_2fa_enabled(self): return self.totp_status == TOTPStatus.ENABLED
CWE-287
4
async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match], Optional[str]]: """ Return True if `text` matches any regex from `word_watchlist` or `token_watchlist` configs. `word_watchlist`'s patterns are placed between word boundaries while `token_watchlist` is ...
CWE-20
0
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-20
0
def test_list(self): self.user.session_set.create(session_key='ABC123', ip='127.0.0.1', expire_date=datetime.now() + timedelta(days=1), user_agent='Firefox') response = self.client.get(reverse('user_sessions:session_list')) ...
CWE-326
9
def _process(tlist): def get_next_comment(): # TODO(andi) Comment types should be unified, see related issue38 return tlist.token_next_by(i=sql.Comment, t=T.Comment) def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" ...
CWE-400
2
def set_admins(self) -> None: name = self.results["deploy"]["func-name"]["value"] key = self.results["deploy"]["func-key"]["value"] table_service = TableService(account_name=name, account_key=key) if self.admins: update_admins(table_service, self.application_name, self.ad...
CWE-285
23
def fetch(cls) -> "InstanceConfig": entry = cls.get(get_instance_name()) if entry is None: entry = cls() entry.save() return entry
CWE-285
23
def auth_ldap_server(self): return self.appbuilder.get_app.config["AUTH_LDAP_SERVER"]
CWE-287
4
async def on_exchange_third_party_invite_request( self, room_id: str, event_dict: Dict
CWE-400
2
def __init__(self, conn=None, host=None, result=None, comm_ok=True, diff=dict()): # which host is this ReturnData about? if conn is not None: self.host = conn.host delegate = getattr(conn, 'delegate', None) if delegate is not None: self.h...
CWE-20
0
def auth_type(self): return self.appbuilder.get_app.config["AUTH_TYPE"]
CWE-287
4
def _get_element_ptr_tuplelike(parent, key): typ = parent.typ assert isinstance(typ, TupleLike) if isinstance(typ, StructType): assert isinstance(key, str) subtype = typ.members[key] attrs = list(typ.tuple_keys()) index = attrs.index(key) annotation = key else: ...
CWE-119
26
def http_parse_auth(s): """https://tools.ietf.org/html/rfc7235#section-2.1 """ scheme, rest = s.split(" ", 1) result = {} while True: m = httplib2.WWW_AUTH_RELAXED.search(rest) if not m: break if len(m.groups()) == 3: key, value, rest = m.groups() ...
CWE-400
2
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) else: ...
CWE-400
2
def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
CWE-400
2
def __init__(self): super(ManyCookies, self).__init__() self.putChild(b'', HelloWorld()) self.putChild(b'login', self.SetMyCookie())
CWE-200
10
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_STRI...
CWE-400
2
def run_tests(self): # pytest may be not installed yet import pytest args = ['--forked', '--fulltrace', '--no-cov', 'tests/'] if self.test_suite: args += ['-k', self.test_suite] sys.stderr.write('setup.py:test run pytest {}\n'.format(' '.join(args))) errno...
CWE-400
2
def from_crawler(cls, crawler): splash_base_url = crawler.settings.get('SPLASH_URL', cls.default_splash_url) log_400 = crawler.settings.getbool('SPLASH_LOG_400', True) slot_policy = crawler.settings.get('SPLASH_SLOT_POLICY', ...
CWE-200
10
async def on_send_join_request( self, origin: str, content: JsonDict, room_id: str
CWE-400
2
def test_change_response_class_to_text(): mw = _get_mw() req = SplashRequest('http://example.com/', magic_response=True) req = mw.process_request(req, None) # Such response can come when downloading a file, # or returning splash:html(): the headers say it's binary, # but it can be decoded so it ...
CWE-200
10
def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode( _sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest() ).strip().decode("utf-8")
CWE-400
2
def test_auth_type_stored_in_session_file(self, httpbin): self.config_dir = mk_config_dir() self.session_path = self.config_dir / 'test-session.json' class Plugin(AuthPlugin): auth_type = 'test-saved' auth_require = True def get_auth(self, username=None,...
CWE-200
10
def fetch(cls) -> "InstanceConfig": entry = cls.get(get_instance_name()) if entry is None: entry = cls() entry.save() return entry
CWE-346
16
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if user is None: return FormattedResponse(status=HTTP_401_UNAUT...
CWE-287
4
def __init__(self, method, uri, headers, bodyProducer, persistent=False): """ @param method: The HTTP method for this request, ex: b'GET', b'HEAD', b'POST', etc. @type method: L{bytes} @param uri: The relative URI of the resource to request. For example, C{b...
CWE-74
1
def test_digest_next_nonce_nc(): # Test that if the server sets nextnonce that we reset # the nonce count back to 1 http = httplib2.Http() password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe...
CWE-400
2
def test_can_read_token_from_query_parameters(self): """Tests that Sydent correct extracts an auth token from query parameters""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details?access_token=" + self.test_to...
CWE-20
0
def _normalize_headers(headers): return dict( [ ( _convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(), ) for (key, value) in headers.items() ] )
CWE-400
2
def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
CWE-400
2
def build_cert(self, key_filename, entry, metadata): """ creates a new certificate according to the specification """ req_config = self.build_req_config(entry, metadata) req = self.build_request(key_filename, req_config, entry) ca = self.cert_specs[entry.get('name')][...
CWE-20
0
def test_with_admins(self) -> None: no_admins = InstanceConfig(admins=None) with_admins = InstanceConfig(admins=[UUID(int=0)]) with_admins_2 = InstanceConfig(admins=[UUID(int=1)]) no_admins.update(with_admins) self.assertEqual(no_admins.admins, None) with_admins.upd...
CWE-285
23
def test_get_mpi_implementation(self): def test(output, expected, exit_code=0): ret = (output, exit_code) if output is not None else None env = {'VAR': 'val'} with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m: impleme...
CWE-668
7
async def on_GET(self, origin, content, query, context, event_id): return await self.handler.on_event_auth(origin, context, event_id)
CWE-400
2
def generic_visit(self, node): if type(node) not in SAFE_NODES: #raise Exception("invalid expression (%s) type=%s" % (expr, type(node))) raise Exception("invalid expression (%s)" % expr) super(CleansingNodeVisitor, self).generic_visit(node)
CWE-74
1
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 cookies(self) -> RequestsCookieJar: jar = RequestsCookieJar() for name, cookie_dict in self['cookies'].items(): jar.set_cookie(create_cookie( name, cookie_dict.pop('value'), **cookie_dict)) jar.clear_expired_cookies() return jar
CWE-200
10
def fixed_fetch( url, payload=None, method="GET", headers={}, allow_truncated=False, follow_redirects=True, deadline=None,
CWE-400
2
def _get_mw(): crawler = _get_crawler({}) return SplashMiddleware.from_crawler(crawler)
CWE-200
10
def testFlushFunction(self): logdir = self.get_temp_dir() with context.eager_mode(): writer = summary_ops.create_file_writer_v2( logdir, max_queue=999999, flush_millis=999999) with writer.as_default(): get_total = lambda: len(events_from_logdir(logdir)) # Note: First tf.c...
CWE-20
0
def test_roundtrip_file(self): f = open(self.filename, 'wb') self.x.tofile(f) f.close() # NB. doesn't work with flush+seek, due to use of C stdio f = open(self.filename, 'rb') y = np.fromfile(f, dtype=self.dtype) f.close() assert_array_equal(y, self.x....
CWE-20
0
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gm...
CWE-400
2
def settings(request): """ Default scrapy-splash settings """ s = dict( # collect scraped items to .collected_items attribute ITEM_PIPELINES={ 'tests.utils.CollectorPipeline': 100, }, # scrapy-splash settings SPLASH_URL=os.environ.get('SPLASH_URL'), D...
CWE-200
10
def safe_text(raw_text: str) -> jinja2.Markup: """ Process text: treat it as HTML but escape any tags (ie. just escape the HTML) then linkify it. """ return jinja2.Markup( bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False)) )
CWE-74
1
def test_digest_object_with_opaque(): credentials = ("joe", "password") host = None request_uri = "/digest/opaque/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"' } content = "" ...
CWE-400
2
def get_revision(self): """Read svn revision information for the Bcfg2 repository.""" try: data = Popen(("env LC_ALL=C svn info %s" % (self.datastore)), shell=True, stdout=PIPE).communicate()[0].split('\n') return [line.split(...
CWE-20
0
def _unpack_returndata(buf, contract_sig, skip_contract_check, context): return_t = contract_sig.return_type if return_t is None: return ["pass"], 0, 0 return_t = calculate_type_for_external_return(return_t) # if the abi signature has a different type than # the vyper type, we need to wrap ...
CWE-119
26
def format_time(self, data): """ A hook to control how times 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 "03:02:...
CWE-20
0
def __init__( self, credentials, host, request_uri, headers, response, content, http
CWE-400
2
def response(self, response, content): if "authentication-info" not in response: challenge = _parse_www_authenticate(response, "www-authenticate").get( "digest", {} ) if "true" == challenge.get("stale"): self.challenge["nonce"] = challenge[...
CWE-400
2