Skip to content

Commit

Permalink
Remove long credential format
Browse files Browse the repository at this point in the history
  • Loading branch information
GamePad64 committed Dec 8, 2024
1 parent adc74c2 commit db26ebe
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 146 deletions.
3 changes: 2 additions & 1 deletion notifico-core/src/credentials/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::error::EngineError;
use async_trait::async_trait;
use regex::Regex;
use std::collections::HashMap;
use std::str::FromStr;
use tracing::info;
use uuid::Uuid;

Expand All @@ -29,7 +30,7 @@ impl EnvCredentialStorage {
.get(1)
.map_or_else(Uuid::nil, |m| Uuid::parse_str(m.as_str()).unwrap());
let name = captures.get(2).unwrap().as_str();
let credential = Credential::Short(value);
let credential = Credential::from_str(&value).unwrap();

storage.insert(
CredentialKey {
Expand Down
32 changes: 18 additions & 14 deletions notifico-core/src/credentials/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub mod memory;
use crate::error::EngineError;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::str::FromStr;
use uuid::Uuid;

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand All @@ -15,18 +15,20 @@ pub enum CredentialSelector {

/// Generic credential with type information.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Credential {
Long { r#type: String, value: Value },
Short(String),
pub struct Credential {
pub transport: String,
pub value: String,
}

impl Credential {
pub fn transport(&self) -> &str {
match self {
Credential::Long { r#type, .. } => r#type,
Credential::Short(url) => url.split(":").next().unwrap(),
}
impl FromStr for Credential {
type Err = EngineError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let (transport, value) = s
.split_once(':')
.ok_or(EngineError::InvalidCredentialFormat)?;
let (transport, value) = (transport.to_owned(), value.to_owned());
Ok(Self { transport, value })
}
}

Expand Down Expand Up @@ -55,8 +57,10 @@ impl dyn CredentialStorage {
where
T: TypedCredential,
{
self.get_credential(project, &selector)
.await
.and_then(|c| c.try_into())
let credential = self.get_credential(project, &selector).await?;
if credential.transport != T::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat);
}
credential.try_into()
}
}
4 changes: 4 additions & 0 deletions notifico-core/src/simpletransport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ impl EnginePlugin for SimpleTransportWrapper {
.get_credential(context.project_id, &credential_selector)
.await?;

if credential.transport != self.name() {
return Err(EngineError::InvalidCredentialFormat);
}

let contacts = if self.inner.has_contacts() {
context.get_recipient()?.contacts.clone()
} else {
Expand Down
7 changes: 4 additions & 3 deletions notificox/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use notifico_template::source::DummyTemplateSource;
use notifico_template::Templater;
use notifico_transports::all_transports;
use serde_json::{json, Map, Value};
use std::str::FromStr;
use std::sync::Arc;
use tokio::task::JoinSet;
use uuid::Uuid;
Expand Down Expand Up @@ -74,7 +75,7 @@ async fn main() {
let mut transport_registry = TransportRegistry::new();
let recorder = Arc::new(BaseRecorder::new());

let credential = Credential::Short(credential);
let credential = Credential::from_str(&credential).unwrap();

let credentials = {
let mut credentials = MemoryCredentialStorage::default();
Expand Down Expand Up @@ -113,9 +114,9 @@ async fn main() {
let step = SerializedStep(step.as_object().cloned().unwrap());
pipeline.steps.push(step);
}
let transport_name = credential.transport();
let transport_name = credential.transport;
let step = SerializedStep(
json!({ "step": transport_registry.get_step(transport_name).unwrap(), "credential": "notificox" })
json!({ "step": transport_registry.get_step(&transport_name).unwrap(), "credential": "notificox" })
.as_object()
.cloned()
.unwrap(),
Expand Down
19 changes: 2 additions & 17 deletions transports/notifico-gotify/src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,9 @@ impl TryFrom<Credential> for GotifyCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}
let url = Url::parse(&value.value).map_err(|_| EngineError::InvalidCredentialFormat)?;

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => {
let mut url = url.splitn(2, ":");
let _ = url.next();
let url = url.next().unwrap_or_default();
let url = Url::parse(url).map_err(|_| EngineError::InvalidCredentialFormat)?;

Ok(Self { url })
}
}
Ok(Self { url })
}
}

Expand Down
14 changes: 1 addition & 13 deletions transports/notifico-pushover/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,7 @@ impl TryFrom<Credential> for PushoverCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => Ok(Self {
token: url.strip_prefix("pushover:").unwrap_or_default().to_owned(),
}),
}
Ok(Self { token: value.value })
}
}

Expand Down
14 changes: 1 addition & 13 deletions transports/notifico-slack/src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,7 @@ impl TryFrom<Credential> for SlackCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => Ok(Self {
token: url.strip_prefix("slack:").unwrap_or_default().to_owned(),
}),
}
Ok(Self { token: value.value })
}
}

