code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
def feed_author(book_id): off = request.args.get("offset") or 0 entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0, db.Books, db.Books.authors.any(db.Authors.id == book_id), [db.Books.timestamp.desc()]) return render_xml_template('feed.xml', entries=entries, pagination=pagination)
CWE-918
16
def test_received_headers_finished_expect_continue_true(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.expect_continue = True preq.headers_finished = True preq.completed = False preq.empty = False inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual(sock.sent, b"HTTP/1.1 100 Continue\r\n\r\n") self.assertEqual(inst.sent_continue, True) self.assertEqual(preq.completed, False)
CWE-444
41
def kebab_case(value: str) -> str: return stringcase.spinalcase(group_title(_sanitize(value)))
CWE-94
14
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)
CWE-59
36
def expr(self, node, msg=None, *, exc=ValueError): mod = ast.Module([ast.Expr(node)]) self.mod(mod, msg, exc=exc)
CWE-125
47
def ratings_list(): if current_user.check_visibility(constants.SIDEBAR_RATING): if current_user.get_view_property('ratings', 'dir') == 'desc': order = db.Ratings.rating.desc() order_no = 0 else: order = db.Ratings.rating.asc() order_no = 1 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating')).order_by(order).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(), title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no) else: abort(404)
CWE-918
16
def test_keepalive_http10_explicit(self): # If header Connection: Keep-Alive is explicitly sent, # we want to keept the connection open, we also need to return # the corresponding header data = "Keep me alive" s = tobytes( "GET / HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) connection = response.getheader("Connection", "") self.assertEqual(connection, "Keep-Alive")
CWE-444
41
def __getattr__(_self, attr): if attr == "nameResolver": return nameResolver else: return getattr(real_reactor, attr)
CWE-601
11
def show_book(book_id): entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True) if entries: read_book = entries[1] archived_book = entries[2] entry = entries[0] entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED entry.is_archived = archived_book for index in range(0, len(entry.languages)): entry.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[ index].lang_code) cc = get_cc_columns(filter_config_custom_read=True) book_in_shelfs = [] shelfs = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all() for sh in shelfs: book_in_shelfs.append(sh.shelf) entry.tags = sort(entry.tags, key=lambda tag: tag.name) entry.ordered_authors = calibre_db.order_authors([entry]) entry.kindle_list = check_send_to_kindle(entry) entry.reader_list = check_read_formats(entry) entry.audioentries = [] for media_format in entry.data: if media_format.format.lower() in constants.EXTENSIONS_AUDIO: entry.audioentries.append(media_format.format.lower()) return render_title_template('detail.html', entry=entry, cc=cc, is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', title=entry.title, books_shelfs=book_in_shelfs, page="book") else: log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index"))
CWE-918
16
def feed_read_books(): off = request.args.get("offset") or 0 result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True) return render_xml_template('feed.xml', entries=result, pagination=pagination)
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") # We enter chroot as root so we ignore privlege escalation? if executable: local_cmd = [self.chroot_cmd, self.chroot, executable, '-c', cmd] else: local_cmd = '%s "%s" %s' % (self.chroot_cmd, self.chroot, cmd) vvv("EXEC %s" % (local_cmd), host=self.chroot) 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 put_file(path): try: dest_path = sanitized_join( path, pathlib.Path(app.config["DATA_ROOT"]), ) except ValueError: return flask.Response( "Not Found", 404, mimetype="text/plain", ) verification_key = flask.request.args.get("v", "") length = int(flask.request.headers.get("Content-Length", 0)) hmac_input = "{} {}".format(path, length).encode("utf-8") key = app.config["SECRET_KEY"] mac = hmac.new(key, hmac_input, hashlib.sha256) digest = mac.hexdigest() if not hmac.compare_digest(digest, verification_key): return flask.Response( "Invalid verification key", 403, mimetype="text/plain", ) content_type = flask.request.headers.get( "Content-Type", "application/octet-stream", ) dest_path.parent.mkdir(parents=True, exist_ok=True, mode=0o770) data_file, metadata_file = get_paths(dest_path) try: with write_file(data_file) as fout: stream_file(flask.request.stream, fout, length) with metadata_file.open("x") as f: json.dump( { "headers": {"Content-Type": content_type}, }, f, ) except EOFError: return flask.Response( "Bad Request", 400, mimetype="text/plain", ) except OSError as exc: if exc.errno == errno.EEXIST: return flask.Response( "Conflict", 409, mimetype="text/plain", ) raise return flask.Response( "Created", 201, mimetype="text/plain", )
CWE-22
2
def traverse(cls, base, request, path_items): """See ``zope.app.pagetemplate.engine``.""" path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if ITraversable.providedBy(base): base = getattr(base, cls.traverseMethod)(name) else: base = traversePathElement(base, name, path_items, request=request) return base
CWE-22
2
def allow_all(tag: str, name: str, value: str) -> bool: return True
CWE-79
1
def _get_obj_absolute_path(obj_path): return os.path.join(DATAROOT, obj_path)
CWE-22
2
def _create(self): url = urljoin(recurly.base_uri(), self.collection_path) return self.post(url)
CWE-918
16
def render_delete_book_result(book_format, jsonResponse, warning, book_id): if book_format: if jsonResponse: return json.dumps([warning, {"location": url_for("editbook.edit_book", book_id=book_id), "type": "success", "format": book_format, "message": _('Book Format Successfully Deleted')}]) else: flash(_('Book Format Successfully Deleted'), category="success") return redirect(url_for('editbook.edit_book', book_id=book_id)) else: if jsonResponse: return json.dumps([warning, {"location": url_for('web.index'), "type": "success", "format": book_format, "message": _('Book Successfully Deleted')}]) else: flash(_('Book Successfully Deleted'), category="success") return redirect(url_for('web.index'))
CWE-918
16
def scriptPath(*pathSegs): startPath = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) return os.path.join(startPath, *pathSegs)
CWE-78
6
def feed_seriesindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Series.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_series', pagination=pagination)
CWE-918
16
def _consumer(self, auth): auth.process_response() errors = auth.get_errors() if not errors: if auth.is_authenticated(): return True else: return False else: current_app.logger.error('Error processing %s' % (', '.join(errors))) return False
CWE-601
11
def feed_ratings(book_id): off = request.args.get("offset") or 0 entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0, db.Books, db.Books.ratings.any(db.Ratings.id == book_id), [db.Books.timestamp.desc()]) return render_xml_template('feed.xml', entries=entries, pagination=pagination)
CWE-918
16
def test_parse_header_11_te_chunked(self): # NB: test that capitalization of header value is unimportant data = b"GET /foobar HTTP/1.1\ntransfer-encoding: ChUnKed" self.parser.parse_header(data) self.assertEqual(self.parser.body_rcv.__class__.__name__, "ChunkedReceiver")
CWE-444
41
def test_confirmation_expired(self) -> None: email = self.nonreg_email("alice") realm = get_realm("zulip") inviter = self.example_user("iago") prereg_user = PreregistrationUser.objects.create( email=email, referred_by=inviter, realm=realm ) date_sent = timezone_now() - datetime.timedelta(weeks=3) with patch("confirmation.models.timezone_now", return_value=date_sent): url = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) target_url = "/" + url.split("/", 3)[3] result = self.client_get(target_url) self.assertEqual(result.status_code, 404) self.assert_in_response( "Whoops. The confirmation link has expired or been deactivated.", result )
CWE-613
7
def print_train_stats(): print( "TEMPLATE STATISTICS (TRAIN) {} templates, {} rules)".format( len(template_counts), len(tids) ) ) print( "TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} " "final: {finalerrors:5d} {finalacc:.4f} ".format(**train_stats) ) head = "#ID | Score (train) | #Rules | Template" print(head, "\n", "-" * len(head), sep="") train_tplscores = sorted( weighted_traincounts.items(), key=det_tplsort, reverse=True ) for (tid, trainscore) in train_tplscores: s = "{} | {:5d} {:5.3f} |{:4d} {:.3f} | {}".format( tid, trainscore, trainscore / tottrainscores, template_counts[tid], template_counts[tid] / len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s)
CWE-1333
73
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
CWE-125
47
def __init__(self, hs): self.server_name = hs.hostname self.client = hs.get_http_client()
CWE-601
11
def test_login_unknown_code(self): response = self.client.post('/accounts-rest/login/code/', { 'code': 'unknown', }) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), { 'code': ['Login code is invalid. It might have expired.'], })
CWE-312
71
def publish(request, category_id=None): if category_id: get_object_or_404( Category.objects.visible(), pk=category_id) user = request.user form = TopicForm( user=user, data=post_data(request), initial={'category': category_id}) cform = CommentForm( user=user, data=post_data(request)) if (is_post(request) and all([form.is_valid(), cform.is_valid()]) and not request.is_limited()): if not user.st.update_post_hash(form.get_topic_hash()): return redirect( request.POST.get('next', None) or form.get_category().get_absolute_url()) # wrap in transaction.atomic? topic = form.save() cform.topic = topic comment = cform.save() comment_posted(comment=comment, mentions=cform.mentions) return redirect(topic.get_absolute_url()) return render( request=request, template_name='spirit/topic/publish.html', context={'form': form, 'cform': cform})
CWE-601
11
def delete(request, pk, remove=True): comment = get_object_or_404(Comment, pk=pk) if is_post(request): (Comment.objects .filter(pk=pk) .update(is_removed=remove)) return redirect(request.GET.get('next', comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/moderate.html', context={'comment': comment})
CWE-601
11
def PUT(self, path, body, ensure_encoding=True, log_request_body=True): return self._request('PUT', path, body=body, ensure_encoding=ensure_encoding, log_request_body=log_request_body)
CWE-295
52
def test_property_from_data_array(self, mocker): name = mocker.MagicMock() required = mocker.MagicMock() data = oai.Schema(type="array", items={"type": "number", "default": "0.0"},) ListProperty = mocker.patch(f"{MODULE_NAME}.ListProperty") FloatProperty = mocker.patch(f"{MODULE_NAME}.FloatProperty") from openapi_python_client.parser.properties import property_from_data p = property_from_data(name=name, required=required, data=data) FloatProperty.assert_called_once_with(name=f"{name}_item", required=True, default="0.0") ListProperty.assert_called_once_with( name=name, required=required, default=None, inner_property=FloatProperty.return_value ) assert p == ListProperty.return_value
CWE-94
14
def convert_bookformat(book_id): # check to see if we have form fields to work with - if not send user back book_format_from = request.form.get('book_format_from', None) book_format_to = request.form.get('book_format_to', None) if (book_format_from is None) or (book_format_to is None): flash(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to) rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(), book_format_to.upper(), current_user.name) if rtn is None: flash(_(u"Book successfully queued for converting to %(book_format)s", book_format=book_format_to), category="success") else: flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id))
CWE-918
16
def get(self, arg,word=None): #print "match auto" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") #jsonp result = rtxcomplete.prefix(word,limit) result = callback+"("+json.dumps(result)+");" #jsonp #result = json.dumps(result) #typeahead self.write(result) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[2] self.write("error")
CWE-79
1
def test_logout_get(self): login_code = LoginCode.objects.create(user=self.user, code='foobar') self.client.login(username=self.user.username, code=login_code.code) response = self.client.post('/accounts/logout/?next=/accounts/login/') self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '/accounts/login/') self.assertTrue(response.wsgi_request.user.is_anonymous)
CWE-312
71
def test_get_frontend_context_variables_xss(component): # Set component.name to a potential XSS attack component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>' frontend_context_variables = component.get_frontend_context_variables() frontend_context_variables_dict = orjson.loads(frontend_context_variables) assert len(frontend_context_variables_dict) == 1 assert ( frontend_context_variables_dict.get("name") == "&lt;a&gt;&lt;style&gt;@keyframes x{}&lt;/style&gt;&lt;a style=&quot;animation-name:x&quot; onanimationend=&quot;alert(1)&quot;&gt;&lt;/a&gt;" )
CWE-79
1
def check_username(username): username = username.strip() if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar(): log.error(u"This username is already taken") raise Exception (_(u"This username is already taken")) return username
CWE-918
16
def test_before_start_response_http_11_close(self): to_send = tobytes( "GET /before_start_response HTTP/1.1\n" "Connection: close\n\n" ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["connection"], "close") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
CWE-444
41
async def ignore(self, ctx, command: str.lower): """ Ignore or unignore the specified action. The bot will no longer respond to these actions. """ try: custom = await self.config.guild(ctx.guild).get_raw("custom", command) except KeyError: custom = NotImplemented if custom is None: await self.config.guild(ctx.guild).clear_raw("custom", command) await ctx.send("I will no longer ignore the {command} action".format(command=command)) else: await self.config.guild(ctx.guild).set_raw("custom", command, value=None) await ctx.send("I will now ignore the {command} action".format(command=command))
CWE-502
15
def make_homeserver(self, reactor, clock): self.http_client = Mock() hs = self.setup_test_homeserver(http_client=self.http_client) return hs
CWE-601
11
def index(): """ Index handler """ send = request.vars.send if DEMO_MODE: session.authorized = True session.last_time = t0 if not send: send = URL('site') if session.authorized: redirect(send) elif failed_login_count() >= allowed_number_of_attempts: time.sleep(2 ** allowed_number_of_attempts) raise HTTP(403) elif request.vars.password: if verify_password(request.vars.password[:1024]): session.authorized = True login_record(True) if CHECK_VERSION: session.check_version = True else: session.check_version = False session.last_time = t0 if isinstance(send, list): # ## why does this happen? send = str(send[0]) redirect(send) else: times_denied = login_record(False) if times_denied >= allowed_number_of_attempts: response.flash = \ T('admin disabled because too many invalid login attempts') elif times_denied == allowed_number_of_attempts - 1: response.flash = \ T('You have one more login attempt before you are locked out') else: response.flash = T('invalid password.') return dict(send=send)
CWE-601
11
def __init__(self, hs: "HomeServer"): self.config = hs.config self.http_client = hs.get_simple_http_client() self.clock = hs.get_clock() self._instance_name = hs.get_instance_name() # These are safe to load in monolith mode, but will explode if we try # and use them. However we have guards before we use them to ensure that # we don't route to ourselves, and in monolith mode that will always be # the case. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs) self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs) self.edu_handlers = ( {} ) # type: Dict[str, Callable[[str, dict], Awaitable[None]]] self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]] # Map from type to instance name that we should route EDU handling to. self._edu_type_to_instance = {} # type: Dict[str, str]
CWE-601
11
def _returndata_encoding(contract_sig): if contract_sig.is_from_json: return Encoding.JSON_ABI return Encoding.ABI
CWE-190
19
def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = tobytes( "GET /short_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) content_length = int(headers.get("content-length")) response_body = fp.read(content_length) self.assertEqual(int(status), 200) self.assertNotEqual(content_length, len(response_body)) self.assertEqual(len(response_body), content_length - 1) self.assertEqual(response_body, tobytes("abcdefghi")) # remote closed connection (despite keepalive header); not sure why # first send succeeds self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
CWE-444
41
def test_filelike_http11(self): to_send = "GET /filelike 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 adv_search_serie(q, include_series_inputs, exclude_series_inputs): for serie in include_series_inputs: q = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in exclude_series_inputs: q = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return q
CWE-918
16
def _is_javascript_scheme(s): if _is_image_dataurl(s): return None return _is_possibly_malicious_scheme(s)
CWE-79
1
def create_book_on_upload(modif_date, meta): title = meta.title authr = meta.author sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr) title_dir = helper.get_valid_filename(title, chars=96) author_dir = helper.get_valid_filename(db_author.name, chars=96) # combine path and normalize path from windows systems path = os.path.join(author_dir, title_dir).replace('\\', '/') # Calibre adds books with utc as timezone db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1), '1', datetime.utcnow(), path, meta.cover, db_author, [], "") modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session, 'author') # Add series_index to book modif_date |= edit_book_series_index(meta.series_id, db_book) # add languages invalid=[] modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid) if invalid: for l in invalid: flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning") # handle tags modif_date |= edit_book_tags(meta.tags, db_book) # handle publisher modif_date |= edit_book_publisher(meta.publisher, db_book) # handle series modif_date |= edit_book_series(meta.series, db_book) # Add file to book file_size = os.path.getsize(meta.file_path) db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir) db_book.data.append(db_data) calibre_db.session.add(db_book) # flush content, get db_book.id available calibre_db.session.flush() return db_book, input_authors, title_dir, renamed_authors
CWE-918
16
def test_received_cl_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = b"""\ GET /foobar HTTP/8.4 Content-Length: 10 """ result = self.parser.received(data) self.assertEqual(result, 41) self.assertTrue(self.parser.completed) self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))
CWE-444
41
def on_permitted_domain(team: Team, request: HttpRequest) -> bool: permitted_domains = ["127.0.0.1", "localhost"] for url in team.app_urls: hostname = parse_domain(url) if hostname: permitted_domains.append(hostname) origin = parse_domain(request.headers.get("Origin")) referer = parse_domain(request.headers.get("Referer")) for permitted_domain in permitted_domains: if "*" in permitted_domain: pattern = "^{}$".format(permitted_domain.replace(".", "\\.").replace("*", "(.*)")) if (origin and re.search(pattern, origin)) or (referer and re.search(pattern, referer)): return True else: if permitted_domain == origin or permitted_domain == referer: return True return False
CWE-601
11
def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None): frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
CWE-79
1
def job_cancel(request, client_id, project_name, job_id): """ cancel a job :param request: request object :param client_id: client id :param project_name: project name :param job_id: job id :return: json of cancel """ if request.method == 'GET': client = Client.objects.get(id=client_id) try: scrapyd = get_scrapyd(client) result = scrapyd.cancel(project_name, job_id) return JsonResponse(result) except ConnectionError: return JsonResponse({'message': 'Connect Error'})
CWE-78
6
def test_received_preq_completed_empty(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, [])
CWE-444
41
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_get_header_lines_folded(self): # From RFC2616: # HTTP/1.1 header field values can be folded onto multiple lines if the # continuation line begins with a space or horizontal tab. All linear # white space, including folding, has the same semantics as SP. A # recipient MAY replace any linear white space with a single SP before # interpreting the field value or forwarding the message downstream. # We are just preserving the whitespace that indicates folding. result = self._callFUT(b"slim\n slam") self.assertEqual(result, [b"slim slam"])
CWE-444
41
def table_get_custom_enum(c_id): ret = list() cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.id == c_id) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none()) ret.append({'value': "", 'text': ""}) for idx, en in enumerate(cc.get_display_dict()['enum_values']): ret.append({'value': en, 'text': en}) return json.dumps(ret)
CWE-918
16
def edit_user_table(): visibility = current_user.view_settings.get('useredit', {}) languages = calibre_db.speaking_language() translations = babel.list_translations() + [LC('en')] allUser = ub.session.query(ub.User) tags = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() if config.config_restricted_column: custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all() else: custom_values = [] if not config.config_anonbrowse: allUser = allUser.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) kobo_support = feature_support['kobo'] and config.config_kobo_sync return render_title_template("user_table.html", users=allUser.all(), tags=tags, custom_values=custom_values, translations=translations, languages=languages, visiblility=visibility, all_roles=constants.ALL_ROLES, kobo_support=kobo_support, sidebar_settings=constants.sidebar_settings, title=_(u"Edit Users"), page="usertable")
CWE-918
16
def render_hot_books(page, order): if current_user.check_visibility(constants.SIDEBAR_HOT): if order[1] not in ['hotasc', 'hotdesc']: # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+ #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or # order[0][0].compare(func.count(ub.Downloads.book_id).asc())): order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() off = int(int(config.config_books_per_page) * (page - 1)) all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*order[0]).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.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == book.Downloads.book_id).first() if downloadBook: entries.append(downloadBook) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination(page, config.config_books_per_page, numBooks) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1]) else: abort(404)
CWE-918
16
def get_files_from_storage(paths): """Return S3 file where the name does not include the path.""" for path in paths: path = pathlib.PurePosixPath(path) try: location = storage.aws_location except AttributeError: location = storage.location try: f = storage.open(str(path.relative_to(location))) f.name = path.name yield f except (OSError, ValueError): logger.exception("File not found: %s", path)
CWE-22
2
def property_from_data( name: str, required: bool, data: Union[oai.Reference, oai.Schema]
CWE-94
14
def test_stopped_typing(self): self.room_members = [U_APPLE, U_BANANA, U_ONION] # Gut-wrenching from synapse.handlers.typing import RoomMember member = RoomMember(ROOM_ID, U_APPLE.to_string()) self.handler._member_typing_until[member] = 1002000 self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()} self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.stopped_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) put_json = self.hs.get_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": False, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], )
CWE-601
11
def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("but got <_ast.expr", str(cm.exception))
CWE-125
47
def feed_ratingindex(): off = request.args.get("offset") or 0 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating'))\ .order_by(db.Ratings.rating).all() pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries)) element = list() for entry in entries: element.append(FeedObject(entry[0].id, _("{} Stars").format(entry.name))) return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination)
CWE-918
16
def _get_obj_absolute_path(obj_path): return os.path.join(DATAROOT, obj_path)
CWE-22
2
def main(srcfile, dump_module=False): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) auto_gen_msg = common_msg % argv0 mod = asdl.parse(srcfile) if dump_module: print('Parsed Module:') print(mod) if not asdl.check(mod): sys.exit(1) if INC_DIR: p = "%s/%s-ast.h" % (INC_DIR, mod.name) f = open(p, "w") f.write(auto_gen_msg) f.write('#include "asdl.h"\n\n') c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) f.write("PyObject* Ta3AST_mod2obj(mod_ty t);\n") f.write("mod_ty Ta3AST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n") f.write("int Ta3AST_Check(PyObject* obj);\n") f.close() if SRC_DIR: p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") f = open(p, "w") f.write(auto_gen_msg) f.write('#include <stddef.h>\n') f.write('\n') f.write('#include "Python.h"\n') f.write('#include "%s-ast.h"\n' % mod.name) f.write('\n') f.write("static PyTypeObject AST_type;\n") v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), Obj2ModPrototypeVisitor(f), FunctionVisitor(f), ObjVisitor(f), Obj2ModVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
CWE-125
47
def _get_index_absolute_path(index): return os.path.join(INDEXDIR, index)
CWE-22
2
def __init__(self, expression, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or [] # Transform minus sign prefixed strings into an OrderBy() expression. ordering = ( (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(expression, **extra) self.ordering = self._parse_expressions(*ordering)
CWE-89
0
def open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 content = {"header": [], "body": None} for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 content["body"] = ElementTree.tostring(part[0], encoding="UTF-8") elif part.tag == "{%s}Header" % soapenv.NAMESPACE: for item in part: _str = ElementTree.tostring(item, encoding="UTF-8") content["header"].append(_str) return content
CWE-611
13
def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host). Always returns ``False`` on an empty url. """ if not url: return False netloc = urllib_parse.urlparse(url)[1] return not netloc or netloc == host
CWE-79
1
def testUnravelIndexZeroDim(self): with self.cached_session(): for dtype in [dtypes.int32, dtypes.int64]: with self.assertRaisesRegex(errors.InvalidArgumentError, "index is out of bound as with dims"): indices = constant_op.constant([2, 5, 7], dtype=dtype) dims = constant_op.constant([3, 0], dtype=dtype) self.evaluate(array_ops.unravel_index(indices=indices, dims=dims))
CWE-369
60
def sentences_stats(self, type, vId = None): return self.sql_execute(self.prop_sentences_stats(type, vId))
CWE-79
1
def render_edit_book(book_id): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) for lang in book.languages: lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) book.authors = calibre_db.order_authors([book]) author_names = [] for authr in book.authors: author_names.append(authr.name.replace('|', ',')) # Option for showing convertbook button valid_source_formats=list() allowed_conversion_formats = list() kepub_possible=None if config.config_converterpath: for file in book.data: if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM: valid_source_formats.append(file.format.lower()) if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]: kepub_possible = True if not config.config_converterpath: valid_source_formats.append('epub') # Determine what formats don't already exist if config.config_converterpath: allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:] for file in book.data: if file.format.lower() in allowed_conversion_formats: allowed_conversion_formats.remove(file.format.lower()) if kepub_possible: allowed_conversion_formats.append('kepub') return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc, title=_(u"edit metadata"), page="editbook", conversion_formats=allowed_conversion_formats, config=config, source_formats=valid_source_formats)
CWE-918
16
def main(): app = create_app() init_errorhandler() app.register_blueprint(web) app.register_blueprint(opds) app.register_blueprint(jinjia) app.register_blueprint(about) app.register_blueprint(shelf) app.register_blueprint(admi) app.register_blueprint(remotelogin) app.register_blueprint(meta) app.register_blueprint(gdrive) app.register_blueprint(editbook) if kobo_available: app.register_blueprint(kobo) app.register_blueprint(kobo_auth) if oauth_available: app.register_blueprint(oauth) success = web_server.start() sys.exit(0 if success else 1)
CWE-918
16
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, )
CWE-918
16
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), ) self.event_source = hs.get_event_sources().sources["typing"] hs.get_federation_handler = Mock() async def get_user_by_access_token(token=None, allow_guest=False): return { "user": UserID.from_string(self.auth_user_id), "token_id": 1, "is_guest": False, } hs.get_auth().get_user_by_access_token = get_user_by_access_token async def _insert_client_ip(*args, **kwargs): return None hs.get_datastore().insert_client_ip = _insert_client_ip def get_room_members(room_id): if room_id == self.room_id: return defer.succeed([self.user]) else: return defer.succeed([]) @defer.inlineCallbacks def fetch_room_distributions_into( room_id, localusers=None, remotedomains=None, ignore_user=None ): members = yield get_room_members(room_id) for member in members: if ignore_user is not None and member == ignore_user: continue if hs.is_mine(member): if localusers is not None: localusers.add(member) else: if remotedomains is not None: remotedomains.add(member.domain) hs.get_room_member_handler().fetch_room_distributions_into = ( fetch_room_distributions_into ) return hs
CWE-601
11
def glob_to_regex(glob): """Converts a glob to a compiled regex object. The regex is anchored at the beginning and end of the string. Args: glob (str) Returns: re.RegexObject """ res = "" for c in glob: if c == "*": res = res + ".*" elif c == "?": res = res + "." else: res = res + re.escape(c) # \A anchors at start of string, \Z at end of string return re.compile(r"\A" + res + r"\Z", re.IGNORECASE)
CWE-331
72
def update(request, pk): topic = Topic.objects.for_update_or_404(pk, request.user) category_id = topic.category_id form = TopicForm( user=request.user, data=post_data(request), instance=topic) if is_post(request) and form.is_valid(): topic = form.save() if topic.category_id != category_id: Comment.create_moderation_action( user=request.user, topic=topic, action=Comment.MOVED) return redirect(request.POST.get('next', topic.get_absolute_url())) return render( request=request, template_name='spirit/topic/update.html', context={'form': form})
CWE-601
11
def _factorial(x): if x<=10000: return float(math.factorial(x)) else: raise Exception('factorial argument too large')
CWE-94
14
def get_file(recipe): if not recipe.link: recipe.link = Dropbox.get_share_link(recipe) recipe.save() response = requests.get(recipe.link.replace('www.dropbox.', 'dl.dropboxusercontent.')) return io.BytesIO(response.content)
CWE-918
16
def test_mixed(self): self.assertEqual(self._callFUT(b"\n\n00\r\n\r\n"), 2)
CWE-444
41
async def tenorkey(self, ctx): """ Sets a Tenor GIF API key to enable reaction gifs with act commands. You can obtain a key from here: https://tenor.com/developer/dashboard """ instructions = [ "Go to the Tenor developer dashboard: https://tenor.com/developer/dashboard", "Log in or sign up if you haven't already.", "Click `+ Create new app` and fill out the form.", "Copy the key from the app you just created.", "Give the key to Red with this command:\n" f"`{ctx.prefix}set api tenor api_key your_api_key`\n" "Replace `your_api_key` with the key you just got.\n" "Everything else should be the same.", ] instructions = [f"**{i}.** {v}" for i, v in enumerate(instructions, 1)] await ctx.maybe_send_embed("\n".join(instructions))
CWE-502
15
def encode_non_url_reserved_characters(url): # safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 return urlquote(url, safe=":/?#[]@!$&'()*+,;=")
CWE-601
11
def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False): # Create new_author_dir from parameter or from database # Create new title_dir from database and add id if first_author: new_authordir = get_valid_filename(first_author, chars=96) for r in renamed_author: new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first() old_author_dir = get_valid_filename(r, chars=96) new_author_rename_dir = get_valid_filename(new_author.name, chars=96) if gdrive: gFile = gd.getFileFromEbooksFolder(None, old_author_dir) if gFile: gd.moveGdriveFolderRemote(gFile, new_author_rename_dir) else: if os.path.isdir(os.path.join(calibre_path, old_author_dir)): try: old_author_path = os.path.join(calibre_path, old_author_dir) new_author_path = os.path.join(calibre_path, new_author_rename_dir) shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path)) except (OSError) as ex: log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex) log.debug(ex, exc_info=True) return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s", src=old_author_path, dest=new_author_path, error=str(ex)) else: new_authordir = get_valid_filename(localbook.authors[0].name, chars=96) return new_authordir
CWE-918
16
def send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id): """Send email with attachments""" book = calibre_db.get_book(book_id) if convert == 1: # returns None if success, otherwise errormessage return convert_book_format(book_id, calibrepath, u'epub', book_format.lower(), user_id, kindle_mail) if convert == 2: # returns None if success, otherwise errormessage return convert_book_format(book_id, calibrepath, u'azw3', book_format.lower(), user_id, kindle_mail) for entry in iter(book.data): if entry.format.upper() == book_format.upper(): converted_file_name = entry.name + '.' + book_format.lower() link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(book.title)) EmailText = _(u"%(book)s send to Kindle", book=link) WorkerThread.add(user_id, TaskEmail(_(u"Send to Kindle"), book.path, converted_file_name, config.get_mail_settings(), kindle_mail, EmailText, _(u'This e-mail has been sent via Calibre-Web.'))) return return _(u"The requested file could not be read. Maybe wrong permissions?")
CWE-918
16
def test_http11_listlentwo(self): body = string.ascii_letters to_send = "GET /list_lentwo HTTP/1.1\n" "Content-Length: %s\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in (body[0], body[1:]): expected += tobytes( "%s\r\n%s\r\n" % (str(hex(len(chunk))[2:].upper()), chunk) ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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 save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1" or ip == "0.0.0.0" or ip == "::": log.error("Localhost was accessed for cover upload") return False, _("You are not allowed to access localhost for cover uploads") img = requests.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling img.raise_for_status() return save_cover(img, book_path) except (socket.gaierror, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout) as ex: log.info(u'Cover Download Error %s', ex) return False, _("Error Downloading Cover") except MissingDelegateError as ex: log.info(u'File Format Error %s', ex) return False, _("Cover Format Error")
CWE-918
16
def testCapacity(self): capacity = 3 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, name='pi') gi = array_ops.placeholder(dtypes.int64, name='gi') with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea( [ dtypes.int32, ], capacity=capacity, shapes=[[]]) stage = stager.put(pi, [x], [0]) get = stager.get() size = stager.size() G.finalize() from six.moves import queue as Queue import threading queue = Queue.Queue() n = 8 with self.session(graph=G) as sess: # Stage data in a separate thread which will block # when it hits the staging area's capacity and thus # not fill the queue with n tokens def thread_run(): for i in range(n): sess.run(stage, feed_dict={x: i, pi: i}) queue.put(0) t = threading.Thread(target=thread_run) t.daemon = True t.start() # Get tokens from the queue until a timeout occurs try: for i in range(n): queue.get(timeout=TIMEOUT) except Queue.Empty: pass # Should've timed out on the iteration 'capacity' if not i == capacity: self.fail("Expected to timeout on iteration '{}' " "but instead timed out on iteration '{}' " "Staging Area size is '{}' and configured " "capacity is '{}'.".format(capacity, i, sess.run(size), capacity)) # Should have capacity elements in the staging area self.assertTrue(sess.run(size) == capacity) # Clear the staging area completely for i in range(n): sess.run(get) self.assertTrue(sess.run(size) == 0)
CWE-843
43
def make_homeserver(self, reactor, clock): config = self.default_config() config["redaction_retention_period"] = "30d" return self.setup_test_homeserver( resource_for_federation=Mock(), http_client=None, config=config )
CWE-601
11
def test_process_request__no_file(self, rf, caplog): request = rf.post("/", data={"file": "does_not_exist.txt", "s3file": "file"}) S3FileMiddleware(lambda x: None)(request) assert not request.FILES.getlist("file") assert "File not found: does_not_exist.txt" in caplog.text
CWE-22
2
def _contains_display_name(self, display_name: str) -> bool: if not display_name: return False body = self._event.content.get("body", None) if not body or not isinstance(body, str): return False # Similar to _glob_matches, but do not treat display_name as a glob. r = regex_cache.get((display_name, False, True), None) if not r: r1 = re.escape(display_name) r1 = _re_word_boundary(r1) r = re.compile(r1, flags=re.IGNORECASE) regex_cache[(display_name, False, True)] = r return bool(r.search(body))
CWE-331
72
def get_response(self): token_serializer = self.token_serializer_class( instance=self.token, context=self.get_serializer_context(), ) data = token_serializer.data data['next'] = self.serializer.validated_data['code'].next return Response(data, status=status.HTTP_200_OK)
CWE-312
71
def test_file_insert(self, request, 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" with wait_for_page_load(driver, timeout=10): file_input.submit() assert storage.exists("tmp/%s.txt" % request.node.name) with pytest.raises(NoSuchElementException): error = driver.find_element(By.XPATH, "//body[@JSError]") pytest.fail(error.get_attribute("JSError"))
CWE-22
2
def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_) except (AttributeError, KeyError, TypeError) as e: return False
CWE-22
2
def render_prepare_search_form(cc): # prepare data for search-form tags = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() series = calibre_db.session.query(db.Series)\ .join(db.books_series_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series'))\ .order_by(db.Series.name)\ .filter(calibre_db.common_filters()).all() shelves = ub.session.query(ub.Shelf)\ .filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(current_user.id)))\ .order_by(ub.Shelf.name).all() extensions = calibre_db.session.query(db.Data)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(db.Data.format)\ .order_by(db.Data.format).all() if current_user.filter_language() == u"all": languages = calibre_db.speaking_language() else: languages = None return render_title_template('search_form.html', tags=tags, languages=languages, extensions=extensions, series=series,shelves=shelves, title=_(u"Advanced Search"), cc=cc, page="advsearch")
CWE-918
16
def logout(): if current_user is not None and current_user.is_authenticated: ub.delete_user_session(current_user.id, flask_session.get('_id',"")) logout_user() if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() log.debug(u"User logged out") return redirect(url_for('web.login'))
CWE-918
16
def test_request_login_code(self): response = self.client.post('/accounts-rest/login/', { 'username': self.user.username, 'next': '/private/', }) self.assertEqual(response.status_code, 200) login_code = LoginCode.objects.filter(user=self.user).first() self.assertIsNotNone(login_code) self.assertEqual(login_code.next, '/private/') self.assertEqual(len(mail.outbox), 1) self.assertIn( 'http://testserver/accounts/login/code/?code={}'.format(login_code.code), mail.outbox[0].body, )
CWE-312
71
def _decompress(compressed_path: Text, target_path: Text) -> None: with tarfile.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists
CWE-23
74
def test_credits_one(self, expected_count=1): self.add_change() data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( data, [{"Czech": [("[email protected]", "Weblate Test", expected_count)]}] )
CWE-79
1
def test_build_attr(self): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", "data-fields-policy", "data-fields-key", } assert ClearableFileInput().build_attrs({})["class"] == "s3file" assert ( ClearableFileInput().build_attrs({"class": "my-class"})["class"] == "my-class s3file" )
CWE-22
2
def test_filelike_nocl_http10(self): to_send = "GET /filelike_nocl HTTP/1.0\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.0") 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) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
CWE-444
41