Skip to content

refactor(rust/signed-doc): add parameters field #317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 47 additions & 84 deletions rust/signed_doc/src/metadata/extra_fields.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
//! Catalyst Signed Document Extra Fields.

use catalyst_types::{problem_report::ProblemReport, uuid::UuidV4};
use catalyst_types::problem_report::ProblemReport;
use coset::{cbor::Value, Label, ProtectedHeader};

use super::{
cose_protected_header_find,
utils::{decode_document_field_from_protected_header, CborUuidV4},
DocumentRef, Section,
cose_protected_header_find, utils::decode_document_field_from_protected_header, DocumentRef,
Section,
};

/// `ref` field COSE key value
Expand All @@ -19,13 +18,13 @@ const REPLY_KEY: &str = "reply";
const SECTION_KEY: &str = "section";
/// `collabs` field COSE key value
const COLLABS_KEY: &str = "collabs";
/// `brand_id` field COSE key value
/// `parameters` field COSE key value
const PARAMETERS_KEY: &str = "parameters";
/// `brand_id` field COSE key value (alias of the `parameters` field)
const BRAND_ID_KEY: &str = "brand_id";
/// `campaign_id` field COSE key value
/// `campaign_id` field COSE key value (alias of the `parameters` field)
const CAMPAIGN_ID_KEY: &str = "campaign_id";
/// `election_id` field COSE key value
const ELECTION_ID_KEY: &str = "election_id";
/// `category_id` field COSE key value
/// `category_id` field COSE key value (alias of the `parameters` field)
const CATEGORY_ID_KEY: &str = "category_id";

/// Extra Metadata Fields.
Expand All @@ -48,18 +47,9 @@ pub struct ExtraFields {
/// Reference to the document collaborators. Collaborator type is TBD.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
collabs: Vec<String>,
/// Unique identifier for the brand that is running the voting.
/// Reference to the parameters document.
#[serde(skip_serializing_if = "Option::is_none")]
brand_id: Option<DocumentRef>,
/// Unique identifier for the campaign of voting.
#[serde(skip_serializing_if = "Option::is_none")]
campaign_id: Option<DocumentRef>,
/// Unique identifier for the election.
#[serde(skip_serializing_if = "Option::is_none")]
election_id: Option<UuidV4>,
/// Unique identifier for the voting category as a collection of proposals.
#[serde(skip_serializing_if = "Option::is_none")]
category_id: Option<DocumentRef>,
parameters: Option<DocumentRef>,
}

