mcanoglu/cwe-class-group huggingface dataset:
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")) as keyfile:
            algo.prepare_key(keyfile.read())

// Vulnerability class: CWE-327
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:
                ipaddr = socket.gethostbyname(client)
                self.ipcache[client] = (ipaddr, client)
                return (ipaddr, client)
            except socket.gaierror:
                cmd = "getent hosts %s" % client
                ipaddr = Popen(cmd, shell=True, \
                               stdout=PIPE).stdout.read().strip().split()
                if ipaddr:
                    self.ipcache[client] = (ipaddr, client)
                    return (ipaddr, client)
                self.ipcache[client] = False
                self.logger.error("Failed to find IP address for %s" % client)
                raise socket.gaierror

// Vulnerability class: CWE-20
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,
        arm_template: str,
        workbook_data: str,
        create_registration: bool,
        migrations: List[str],
        export_appinsights: bool,
        log_service_principal: bool,
        multi_tenant_domain: str,
        upgrade: bool,
        subscription_id: Optional[str],
        admins: List[UUID]

// Vulnerability class: CWE-346
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():
            if format == long_format:
                if hasattr(self, "to_%s" % short_format):
                    desired_format = short_format
                    break
        
        if desired_format is None:
            raise UnsupportedFormat("The format indicated '%s' had no available serialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format)
        
        serialized = getattr(self, "to_%s" % desired_format)(bundle, options)
        return serialized

// Vulnerability class: CWE-20
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(cookie, attname)
                for attname in stored_attrs
            }

// Vulnerability class: CWE-200
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(data, (list, tuple)):
            return [self.to_simple(item, options) for item in data]
        if isinstance(data, dict):
            return dict((key, self.to_simple(val, options)) for (key, val) in data.iteritems())
        elif isinstance(data, Bundle):
            return dict((key, self.to_simple(val, options)) for (key, val) in data.data.iteritems())
        elif hasattr(data, 'dehydrated_type'):
            if getattr(data, 'dehydrated_type', None) == 'related' and data.is_m2m == False:
                if data.full:
                    return self.to_simple(data.fk_resource, options)
                else:
                    return self.to_simple(data.value, options)
            elif getattr(data, 'dehydrated_type', None) == 'related' and data.is_m2m == True:
                if data.full:
                    return [self.to_simple(bundle, options) for bundle in data.m2m_bundles]
                else:
                    return [self.to_simple(val, options) for val in data.value]
            else:
                return self.to_simple(data.value, options)
        elif isinstance(data, datetime.datetime):
            return self.format_datetime(data)
        elif isinstance(data, datetime.date):
            return self.format_date(data)
        elif isinstance(data, datetime.time):
            return self.format_time(data)
        elif isinstance(data, bool):
            return data
        elif type(data) in (long, int, float):
            return data
        elif data is None:
            return None
        else:
            return force_unicode(data)

// Vulnerability class: CWE-20
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

// Vulnerability class: CWE-200
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)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = is_active_subscriber(
            user_profile=user_profile,
            recipient=recipient)

        return json_success(result) # results are ignored for HEAD requests
    return json_response(data=result, status=404)

// Vulnerability class: CWE-863
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}
        denorm_chars = [
            c for c in map(chr, range(128, sys.maxunicode))
            if (hex_chars & set(unicodedata.decomposition(c).split()))
            and c not in illegal_chars
        ]
        # Sanity check that we found at least one such character
        self.assertIn('\u2100', denorm_chars)
        self.assertIn('\uFF03', denorm_chars)

        # bpo-36742: Verify port separators are ignored when they
        # existed prior to decomposition
        urllib.parse.urlsplit('http://\u30d5\u309a:80')
        with self.assertRaises(ValueError):
            urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')

        for scheme in ["http", "https", "ftp"]:
            for c in denorm_chars:
                url = "{}://netloc{}false.netloc/path".format(scheme, c)
                with self.subTest(url=url, char='{:04X}'.format(ord(c))):
                    with self.assertRaises(ValueError):
                        urllib.parse.urlsplit(url)

// Vulnerability class: CWE-522
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 value and floating:
        return float(value)
    return value

