Skip to content

Commit

Permalink
Merge pull request #3 from rpalakkal/dev
Browse files Browse the repository at this point in the history
Dev checking -- dont merge yet
  • Loading branch information
maceip authored Jun 23, 2024
2 parents 13a0737 + c66fc24 commit 493fc4f
Show file tree
Hide file tree
Showing 10 changed files with 110 additions and 177 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ target
teleport.env
exex.manifest.sgx
exex.manifest
exex.sig
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ $(SELF_EXE): Cargo.toml

exex.manifest: exex.manifest.template
gramine-manifest \
-Dentrypoint=$$(command -v gramine-ratls) \
-Dentrypoint=$$(command -v gramine-ratls) \
-Dlog_level=$(GRAMINE_LOG_LEVEL) \
-Darch_libdir=$(ARCH_LIBDIR) \
-Dself_exe=$(SELF_EXE) \
$< $@
$< > $@

# Make on Ubuntu <= 20.04 doesn't support "Rules with Grouped Targets" (`&:`),
# see the helloworld example for details on this workaround.
Expand Down
24 changes: 15 additions & 9 deletions exex.manifest.template
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@

# Rust manifest example

libos.entrypoint = "/gramine-ratls"

loader.entrypoint = "file:{{ gramine.libos }}"
libos.entrypoint = "/gramine-ratls"
loader.log_level = "{{ log_level }}"

loader.env.LD_LIBRARY_PATH = "/usr/local/lib:/usr{{ arch_libdir }}:{{ arch_libdir }}"
Expand All @@ -14,25 +12,27 @@ loader.env.MALLOC_ARENA_MAX = "1"
loader.env.RUST_BACKTRACE = "full"
loader.env.RUST_LOG = "info"


loader.argv = [
"gramine-ratls", "/tmp/crt.pem", "/tmp/key.pem", "--",
"target/release/exex",
]
]

loader.uid = 65534
loader.gid = 65534

fs.mounts = [
{ type = "encrypted", path = "/main.db", uri = "file:main.db", key_name = "teleportexex" },
{ path = "/gramine-ratls", uri = "file:{{ entrypoint }}" },
{ path = "/teleport.env", uri = "file:teleport.env" },
{ path = "/lib", uri = "file:{{ gramine.runtimedir() }}" },
{ path = "/gramine-ratls", uri = "file:{{ entrypoint }}" },
{ path = "{{ arch_libdir }}", uri = "file:{{ arch_libdir }}" },
{ path = "/tmp", type = "tmpfs" },
{ path = "/usr/lib/ssl/certs/", uri = "file:/usr/lib/ssl/certs/" }, # add this line
{ path = "/etc/ssl/certs/", uri = "file:/etc/ssl/certs/" }, # add this line

{ path = "/tmp/botCert.pem", uri = "file:/home/ecs-user/fullchain.pem" },
{ path = "/tmp/botKey.pem", uri = "file:/home/ecs-user/privkey.pem" },
]

fs.insecure__keys.teleportexex = "38EBF5306BC11707AD66F60FC12F212D"

sys.enable_extra_runtime_domain_names_conf = true