impl ExtraFields {
Expand Down Expand Up @@ -93,28 +83,10 @@ impl ExtraFields {
&self.collabs
}

/// Return `brand_id` field.
#[must_use]
pub fn brand_id(&self) -> Option<DocumentRef> {
self.brand_id
}

/// Return `campaign_id` field.
#[must_use]
pub fn campaign_id(&self) -> Option<DocumentRef> {
self.campaign_id
}

/// Return `election_id` field.
/// Return `parameters` field.
#[must_use]
pub fn election_id(&self) -> Option<UuidV4> {
self.election_id
}

/// Return `category_id` field.
#[must_use]
pub fn category_id(&self) -> Option<DocumentRef> {
self.category_id
pub fn parameters(&self) -> Option<DocumentRef> {
self.parameters
}

/// Fill the COSE header `ExtraFields` data into the header builder.
Expand All @@ -141,26 +113,11 @@ impl ExtraFields {
Value::Array(self.collabs.iter().cloned().map(Value::Text).collect()),
);
}
if let Some(brand_id) = &self.brand_id {
builder = builder.text_value(BRAND_ID_KEY.to_string(), Value::try_from(*brand_id)?);
}

if let Some(campaign_id) = &self.campaign_id {
builder =
builder.text_value(CAMPAIGN_ID_KEY.to_string(), Value::try_from(*campaign_id)?);
if let Some(parameters) = &self.parameters {
builder = builder.text_value(PARAMETERS_KEY.to_string(), Value::try_from(*parameters)?);
}

if let Some(election_id) = &self.election_id {
builder = builder.text_value(
ELECTION_ID_KEY.to_string(),
Value::try_from(CborUuidV4(*election_id))?,
);
}

if let Some(category_id) = &self.category_id {
builder =
builder.text_value(CATEGORY_ID_KEY.to_string(), Value::try_from(*category_id)?);
}
Ok(builder)
}

Expand Down Expand Up @@ -196,41 +153,47 @@ impl ExtraFields {
COSE_DECODING_CONTEXT,
error_report,
);
let brand_id = decode_document_field_from_protected_header(
protected,

// process `parameters` field and all its aliases
let (parameters, count) = [
PARAMETERS_KEY,
BRAND_ID_KEY,
COSE_DECODING_CONTEXT,
error_report,
);
let campaign_id = decode_document_field_from_protected_header(
protected,
CAMPAIGN_ID_KEY,
COSE_DECODING_CONTEXT,
error_report,
);
let election_id = decode_document_field_from_protected_header::<CborUuidV4>(
protected,
ELECTION_ID_KEY,
COSE_DECODING_CONTEXT,
error_report,
)
.map(|v| v.0);
let category_id = decode_document_field_from_protected_header(
protected,
CATEGORY_ID_KEY,
COSE_DECODING_CONTEXT,
error_report,
);
]
.iter()
.map(|field_name| -> Option<DocumentRef> {
decode_document_field_from_protected_header(
protected,
field_name,
COSE_DECODING_CONTEXT,
error_report,
)
})
.fold((None, 0_u32), |(res, count), v| {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick -> #327
Couldn't make a classic gh suggestion, because the code spans deleted lines.

(
res.or(v),
if v.is_some() {
count.saturating_add(1)
} else {
count
},
)
});
if count > 1 {
error_report.duplicate_field(
"brand_id, campaign_id, category_id",
"Only value at the same time is allowed parameters, brand_id, campaign_id, category_id",
"Validation of parameters field aliases"
);
}

let mut extra = ExtraFields {
doc_ref,
template,
reply,
section,
brand_id,
campaign_id,
election_id,
category_id,
parameters,
..Default::default()
};

Expand Down
51 changes: 29 additions & 22 deletions rust/signed_doc/src/validator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub(crate) mod utils;

use std::{
collections::HashMap,
fmt,
sync::LazyLock,
time::{Duration, SystemTime},
};
Expand All @@ -13,18 +14,19 @@ use anyhow::Context;
use catalyst_types::{
catalyst_id::{role_index::RoleId, CatalystId},
problem_report::ProblemReport,
uuid::Uuid,
uuid::{Uuid, UuidV4},
};
use coset::{CoseSign, CoseSignature};
use rules::{
CategoryRule, ContentEncodingRule, ContentRule, ContentSchema, ContentTypeRule, RefRule,
ContentEncodingRule, ContentRule, ContentSchema, ContentTypeRule, ParametersRule, RefRule,
ReplyRule, Rules, SectionRule, SignatureKidRule,
};

use crate::{
doc_types::{
COMMENT_DOCUMENT_UUID_TYPE, COMMENT_TEMPLATE_UUID_TYPE, PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
PROPOSAL_DOCUMENT_UUID_TYPE, PROPOSAL_TEMPLATE_UUID_TYPE,
CATEGORY_DOCUMENT_UUID_TYPE, COMMENT_DOCUMENT_UUID_TYPE, COMMENT_TEMPLATE_UUID_TYPE,
PROPOSAL_ACTION_DOCUMENT_UUID_TYPE, PROPOSAL_DOCUMENT_UUID_TYPE,
PROPOSAL_TEMPLATE_UUID_TYPE,
},
providers::{CatalystSignedDocumentProvider, VerifyingKeyProvider},
CatalystSignedDocument, ContentEncoding, ContentType,
Expand All @@ -33,6 +35,14 @@ use crate::{
/// A table representing a full set or validation rules per document id.
static DOCUMENT_RULES: LazyLock<HashMap<Uuid, Rules>> = LazyLock::new(document_rules_init);

/// Returns an [`UuidV4`] from the provided argument, panicking if the argument is
/// invalid.
#[allow(clippy::expect_used)]
fn expect_uuidv4<T>(t: T) -> UuidV4
where T: TryInto<UuidV4, Error: fmt::Debug> {
t.try_into().expect("Must be a valid UUID V4")
}

/// `DOCUMENT_RULES` initialization function
#[allow(clippy::expect_used)]
fn document_rules_init() -> HashMap<Uuid, Rules> {
Expand All @@ -47,18 +57,20 @@ fn document_rules_init() -> HashMap<Uuid, Rules> {
optional: false,
},
content: ContentRule::Templated {
exp_template_type: PROPOSAL_TEMPLATE_UUID_TYPE
.try_into()
.expect("Must be a valid UUID V4"),
exp_template_type: expect_uuidv4(PROPOSAL_TEMPLATE_UUID_TYPE),
},
parameters: ParametersRule::Specified {
exp_parameters_type: expect_uuidv4(CATEGORY_DOCUMENT_UUID_TYPE),
optional: true,
},
category: CategoryRule::Specified { optional: true },
doc_ref: RefRule::NotSpecified,
reply: ReplyRule::NotSpecified,
section: SectionRule::NotSpecified,
kid: SignatureKidRule {
exp: &[RoleId::Proposer],
},
};

document_rules_map.insert(PROPOSAL_DOCUMENT_UUID_TYPE, proposal_document_rules);

let comment_document_rules = Rules {
Expand All @@ -70,24 +82,18 @@ fn document_rules_init() -> HashMap<Uuid, Rules> {
optional: false,
},
content: ContentRule::Templated {
exp_template_type: COMMENT_TEMPLATE_UUID_TYPE
.try_into()
.expect("Must be a valid UUID V4"),
exp_template_type: expect_uuidv4(COMMENT_TEMPLATE_UUID_TYPE),
},
doc_ref: RefRule::Specified {
exp_ref_type: PROPOSAL_DOCUMENT_UUID_TYPE
.try_into()
.expect("Must be a valid UUID V4"),
exp_ref_type: expect_uuidv4(PROPOSAL_DOCUMENT_UUID_TYPE),
optional: false,
},
reply: ReplyRule::Specified {
exp_reply_type: COMMENT_DOCUMENT_UUID_TYPE
.try_into()
.expect("Must be a valid UUID V4"),
exp_reply_type: expect_uuidv4(COMMENT_DOCUMENT_UUID_TYPE),
optional: true,
},
section: SectionRule::Specified { optional: true },
category: CategoryRule::NotSpecified,
parameters: ParametersRule::NotSpecified,
kid: SignatureKidRule {
exp: &[RoleId::Role0],
},
Expand All @@ -112,11 +118,12 @@ fn document_rules_init() -> HashMap<Uuid, Rules> {
optional: false,
},
content: ContentRule::Static(ContentSchema::Json(proposal_action_json_schema)),
category: CategoryRule::Specified { optional: true },
parameters: ParametersRule::Specified {
exp_parameters_type: expect_uuidv4(CATEGORY_DOCUMENT_UUID_TYPE),
optional: true,
},
doc_ref: RefRule::Specified {
exp_ref_type: PROPOSAL_DOCUMENT_UUID_TYPE
.try_into()
.expect("Must be a valid UUID V4"),
exp_ref_type: expect_uuidv4(PROPOSAL_DOCUMENT_UUID_TYPE),
optional: false,
},
reply: ReplyRule::NotSpecified,
Expand Down
Loading
Loading