// Vulnerability class: CWE-74
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.add_message(
            request,
            messages.INFO,
            'All Scans deleted!')
    return HttpResponseRedirect(reverse('scan_history'))

// Vulnerability class: CWE-330
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.registerStep(
            'dependable', '1', _underscoreSiteTitle, ('purging', ))
        registry.registerStep(
            'dependent', '1', _uppercaseSiteTitle, ('dependable', ))
        registry.registerStep('purging', '1', _purgeIfRequired)

        tool.runAllImportStepsFromProfile(PROFILE_ID)

        prefix = str('import-all-%s' % PROFILE_ID)
        logged = [x for x in tool.objectIds('File') if x.startswith(prefix)]
        self.assertEqual(len(logged), 1)

        # Check acess restriction on log files
        logged = [x for x in tool.objectIds('File')]
        for file_id in logged:
            file_ob = tool._getOb(file_id)
            rop_info = file_ob.rolesOfPermission(view)
            allowed_roles = sorted([x['name'] for x in rop_info
                                    if x['selected']])
            self.assertEqual(allowed_roles, ['Manager', 'Owner'])
            self.assertFalse(file_ob.acquiredRolesAreUsedBy(view))

// Vulnerability class: CWE-200
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 named-server initialised
        if self.name:
            # use two -- to ensure no collision possibilities
            # are created by an ambiguous boundary between username and
            # servername.
            # -- cannot occur in a string where - is the escape char.
            servername = '--{}'.format(self.name)
            safe_servername = '--{}'.format(escapism.escape(self.name, safe=safe_chars, escape_char='-').lower())
        else:
            servername = ''
            safe_servername = ''

        legacy_escaped_username = ''.join([s if s in safe_chars else '-' for s in self.user.name.lower()])
        safe_username = escapism.escape(self.user.name, safe=safe_chars, escape_char='-').lower()
        return template.format(
            userid=self.user.id,
            username=safe_username,
            unescaped_username=self.user.name,
            legacy_escape_username=legacy_escaped_username,
            servername=safe_servername,
            unescaped_servername=servername,
        )

// Vulnerability class: CWE-863
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.strip('"'), S_IFREG)[1]
            if mcon.split(":")[2] == "lib_t":
                return self.report()
        return None

// Vulnerability class: CWE-77
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]
        except KeyError:
            return 'application/json'

// Vulnerability class: CWE-20
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 {}
        return 'Sorry, not implemented yet. Please append "?format=json" to your URL.'

// Vulnerability class: CWE-20
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

        """
        return random.randrange(0, 256)

// Vulnerability class: CWE-330
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 "2010-12-16T03:02:14".
        """
        if self.datetime_formatting == 'rfc-2822':
            return format_datetime(data)
        
        return data.isoformat()

// Vulnerability class: CWE-20
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_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
            )
            while authenticate:
                # Break off the scheme at the beginning of the line
                if headername == "authentication-info":
                    (auth_scheme, the_rest) = ("digest", authenticate)
                else:
                    (auth_scheme, the_rest) = authenticate.split(" ", 1)
                # Now loop over all the key value pairs that come after the scheme,
                # being careful not to roll into the next scheme
                match = www_auth.search(the_rest)
                auth_params = {}
                while match:
                    if match and len(match.groups()) == 3:
                        (key, value, the_rest) = match.groups()
                        auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
                            r"\1", value
                        )  # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
                    match = www_auth.search(the_rest)
                retval[auth_scheme.lower()] = auth_params
                authenticate = the_rest.strip()
        except ValueError:
            raise MalformedHeader("WWW-Authenticate")
    return retval

// Vulnerability class: CWE-400
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:
            # Use binascii.hexlify() because a hex encoded bytestring is
            # Unicode on Python 3.
            password = binascii.hexlify(self.digest(force_bytes(password)).digest())
        else:
            password = force_bytes(password)

        # Ensure that our data is a bytestring
        data = force_bytes(data)
        # force_bytes() necessary for py-bcrypt compatibility
        hashpw = force_bytes(bcrypt.hashpw(password, data))

        return constant_time_compare(data, hashpw)

