code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
def check_send_to_kindle_with_converter(formats): bookformats = list() if 'EPUB' in formats and 'MOBI' not in formats: bookformats.append({'format': 'Mobi', 'convert': 1, 'text': _('Convert %(orig)s to %(format)s and send to Kindle', orig='Epub', format='Mobi')}) if 'AZW3' in formats and not 'MOBI' in formats: bookformats.append({'format': 'Mobi', 'convert': 2, 'text': _('Convert %(orig)s to %(format)s and send to Kindle', orig='Azw3', format='Mobi')}) return bookformats
CWE-918
16
def get_credits(request, project=None, component=None): """View for credits.""" if project is None: obj = None kwargs = {"translation__isnull": False} elif component is None: obj = get_project(request, project) kwargs = {"translation__component__project": obj} else: obj = get_component(request, project, component) kwargs = {"translation__component": obj} form = ReportsForm(request.POST) if not form.is_valid(): show_form_errors(request, form) return redirect_param(obj or "home", "#reports") data = generate_credits( None if request.user.has_perm("reports.view", obj) else request.user, form.cleaned_data["start_date"], form.cleaned_data["end_date"], **kwargs, ) if form.cleaned_data["style"] == "json": return JsonResponse(data=data, safe=False) if form.cleaned_data["style"] == "html": start = "<table>" row_start = "<tr>" language_format = "<th>{0}</th>" translator_start = "<td><ul>" translator_format = '<li><a href="mailto:{0}">{1}</a> ({2})</li>' translator_end = "</ul></td>" row_end = "</tr>" mime = "text/html" end = "</table>" else: start = "" row_start = "" language_format = "* {0}\n" translator_start = "" translator_format = " * {1} <{0}> ({2})" translator_end = "" row_end = "" mime = "text/plain" end = "" result = [start] for language in data: name, translators = language.popitem() result.append(row_start) result.append(language_format.format(name)) result.append( translator_start + "\n".join(translator_format.format(*t) for t in translators) + translator_end ) result.append(row_end) result.append(end) return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8")
CWE-79
1
def _get_index_absolute_path(index): return os.path.join(INDEXDIR, index)
CWE-22
2
def _get_unauth_response(self, request, reason): """ Get an error response (or raise a Problem) for a given request and reason message. :type request: Request. :param request: HttpRequest :type reason: Reason string. :param reason: str """ if request.is_ajax(): return HttpResponseForbidden(json.dumps({"error": force_text(reason)})) error_params = urlencode({"error": force_text(reason)}) login_url = force_str(reverse("shuup_admin:login") + "?" + error_params) resp = redirect_to_login(next=request.path, login_url=login_url) if is_authenticated(request.user): # Instead of redirecting to the login page, let the user know what's wrong with # a helpful link. raise ( Problem(_("Can't view this page. %(reason)s") % {"reason": reason}).with_link( url=resp.url, title=_("Log in with different credentials...") ) ) return resp
CWE-79
1
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_args_t, encoding=Encoding.ABI) else: base_args_ofst = IRnode(4, location=CALLDATA, typ=base_args_t, encoding=Encoding.ABI) for i, arg in enumerate(sig.base_args): arg_ir = get_element_ptr(base_args_ofst, i) if _should_decode(arg.typ): # allocate a memory slot for it and copy p = context.new_variable(arg.name, arg.typ, is_mutable=False) dst = IRnode(p, typ=arg.typ, location=MEMORY) copy_arg = make_setter(dst, arg_ir) copy_arg.source_pos = getpos(arg.ast_source) ret.append(copy_arg) else: # leave it in place context.vars[arg.name] = VariableRecord( name=arg.name, pos=arg_ir, typ=arg.typ, mutable=False, location=arg_ir.location, encoding=Encoding.ABI, ) return ret
CWE-190
19
def test_level_as_none(self): body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=0, col_offset=0)] mod = ast.Module(body) code = compile(mod, 'test', 'exec') ns = {} exec(code, ns) self.assertIn('sleep', ns)
CWE-125
47
def test_filelike_longcl_http11(self): to_send = "GET /filelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body)
CWE-444
41
def _normalize_path(self, path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:])
CWE-59
36
def custom_login(request, **kwargs): # Currently, Django 1.5 login view does not redirect somewhere if the user is logged in if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) if request.method == "POST" and request.is_limited(): return redirect(request.get_full_path()) return _login_view(request, authentication_form=LoginForm, **kwargs)
CWE-601
11
def test_visitor(self): class CustomVisitor(self.asdl.VisitorBase): def __init__(self): super().__init__() self.names_with_seq = [] def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value) def visitSum(self, sum): for t in sum.types: self.visit(t) def visitConstructor(self, cons): for f in cons.fields: if f.seq: self.names_with_seq.append(cons.name) v = CustomVisitor() v.visit(self.types['mod']) self.assertEqual(v.names_with_seq, ['Module', 'Interactive', 'Suite'])
CWE-125
47
def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],
CWE-94
14
def test_parse_header_bad_content_length(self): data = b"GET /foobar HTTP/8.4\ncontent-length: abc" self.parser.parse_header(data) self.assertEqual(self.parser.body_rcv, None)
CWE-444
41
def opds_download_link(book_id, book_format): # I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest # workaround, loading the user from the request and checking it's download rights here # in case of anonymous browsing user is None user = load_user_from_request(request) or current_user if not user.role_download(): return abort(403) if "Kobo" in request.headers.get('User-Agent'): client = "kobo" else: client = "" return get_download_link(book_id, book_format.lower(), client)
CWE-918
16
def test_credits_view_rst(self): response = self.get_credits("rst") self.assertEqual(response.status_code, 200) self.assertEqual( response.content.decode(), "\n\n* Czech\n\n * Weblate Test <[email protected]> (1)\n\n", )
CWE-79
1
def feed_get_cover(book_id): return get_book_cover(book_id)
CWE-918
16
def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. """ # Create the tables in the database conn = self._connect() try: with conn: self._create_tables(conn, last_upgrade_to_run) finally: conn.close() # Set the file permissions os.chmod(self.filename, stat.S_IRUSR | stat.S_IWUSR)
CWE-367
29
def load_event(self, args, filename, from_misp, stix_version): self.outputname = '{}.json'.format(filename) if len(args) > 0 and args[0]: self.add_original_file(filename, args[0], stix_version) try: event_distribution = args[1] if not isinstance(event_distribution, int): event_distribution = int(event_distribution) if event_distribution.isdigit() else 5 except IndexError: event_distribution = 5 try: attribute_distribution = args[2] if attribute_distribution == 'event': attribute_distribution = event_distribution elif not isinstance(attribute_distribution, int): attribute_distribution = int(attribute_distribution) if attribute_distribution.isdigit() else event_distribution except IndexError: attribute_distribution = event_distribution self.misp_event.distribution = event_distribution self.__attribute_distribution = attribute_distribution self.from_misp = from_misp self.load_mapping()
CWE-78
6
def check_xsrf_cookie(self): """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument. To prevent cross-site request forgery, we set an ``_xsrf`` cookie and include the same value as a non-cookie field with all ``POST`` requests. If the two do not match, we reject the form submission as a potential forgery. The ``_xsrf`` value may be set as either a form field named ``_xsrf`` or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken`` (the latter is accepted for compatibility with Django). See http://en.wikipedia.org/wiki/Cross-site_request_forgery Prior to release 1.1.1, this check was ignored if the HTTP header ``X-Requested-With: XMLHTTPRequest`` was present. This exception has been shown to be insecure and has been removed. For more information please see http://www.djangoproject.com/weblog/2011/feb/08/security/ http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails """ token = (self.get_argument("_xsrf", None) or self.request.headers.get("X-Xsrftoken") or self.request.headers.get("X-Csrftoken")) if not token: raise HTTPError(403, "'_xsrf' argument missing from POST") if not _time_independent_equals(utf8(self.xsrf_token), utf8(token)): raise HTTPError(403, "XSRF cookie does not match POST argument")
CWE-203
38
def edit_book_comments(comments, book): modif_date = False if comments: comments = clean_html(comments) if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date
CWE-918
16
def Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript""" # Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data #Hack to support hi-res rendering scale = int(scale) or 1 orig_size = size orig_bbox = bbox size = (size[0] * scale, size[1] * scale) bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale] #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox) import tempfile, os, subprocess file = tempfile.mktemp() # Build ghostscript command command = ["gs", "-q", # quite mode "-g%dx%d" % size, # set output geometry (pixels) "-r%d" % (72*scale), # set input DPI (dots per inch) "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode "-sDEVICE=ppmraw", # ppm driver "-sOutputFile=%s" % file,# output file ] if gs_windows_binary is not None: if gs_windows_binary is False: raise WindowsError('Unable to locate Ghostscript on paths') command[0] = gs_windows_binary # push data through ghostscript try: gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # adjust for image origin if bbox[0] != 0 or bbox[1] != 0: gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii')) fp.seek(offset) while length > 0: s = fp.read(8192) if not s: break length = length - len(s) gs.stdin.write(s) gs.stdin.close() status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass return im
CWE-59
36
def feed_hot(): off = request.args.get("offset") or 0 all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by( func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id) hot_books = all_books.offset(off).limit(config.config_books_per_page) entries = list() for book in hot_books: downloadBook = calibre_db.get_book(book.Downloads.book_id) if downloadBook: entries.append( calibre_db.get_filtered_book(book.Downloads.book_id) ) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, numBooks) return render_xml_template('feed.xml', entries=entries, pagination=pagination)
CWE-918
16
def values_from_list(values: List[str]) -> Dict[str, str]: """ Convert a list of values into dict of {name: value} """ output: Dict[str, str] = {} for i, value in enumerate(values): if value[0].isalpha(): key = value.upper() else: key = f"VALUE_{i}" if key in output: raise ValueError(f"Duplicate key {key} in Enum") output[key] = value return output
CWE-94
14
def setUp(self): shape = (2, 4, 3) rand = np.random.random self.x = rand(shape) + rand(shape).astype(np.complex)*1j self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype self.filename = tempfile.mktemp()
CWE-59
36
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label=label, selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-color'] = self.queryset.get(pk=value).color return result
CWE-79
1
def snake_case(value: str) -> str: return stringcase.snakecase(group_title(_sanitize(value)))
CWE-94
14
def test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed (no content-length) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
CWE-444
41
def sentences_victim(self, type, data = None, sRun = 1, column = 0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: return self.sql_execute(self.prop_sentences_victim(type, data))
CWE-89
0
def language_overview(): if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all": order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1 charlist = list() languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True) for lang in languages: upper_lang = lang[0].name[0].upper() if upper_lang not in charlist: charlist.append(upper_lang) return render_title_template('languages.html', languages=languages, charlist=charlist, title=_(u"Languages"), page="langlist", data="language", order=order_no) else: abort(404)
CWE-918
16
def save_cover(img, book_path): content_type = img.headers.get('content-type') if use_IM: if content_type not in ('image/jpeg', 'image/png', 'image/webp', 'image/bmp'): log.error("Only jpg/jpeg/png/webp/bmp files are supported as coverfile") return False, _("Only jpg/jpeg/png/webp/bmp files are supported as coverfile") # convert to jpg because calibre only supports jpg if content_type != 'image/jpg': try: if hasattr(img, 'stream'): imgc = Image(blob=img.stream) else: imgc = Image(blob=io.BytesIO(img.content)) imgc.format = 'jpeg' imgc.transform_colorspace("rgb") img = imgc except (BlobError, MissingDelegateError): log.error("Invalid cover file content") return False, _("Invalid cover file content") else: if content_type not in 'image/jpeg': log.error("Only jpg/jpeg files are supported as coverfile") return False, _("Only jpg/jpeg files are supported as coverfile") if config.config_use_google_drive: tmp_dir = os.path.join(gettempdir(), 'calibre_web') if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) ret, message = save_cover_from_filestorage(tmp_dir, "uploaded_cover.jpg", img) if ret is True: gd.uploadFileToEbooksFolder(os.path.join(book_path, 'cover.jpg').replace("\\","/"), os.path.join(tmp_dir, "uploaded_cover.jpg")) log.info("Cover is saved on Google Drive") return True, None else: return False, message else: return save_cover_from_filestorage(os.path.join(config.config_calibre_dir, book_path), "cover.jpg", img)
CWE-918
16
def get_object_src_http(dataset, rel_path): path = _get_obj_abosolute_path(dataset, rel_path) response = send_file(path, cache_timeout=datetime.timedelta( days=365).total_seconds(), add_etags=True, conditional=True) return response
CWE-22
2
def set_session_tracks(display_obj): """Save igv tracks as a session object. This way it's easy to verify that a user is requesting one of these files from remote_static view endpoint Args: display_obj(dict): A display object containing case name, list of genes, lucus and tracks """ session_tracks = list(display_obj.get("reference_track", {}).values()) for key, track_items in display_obj.items(): if key not in ["tracks", "custom_tracks", "sample_tracks"]: continue for track_item in track_items: session_tracks += list(track_item.values()) session["igv_tracks"] = session_tracks
CWE-918
16
def check_auth(username, password): try: username = username.encode('windows-1252') except UnicodeEncodeError: username = username.encode('utf-8') user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.decode('utf-8').lower()).first() if bool(user and check_password_hash(str(user.password), password)): return True else: ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr) log.warning('OPDS Login failed for user "%s" IP-address: %s', username.decode('utf-8'), ip_Address) return False
CWE-918
16
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None): ''' run a command on the chroot ''' if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported: raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method) if in_data: raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining") # Ignores privilege escalation local_cmd = self._generate_cmd(executable, cmd) vvv("EXEC %s" % (local_cmd), host=self.jail) p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring), cwd=self.runner.basedir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() return (p.returncode, '', stdout, stderr)
CWE-59
36
def all(cls, **kwargs): """Return a `Page` of instances of this `Resource` class from its general collection endpoint. Only `Resource` classes with specified `collection_path` endpoints can be requested with this method. Any provided keyword arguments are passed to the API endpoint as query parameters. """ url = urljoin(recurly.base_uri(), cls.collection_path) if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.page_for_url(url)
CWE-918
16
def get_valid_filename(value, replace_whitespace=True, chars=128): """ Returns the given string converted to a string that can be used for a clean filename. Limits num characters to 128 max. """ if value[-1:] == u'.': value = value[:-1]+u'_' value = value.replace("/", "_").replace(":", "_").strip('\0') if use_unidecode: if config.config_unicode_filename: value = (unidecode.unidecode(value)) else: value = value.replace(u'§', u'SS') value = value.replace(u'ß', u'ss') value = unicodedata.normalize('NFKD', value) re_slugify = re.compile(r'[\W\s-]', re.UNICODE) value = re_slugify.sub('', value) if replace_whitespace: # *+:\"/<>? are replaced by _ value = re.sub(r'[*+:\\\"/<>?]+', u'_', value, flags=re.U) # pipe has to be replaced with comma value = re.sub(r'[|]+', u',', value, flags=re.U) value = value[:chars].strip() if not value: raise ValueError("Filename cannot be empty") return value
CWE-918
16
def sentences_victim(self, type, data = None, sRun = 1, column = 0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: return self.sql_execute(self.prop_sentences_victim(type, data))
CWE-79
1
def preprocess_input_exprs_arg_string(input_exprs_str): """Parses input arg into dictionary that maps input key to python expression. Parses input string in the format of 'input_key=<python expression>' into a dictionary that maps each input_key to its python expression. Args: input_exprs_str: A string that specifies python expression for input keys. Each input is separated by semicolon. For each input key: 'input_key=<python expression>' Returns: A dictionary that maps input keys to their values. Raises: RuntimeError: An error when the given input string is in a bad format. """ input_dict = {} for input_raw in filter(bool, input_exprs_str.split(';')): if '=' not in input_exprs_str: raise RuntimeError('--input_exprs "%s" format is incorrect. Please follow' '"<input_key>=<python expression>"' % input_exprs_str) input_key, expr = input_raw.split('=', 1) # ast.literal_eval does not work with numpy expressions input_dict[input_key] = eval(expr) # pylint: disable=eval-used return input_dict
CWE-94
14
def put_file(self, in_path, out_path): ''' transfer a file from local to chroot ''' out_path = self._normalize_path(out_path, self.get_jail_path()) vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail) self._copy_file(in_path, out_path)
CWE-59
36
def basic_parser(xml): return parse(BytesIO(xml))
CWE-611
13
def get_vars_next(self): next = current.request.vars._next host = current.request.env.http_host if isinstance(next, (list, tuple)): next = next[0] if next and self.settings.prevent_open_redirect_attacks: return self.prevent_open_redirect(next, host) return next or None
CWE-601
11
def whitelist(f): """Decorator: Whitelist method to be called remotely via REST API.""" f.whitelisted = True return f
CWE-79
1
def test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None self.assertEqual(ast.dump(src, include_attributes=True), "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), " "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, " "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), " "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)])" )
CWE-125
47
def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body)
CWE-125
47
def _fill(self, target=1, more=None, untilend=False): if more: target = len(self._buf) + more while untilend or (len(self._buf) < target): # crutch to enable HttpRequest.from_bytes if self._sock is None: chunk = b"" else: chunk = self._sock.recv(8 << 10) # print('!!! recv', chunk) if not chunk: self._end = True if untilend: return else: raise EOFError self._buf += chunk
CWE-93
33
def prepare(self, reactor, clock, hs): # build a replication server server_factory = ReplicationStreamProtocolFactory(hs) self.streamer = hs.get_replication_streamer() self.server = server_factory.buildProtocol(None) # Make a new HomeServer object for the worker self.reactor.lookups["testserv"] = "1.2.3.4" self.worker_hs = self.setup_test_homeserver( http_client=None, homeserver_to_use=GenericWorkerServer, config=self._get_worker_hs_config(), reactor=self.reactor, ) # Since we use sqlite in memory databases we need to make sure the # databases objects are the same. self.worker_hs.get_datastore().db_pool = hs.get_datastore().db_pool self.test_handler = self._build_replication_data_handler() self.worker_hs._replication_data_handler = self.test_handler repl_handler = ReplicationCommandHandler(self.worker_hs) self.client = ClientReplicationStreamProtocol( self.worker_hs, "client", "test", clock, repl_handler, ) self._client_transport = None self._server_transport = None
CWE-601
11
def test_invalid_identitifer(self): m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))]) ast.fix_missing_locations(m) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("identifier must be of type str", str(cm.exception))
CWE-125
47
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title).lower()}-client" self.project_dir: Path = Path.cwd() / self.project_name self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = f"A client library for accessing {self.openapi.title}" self.version: str = openapi.version self.env.filters.update(self.TEMPLATE_FILTERS)
CWE-94
14
def feed_booksindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\ .filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all() elements = [] if off == 0: elements.append({'id': "00", 'name':_("All")}) shift = 1 for entry in entries[ off + shift - 1: int(off + int(config.config_books_per_page) - shift)]: elements.append({'id': entry.id, 'name': entry.id}) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries) + 1) return render_xml_template('feed.xml', letterelements=elements, folder='opds.feed_letter_books', pagination=pagination)
CWE-918
16
def get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False, config_read_column=False, *join):
CWE-918
16
def freeze(self, monkeypatch): """Freeze datetime and UUID.""" monkeypatch.setattr( "s3file.forms.S3FileInputMixin.upload_folder", os.path.join(storage.aws_location, "tmp"), )
CWE-22
2
def yet_another_upload_file(request): path = tempfile.mkdtemp() file_name = os.path.join(path, "yet_another_%s.txt" % request.node.name) with open(file_name, "w") as f: f.write(request.node.name) return file_name
CWE-22
2
def test_received_control_line_finished_garbage_in_input(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"garbage\n") self.assertEqual(result, 8) self.assertTrue(inst.error)
CWE-444
41
def test_get_response_requests_exception(self, mock_get): mock_response = mock.Mock() mock_response.status_code = 500 mock_response.text = "Server Error" exception_message = "Some requests exception" requests_exception = requests.RequestException(exception_message) mock_response.raise_for_status.side_effect = requests_exception mock_get.return_value = mock_response url = "https://example.com/" query_runner = BaseHTTPQueryRunner({}) response, error = query_runner.get_response(url) mock_get.assert_called_once_with("get", url, auth=None) self.assertIsNotNone(error) self.assertEqual(exception_message, error)
CWE-918
16
def mysql_insensitive_starts_with(field: Field, value: str) -> Criterion: return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"{value}%"))
CWE-89
0
def image(self, request, pk): obj = self.get_object() if obj.get_space() != request.space: raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403) serializer = self.serializer_class(obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() image = None filetype = ".jpeg" # fall-back to .jpeg, even if wrong, at least users will know it's an image and most image viewers can open it correctly anyways if 'image' in serializer.validated_data: image = obj.image filetype = mimetypes.guess_extension(serializer.validated_data['image'].content_type) or filetype elif 'image_url' in serializer.validated_data: try: response = requests.get(serializer.validated_data['image_url']) image = File(io.BytesIO(response.content)) filetype = mimetypes.guess_extension(response.headers['content-type']) or filetype except UnidentifiedImageError as e: print(e) pass except MissingSchema as e: print(e) pass except Exception as e: print(e) pass if image is not None: img = handle_image(request, image, filetype) obj.image = File(img, name=f'{uuid.uuid4()}_{obj.pk}{filetype}') obj.save() return Response(serializer.data) return Response(serializer.errors, 400)
CWE-918
16
def HEAD(self, path): return self._request('HEAD', path)
CWE-295
52
def testRuntimeError(self, inputs, exception=errors.InvalidArgumentError, message=None):
CWE-125
47
def do_download_file(book, book_format, client, data, headers): if config.config_use_google_drive: #startTime = time.time() df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format) #log.debug('%s', time.time() - startTime) if df: return gd.do_gdrive_download(df, headers) else: abort(404) else: filename = os.path.join(config.config_calibre_dir, book.path) if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)): # ToDo: improve error handling log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format)) if client == "kobo" and book_format == "kepub": headers["Content-Disposition"] = headers["Content-Disposition"].replace(".kepub", ".kepub.epub") response = make_response(send_from_directory(filename, data.name + "." + book_format)) # ToDo Check headers parameter for element in headers: response.headers[element[0]] = element[1] log.info('Downloading file: {}'.format(os.path.join(filename, data.name + "." + book_format))) return response
CWE-918
16
def remote_static(): """Stream *large* static files with special requirements.""" file_path = request.args.get("file") or "." # Check that user is logged in or that file extension is valid if current_user.is_authenticated is False or file_path not in session.get("igv_tracks", []): LOG.warning(f"{file_path} not in {session.get('igv_tracks', [])}") return abort(403) range_header = request.headers.get("Range", None) if not range_header and (file_path.endswith(".bam") or file_path.endswith(".cram")): return abort(500) new_resp = send_file_partial(file_path) return new_resp
CWE-918
16
def put_file(self, in_path, out_path): ''' transfer a file from local to chroot ''' if not out_path.startswith(os.path.sep): out_path = os.path.join(os.path.sep, out_path) normpath = os.path.normpath(out_path) out_path = os.path.join(self.chroot, normpath[1:]) vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: shutil.copyfile(in_path, out_path) except shutil.Error: traceback.print_exc() raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path)) except IOError: traceback.print_exc() raise errors.AnsibleError("failed to transfer file to %s" % out_path)
CWE-59
36
def del_project(request, client_id, project): if request.method == 'GET': client = Client.objects.get(id=client_id) try: scrapyd = get_scrapyd(client) result = scrapyd.delete_project(project=project) return JsonResponse(result) except ConnectionError: return JsonResponse({'message': 'Connect Error'})
CWE-78
6
def formatType(self): format_type = self.type.lower() if format_type == 'amazon': return u"Amazon" elif format_type.startswith("amazon_"): return u"Amazon.{0}".format(format_type[7:]) elif format_type == "isbn": return u"ISBN" elif format_type == "doi": return u"DOI" elif format_type == "douban": return u"Douban" elif format_type == "goodreads": return u"Goodreads" elif format_type == "babelio": return u"Babelio" elif format_type == "google": return u"Google Books" elif format_type == "kobo": return u"Kobo" elif format_type == "litres": return u"ЛитРес" elif format_type == "issn": return u"ISSN" elif format_type == "isfdb": return u"ISFDB" if format_type == "lubimyczytac": return u"Lubimyczytac" else: return self.type
CWE-918
16
def test_template_render_with_noautoescape(self): """ Test if the autoescape value is getting passed to urlize_quoted_links filter. """ template = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" "{% endautoescape %}") rendered = template.render(Context({'content': '"http://example.com"'})) assert rendered == '"<a href="http://example.com" rel="nofollow">http://example.com</a>"'
CWE-79
1
def pref_get(key): if get_user() is None: return "Authentication required", 401 if key in get_preferences(): return Response(json.dumps({'key': key, 'value': get_preferences()[key]})) else: return Response(json.dumps({'key': key, 'error': 'novalue'}))
CWE-79
1
def test_confirmation_obj_not_exist_error(self) -> None: """Since the key is a param input by the user to the registration endpoint, if it inserts an invalid value, the confirmation object won't be found. This tests if, in that scenario, we handle the exception by redirecting the user to the confirmation_link_expired_error page. """ email = self.nonreg_email("alice") password = "password" realm = get_realm("zulip") inviter = self.example_user("iago") prereg_user = PreregistrationUser.objects.create( email=email, referred_by=inviter, realm=realm ) confirmation_link = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) registration_key = "invalid_confirmation_key" url = "/accounts/register/" response = self.client_post( url, {"key": registration_key, "from_confirmation": 1, "full_nme": "alice"} ) self.assertEqual(response.status_code, 404) self.assert_in_response("The registration link has expired or is not valid.", response) registration_key = confirmation_link.split("/")[-1] response = self.client_post( url, {"key": registration_key, "from_confirmation": 1, "full_nme": "alice"} ) self.assert_in_success_response(["We just need you to do one last thing."], response) response = self.submit_reg_form_for_user(email, password, key=registration_key) self.assertEqual(response.status_code, 302)
CWE-613
7
def test_constant_initializer_with_numpy(self): initializer = initializers.Constant(np.ones((3, 2))) model = sequential.Sequential() model.add(layers.Dense(2, input_shape=(3,), kernel_initializer=initializer)) model.add(layers.Dense(3)) model.compile( loss='mse', optimizer='sgd', metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) json_str = model.to_json() models.model_from_json(json_str) if yaml is not None: yaml_str = model.to_yaml() models.model_from_yaml(yaml_str)
CWE-502
15
def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n" "Connection: Keep-Alive\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") # first request succeeds (content-length 5) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
CWE-444
41
def run_custom_method(doctype, name, custom_method): """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}""" doc = frappe.get_doc(doctype, name) if getattr(doc, custom_method, frappe._dict()).is_whitelisted: frappe.call(getattr(doc, custom_method), **frappe.local.form_dict) else: frappe.throw(_("Not permitted"), frappe.PermissionError)
CWE-79
1
def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure nobody tries to escape from basedir for f in filelist: if '/../' in f: return 'invalid_file' # make sure all files are smaller than maximum download size size_limit = cherry.config['media.maximum_download_size'] try: if self.model.file_size_within_limit(filelist, size_limit): return 'ok' else: return 'too_big' except OSError as e: # use OSError for python2 compatibility return str(e)
CWE-79
1
def __init__(self, bot): super().__init__() self.bot = bot self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True) self.config.register_global(custom={}, tenorkey=None) self.config.register_guild(custom={}) self.try_after = None
CWE-502
15
def _copy_file(self, in_path, out_path): if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: shutil.copyfile(in_path, out_path) except shutil.Error: traceback.print_exc() raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path)) except IOError: traceback.print_exc() raise errors.AnsibleError("failed to transfer file to %s" % out_path)
CWE-59
36
def constructObject(data): try: classBase = eval(data[""] + "." + data[""].title()) except NameError: logger.error("Don't know how to handle message type: \"%s\"", data[""]) return None try: returnObj = classBase() returnObj.decode(data) except KeyError as e: logger.error("Missing mandatory key %s", e) return None except: logger.error("classBase fail", exc_info=True) return None else: return returnObj
CWE-94
14
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_token ) token = tokenFromRequest(request) self.assertEqual(token, self.test_token)
CWE-918
16
def ready(self): pass
CWE-532
28
def test_file_logger_log_hyperparams(tmpdir): logger = CSVLogger(tmpdir) hparams = { "float": 0.3, "int": 1, "string": "abc", "bool": True, "dict": {"a": {"b": "c"}}, "list": [1, 2, 3], "namespace": Namespace(foo=Namespace(bar="buzz")), "layer": torch.nn.BatchNorm1d, } logger.log_hyperparams(hparams) logger.save() path_yaml = os.path.join(logger.log_dir, ExperimentWriter.NAME_HPARAMS_FILE) params = load_hparams_from_yaml(path_yaml) assert all(n in params for n in hparams)
CWE-502
15
def test_file_insert_submit_value(self, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//input[@name='save']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save" in driver.page_source driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_button = driver.find_element(By.XPATH, "//button[@name='save_continue']") with wait_for_page_load(driver, timeout=10): save_button.click() assert "save_continue" in driver.page_source assert "continue_value" in driver.page_source
CWE-22
2
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: """Tests if value matches glob. Args: glob value: String to test against glob. word_boundary: Whether to match against word boundaries or entire string. Defaults to False. """ try: r = regex_cache.get((glob, True, word_boundary), None) if not r: r = _glob_to_re(glob, word_boundary) regex_cache[(glob, True, word_boundary)] = r return bool(r.search(value)) except re.error: logger.warning("Failed to parse glob to regex: %r", glob) return False
CWE-331
72
def test_register(self) -> None: reset_emails_in_zulip_realm() realm = get_realm("zulip") stream_names = [f"stream_{i}" for i in range(40)] for stream_name in stream_names: stream = self.make_stream(stream_name, realm=realm) DefaultStream.objects.create(stream=stream, realm=realm) # Clear all the caches. flush_per_request_caches() ContentType.objects.clear_cache() with queries_captured() as queries, cache_tries_captured() as cache_tries: self.register(self.nonreg_email("test"), "test") # Ensure the number of queries we make is not O(streams) self.assert_length(queries, 89) # We can probably avoid a couple cache hits here, but there doesn't # seem to be any O(N) behavior. Some of the cache hits are related # to sending messages, such as getting the welcome bot, looking up # the alert words for a realm, etc. self.assert_length(cache_tries, 21) user_profile = self.nonreg_user("test") self.assert_logged_in_user_id(user_profile.id) self.assertFalse(user_profile.enable_stream_desktop_notifications)
CWE-613
7
def testInputParserBoth(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) x1 = np.ones([2, 10]) input_str = 'x0=' + input_path + '[a]' input_expr_str = 'x1=np.ones([2,10])' feed_dict = saved_model_cli.load_inputs_from_input_arg_string( input_str, input_expr_str, '') self.assertTrue(np.all(feed_dict['x0'] == x0)) self.assertTrue(np.all(feed_dict['x1'] == x1))
CWE-94
14
void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride, int pad_width, int pad_height, int filter_width, int filter_height, int32 output_activation_min, int32 output_activation_max, uint8* output_data, const Dims<4>& output_dims) { AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, pad_height, filter_width, filter_height, output_activation_min, output_activation_max, output_data, output_dims); }
CWE-835
42
def test_in_generator(self): to_send = "GET /in_generator HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(response_body, b"") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
CWE-444
41
def extension_element_from_string(xml_string): element_tree = ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
CWE-611
13
def starts_with(field: Term, value: str) -> Criterion: return field.like(f"{value}%")
CWE-89
0
def table_get_locale(): locale = babel.list_translations() + [LC('en')] ret = list() current_locale = get_locale() for loc in locale: ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)}) return json.dumps(ret)
CWE-918
16
def test_large_body(self): # 1024 characters. body = "This string has 32 characters.\r\n" * 32 s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(body), body) ) self.connect() self.sock.send(s) fp = self.sock.makefile("rb", 0) line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(echo.content_length, "1024") self.assertEqual(echo.body, tobytes(body))
CWE-444
41
def testPeek(self): with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64) gi = array_ops.placeholder(dtypes.int64) p = array_ops.placeholder(dtypes.int32, name='p') with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea( [ dtypes.int32, ], shapes=[[]]) stage = stager.put(pi, [x], [0]) peek = stager.peek(gi) size = stager.size() G.finalize() n = 10 with self.session(graph=G) as sess: for i in range(n): sess.run(stage, feed_dict={x: i, pi: i}) for i in range(n): self.assertTrue(sess.run(peek, feed_dict={gi: i})[0] == i) self.assertTrue(sess.run(size) == 10)
CWE-843
43
def delete_user_session(user_id, session_key): try: log.info("Deleted session_key : " + session_key) session.query(User_Sessions).filter(User_Sessions.user_id==user_id, User_Sessions.session_key==session_key).delete() session.commit() except (exc.OperationalError, exc.InvalidRequestError): session.rollback() log.exception(e)
CWE-79
1
def authorized(): resp = google_remote_app().authorized_response() access_token = resp["access_token"] if access_token is None: logger.warning("Access token missing in call back request.") flash("Validation error. Please retry.") return redirect(url_for("redash.login")) profile = get_user_profile(access_token) if profile is None: flash("Validation error. Please retry.") return redirect(url_for("redash.login")) if "org_slug" in session: org = models.Organization.get_by_slug(session.pop("org_slug")) else: org = current_org if not verify_profile(org, profile): logger.warning( "User tried to login with unauthorized domain name: %s (org: %s)", profile["email"], org, ) flash("Your Google Apps account ({}) isn't allowed.".format(profile["email"])) return redirect(url_for("redash.login", org_slug=org.slug)) picture_url = "%s?sz=40" % profile["picture"] user = create_and_login_user(org, profile["name"], profile["email"], picture_url) if user is None: return logout_and_redirect_to_index() unsafe_next_path = request.args.get("state") or url_for( "redash.index", org_slug=org.slug ) next_path = get_next_path(unsafe_next_path) return redirect(next_path)
CWE-601
11
def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value)
CWE-94
14
def test_received_nonsense_nothing(self): data = b"""\ """ result = self.parser.received(data) self.assertEqual(result, 2) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {})
CWE-444
41
def generate_auth_token(user_id): host_list = request.host.rsplit(':') if len(host_list) == 1: host = ':'.join(host_list) else: host = ':'.join(host_list[0:-1]) if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'): warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device') return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), warning = warning ) else: # Invalidate any prevously generated Kobo Auth token for this user. auth_token = ub.session.query(ub.RemoteAuthToken).filter( ub.RemoteAuthToken.user_id == user_id ).filter(ub.RemoteAuthToken.token_type==1).first() if not auth_token: auth_token = ub.RemoteAuthToken() auth_token.user_id = user_id auth_token.expiration = datetime.max auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8") auth_token.token_type = 1 ub.session.add(auth_token) ub.session_commit() books = calibre_db.session.query(db.Books).join(db.Data).all() for book in books: formats = [data.format for data in book.data] if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats: helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name) return render_title_template( "generate_kobo_auth_url.html", title=_(u"Kobo Setup"), kobo_auth_url=url_for( "kobo.TopLevelEndpoint", auth_token=auth_token.auth_token, _external=True ), warning = False )
CWE-918
16
def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example-äüö.com')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>' )
CWE-79
1
def list_zones(self): pipe = subprocess.Popen([self.zoneadm_cmd, 'list', '-ip'], cwd=self.runner.basedir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #stdout, stderr = p.communicate() zones = [] for l in pipe.stdout.readlines(): # 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared s = l.split(':') if s[1] != 'global': zones.append(s[1]) return zones
CWE-59
36
def receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest]) return json.dumps({'status' : 'OK', 'vId' : vrequest});
CWE-79
1
def get(self): if not current_user.is_authenticated(): return "Must be logged in to log out", 200 logout_user() return "Logged Out", 200
CWE-601
11
def DELETE(self, path, body=None, log_request_body=True): return self._request('DELETE', path, body=body, log_request_body=log_request_body)
CWE-295
52
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, B2_ACCOUNT_INFO_ENV_VAR: os.path.join(d, 'b2_account_info'), } ) expected_path = os.path.abspath(os.path.join(d, 'b2_account_info')) actual_path = os.path.abspath(account_info.filename) assert expected_path == actual_path
CWE-367
29
def test_received_preq_error(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(len(inst.server.tasks), 1) self.assertTrue(inst.requests)
CWE-444
41
def authorize_and_redirect(request): if not request.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not request.META.get("HTTP_REFERER"): return HttpResponse('You need to make a request that includes the "Referer" header.', status=400) referer_url = urlparse(request.META["HTTP_REFERER"]) redirect_url = urlparse(request.GET["redirect"]) if referer_url.hostname != redirect_url.hostname: return HttpResponse(f"Can only redirect to the same domain as the referer: {referer_url.hostname}", status=400) if referer_url.scheme != redirect_url.scheme: return HttpResponse(f"Can only redirect to the same scheme as the referer: {referer_url.scheme}", status=400) if referer_url.port != redirect_url.port: return HttpResponse( f"Can only redirect to the same port as the referer: {referer_url.port or 'no port in URL'}", status=400 ) return render_template( "authorize_and_redirect.html", request=request, context={"domain": redirect_url.hostname, "redirect_url": request.GET["redirect"]}, )
CWE-601
11
def delete(request, pk): like = get_object_or_404(CommentLike, pk=pk, user=request.user) if is_post(request): like.delete() like.comment.decrease_likes_count() if is_ajax(request): url = reverse( 'spirit:comment:like:create', kwargs={'comment_id': like.comment.pk}) return json_response({'url_create': url, }) return redirect(request.POST.get('next', like.comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/like/delete.html', context={'like': like})
CWE-601
11