Expand All @@ -49,6 +49,8 @@ sgx.trusted_files = [
"file:{{ arch_libdir }}/",
"file:teleport.env",
"file:main.db",
"file:/home/ecs-user/privkey.pem",
"file:/home/ecs-user/fullchain.pem",
"file:/usr/lib/ssl/certs/",
"file:/etc/ssl/certs/",

Expand All @@ -61,4 +63,8 @@ sgx.trusted_files = [
# - any threads and threadpools you might be starting
# - helper threads internal to Gramine — see:
# https://gramine.readthedocs.io/en/stable/manifest-syntax.html#number-of-threads
sgx.max_threads = {{ '1' if env.get('EDMM', '0') == '1' else '32' }}
sgx.enclave_size = "2G"
sgx.max_threads = 128
sys.insecure__allow_eventfd = true
sys.stack.size = "2M"
sys.brk.max_size = "256M"
11 changes: 11 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
reorder_imports = true
imports_granularity = "Crate"
use_small_heuristics = "Max"
comment_width = 100
wrap_comments = true
binop_separator = "Back"
trailing_comma = "Vertical"
trailing_semicolon = false
use_field_init_shorthand = true
format_code_in_doc_comments = true
doc_comment_code_block_width = 100
24 changes: 5 additions & 19 deletions src/actions/nft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,9 @@ pub async fn subscribe_to_nft_events<A: TeleportDB>(
let ws = WsConnect::new(ws_rpc_url);
let provider = ProviderBuilder::new().on_ws(ws).await?;

let filter = Filter::new()
.address(NFT_ADDRESS)
.from_block(BlockNumberOrTag::Latest);
let filter = Filter::new().address(NFT_ADDRESS).from_block(BlockNumberOrTag::Latest);

log::info!(
"Subscribed to events for contract at: {}",
NFT_ADDRESS.to_string()
);
log::info!("Subscribed to events for contract at: {}", NFT_ADDRESS.to_string());

let sub = provider.subscribe_logs(&filter).await?;
let mut stream = sub.into_stream();
Expand Down Expand Up @@ -112,10 +107,8 @@ pub async fn redeem_nft(
content: String,
) -> eyre::Result<String> {
let rpc_url = rpc_url.parse()?;
let provider = ProviderBuilder::new()
.with_recommended_fillers()
.wallet(wallet)
.on_http(rpc_url);
let provider =
ProviderBuilder::new().with_recommended_fillers().wallet(wallet).on_http(rpc_url);

let nft = NFT::new(NFT_ADDRESS, provider);
let token_id = Uint::from_str(&token_id)?;
Expand Down Expand Up @@ -165,13 +158,6 @@ mod tests {
.with_recommended_fillers()
.wallet(wallet)
.on_http(rpc_url.parse().unwrap());
mint_nft(
provider,
recipient_address,
1.to_string(),
"policy".to_string(),
)
.await
.unwrap();
mint_nft(provider, recipient_address, 1.to_string(), "policy".to_string()).await.unwrap();
}
}
37 changes: 8 additions & 29 deletions src/db/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ impl TeleportDB for InMemoryDB {
}

async fn get_user_by_teleport_id(&self, teleport_id: String) -> eyre::Result<User> {
let user = self
.users
.get(&teleport_id)
.ok_or_else(|| eyre::eyre!("User not found"))?;
let user = self.users.get(&teleport_id).ok_or_else(|| eyre::eyre!("User not found"))?;
Ok(user.clone())
}

Expand All @@ -45,10 +42,7 @@ impl TeleportDB for InMemoryDB {
.x_id_to_teleport_id
.get(&x_id)
.ok_or_else(|| eyre::eyre!("User teleport_id not found for x_id"))?;
let user = self
.users
.get(teleport_id)
.ok_or_else(|| eyre::eyre!("User not found"))?;
let user = self.users.get(teleport_id).ok_or_else(|| eyre::eyre!("User not found"))?;
Ok(user.clone())
}

Expand All @@ -71,19 +65,13 @@ impl TeleportDB for InMemoryDB {
.pending_nfts
.remove(&tx_hash)
.ok_or_else(|| eyre::eyre!("Pending NFT not found"))?;
let nft = NFT {
teleport_id: pending_nft.teleport_id,
token_id,
};
let nft = NFT { teleport_id: pending_nft.teleport_id, token_id };
self.nfts.insert(pending_nft.nft_id, nft);
Ok(())
}

async fn get_nft(&self, nft_id: String) -> eyre::Result<NFT> {
let nft = self
.nfts
.get(&nft_id)
.ok_or_else(|| eyre::eyre!("NFT not found"))?;
let nft = self.nfts.get(&nft_id).ok_or_else(|| eyre::eyre!("NFT not found"))?;
Ok(nft.clone())
}

Expand All @@ -93,10 +81,7 @@ impl TeleportDB for InMemoryDB {
}

async fn get_tweet(&self, token_id: String) -> eyre::Result<String> {
let tweet_id = self
.tweets
.get(&token_id)
.ok_or_else(|| eyre::eyre!("Tweet not found"))?;
let tweet_id = self.tweets.get(&token_id).ok_or_else(|| eyre::eyre!("Tweet not found"))?;
Ok(tweet_id.clone())
}
}
Expand All @@ -115,9 +100,7 @@ mod tests {
embedded_address: "address".to_string(),
sk: None,
};
db.add_user("2".to_string(), user.clone())
.await
.expect("Failed to add user tokens");
db.add_user("2".to_string(), user.clone()).await.expect("Failed to add user tokens");
let user = db.get_user_by_teleport_id("2".to_string()).await?;
assert_eq!(user.access_token, "access token");
assert_eq!(user.access_secret, "access secret");
Expand All @@ -135,14 +118,10 @@ mod tests {
embedded_address: "address".to_string(),
sk: None,
};
db.add_user("2".to_string(), user.clone())
.await
.expect("Failed to add user tokens");
db.add_user("2".to_string(), user.clone()).await.expect("Failed to add user tokens");
user.x_id = Some("1".to_string());
user.sk = Some("sk".to_string());
db.add_user("2".to_string(), user.clone())
.await
.expect("Failed to add user tokens");
db.add_user("2".to_string(), user.clone()).await.expect("Failed to add user tokens");
let fetched_user = db.get_user_by_x_id("1".to_string()).await?;
assert_eq!(user, fetched_user);
Ok(())
Expand Down
70 changes: 29 additions & 41 deletions src/endpoints.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::sync::Arc;
use tokio::fs;

use axum::{
extract::{Query, State},
Expand Down Expand Up @@ -47,6 +48,11 @@ pub struct TweetIdResponse {
tweet_id: String,
}

#[derive(Serialize)]
pub struct AttestationResponse {
cert: String,
}

#[derive(Deserialize)]
pub struct RedeemQuery {
nft_id: String,
Expand All @@ -72,27 +78,23 @@ pub async fn new_user<A: TeleportDB>(
let teleport_id = query.teleport_id;

let db_lock = shared_state.db.lock().await;
let existing_user = db_lock
.get_user_by_teleport_id(teleport_id.clone())
.await
.ok();
let existing_user = db_lock.get_user_by_teleport_id(teleport_id.clone()).await.ok();
if let Some(user) = existing_user {
if user.x_id.is_some() {
let x_info = get_user_x_info(user.access_token, user.access_secret).await;
let encoded_x_info = serde_urlencoded::to_string(&x_info)
.expect("Failed to encode x_info as query params");
let url_with_params = format!(
"http://localhost:4000/create?already_created=true&success=true&{}",
"https://teleport.best/create?already_created=true&success=true&{}",
encoded_x_info
);
return Redirect::temporary(&url_with_params);
}
}
drop(db_lock);

let (oauth_token, oauth_token_secret) = request_oauth_token(teleport_id.clone())
.await
.expect("Failed to request oauth token");
let (oauth_token, oauth_token_secret) =
request_oauth_token(teleport_id.clone()).await.expect("Failed to request oauth token");
let user = User {
x_id: None,
access_token: oauth_token.clone(),
Expand All @@ -101,15 +103,10 @@ pub async fn new_user<A: TeleportDB>(
sk: None,
};
let mut db = shared_state.db.lock().await;
db.add_user(teleport_id.clone(), user)
.await
.expect("Failed to add oauth tokens to database");
db.add_user(teleport_id.clone(), user).await.expect("Failed to add oauth tokens to database");
drop(db);

let url = format!(
"https://api.twitter.com/oauth/authenticate?oauth_token={}",
oauth_token
);
let url = format!("https://api.twitter.com/oauth/authenticate?oauth_token={}", oauth_token);

Redirect::temporary(&url)
}
Expand All @@ -123,16 +120,12 @@ pub async fn callback<A: TeleportDB>(
let teleport_id = query.teleport_id;

let mut db = shared_state.db.lock().await;
let oauth_user = db
.get_user_by_teleport_id(teleport_id.clone())
.await
.expect("Failed to get oauth tokens");
let oauth_user =
db.get_user_by_teleport_id(teleport_id.clone()).await.expect("Failed to get oauth tokens");
assert_eq!(oauth_token, oauth_user.access_token);

let (access_token, access_secret) =
authorize_token(oauth_token, oauth_user.access_secret, oauth_verifier)
.await
.unwrap();
authorize_token(oauth_token, oauth_user.access_secret, oauth_verifier).await.unwrap();
let x_info = get_user_x_info(access_token.clone(), access_secret.clone()).await;
let sk = gen_sk().expect("Failed to generate sk");
let user = User {
Expand All @@ -142,9 +135,7 @@ pub async fn callback<A: TeleportDB>(
embedded_address: oauth_user.embedded_address,
sk: Some(sk),
};
db.add_user(teleport_id.clone(), user.clone())
.await
.expect("Failed to add user to database");
db.add_user(teleport_id.clone(), user.clone()).await.expect("Failed to add user to database");
drop(db);

//temp: give eoa some eth for gas
Expand All @@ -154,10 +145,7 @@ pub async fn callback<A: TeleportDB>(

let encoded_x_info =
serde_urlencoded::to_string(&x_info).expect("Failed to encode x_info as query params");
let url_with_params = format!(
"http://localhost:4000/create?success=true&{}",
encoded_x_info
);
let url_with_params = format!("https://teleport.best/create?success=true&{}", encoded_x_info);

Redirect::temporary(&url_with_params)
}
Expand Down Expand Up @@ -185,10 +173,7 @@ pub async fn mint<A: TeleportDB>(
let mut db = shared_state.db.lock().await;
db.add_pending_nft(
tx_hash.clone(),
PendingNFT {
teleport_id: query.teleport_id.clone(),
nft_id: query.nft_id.clone(),
},
PendingNFT { teleport_id: query.teleport_id.clone(), nft_id: query.nft_id.clone() },
)
.await
.expect("Failed to add pending NFT");
Expand All @@ -202,10 +187,7 @@ pub async fn redeem<A: TeleportDB>(
Query(query): Query<RedeemQuery>,
) -> Json<TxHashResponse> {
let db = shared_state.db.lock().await;
let nft = db
.get_nft(query.nft_id.clone())
.await
.expect("Failed to get NFT by id");
let nft = db.get_nft(query.nft_id.clone()).await.expect("Failed to get NFT by id");
let user = db
.get_user_by_teleport_id(nft.teleport_id.clone())
.await
Expand All @@ -228,15 +210,21 @@ pub async fn get_tweet_id<A: TeleportDB>(
Query(query): Query<TweetIdQuery>,
) -> Json<TweetIdResponse> {
let db = shared_state.db.lock().await;
let tweet_id = db
.get_tweet(query.token_id.clone())
.await
.expect("Failed to get tweet id");
let tweet_id = db.get_tweet(query.token_id.clone()).await.expect("Failed to get tweet id");
drop(db);

Json(TweetIdResponse { tweet_id })
}

pub async fn get_ratls_cert<A: TeleportDB>(
State(shared_state): State<SharedState<A>>,
) -> Json<AttestationResponse> {
let cert = fs::read_to_string(std::env::var("TLS_CERT_PATH").expect("TLS_CERT_PATH not set"))
.await
.expect("gramine ratls rootCA.crt not found");
Json(AttestationResponse { cert })
}

pub async fn hello_world() -> &'static str {
log::info!("Hello, World!");
"Hello, World!"
Expand Down
Loading

0 comments on commit 493fc4f

Please sign in to comment.