// Vulnerability class: CWE-200
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 will be used for each test if changed to be
    # a file on disk.
    if 'db' not in test_config:
        test_config['db'] = {'db.file': ':memory:'}
    else:
        test_config['db'].setdefault('db.file', ':memory:')

    reactor = MemoryReactorClock()
    return Sydent(reactor=reactor, cfg=parse_config_dict(test_config))

// Vulnerability class: CWE-20
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[0] = hex(build_call[0])
            build_calls.append(build_call)

        (call_array, calldata, sig_r, sig_s) = self.signer.sign_transaction(hex(account.contract_address), build_calls, nonce, max_fee)
        return await account.__execute__(call_array, calldata, nonce).invoke(signature=[sig_r, sig_s])

// Vulnerability class: CWE-863
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')
            f.close()

            for mode in ['rb', 'r+b']:
                err_msg = "%d %s" % (size, mode)

                f = open(self.filename, mode)
                f.read(2)
                np.fromfile(f, dtype=np.float64, count=1)
                pos = f.tell()
                f.close()
                assert_equal(pos, 10, err_msg=err_msg)

        os.unlink(self.filename)

// Vulnerability class: CWE-20
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, basestring):
            affinity_uuids = [affinity_uuids]
        if affinity_uuids:
            return not any([i for i in affinity_uuids
                              if self._affinity_host(context, i) == me])
        # With no different_host key
        return True

// Vulnerability class: CWE-20
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)
            else:
                # email.Header got lots of smarts, so use it.
                headers = header.Header(
                    v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
                )
                print(headers.encode(), file=self._fp)
        # A blank line always separates headers from body.
        print(file=self._fp)

    return _write_headers

// Vulnerability class: CWE-400
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.SparseTensorValue(bad_idx, val, shape)
        s = sparse_ops.sparse_add(sparse, dense)

        with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
                                    "invalid index"):
          self.evaluate(s)

// Vulnerability class: CWE-20
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.example.com/execute",
                            # Scrapy doesn't pass request to constructor
                            # request=req2,
                            headers={b'Content-Type': b'application/json'},
                            body=res_body.encode('utf8'))
    response2 = mw.process_response(req2, response, None)
    assert response2.url == "http://example.com/"

// Vulnerability class: CWE-200
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 self.content_types.items():
            if format == long_format:
                if hasattr(self, "from_%s" % short_format):
                    desired_format = short_format
                    break
        
        if desired_format is None:
            raise UnsupportedFormat("The format indicated '%s' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format)
        
        deserialized = getattr(self, "from_%s" % desired_format)(content)
        return deserialized

// Vulnerability class: CWE-20
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 (list, tuple):
        return 'list'
    elif data_type == dict:
        return 'hash'
    elif data is None:
        return 'null'
    elif isinstance(data, basestring):
        return 'string'

// Vulnerability class: CWE-20
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_regex.match(client_secret) is not None

// Vulnerability class: CWE-20
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(message)
            await ctx.send(f"The message has been set to `{message}`.")
        except KeyError:
            await ctx.send(
                "Setting the message failed. Please make sure to only use supported variables in  `\{\}`"
            )

// Vulnerability class: CWE-74
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,
                    resp_chunk_size=self.CHUNKSIZE)
        except swiftclient.ClientException, e:
            if e.http_status == httplib.NOT_FOUND:
                uri = location.get_uri()
                raise exception.NotFound(_("Swift could not find image at "
                                           "uri %(uri)s") % locals())
            else:
                raise

        class ResponseIndexable(glance.store.Indexable):
            def another(self):
                try:
                    return self.wrapped.next()
                except StopIteration:
                    return ''

        length = int(resp_headers.get('content-length', 0))
        return (ResponseIndexable(resp_body, length), length)

// Vulnerability class: CWE-200
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 " % bits
        elif type == 'dsa':
            cmd = "openssl dsaparam -noout -genkey %s" % bits
        key = Popen(cmd, shell=True, stdout=PIPE).stdout.read()
        return key

// Vulnerability class: CWE-20
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.reactor,
            connectTimeout=15,
        )

