Skip to content
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

TECH 292 - Remove SupportedTypes Constraint #74

Merged
merged 14 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
567 changes: 252 additions & 315 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,6 @@ To simplify the deployment of the canisters we provide a script `deploy-civic.sh
./scripts/deploy-civic.sh local
```

Note: The script stops dfx after it executes. If you want to call your canisters, you have to start it again as `dfx start --background`.

### Manual deployment
Steps for the manual deployment:
1. **Create canisters and start the local Internet Computer replica**:
Expand Down
1 change: 1 addition & 0 deletions lib/vc_util/src/issuer_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub enum IssueCredentialError {
SignatureNotFound(String),
Internal(String),
UnsupportedCredentialSpec(String),
CredentialNotFound(String)
}

#[derive(Clone, Debug, CandidType, Deserialize, Eq, PartialEq)]
Expand Down
10 changes: 0 additions & 10 deletions scripts/deploy-civic.sh
Original file line number Diff line number Diff line change
Expand Up @@ -157,18 +157,8 @@ main() {
exit 1
fi

# Stop the local DFX environment if it was started
if [ "$network" = "local" ]; then
echo "Stopping local DFX environment..."
if ! dfx stop >>$log_file 2>&1; then
echo "Error: Failed to stop local DFX environment. Check $log_file for details."
exit 1
fi
fi

echo "Deployment completed successfully."
echo "Please check deploy.log for details."

}

# Execute main function with provided network argument
Expand Down
22 changes: 11 additions & 11 deletions src/civic_canister_backend/src/consent_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,32 @@ use vc_util::issuer_api::{
};
use SupportedLanguage::{English, German};

/// Consent messages for the VerifiedAdult VC to be shown and approved to the user during the VC sharing flow
const ADULT_VC_DESCRIPTION_EN: &str = r###"# Verified Adult
/// Consent messages for the CivicPass VC to be shown and approved to the user during the VC sharing flow
const CIVIC_PASS_VC_DESCRIPTION_EN: &str = r###"# Civic Pass

Credential that states that the holder's age is at least 18 years."###;
const ADULT_VC_DESCRIPTION_DE: &str = r###"# Erwachsene Person
Credential that states that the holder possesses a Civic Pass."###;
const CIVIC_PASS_VC_DESCRIPTION_DE: &str = r###"# Civic Pass

Ausweis, der bestätigt, dass der Besitzer oder die Besitzerin mindestens 18 Jahre alt ist."###;
Bescheinigung, aus der hervorgeht, dass der Inhaber einen Civic Pass besitzt."###;

lazy_static! {
static ref CONSENT_MESSAGE_TEMPLATES: HashMap<(CredentialTemplateType, SupportedLanguage), &'static str> =
HashMap::from([
(
(CredentialTemplateType::VerifiedAdult, English),
ADULT_VC_DESCRIPTION_EN
(CredentialTemplateType::CivicPass, English),
CIVIC_PASS_VC_DESCRIPTION_EN
),
(
(CredentialTemplateType::VerifiedAdult, German),
ADULT_VC_DESCRIPTION_DE
(CredentialTemplateType::CivicPass, German),
CIVIC_PASS_VC_DESCRIPTION_DE
)
]);
}

/// Supported consent message types
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum CredentialTemplateType {
VerifiedAdult,
CivicPass,
}

/// Supported languages for consent messages
Expand All @@ -48,7 +48,7 @@ pub enum SupportedLanguage {
impl From<&SupportedCredentialType> for CredentialTemplateType {
fn from(value: &SupportedCredentialType) -> Self {
match value {
SupportedCredentialType::VerifiedAdult => CredentialTemplateType::VerifiedAdult,
SupportedCredentialType::CivicPass => CredentialTemplateType::CivicPass,
}
}
}
Expand Down
75 changes: 41 additions & 34 deletions src/civic_canister_backend/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,13 @@ lazy_static! {
/// Supported types of credentials that can be issued by this canister.
#[derive(Debug)]
pub enum SupportedCredentialType {
VerifiedAdult,
CivicPass,
}

impl fmt::Display for SupportedCredentialType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SupportedCredentialType::VerifiedAdult => write!(f, "VerifiedAdult"),
SupportedCredentialType::CivicPass => write!(f, "CivicPass"),
}
}
}
Expand Down Expand Up @@ -211,13 +212,6 @@ impl From<Vec<FullCredential>> for CredentialList {
}
}

/// Enumerates potential errors that can occur during credential operations.
#[derive(CandidType, Deserialize, Debug)]
pub enum CredentialError {
NoCredentialFound(String),
UnauthorizedSubject(String),
}

