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

Remove email and recovery related identity endpoints #1833

Merged
merged 5 commits into from
Oct 15, 2024
Merged
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
239 changes: 2 additions & 237 deletions crates/cli/src/subcommands/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,12 @@ use crate::{
config::{Config, IdentityConfig},
util::{init_default, y_or_n, IdentityTokenJson, InitDefaultResultType},
};
use std::io::Write;

use crate::util::print_identity_config;
use anyhow::Context;
use clap::{Arg, ArgAction, ArgMatches, Command};
use email_address::EmailAddress;
use reqwest::{StatusCode, Url};
use serde::Deserialize;
use reqwest::Url;
use spacetimedb::auth::identity::decode_token;
use spacetimedb_client_api_messages::recovery::RecoveryCodeResponse;
use spacetimedb_lib::Identity;
use tabled::{
settings::{object::Columns, Alignment, Modify, Style},
Expand All @@ -29,15 +25,6 @@ pub fn cli() -> Command {

fn get_subcommands() -> Vec<Command> {
vec![
Command::new("find").about("Find an identity for an email")
.arg(
Arg::new("email")
.required(true)
.help("The email associated with the identity that you would like to find"),
)
.arg(common_args::server()
.help("The server to search for identities matching the email"),
),
Command::new("import")
.about("Import an existing identity into your spacetime config")
.arg(
Expand Down Expand Up @@ -113,20 +100,6 @@ fn get_subcommands() -> Vec<Command> {
.help("Nickname for this identity")
.conflicts_with("no-save"),
)
.arg(
Arg::new("email")
.long("email")
.short('e')
.help("Recovery email for this identity")
.conflicts_with("no-email"),
)
.arg(
Arg::new("no-email")
.long("no-email")
.help("Creates an identity without a recovery email")
.conflicts_with("email")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("default")
.help("Make the new identity the default for the server")
Expand All @@ -135,21 +108,6 @@ fn get_subcommands() -> Vec<Command> {
.conflicts_with("no-save")
.action(ArgAction::SetTrue),
),
Command::new("recover")
.about("Recover an existing identity and import it into your local config")
.arg(
Arg::new("email")
.required(true)
.help("The email associated with the identity that you would like to recover."),
)
.arg(common_args::identity().required(true).help(
"The identity you would like to recover. This identity must be associated with the email provided.",
).value_parser(clap::value_parser!(Identity)))
.arg(common_args::server()
.help("The server from which to request recovery codes"),
)
// TODO: project flag?
,
Command::new("remove")
.about("Removes a saved identity from your spacetime config")
.arg(common_args::identity()
Expand Down Expand Up @@ -191,31 +149,6 @@ fn get_subcommands() -> Vec<Command> {
)
// TODO: project flag?
,
Command::new("set-email")
.about("Associates an email address with an identity")
.arg(
common_args::identity()
.help("The identity string or name that should be associated with the email")
.required(true),
)
.arg(
Arg::new("email")
.help("The email that should be assigned to the provided identity")
.required(true),
)
.arg(
common_args::server()
.help("The server that should be informed of the email change")
.conflicts_with("all-servers")
)
.arg(
Arg::new("all-servers")
.long("all-servers")
.short('a')
.action(ArgAction::SetTrue)
.help("Inform all known servers of the email change")
.conflicts_with("server")
),
Command::new("set-name").about("Set the name of an identity or rename an existing identity nickname").arg(
common_args::identity()
.help("The identity string or name to be named. If a name is supplied, the corresponding identity will be renamed.")
Expand All @@ -241,10 +174,7 @@ async fn exec_subcommand(config: Config, cmd: &str, args: &ArgMatches) -> Result
"remove" => exec_remove(config, args).await,
"set-name" => exec_set_name(config, args).await,
"import" => exec_import(config, args).await,
"set-email" => exec_set_email(config, args).await,
"find" => exec_find(config, args).await,
"token" => exec_token(config, args).await,
"recover" => exec_recover(config, args).await,
unknown => Err(anyhow::anyhow!("Invalid subcommand: {}", unknown)),
}
}
Expand Down Expand Up @@ -370,21 +300,7 @@ async fn exec_new(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
config.can_set_name(x)?;
}

let email = args.get_one::<String>("email");
let no_email = args.get_flag("no-email");
if email.is_none() && !no_email {
return Err(anyhow::anyhow!(
"You must either supply an email with --email <email>, or pass the --no-email flag."
));
}

let mut query_params = Vec::<(&str, &str)>::new();
if let Some(email) = email {
if !EmailAddress::is_valid(email.as_str()) {
return Err(anyhow::anyhow!("The email you provided is malformed: {}", email));
}
query_params.push(("email", email.as_str()))
}
let query_params = Vec::<(&str, &str)>::new();

let mut builder = reqwest::Client::new().post(Url::parse_with_params(
format!("{}/identity", config.get_host_url(server)?).as_str(),
Expand Down Expand Up @@ -413,7 +329,6 @@ async fn exec_new(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E

println!(" IDENTITY {}", identity);
println!(" NAME {}", alias.unwrap_or(&String::new()));
println!(" EMAIL {}", email.unwrap_or(&String::new()));

Ok(())
}
Expand Down Expand Up @@ -510,45 +425,6 @@ Fetch the server's fingerprint with:
Ok(())
}

#[derive(Debug, Clone, Deserialize)]
struct GetIdentityResponse {
identities: Vec<GetIdentityResponseEntry>,
}

#[derive(Debug, Clone, Deserialize)]
struct GetIdentityResponseEntry {
identity: String,
email: String,
}

/// Executes the `identity find` command which finds an identity by email.
async fn exec_find(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let email = args.get_one::<String>("email").unwrap().clone();
let server = args.get_one::<String>("server").map(|s| s.as_ref());
let client = reqwest::Client::new();
let builder = client.get(format!("{}/identity?email={}", config.get_host_url(server)?, email));

let res = builder.send().await?;

if res.status() == StatusCode::OK {
let response: GetIdentityResponse = res.json().await?;
if response.identities.is_empty() {
return Err(anyhow::anyhow!("Could not find identity for: {}", email));
}

for identity in response.identities {
println!("Identity");
println!(" IDENTITY {}", identity.identity);
println!(" EMAIL {}", identity.email);
}
Ok(())
} else if res.status() == StatusCode::NOT_FOUND {
Err(anyhow::anyhow!("Could not find identity for: {}", email))
} else {
Err(anyhow::anyhow!("Error occurred in lookup: {}", res.status()))
}
}

/// Executes the `identity token` command which prints the token for an identity.
async fn exec_token(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let identity = args.get_one::<String>("identity").unwrap();
Expand All @@ -573,114 +449,3 @@ async fn exec_set_name(mut config: Config, args: &ArgMatches) -> Result<(), anyh
config.save();
Ok(())
}

/// Executes the `identity set-email` command which sets the email for an identity.
async fn exec_set_email(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let email = args.get_one::<String>("email").unwrap().clone();
let server = args.get_one::<String>("server").map(|s| s.as_ref());
let identity = args.get_one::<String>("identity").unwrap();
let identity_config = config
.get_identity_config(identity)
.ok_or_else(|| anyhow::anyhow!("Missing identity credentials for identity: {identity}"))?;

// TODO: check that the identity is valid for the server

reqwest::Client::new()
.post(format!(
"{}/identity/{}/set-email?email={}",
config.get_host_url(server)?,
identity_config.identity,
email
))
.basic_auth("token", Some(&identity_config.token))
.send()
.await?
.error_for_status()?;

println!(" Associated email with identity");
print_identity_config(identity_config);
println!(" EMAIL {}", email);

Ok(())
}

/// Executes the `identity recover` command which recovers an identity from an email.
async fn exec_recover(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let identity = args.get_one::<Identity>("identity").unwrap();
let email = args.get_one::<String>("email").unwrap();
let server = args.get_one::<String>("server").map(|s| s.as_ref());

let query_params = [
("email", email.as_str()),
("identity", &*identity.to_hex()),
("link", "false"),
];

if config.get_identity_config_by_identity(identity).is_some() {
return Err(anyhow::anyhow!("No need to recover this identity, it is already stored in your config. Use `spacetime identity list` to list identities."));
}

let client = reqwest::Client::new();
let builder = client.post(Url::parse_with_params(
format!("{}/identity/request_recovery_code", config.get_host_url(server)?,).as_str(),
query_params,
)?);
let res = builder.send().await?;
res.error_for_status()?;

println!(
"We have successfully sent a recovery code to {}. Enter the code now.",
email
);
for _ in 0..5 {
print!("Recovery Code: ");
std::io::stdout().flush()?;
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let code = match line.trim().parse::<u32>() {
Ok(value) => value,
Err(_) => {
println!("Malformed code. Please try again.");
continue;
}
};

let client = reqwest::Client::new();
let builder = client.post(Url::parse_with_params(
format!("{}/identity/confirm_recovery_code", config.get_host_url(server)?,).as_str(),
vec![
("code", code.to_string().as_str()),
("email", email.as_str()),
("identity", identity.to_hex().as_str()),
],
)?);
let res = builder.send().await?;
match res.error_for_status() {
Ok(res) => {
let buf = res.bytes().await?.to_vec();
let utf8 = String::from_utf8(buf)?;
let response: RecoveryCodeResponse = serde_json::from_str(utf8.as_str())?;
let identity_config = IdentityConfig {
nickname: None,
identity: response.identity,
token: response.token,
};
config.identity_configs_mut().push(identity_config.clone());
config.set_default_identity_if_unset(server, &identity_config.identity.to_hex())?;
config.save();
println!("Success. Identity imported.");
print_identity_config(&identity_config);
// TODO: Remove this once print_identity_config prints email
println!(" EMAIL {}", email);
return Ok(());
}
Err(_) => {
println!("Invalid recovery code, please try again.");
}
}
}

Err(anyhow::anyhow!(
"Maximum amount of attempts reached. Please start the process over."
))
}
1 change: 0 additions & 1 deletion crates/client-api-messages/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@

pub mod energy;
pub mod name;
pub mod recovery;
pub mod timestamp;
pub mod websocket;
19 changes: 0 additions & 19 deletions crates/client-api-messages/src/recovery.rs

This file was deleted.

11 changes: 10 additions & 1 deletion crates/client-api/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use axum::response::IntoResponse;
use axum_extra::typed_header::TypedHeader;
use headers::{authorization, HeaderMapExt};
use http::{request, HeaderValue, StatusCode};
use rand::Rng;
use serde::Deserialize;
use spacetimedb::auth::identity::{
decode_token, encode_token, DecodingKey, EncodingKey, JwtError, JwtErrorKind, SpacetimeIdentityClaims,
Expand Down Expand Up @@ -96,7 +97,15 @@ pub struct SpacetimeAuth {
impl SpacetimeAuth {
/// Allocate a new identity, and mint a new token for it.
pub async fn alloc(ctx: &(impl NodeDelegate + ControlStateDelegate + ?Sized)) -> axum::response::Result<Self> {
let identity = ctx.create_identity().await.map_err(log_and_500)?;
// TODO: I'm just sticking in a random string until we change how identities are generated.
jsdt marked this conversation as resolved.
Show resolved Hide resolved
let identity = {
let mut rng = rand::thread_rng();
let mut random_bytes = [0u8; 16]; // Example: 16 random bytes
rng.fill(&mut random_bytes);

let preimg = [b"clockworklabs:", &random_bytes[..]].concat();
Identity::from_hashing_bytes(preimg)
};
let creds = SpacetimeCreds::encode_token(ctx.private_key(), identity).map_err(log_and_500)?;
Ok(Self { creds, identity })
}
Expand Down
Loading
Loading