// Vulnerability class: CWE-20
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_types is not None:
            self.content_types = content_types
        
        if datetime_formatting is not None:
            self.datetime_formatting = datetime_formatting
        
        for format in self.formats:
            try:
                self.supported_formats.append(self.content_types[format])
            except KeyError:
                raise ImproperlyConfigured("Content type for specified type '%s' not found. Please provide it at either the class level or via the arguments." % format)

// Vulnerability class: CWE-20
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.assertTrue(is_valid_hostname("ExAmPlE.CoM"))
        self.assertTrue(is_valid_hostname("example.com:4242"))
        self.assertTrue(is_valid_hostname("localhost"))
        self.assertTrue(is_valid_hostname("localhost:9000"))
        self.assertTrue(is_valid_hostname("a.b:1234"))

        self.assertFalse(is_valid_hostname("example.com:65536"))
        self.assertFalse(is_valid_hostname("example.com:0"))
        self.assertFalse(is_valid_hostname("example.com:a"))
        self.assertFalse(is_valid_hostname("example.com:04242"))
        self.assertFalse(is_valid_hostname("example.com: 4242"))
        self.assertFalse(is_valid_hostname("example.com/example.com"))
        self.assertFalse(is_valid_hostname("example.com#example.com"))

// Vulnerability class: CWE-20
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 we are expecting
    # a valid splash json response.
    req = SplashRequest('http://example.com/', magic_response=False)
    req = mw.process_request(req, None)
    resp = Response('http://mysplash.example.com/execute',
                    headers={b'Content-Type': b'application/json'},
                    body=b'non-decodable data: \x98\x11\xe7\x17\x8f',
                    )
    resp2 = mw.process_response(req, resp, None)
    assert isinstance(resp2, Response)
    assert resp2.url == 'http://example.com/'
    assert resp2.headers == {b'Content-Type': [b'application/json']}
    assert resp2.body == b'non-decodable data: \x98\x11\xe7\x17\x8f'

// Vulnerability class: CWE-200
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 admin
        self.assertIsNone(
            check_can_manage_pools_impl(
                InstanceConfig(allow_pool_management=True), UserInfo(object_id=user1)
            )
        )

        # is admin
        self.assertIsNone(
            check_can_manage_pools_impl(
                InstanceConfig(allow_pool_management=False, admins=[user1]),
                UserInfo(object_id=user1),
            )
        )

        # no user oid set
        self.assertIsNotNone(
            check_can_manage_pools_impl(
                InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo()
            )
        )

        # not an admin
        self.assertIsNotNone(
            check_can_manage_pools_impl(
                InstanceConfig(allow_pool_management=False, admins=[user1]),
                UserInfo(object_id=user2),
            )
        )

// Vulnerability class: CWE-346
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.
        invite_token = "sometoken"
        self.helper.send_state(
            room_id=room_id,
            event_type=EventTypes.ThirdPartyInvite,
            state_key=invite_token,
            body={},
            tok=tok,
        )

        d = self.handler.on_exchange_third_party_invite_request(
            room_id=room_id,
            event_dict={
                "type": EventTypes.Member,
                "room_id": room_id,
                "sender": user_id,
                "state_key": "@someone:example.org",
                "content": {
                    "membership": "invite",
                    "third_party_invite": {
                        "display_name": "alice",
                        "signed": {
                            "mxid": "@alice:localhost",
                            "token": invite_token,
                            "signatures": {
                                "magic.forest": {
                                    "ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg"
                                }
                            },
                        },
                    },
                },
            },
        )

        failure = self.get_failure(d, AuthError).value

        self.assertEqual(failure.code, 403, failure)
        self.assertEqual(failure.errcode, Codes.FORBIDDEN, failure)
        self.assertEqual(failure.msg, "You are not invited to this room.")

// Vulnerability class: CWE-400
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)

        result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req)
        self.assert_json_success(result)

        user_profile = self.get_bot_user(email)
        self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST)

        # Test for not allowing a non-owner user to make assign a bot an owner role
        desdemona = self.example_user("desdemona")
        do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)

        req = dict(role=UserProfile.ROLE_REALM_OWNER)

        result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req)
        self.assert_json_error(result, "Must be an organization owner")

