use serde::{Deserialize, Serialize};
pub const MAX_ROW: usize = 64 << 10;
pub const MAX_WHEEL_METADATA: usize = 1 << 20;
pub const MAX_NPM_MANIFEST: usize = 1 << 20;
pub const MAX_ID: usize = 512;
pub const MAX_TEXT: usize = 16 << 10;
pub const MAX_DEPS: usize = 4096;
pub const MAX_CRATE_LINE: usize = 1 << 20;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Pinned {
pub name: String,
pub version: String,
pub from: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RowDep {
pub name: String,
#[serde(default)]
pub req: String,
#[serde(default)]
pub scope: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum IndexRow {
Deb { control: String },
Rpm {
#[serde(default)]
epoch: Option<String>,
#[serde(default)]
summary: Option<String>,
#[serde(default)]
license: Option<String>,
#[serde(default)]
url: Option<String>,
#[serde(default)]
vendor: Option<String>,
#[serde(default)]
sourcerpm: Option<String>,
#[serde(default)]
provides: Vec<String>,
#[serde(default)]
requires: Vec<String>,
},
Helm {
name: String,
version: String,
#[serde(default)]
app_version: Option<String>,
#[serde(default)]
description: Option<String>,
#[serde(default)]
dependencies: Vec<RowDep>,
},
Wheel {
#[serde(default, with = "b64")]
metadata: Option<Vec<u8>>,
#[serde(default)]
sha256: Option<String>,
},
Npm {
manifest: serde_json::Value,
integrity: String,
},
Maven {
group: String,
artifact: String,
version: String,
file: String,
#[serde(default)]
deps: Vec<RowDep>,
},
Go {
module: String,
version: String,
#[serde(default)]
requires: Vec<RowDep>,
},
Composer {
name: String,
#[serde(default)]
version: Option<String>,
},
Apk {
name: String,
version: String,
#[serde(default)]
depends: Vec<String>,
#[serde(default)]
provides: Vec<String>,
},
Crate {
name: String,
version: String,
line: serde_json::Value,
#[serde(default)]
pinned: Vec<Pinned>,
},
}
impl IndexRow {
pub fn kind(&self) -> &'static str {
match self {
IndexRow::Deb { .. } => "deb",
IndexRow::Rpm { .. } => "rpm",
IndexRow::Helm { .. } => "helm",
IndexRow::Wheel { .. } => "wheel",
IndexRow::Npm { .. } => "npm",
IndexRow::Maven { .. } => "maven",
IndexRow::Go { .. } => "go",
IndexRow::Crate { .. } => "crate",
IndexRow::Composer { .. } => "composer",
IndexRow::Apk { .. } => "apk",
}
}
pub fn check(&self) -> Result<(), String> {
let bad = |field: &str, why: &str| Err(format!("the {} row's {field} {why}", self.kind()));
match self {
IndexRow::Deb { control } => {
if control.is_empty() || !text_ok(control, MAX_ROW) {
return bad(
"control",
"is empty, longer than its cap or carries control characters",
);
}
}
IndexRow::Rpm {
epoch,
summary,
license,
url,
vendor,
sourcerpm,
provides,
requires,
} => {
if epoch.as_deref().is_some_and(|e| !id_ok(e)) {
return bad("epoch", "is not an id");
}
for (field, v) in [
("summary", summary),
("license", license),
("url", url),
("vendor", vendor),
("sourcerpm", sourcerpm),
] {
if v.as_deref().is_some_and(|t| !line_ok(t, MAX_TEXT)) {
return bad(
field,
"is longer than its cap or carries control characters",
);
}
}
for (field, v) in [("provides", provides), ("requires", requires)] {
if v.len() > MAX_DEPS
|| v.iter().any(|d| !line_ok(d, MAX_ID * 2) || d.is_empty())
{
return bad(
field,
"has too many entries, or one that is not a dependency",
);
}
}
}
IndexRow::Helm {
name,
version,
app_version,
description,
dependencies,
} => {
if let Err(why) = deps_ok(dependencies) {
return bad("dependencies", why);
}
if !id_ok(name) {
return bad("name", "is not an id");
}
if !id_ok(version) {
return bad("version", "is not an id");
}
if app_version.as_deref().is_some_and(|v| !id_ok(v)) {
return bad("app_version", "is not an id");
}
if description
.as_deref()
.is_some_and(|d| !line_ok(d, MAX_TEXT))
{
return bad(
"description",
"is longer than its cap or carries control characters",
);
}
}
IndexRow::Wheel { metadata, sha256 } => {
if metadata
.as_ref()
.is_some_and(|m| m.len() > MAX_WHEEL_METADATA)
{
return bad("metadata", "is larger than its cap");
}
match (metadata, sha256) {
(Some(_), Some(h)) if hex64(h) => {}
(None, None) => {}
_ => {
return bad(
"sha256",
"is not the metadata's sha256 (64 hex digits, with the metadata only)",
)
}
}
}
IndexRow::Npm {
manifest,
integrity,
} => {
if !manifest.is_object()
|| serde_json::to_vec(manifest)
.map(|v| v.len())
.unwrap_or(usize::MAX)
> MAX_NPM_MANIFEST
{
return bad("manifest", "is not an object, or is larger than its cap");
}
let b64 = integrity.strip_prefix("sha512-").unwrap_or("");
if b64.is_empty()
|| b64.len() > 100
|| !b64
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'='))
{
return bad("integrity", "is not a sha512- integrity");
}
}
IndexRow::Maven {
group,
artifact,
version,
file,
deps,
} => {
if let Err(why) = deps_ok(deps) {
return bad("deps", why);
}
for (field, v) in [
("group", group),
("artifact", artifact),
("version", version),
("file", file),
] {
if !id_ok(v)
|| v.contains('/')
|| v.contains('\\')
|| v == "."
|| v == ".."
|| v.starts_with("..")
{
return bad(field, "is not one path segment");
}
}
}
IndexRow::Go {
module,
version,
requires,
} => {
if let Err(why) = deps_ok(requires) {
return bad("requires", why);
}
if !id_ok(module) {
return bad("module", "is not an id");
}
if !id_ok(version) {
return bad("version", "is not an id");
}
}
IndexRow::Apk {
name,
version,
depends,
provides,
} => {
if !id_ok(name) || !id_ok(version) {
return bad("name", "or its version is not an id");
}
for (field, v) in [("depends", depends), ("provides", provides)] {
if v.len() > MAX_DEPS
|| v.iter().any(|d| d.is_empty() || !line_ok(d, MAX_ID * 2))
{
return bad(
field,
"has too many entries, or one that is not a dependency",
);
}
}
}
IndexRow::Composer { name, version } => {
let vendor_package = name.split_once('/').is_some_and(|(v, p)| {
!v.is_empty() && !p.is_empty() && !p.contains('/') && v != ".." && p != ".."
});
if !id_ok(name) || !vendor_package {
return bad("name", "is not `vendor/package`");
}
if version.as_deref().is_some_and(|v| !id_ok(v)) {
return bad("version", "is not an id");
}
}
IndexRow::Crate {
name,
version,
line,
pinned,
} => {
if !id_ok(name) || name.contains('/') {
return bad("name", "is not a crate name");
}
if !id_ok(version) {
return bad("version", "is not an id");
}
if !line.is_object()
|| line.get("name").and_then(|n| n.as_str()) != Some(name.as_str())
|| line.get("vers").and_then(|v| v.as_str()) != Some(version.as_str())
|| serde_json::to_vec(line)
.map(|v| v.len())
.unwrap_or(usize::MAX)
> MAX_CRATE_LINE
{
return bad(
"line",
"is not an index line of this crate, or is larger than its cap",
);
}
if pinned.len() > MAX_DEPS
|| pinned
.iter()
.any(|p| !id_ok(&p.name) || !id_ok(&p.version) || !id_ok(&p.from))
{
return bad(
"pinned",
"has too many entries, or one that is not a version",
);
}
}
}
let size = serde_json::to_vec(self)
.map(|v| v.len())
.unwrap_or(usize::MAX);
let cap = match self {
IndexRow::Wheel { .. } => MAX_WHEEL_METADATA * 4 / 3 + MAX_ROW,
IndexRow::Npm { .. } => MAX_NPM_MANIFEST + MAX_ROW,
IndexRow::Crate { .. } => MAX_CRATE_LINE + MAX_DEPS * 2 * MAX_ID,
IndexRow::Helm { .. }
| IndexRow::Maven { .. }
| IndexRow::Go { .. }
| IndexRow::Apk { .. } => MAX_ROW + MAX_DEPS * 3 * MAX_ID,
_ => MAX_ROW,
};
if size > cap {
return bad("size", "is larger than a row may be");
}
Ok(())
}
}
fn text_ok(s: &str, max: usize) -> bool {
s.len() <= max && !s.chars().any(|c| c.is_control() && c != '\n' && c != '\t')
}
fn line_ok(s: &str, max: usize) -> bool {
s.len() <= max && !s.chars().any(char::is_control)
}
fn deps_ok(deps: &[RowDep]) -> Result<(), &'static str> {
if deps.len() > MAX_DEPS
|| deps
.iter()
.any(|d| !id_ok(&d.name) || !line_ok(&d.req, MAX_ID) || !line_ok(&d.scope, MAX_ID))
{
return Err("has too many entries, or one that is not a dependency");
}
Ok(())
}
fn id_ok(s: &str) -> bool {
!s.is_empty() && line_ok(s, MAX_ID)
}
fn hex64(s: &str) -> bool {
s.len() == 64
&& s.bytes()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
}
mod b64 {
use base64::Engine as _;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
match v {
Some(b) => s.serialize_some(&base64::engine::general_purpose::STANDARD.encode(b)),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
let s: Option<String> = Option::deserialize(d)?;
s.map(|t| {
base64::engine::general_purpose::STANDARD
.decode(t)
.map_err(serde::de::Error::custom)
})
.transpose()
}
}