feat: harden community production foundation through story 1.5
This commit is contained in:
1 parent
c30461cc92
commit
f6fc2e5c9b
161 files changed
+16758
-2515
No files matched your search
@@ -0,0 +1,206 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
const MAX_DIAGNOSTICS: usize = 100;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub enum DiagnosticCode {
|
||||
MissingRequired,
|
||||
InvalidEncoding,
|
||||
InvalidType,
|
||||
OutOfRange,
|
||||
UnknownField,
|
||||
Conflict,
|
||||
UnsafeCombination,
|
||||
DeprecatedNoEffect,
|
||||
}
|
||||
|
||||
impl Serialize for DiagnosticCode {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl DiagnosticCode {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::MissingRequired => "config.missing_required",
|
||||
Self::InvalidEncoding => "config.invalid_encoding",
|
||||
Self::InvalidType => "config.invalid_type",
|
||||
Self::OutOfRange => "config.out_of_range",
|
||||
Self::UnknownField => "config.unknown_field",
|
||||
Self::Conflict => "config.conflict",
|
||||
Self::UnsafeCombination => "config.unsafe_combination",
|
||||
Self::DeprecatedNoEffect => "config.deprecated_no_effect",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
pub struct Diagnostic {
|
||||
pub code: DiagnosticCode,
|
||||
pub field: String,
|
||||
pub message_ru: &'static str,
|
||||
pub message_en: &'static str,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub(crate) fn new(code: DiagnosticCode, field: impl Into<String>) -> Self {
|
||||
let (message_ru, message_en) = match code {
|
||||
DiagnosticCode::MissingRequired => (
|
||||
"Обязательный параметр не настроен.",
|
||||
"A required configuration field is not configured.",
|
||||
),
|
||||
DiagnosticCode::InvalidEncoding => (
|
||||
"Параметр должен быть корректной строкой UTF-8.",
|
||||
"The configuration field must be valid UTF-8.",
|
||||
),
|
||||
DiagnosticCode::InvalidType => (
|
||||
"Параметр имеет недопустимый тип или формат.",
|
||||
"The configuration field has an invalid type or format.",
|
||||
),
|
||||
DiagnosticCode::OutOfRange => (
|
||||
"Параметр находится вне допустимых границ.",
|
||||
"The configuration field is outside its allowed bounds.",
|
||||
),
|
||||
DiagnosticCode::UnknownField => (
|
||||
"Неизвестный параметр в управляемом пространстве имён.",
|
||||
"Unknown field in an owned configuration namespace.",
|
||||
),
|
||||
DiagnosticCode::Conflict => (
|
||||
"Одновременно заданы конфликтующие источники конфигурации.",
|
||||
"Conflicting configuration sources are set at the same time.",
|
||||
),
|
||||
DiagnosticCode::UnsafeCombination => (
|
||||
"Комбинация параметров небезопасна или противоречива.",
|
||||
"The configuration combination is unsafe or inconsistent.",
|
||||
),
|
||||
DiagnosticCode::DeprecatedNoEffect => (
|
||||
"Устаревший параметр не имеет поддерживаемого эффекта.",
|
||||
"The deprecated field has no supported effect.",
|
||||
),
|
||||
};
|
||||
let mut field = field.into();
|
||||
if field.len() > 256 {
|
||||
let mut boundary = 256;
|
||||
while !field.is_char_boundary(boundary) {
|
||||
boundary -= 1;
|
||||
}
|
||||
field.truncate(boundary);
|
||||
}
|
||||
Self {
|
||||
code,
|
||||
field,
|
||||
message_ru,
|
||||
message_en,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ConfigError {
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
omitted: usize,
|
||||
}
|
||||
|
||||
impl ConfigError {
|
||||
pub fn single(code: DiagnosticCode, field: impl Into<String>) -> Self {
|
||||
Self::from_diagnostics(vec![Diagnostic::new(code, field)])
|
||||
}
|
||||
|
||||
pub(crate) fn from_diagnostics(mut diagnostics: Vec<Diagnostic>) -> Self {
|
||||
diagnostics.sort();
|
||||
diagnostics.dedup();
|
||||
let mut omitted = diagnostics.len().saturating_sub(MAX_DIAGNOSTICS);
|
||||
diagnostics.truncate(MAX_DIAGNOSTICS);
|
||||
while serialized_len(&diagnostics, omitted) > 65_536 && !diagnostics.is_empty() {
|
||||
diagnostics.pop();
|
||||
omitted += 1;
|
||||
}
|
||||
Self {
|
||||
diagnostics,
|
||||
omitted,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn diagnostics(&self) -> &[Diagnostic] {
|
||||
&self.diagnostics
|
||||
}
|
||||
|
||||
pub fn omitted(&self) -> usize {
|
||||
self.omitted
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> String {
|
||||
#[derive(Serialize)]
|
||||
struct Report<'a> {
|
||||
diagnostics: &'a [Diagnostic],
|
||||
omitted: usize,
|
||||
}
|
||||
serde_json::to_string(&Report {
|
||||
diagnostics: &self.diagnostics,
|
||||
omitted: self.omitted,
|
||||
})
|
||||
.unwrap_or_else(|_| "{\"diagnostics\":[],\"omitted\":0}".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn serialized_len(diagnostics: &[Diagnostic], omitted: usize) -> usize {
|
||||
#[derive(Serialize)]
|
||||
struct Report<'a> {
|
||||
diagnostics: &'a [Diagnostic],
|
||||
omitted: usize,
|
||||
}
|
||||
serde_json::to_vec(&Report {
|
||||
diagnostics,
|
||||
omitted,
|
||||
})
|
||||
.map_or(usize::MAX, |value| value.len())
|
||||
}
|
||||
|
||||
impl fmt::Display for ConfigError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
for (index, diagnostic) in self.diagnostics.iter().enumerate() {
|
||||
if index > 0 {
|
||||
formatter.write_str("; ")?;
|
||||
}
|
||||
write!(
|
||||
formatter,
|
||||
"{} field={} ru={} en={}",
|
||||
diagnostic.code.as_str(),
|
||||
diagnostic.field,
|
||||
diagnostic.message_ru,
|
||||
diagnostic.message_en
|
||||
)?;
|
||||
}
|
||||
if self.omitted > 0 {
|
||||
write!(formatter, "; diagnostics_omitted={}", self.omitted)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConfigError {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unicode_fields_and_worst_case_json_remain_bounded() {
|
||||
let field = format!("{}{}", "\\\"".repeat(120), "💣".repeat(100));
|
||||
let diagnostics = (0..200)
|
||||
.map(|index| Diagnostic::new(DiagnosticCode::InvalidType, format!("{index}:{field}")))
|
||||
.collect();
|
||||
let error = ConfigError::from_diagnostics(diagnostics);
|
||||
let json = error.to_json();
|
||||
assert!(json.len() <= 65_536);
|
||||
assert!(error.omitted() > 0);
|
||||
assert!(serde_json::from_str::<serde_json::Value>(&json).is_ok());
|
||||
assert!(json.contains("config.invalid_type"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user