// Vulnerability class: CWE-863
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_regex.match(client_secret) is not None

// Vulnerability class: CWE-20
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 PyUnresolvedReferences
                raise AnymailWebhookValidationFailure(
                    "Missing or invalid basic auth in Anymail %s webhook" % self.esp_name)

// Vulnerability class: CWE-200
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 = "openssl verify -CAfile %s %s" % (chaincert, cert)
        res = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read()
        if res == cert + ": OK\n":
            return True
        return False

// Vulnerability class: CWE-20
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-12-16".
        """
        if self.datetime_formatting == 'rfc-2822':
            return format_date(data)
        
        return data.isoformat()

// Vulnerability class: CWE-20
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=forms.SelectMultiple(attrs={"size": 10}),
            )
        except Exception:
            self.fields["image"] = GroupModelMultipleChoiceField(
                queryset=kwargs["initial"]["images"],
                widget=forms.SelectMultiple(attrs={"size": 10}),
            )

// Vulnerability class: CWE-200
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"],
        )

    # This token has already been verified by the azure authentication layer
    token = jwt.decode(token_str, options={"verify_signature": False})

    application_id = UUID(token["appid"]) if "appid" in token else None
    object_id = UUID(token["oid"]) if "oid" in token else None
    upn = token.get("upn")
    return UserInfo(application_id=application_id, object_id=object_id, upn=upn)

// Vulnerability class: CWE-285
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_id=user1))
        )

        # is admin
        self.assertTrue(
            can_modify_config_impl(
                InstanceConfig(admins=[user1]), UserInfo(object_id=user1)
            )
        )

        # no user oid set
        self.assertFalse(
            can_modify_config_impl(InstanceConfig(admins=[user1]), UserInfo())
        )

        # not an admin
        self.assertFalse(
            can_modify_config_impl(
                InstanceConfig(admins=[user1]), UserInfo(object_id=user2)
            )
        )

// Vulnerability class: CWE-346
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
    session.add(f.release.package)
    session.add(f.release)
    session.add(f)
    return rv

// Vulnerability class: CWE-20
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(s, login)
   
    if uid: 
        # 2. Try to bind the user to the LDAP
        c = Connection(s, user = uid , password = password, auto_bind = True)
        c.open()
        c.bind()
        result =  c.result["description"] # "success" if bind is ok
        c.unbind()

    return result

// Vulnerability class: CWE-74
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'
    )
    response.status = 401
    content = b""
    d = httplib2.DigestAuthentication(
        credentials, host, request_uri, headers, response, content, None
    )
    # Returns true to force a retry
    assert d.response(response, content)

// Vulnerability class: CWE-400
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 valid port number.

    :param string: The string to validate
    :type string: str

    :return: Whether the input is a valid hostname
    :rtype: bool
    """

    host_parts = string.split(":", 1)

    if len(host_parts) == 1:
        return hostname_regex.match(string) is not None
    else:
        host, port = host_parts
        valid_hostname = hostname_regex.match(host) is not None

        try:
            port_num = int(port)
            valid_port = (
                port == str(port_num)  # exclude things like '08090' or ' 8090'
                and 1 <= port_num < 65536)
        except ValueError:
            valid_port = False

        return valid_hostname and valid_port

// Vulnerability class: CWE-20
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.addRawHeader(
            b"Authorization", b"Bearer " + self.test_token.encode("ascii")
        )

        token = tokenFromRequest(request)

        self.assertEqual(token, self.test_token)

// Vulnerability class: CWE-20
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.writePlistToString(self.to_simple(data, options))

// Vulnerability class: CWE-20
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(':', '')        # ignore characters already included
    n = n.replace('#', '')        # but not the surrounding text
    n = n.replace('?', '')
    netloc2 = unicodedata.normalize('NFKC', n)
    if n == netloc2:
        return
    for c in '/?#@:':
        if c in netloc2:
            raise ValueError("netloc '" + netloc + "' contains invalid " +
                             "characters under NFKC normalization")