Expand Down
29 changes: 8 additions & 21 deletions transports/notifico-smpp/src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,14 @@ impl TryFrom<Credential> for SmppServerCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => {
let url = url.strip_prefix("smpp:").unwrap_or_default();
let url = String::from("smpp://") + url;
let url = Url::parse(&url).map_err(|_| EngineError::InvalidCredentialFormat)?;
Ok(Self {
host: url.host_str().unwrap_or_default().to_owned(),
port: url.port().unwrap_or_default(),
username: url.username().to_owned(),
password: url.password().unwrap_or_default().to_owned(),
})
}
}
let url = String::from("smpp://") + &value.value;
let url = Url::parse(&url).map_err(|_| EngineError::InvalidCredentialFormat)?;
Ok(Self {
host: url.host_str().unwrap_or_default().to_owned(),
port: url.port().unwrap_or_default(),
username: url.username().to_owned(),
password: url.password().unwrap_or_default().to_owned(),
})
}
}

Expand Down
41 changes: 14 additions & 27 deletions transports/notifico-smtp/src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,20 @@ impl TryFrom<Credential> for SmtpServerCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => {
let url = url.strip_prefix("smtp:").unwrap_or_default();
let url = String::from("smtp://") + url;
let url = Url::parse(&url).map_err(|_| EngineError::InvalidCredentialFormat)?;
let query: BTreeMap<Cow<str>, Cow<str>> = url.query_pairs().collect();
let tls = query
.get("tls")
.map(|v| v.as_ref() == "true")
.unwrap_or(false);
Ok(Self {
host: url.host_str().unwrap_or_default().to_owned(),
port: url.port(),
username: url.username().to_owned(),
password: url.password().unwrap_or_default().to_owned(),
tls,
})
}
}
let url = String::from("smtp://") + &value.value;
let url = Url::parse(&url).map_err(|_| EngineError::InvalidCredentialFormat)?;
let query: BTreeMap<Cow<str>, Cow<str>> = url.query_pairs().collect();
let tls = query
.get("tls")
.map(|v| v.as_ref() == "true")
.unwrap_or(false);
Ok(Self {
host: url.host_str().unwrap_or_default().to_owned(),
port: url.port(),
username: url.username().to_owned(),
password: url.password().unwrap_or_default().to_owned(),
tls,
})
}
}

Expand Down
14 changes: 1 addition & 13 deletions transports/notifico-telegram/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,7 @@ impl TryFrom<Credential> for TelegramBotCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => Ok(Self {
token: url.strip_prefix("telegram:").unwrap_or_default().to_owned(),
}),
}
Ok(Self { token: value.value })
}
}

Expand Down
35 changes: 11 additions & 24 deletions transports/notifico-whatsapp/src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,19 @@ impl TryFrom<Credential> for WhatsAppCredentials {
type Error = EngineError;

fn try_from(value: Credential) -> Result<Self, Self::Error> {
if value.transport() != Self::TRANSPORT_NAME {
return Err(EngineError::InvalidCredentialFormat)?;
}
static WABA_REGEX: OnceLock<Regex> = OnceLock::new();
let regex = WABA_REGEX.get_or_init(|| Regex::new("^([0-9]+):([0-9a-zA-Z]+)$").unwrap());

match value {
Credential::Long { value, .. } => {
Ok(serde_json::from_value(value)
.map_err(|_| EngineError::InvalidCredentialFormat)?)
}
Credential::Short(url) => {
static WABA_REGEX: OnceLock<Regex> = OnceLock::new();
let regex = WABA_REGEX
.get_or_init(|| Regex::new("^waba:([0-9]+):([0-9a-zA-Z]+)$").unwrap());
let caps = regex
.captures(&value.value)
.ok_or(EngineError::InvalidCredentialFormat)?;

let caps = regex
.captures(&url)
.ok_or(EngineError::InvalidCredentialFormat)?;

Ok(Self {
phone_id: caps[0]
.parse()
.map_err(|_| EngineError::InvalidCredentialFormat)?,
token: caps[1].to_owned(),
})
}
}
Ok(Self {
phone_id: caps[0]
.parse()
.map_err(|_| EngineError::InvalidCredentialFormat)?,
token: caps[1].to_owned(),
})
}
}

Expand Down

0 comments on commit db26ebe

Please sign in to comment.