Skip to content

Commit

Permalink
Hotfix for vulnerabilities counting (#2647)
Browse files Browse the repository at this point in the history
### What's done:
- Some vulnerabilities cannot be deserialized, so the number get's broken. Added a new endpoint that just makes count(*)
  • Loading branch information
orchestr7 authored Oct 2, 2023
1 parent 6deb3a5 commit 284f097
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ class WebSecurityConfig(
"/api/$v1/contests/*/*/best",
"/api/demo/*/run",
"/api/$v1/vulnerabilities/by-filter",
"/api/$v1/vulnerabilities/count/by-filter",
// `fossGraphView` is public page
"/api/$v1/vulnerabilities/by-identifier-with-description",
"/api/$v1/vulnerabilities/download",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,10 @@ class VulnerabilityController(
summary = "Get vulnerability by identifier with description.",
description = "Get vulnerability by identifier with description.",
)
@ApiResponse(responseCode = "200", description = "Successfully fetched vulnerability by identifier with description")
@ApiResponse(
responseCode = "200",
description = "Successfully fetched vulnerability by identifier with description"
)
fun getVulnerabilityWithDescriptionByIdentifier(
@RequestParam identifier: String,
): Mono<VulnerabilityDto> = vulnerabilityService.getVulnerabilityWithDescriptionByIdentifier(identifier)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ val languageSelector: VFC = FC {
PlatformLanguages.values().map { language ->
a {
className = ClassName("dropdown-item")
style = jso { cursor = "pointer".unsafeCast<Cursor>() }
onClick = { setSelectedLanguage(language) }
span { +language.label }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ val vulnerabilityCollectionView: FC<VulnerabilityCollectionViewProps> = FC { pro
div {
className = ClassName("d-flex justify-content-center")
div {
className = ClassName("col-4 d-flex align-items-stretch")
className = ClassName("col-4 align-items-stretch")
vulnerabilityIntroductionComponent()
}
div {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@

package com.saveourtool.save.frontend.components.views.welcome

import com.saveourtool.save.entities.vulnerability.VulnerabilityDto
import com.saveourtool.save.filters.VulnerabilityFilter
import com.saveourtool.save.filters.VulnerabilityFilter.Companion.approved
import com.saveourtool.save.frontend.components.views.welcome.pagers.vuln.renderVulnerabilityGeneralInfo
import com.saveourtool.save.frontend.externals.fontawesome.*
import com.saveourtool.save.frontend.externals.i18next.TranslationFunction
Expand All @@ -34,6 +33,8 @@ import kotlinx.browser.window
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

const val FIRST_RAW_HEIGHT = 33

val vulnWelcomeView: FC<WelcomeProps> = FC { props ->
useBackground(Style.VULN_DARK)
val (t) = useTranslation("welcome")
Expand All @@ -49,18 +50,18 @@ val vulnWelcomeView: FC<WelcomeProps> = FC { props ->
oauthProviderInfoList?.let { setOauthProviders(it) }
}

val (vulnerabilities, setVulnerabilities) = useState<List<VulnerabilityDto>>(emptyList())
val (vulnerabilitiesNumber, setVulnerabilitiesNumber) = useState(0L)
useRequest {
val vuln = post(
url = "$apiUrl/vulnerabilities/by-filter",
url = "$apiUrl/vulnerabilities/count/by-filter",
headers = jsonHeaders,
body = Json.encodeToString(VulnerabilityFilter.approved),
loadingHandler = ::loadingHandler,
responseHandler = ::noopResponseHandler,
body = Json.encodeToString(approved),
).unsafeMap {
it.decodeFromJsonString<List<VulnerabilityDto>>()
it.decodeFromJsonString<Long>()
}
setVulnerabilities(vuln)
setVulnerabilitiesNumber(vuln)
}

main {
Expand All @@ -86,7 +87,7 @@ val vulnWelcomeView: FC<WelcomeProps> = FC { props ->
className = ClassName("col-3 mr-4 mt-5")
div {
style = jso {
height = 30.rem
height = FIRST_RAW_HEIGHT.rem
}
className = ClassName("card z-index-0")
// if user is not logged in - he needs to input credentials
Expand All @@ -105,7 +106,7 @@ val vulnWelcomeView: FC<WelcomeProps> = FC { props ->
t
)
}
stats(vulnerabilities, t)
stats(vulnerabilitiesNumber, t)
}

div {
Expand All @@ -120,11 +121,11 @@ val vulnWelcomeView: FC<WelcomeProps> = FC { props ->
/**
* add a card getting all vulnerabilities and return nums
*
* @param vulnerabilities
* @param t [TranslationFunction] received from [com.saveourtool.save.frontend.externals.i18next.useTranslation] hook
* @param vulnerabilitiesNumber
*/
@Suppress("IDENTIFIER_LENGTH")
fun ChildrenBuilder.stats(vulnerabilities: List<VulnerabilityDto>, t: TranslationFunction) {
fun ChildrenBuilder.stats(vulnerabilitiesNumber: Long, t: TranslationFunction) {
div {
className = ClassName("card border border-primary rounded rounded-pill col mt-4 justify-content-center")
style = jso {
Expand All @@ -134,7 +135,7 @@ fun ChildrenBuilder.stats(vulnerabilities: List<VulnerabilityDto>, t: Translatio
className = ClassName("row justify-content-center")
h1 {
className = ClassName("text-primary")
+vulnerabilities.size.toString()
+vulnerabilitiesNumber.toString()
style = jso {
fontSize = 4.rem
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package com.saveourtool.save.frontend.components.views.welcome.pagers.vuln

import com.saveourtool.save.frontend.components.basic.markdown
import com.saveourtool.save.frontend.components.views.welcome.FIRST_RAW_HEIGHT
import com.saveourtool.save.frontend.externals.i18next.TranslationFunction
import js.core.jso
import react.ChildrenBuilder
Expand All @@ -30,13 +31,13 @@ fun ChildrenBuilder.renderVulnerabilityGeneralInfo(t: TranslationFunction) {
"What is vulnerability?".t(),
"/img/undraw_question.svg",
"Vulnerability is a weakness or flaw in a system, network, software, or hardware.".t(),
"mr-3",
"mr-3 px-4",
)
textCard(
"Why vulnerability archives important?".t(),
"Why is this archive needed?".t(),
"/img/undraw_share.svg",
"A vulnerability archive is vital as a centralized repository for documented vulnerabilities.".t(),
"ml-3",
"Archive importance".t(),
"ml-3 px-4",
)
}

Expand All @@ -58,7 +59,7 @@ private fun ChildrenBuilder.textCard(
div {
className = ClassName("card border border-primary rounded rounded-pill col $classes")
style = jso {
height = 30.rem
height = FIRST_RAW_HEIGHT.rem
}
div {
className = ClassName("d-flex justify-content-center")
Expand Down
4 changes: 2 additions & 2 deletions save-frontend/src/main/resources/locales/cn/welcome.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"Propose vulnerability": "报告漏洞",
"Top rating": "贡献排名",
"What is vulnerability?": "什么是漏洞",
"Why vulnerability archives important?": "为什么漏洞库如此重要",
"Why is this archive needed?": "为什么漏洞库如此重要",
"Useful links": "有用的链接",
"Vulnerability is a weakness or flaw in a system, network, software, or hardware.": "漏洞是系统、网络、软件或硬件中的弱点或缺陷,未经授权的个人或恶意软件可以利用这些弱点或缺陷来获得未经授权的访问、中断操作或窃取敏感信息。漏洞可能是由编程错误、配置错误、过时的软件或设计缺陷引起的。",
"A vulnerability archive is vital as a centralized repository for documented vulnerabilities.": "漏洞库作为记录漏洞的集中存储库至关重要。它为安全专业人员提供见解,有助于主动风险管理,并能够及时识别和缓解漏洞。它还增强了对趋势、模式和常见漏洞的理解,增强了针对未来威胁的整体安全态势。",
"Archive importance": "This service operates as a centralized repository, crucial for proposing, and reviewing day-one vulnerabilities. It features an aggregated database that allows security professionals to filter and search for vulnerabilities. Beyond this, our platform provides an API, enabling automated services to disclose, upload, and even download vulnerabilities using automated code analysis tools. Additionally, we introduce a specific Cosv extension to the osv schema. This extension is backward-compatible and offers detailed information vital for vulnerability identification and mitigation. This standard is driven by the China Computer Federation.",
"Links": "* [OSV Schema](https://ossf.github.io/osv-schema/) - 提供人类可读和机器可解释的数据格式。\n\n * [COSV Schema 1.0](https://mp.weixin.qq.com/s/1aJT1X09SVQeNzL8eHWT0Q) - 增强开源漏洞描述,\n 促进供应链安全和效率的标准化数据格式。\n\n * [cosv4k](https://github.com/saveourtool/cosv4k) - 用于 COSV Schema 的序列化和反序列化的 Kotlin 和 Java 模型。",
"Go to main page": "回到主页",
"Welcome": "欢迎",
Expand Down
4 changes: 2 additions & 2 deletions save-frontend/src/main/resources/locales/en/welcome.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"Propose vulnerability": "Propose vulnerability",
"Top rating": "Top rating",
"What is vulnerability?": "What is vulnerability?",
"Why vulnerability archives important?": "Why vulnerability archives important?",
"Why is this archive needed?": "Why is this archive needed?",
"Useful links": "Useful links",
"Vulnerability is a weakness or flaw in a system, network, software, or hardware.": "Vulnerability is a weakness or flaw in a system, network, software, or hardware that can be exploited by unauthorized individuals or malicious software to gain unauthorized access, disrupt operations, or steal sensitive information. Vulnerabilities can arise from programming errors, misconfigurations, outdated software, or design flaws.",
"A vulnerability archive is vital as a centralized repository for documented vulnerabilities.": "A vulnerability archive is vital as a centralized repository for documented vulnerabilities. It offers insights for security professionals, aids in proactive risk management, and enables timely vulnerability identification and mitigation. It also enhances understanding of trends, patterns, and common vulnerabilities, fortifying overall security posture against future threats.",
"Archive importance": "This service operates as a centralized repository, crucial for proposing, and reviewing day-one vulnerabilities. It features an aggregated database that allows security professionals to filter and search for vulnerabilities. Beyond this, our platform provides an API, enabling automated services to disclose, upload, and even download vulnerabilities using automated code analysis tools. Additionally, we introduce a specific Cosv extension to the osv schema. This extension is backward-compatible and offers detailed information vital for vulnerability identification and mitigation. This standard is driven by the China Computer Federation.",
"Links": "* [OSV Schema](https://ossf.github.io/osv-schema/) - offers a data format interpretable by humans and machines.\n\n * [COSV Schema 1.0](https://mp.weixin.qq.com/s/1aJT1X09SVQeNzL8eHWT0Q) - enhances open-source vulnerability descriptions,\n promotes standardized data sharing for supply chain security, and operational efficiency.\n\n * [cosv4k](https://github.com/saveourtool/cosv4k) - Kotlin and Java model for the serialization and deserialization of COSV Schema.",
"Go to main page": "Go to main page",
"Welcome": "Welcome",
Expand Down
4 changes: 2 additions & 2 deletions save-frontend/src/main/resources/locales/ru/welcome.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"Propose vulnerability": "Предложить Уязвимость",
"Top rating": "Рейтинг",
"What is vulnerability?": "Что такое Уязвимость?",
"Why vulnerability archives important?": "Почему архив Уязвимостей важен?",
"Why is this archive needed?": "Зачем этот архив нужен?",
"Useful links": "Полезные ссылки",
"Vulnerability is a weakness or flaw in a system, network, software, or hardware.": "Уязвимость — это слабое место или дефект в системе, сети, программном обеспечении или аппаратном обеспечении, который может быть использован третьими лицами или вредоносным программным обеспечением для получения несанкционированного доступа, нарушения работы или кражи конфиденциальной информации. Уязвимости могут возникать из-за программных ошибок, неправильной конфигурации, устаревшего программного обеспечения или конструктивных недостатков.",
"A vulnerability archive is vital as a centralized repository for documented vulnerabilities.": "Архив уязвимостей жизненно важен как централизованное хранилище документированных уязвимостей. Он предоставляет ценные данные для специалистов в области безопасности, способствует прогнозированию рисков и позволяет своевременно определять и устранять уязвимости. Также он расширяет понимание тенденций, моделей и типичных уязвимостей, повышая сохранность от будущих угроз.",
"Archive importance": "Архив уязвимостей жизненно важен как централизованное хранилище документированных уязвимостей. Он предоставляет ценные данные для специалистов в области безопасности, способствует прогнозированию рисков и позволяет своевременно определять и устранять уязвимости. Также он расширяет понимание тенденций, моделей и типичных уязвимостей, повышая сохранность от будущих угроз.",
"Links": "* [OSV Schema](https://ossf.github.io/osv-schema/) - предлагает формат данных, интерпретируемый как людьми, так и машинами.\n\n * [COSV Schema 1.0](https://mp.weixin.qq.com/s/1aJT1X09SVQeNzL8eHWT0Q) - улучшает систему описания уязвимостей с открытым исходным кодом,\nспособствует стандартизированному обмену данными для безопасности цепочки поставок и операционной эффективности.\n\n * [cosv4k](https://github.com/saveourtool/cosv4k) - Kotlin и Java модель для сериализации и десериализации COSV-схемы.",
"Go to main page": "Вернуться на главную страницу",
"Welcome": "Добро пожаловать",
Expand Down

0 comments on commit 284f097

Please sign in to comment.