// Vulnerability class: CWE-522
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:
            200:
              description: Refresh Successful
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      access_token:
                        description: A new refreshed access token
                        type: string
            401:
              $ref: '#/components/responses/401'
            500:
              $ref: '#/components/responses/500'
          security:
            - jwt_refresh: []
        """
        resp = {
            API_SECURITY_ACCESS_TOKEN_KEY: create_access_token(
                identity=get_jwt_identity(), fresh=False
            )
        }
        return self.response(200, **resp)

// Vulnerability class: CWE-287
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")
            captcha.generate()
            answer = captcha.get_answer()
            assert captcha.validate(value=answer)

// Vulnerability class: CWE-754
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.filename)

// Vulnerability class: CWE-20
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)

            if mode != self.module.MODE_OPENPGP:
                decryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv)
            else:
                eiv = ciphertext[:self.module.block_size+2]
                ciphertext = ciphertext[self.module.block_size+2:]
                decryption_cipher = self.module.new(a2b_hex(self.key), mode, eiv)
            decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
            self.assertEqual(self.plaintext, decrypted_plaintext)

// Vulnerability class: CWE-119
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())
                if match.group("next_tok"):
                    # next sentence starts after whitespace
                    last_break = match.start("next_tok")
                else:
                    # next sentence starts at following punctuation
                    last_break = match.end()
        # The last sentence should not contain trailing whitespace.
        yield slice(last_break, len(text.rstrip()))

// Vulnerability class: CWE-400
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
        os.system('rm -rf ' + delete_path)
        obj.delete()
        messageData = {'status': 'true'}
        messages.add_message(
            request,
            messages.INFO,
            'Scan history successfully deleted!')
    else:
        messageData = {'status': 'false'}
        messages.add_message(
            request,
            messages.INFO,
            'Oops! something went wrong!')
    return JsonResponse(messageData)

// Vulnerability class: CWE-330
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

        """
        return random.randrange(0, 256)

// Vulnerability class: CWE-20
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.period_context_re().finditer(text):
            decision_text = match.group() + match.group("after_tok")
            tokens = self._tokenize_words(decision_text)
            tokens = list(self._annotate_first_pass(tokens))
            while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars):
                tokens.pop(0)
            yield {
                "period_index": match.end() - 1,
                "text": decision_text,
                "type1": tokens[0].type,
                "type2": tokens[1].type,
                "type1_in_abbrs": bool(tokens[0].abbr),
                "type1_is_initial": bool(tokens[0].is_initial),
                "type2_is_sent_starter": tokens[1].type_no_sentperiod
                in self._params.sent_starters,
                "type2_ortho_heuristic": self._ortho_heuristic(tokens[1]),
                "type2_ortho_contexts": set(
                    self._params._debug_ortho_context(tokens[1].type_no_sentperiod)
                ),
                "collocation": (
                    tokens[0].type_no_sentperiod,
                    tokens[1].type_no_sentperiod,
                )
                in self._params.collocations,
                "reason": self._second_pass_annotation(tokens[0], tokens[1])
                or REASON_DEFAULT_DECISION,
                "break_decision": tokens[0].sentbreak,
            }

// Vulnerability class: CWE-400
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:
        response, content = http.request(uri, "GET")
        assert response.status == 401
        http.add_credentials("joe", password, "example.org")
        response, content = http.request(uri, "GET")
        assert response.status == 401
        domain = urllib.parse.urlparse(uri)[1]
        http.add_credentials("joe", password, domain)
        response, content = http.request(uri, "GET")
        assert response.status == 200

// Vulnerability class: CWE-400
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_token=%s" % (
                args['matrix_server_name'], urllib.parse.quote(args['access_token']),
            ),
            1024 * 5,
        )
        if 'sub' not in result:
            raise Exception("Invalid response from homeserver")

        user_id = result['sub']
        tok = yield issueToken(self.sydent, user_id)

        # XXX: `token` is correct for the spec, but we released with `access_token`
        # for a substantial amount of time. Serve both to make spec-compliant clients
        # happy.
        defer.returnValue({
            "access_token": tok,
            "token": tok,
        })

// Vulnerability class: CWE-20