fn is_authorized_issuer(caller: Principal) -> bool {
CONFIG.with(|config_cell| {
let config = config_cell.borrow();
Expand All @@ -232,10 +226,10 @@ fn is_authorized_issuer(caller: Principal) -> bool {
async fn add_credentials(
principal: Principal,
new_credentials: Vec<Credential>,
) -> Result<String, CredentialError> {
) -> Result<String, IssueCredentialError> {
// Check if the caller is the authorized principal
if !is_authorized_issuer(caller()) {
return Err(CredentialError::UnauthorizedSubject(
return Err(IssueCredentialError::UnauthorizedSubject(
dankelleher marked this conversation as resolved.
Show resolved Hide resolved
"Unauthorized: You do not have permission to add credentials.".to_string(),
));
}
Expand Down Expand Up @@ -280,10 +274,10 @@ async fn add_credentials(
async fn remove_credential(
principal: Principal,
credential_id: String,
) -> Result<String, CredentialError> {
) -> Result<String, IssueCredentialError> {
// Check if the caller is an authorized issuer
if !is_authorized_issuer(caller()) {
return Err(CredentialError::UnauthorizedSubject(
return Err(IssueCredentialError::UnauthorizedSubject(
dankelleher marked this conversation as resolved.
Show resolved Hide resolved
"Unauthorized: You do not have permission to remove credentials.".to_string(),
));
}
Expand Down Expand Up @@ -313,20 +307,20 @@ async fn remove_credential(
credentials.insert(principal, CredentialList(existing_credentials_vec));
Ok("Credential removed successfully".to_string())
} else {
Err(CredentialError::UnauthorizedSubject(
Err(IssueCredentialError::UnauthorizedSubject(
dankelleher marked this conversation as resolved.
Show resolved Hide resolved
"Unauthorized: You do not have permission to remove this credential."
.to_string(),
))
}
} else {
Err(CredentialError::NoCredentialFound(format!(
Err(IssueCredentialError::UnauthorizedSubject(format!(
"Credential not found with id {} for principal {}",
credential_id,
principal.to_text()
)))
}
} else {
Err(CredentialError::NoCredentialFound(format!(
Err(IssueCredentialError::UnauthorizedSubject(format!(
dankelleher marked this conversation as resolved.
Show resolved Hide resolved
"No credentials found for principal {}",
principal.to_text()
)))
Expand All @@ -343,12 +337,12 @@ async fn update_credential(
principal: Principal,
credential_id: String,
updated_credential: Credential,
) -> Result<String, CredentialError> {
) -> Result<String, IssueCredentialError> {
let caller = caller();

// Check if the caller is an authorized issuer
if !is_authorized_issuer(caller) {
return Err(CredentialError::UnauthorizedSubject(
return Err(IssueCredentialError::UnauthorizedSubject(
"Unauthorized: You do not have permission to update credentials.".to_string(),
));
}
Expand Down Expand Up @@ -380,20 +374,20 @@ async fn update_credential(
updated_stored_credential
))
} else {
Err(CredentialError::UnauthorizedSubject(
Err(IssueCredentialError::UnauthorizedSubject(
"Unauthorized: You do not have permission to update this credential."
.to_string(),
))
}
} else {
Err(CredentialError::NoCredentialFound(format!(
Err(IssueCredentialError::UnauthorizedSubject(format!(
"No credential found with ID {} for principal {}",
credential_id,
principal.to_text()
)))
}
} else {
Err(CredentialError::NoCredentialFound(format!(
Err(IssueCredentialError::UnauthorizedSubject(format!(
"No credentials found for principal {}",
principal.to_text()
)))
Expand All @@ -405,11 +399,11 @@ async fn update_credential(
/// Retrieves all credentials for a given principal.
#[query]
#[candid_method(query)]
fn get_all_credentials(principal: Principal) -> Result<Vec<FullCredential>, CredentialError> {
fn get_all_credentials(principal: Principal) -> Result<Vec<FullCredential>, IssueCredentialError> {
if let Some(c) = CREDENTIALS.with(|c| c.borrow().get(&principal)) {
Ok(c.into())
} else {
Err(CredentialError::NoCredentialFound(format!(
Err(IssueCredentialError::UnauthorizedSubject(format!(
"No credentials found for the principal {}",
principal.to_text()
)))
Expand Down Expand Up @@ -564,8 +558,9 @@ fn verify_authorized_principal(
alias_tuple.id_dapp.to_text(),
credential_type
);
Err(IssueCredentialError::UnauthorizedSubject(format!(
"Unauthorized principal {}",

Err(IssueCredentialError::CredentialNotFound(format!(
"Credential not found for principal {}",
alias_tuple.id_dapp.to_text()
)))
}
Expand All @@ -575,7 +570,7 @@ pub(crate) fn verify_credential_spec(
spec: &CredentialSpec,
) -> Result<SupportedCredentialType, String> {
match spec.credential_type.as_str() {
"VerifiedAdult" => Ok(SupportedCredentialType::VerifiedAdult),
"CivicPass" => Ok(SupportedCredentialType::CivicPass),
other => Err(format!("Credential {} is not supported", other)),
}
}
Expand Down Expand Up @@ -614,13 +609,26 @@ fn prepare_credential_jwt(
return Err(IssueCredentialError::UnsupportedCredentialSpec(err));
}
};
// Currently only supports VerifiedAdults spec
let credential = verify_authorized_principal(credential_type, alias_tuple)?;
Ok(build_credential(
alias_tuple.id_alias,
credential_spec,
credential,
))

let credential = verify_authorized_principal(credential_type, alias_tuple);

match credential {
Err(err) => {
match err {
IssueCredentialError::CredentialNotFound(_) => {
// If the user does not have the credential, return an empty string so the identity canister does not show an error message
return Ok("".to_string());
}
_ => {
return Err(err);
}

}
},
Ok(credential) => {
return Ok(build_credential(alias_tuple.id_dapp, credential_spec, credential));
}
}
}

/// Internal parameters to pass to the build_credential_jwt function.
Expand Down Expand Up @@ -671,7 +679,6 @@ fn build_credential_jwt(params: CredentialParams) -> String {
let mut credential = CredentialBuilder::default()
.id(Url::parse(params.credential_id).unwrap())
.issuer(Url::parse(params.issuer).unwrap())
.type_("VerifiedCredential".to_string())
.type_(params.spec.credential_type)
.subjects(subjects) // add objects to the credentialSubject
.expiration_date(expiration_date);
Expand Down
Loading