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

feat(torii): sql proxy endpoint for querying #2706

Merged
merged 5 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 18 additions & 6 deletions bin/torii/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,14 @@ async fn main() -> anyhow::Result<()> {
options = options.journal_mode(SqliteJournalMode::Wal);
options = options.synchronous(SqliteSynchronous::Normal);

let pool = SqlitePoolOptions::new().min_connections(1).connect_with(options).await?;
let pool = SqlitePoolOptions::new().min_connections(1).connect_with(options.clone()).await?;

let readonly_options = options.read_only(true);
let readonly_pool = SqlitePoolOptions::new()
.min_connections(1)
.max_connections(100)
.connect_with(readonly_options)
.await?;

// Set the number of threads based on CPU count
let cpu_count = std::thread::available_parallelism().unwrap().get();
Expand All @@ -120,7 +127,7 @@ async fn main() -> anyhow::Result<()> {
.await?;
let executor_handle = tokio::spawn(async move { executor.run().await });

let model_cache = Arc::new(ModelCache::new(pool.clone()));
let model_cache = Arc::new(ModelCache::new(readonly_pool.clone()));
let db = Sql::new(pool.clone(), sender.clone(), &args.indexing.contracts, model_cache.clone())
.await?;

Expand Down Expand Up @@ -166,7 +173,7 @@ async fn main() -> anyhow::Result<()> {
let shutdown_rx = shutdown_tx.subscribe();
let (grpc_addr, grpc_server) = torii_grpc::server::new(
shutdown_rx,
&pool,
&readonly_pool,
block_rx,
world_address,
Arc::clone(&provider),
Expand All @@ -181,8 +188,12 @@ async fn main() -> anyhow::Result<()> {
tokio::fs::create_dir_all(&artifacts_path).await?;
let absolute_path = artifacts_path.canonicalize_utf8()?;

let (artifacts_addr, artifacts_server) =
torii_server::artifacts::new(shutdown_tx.subscribe(), &absolute_path, pool.clone()).await?;
let (artifacts_addr, artifacts_server) = torii_server::artifacts::new(
shutdown_tx.subscribe(),
&absolute_path,
readonly_pool.clone(),
)
.await?;

let mut libp2p_relay_server = torii_relay::server::Relay::new(
db,
Expand All @@ -203,11 +214,12 @@ async fn main() -> anyhow::Result<()> {
Some(grpc_addr),
None,
Some(artifacts_addr),
Arc::new(readonly_pool.clone()),
));

let graphql_server = spawn_rebuilding_graphql_server(
shutdown_tx.clone(),
pool.into(),
readonly_pool.into(),
args.external_url,
proxy_server.clone(),
);
Expand Down
1 change: 1 addition & 0 deletions crates/torii/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ tower-http.workspace = true
tower.workspace = true
tracing.workspace = true
warp.workspace = true
form_urlencoded = "1.2.1"
90 changes: 89 additions & 1 deletion crates/torii/server/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;

use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use http::header::CONTENT_TYPE;
use http::{HeaderName, Method};
use hyper::client::connect::dns::GaiResolver;
Expand All @@ -12,6 +14,7 @@ use hyper::service::make_service_fn;
use hyper::{Body, Client, Request, Response, Server, StatusCode};
use hyper_reverse_proxy::ReverseProxy;
use serde_json::json;
use sqlx::{Column, Row, SqlitePool, TypeInfo};
use tokio::sync::RwLock;
use tower::ServiceBuilder;
use tower_http::cors::{AllowOrigin, CorsLayer};
Expand Down Expand Up @@ -60,6 +63,7 @@ pub struct Proxy {
grpc_addr: Option<SocketAddr>,
artifacts_addr: Option<SocketAddr>,
graphql_addr: Arc<RwLock<Option<SocketAddr>>>,
pool: Arc<SqlitePool>,
}

impl Proxy {
Expand All @@ -69,13 +73,15 @@ impl Proxy {
grpc_addr: Option<SocketAddr>,
graphql_addr: Option<SocketAddr>,
artifacts_addr: Option<SocketAddr>,
pool: Arc<SqlitePool>,
) -> Self {
Self {
addr,
allowed_origins,
grpc_addr,
graphql_addr: Arc::new(RwLock::new(graphql_addr)),
artifacts_addr,
pool,
}
}

Expand All @@ -93,6 +99,7 @@ impl Proxy {
let grpc_addr = self.grpc_addr;
let graphql_addr = self.graphql_addr.clone();
let artifacts_addr = self.artifacts_addr;
let pool = self.pool.clone();

let make_svc = make_service_fn(move |conn: &AddrStream| {
let remote_addr = conn.remote_addr().ip();
Expand Down Expand Up @@ -129,12 +136,14 @@ impl Proxy {
),
});

let pool_clone = pool.clone();
let graphql_addr_clone = graphql_addr.clone();
let service = ServiceBuilder::new().option_layer(cors).service_fn(move |req| {
let pool = pool_clone.clone();
let graphql_addr = graphql_addr_clone.clone();
async move {
let graphql_addr = graphql_addr.read().await;
handle(remote_addr, grpc_addr, artifacts_addr, *graphql_addr, req).await
handle(remote_addr, grpc_addr, artifacts_addr, *graphql_addr, pool, req).await
}
});

Expand All @@ -156,6 +165,7 @@ async fn handle(
grpc_addr: Option<SocketAddr>,
artifacts_addr: Option<SocketAddr>,
graphql_addr: Option<SocketAddr>,
pool: Arc<SqlitePool>,
req: Request<Body>,
) -> Result<Response<Body>, Infallible> {
if req.uri().path().starts_with("/static") {
Expand Down Expand Up @@ -224,6 +234,84 @@ async fn handle(
}
}

if req.uri().path().starts_with("/sql") {
let query = if req.method() == Method::GET {
// Get the query from URL parameters
let params = req.uri().query().unwrap_or_default();
form_urlencoded::parse(params.as_bytes())
.find(|(key, _)| key == "q")
.map(|(_, value)| value.to_string())
.unwrap_or_default()
} else if req.method() == Method::POST {
// Get the query from request body
let body_bytes = hyper::body::to_bytes(req.into_body()).await.unwrap_or_default();
String::from_utf8(body_bytes.to_vec()).unwrap_or_default()
Comment on lines +249 to +250
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ohayo, sensei! Avoid silently ignoring errors when reading request body

Using unwrap_or_default() when reading the request body may mask errors that should be handled appropriately. Consider properly handling errors when converting the request body to bytes and when converting bytes to a UTF-8 string.

Apply this diff to handle errors explicitly:

- let body_bytes = hyper::body::to_bytes(req.into_body()).await.unwrap_or_default();
- String::from_utf8(body_bytes.to_vec()).unwrap_or_default()
+ let body_bytes = match hyper::body::to_bytes(req.into_body()).await {
+     Ok(bytes) => bytes,
+     Err(e) => {
+         error!(target: LOG_TARGET, "Failed to read request body: {:?}", e);
+         return Ok(Response::builder()
+             .status(StatusCode::BAD_REQUEST)
+             .body(Body::from("Failed to read request body"))
+             .unwrap());
+     }
+ };
+ let query = match String::from_utf8(body_bytes.to_vec()) {
+     Ok(str) => str,
+     Err(e) => {
+         error!(target: LOG_TARGET, "Invalid UTF-8 sequence: {:?}", e);
+         return Ok(Response::builder()
+             .status(StatusCode::BAD_REQUEST)
+             .body(Body::from("Invalid UTF-8 sequence in request body"))
+             .unwrap());
+     }
+ };

Committable suggestion skipped: line range outside the PR's diff.

} else {
return Ok(Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.body(Body::from("Only GET and POST methods are allowed"))
.unwrap());
};

// Execute the query in a read-only transaction
return match sqlx::query(&query).fetch_all(&*pool).await {
Ok(rows) => {
let result: Vec<_> = rows
.iter()
.map(|row| {
let mut obj = serde_json::Map::new();
for (i, column) in row.columns().iter().enumerate() {
let value: serde_json::Value = match column.type_info().name() {
"TEXT" => row
.get::<Option<String>, _>(i)
.map_or(serde_json::Value::Null, serde_json::Value::String),
"INTEGER" => row
.get::<Option<i64>, _>(i)
.map_or(serde_json::Value::Null, |n| {
serde_json::Value::Number(n.into())
}),
"REAL" => row.get::<Option<f64>, _>(i).map_or(
serde_json::Value::Null,
|f| {
serde_json::Number::from_f64(f).map_or(
serde_json::Value::Null,
serde_json::Value::Number,
)
},
),
"BLOB" => row
.get::<Option<Vec<u8>>, _>(i)
.map_or(serde_json::Value::Null, |bytes| {
serde_json::Value::String(STANDARD.encode(bytes))
}),
_ => row
.get::<Option<String>, _>(i)
.map_or(serde_json::Value::Null, serde_json::Value::String),
};
obj.insert(column.name().to_string(), value);
}
serde_json::Value::Object(obj)
})
.collect();

let json = serde_json::to_string(&result).unwrap();

Ok(Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, "application/json")
.body(Body::from(json))
.unwrap())
}
Err(e) => {
error!("SQL query error: {:?}", e);
Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("Query error"))
.unwrap())
}
};
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical Security Risk: Executing Arbitrary SQL Queries

Ohayo, sensei! The /sql endpoint currently allows users to execute arbitrary SQL queries directly against the database. This poses a significant security risk, including potential data leakage and SQL injection attacks. Even with a read-only SqlitePool, exposing direct query execution can compromise the integrity and confidentiality of the data.

I recommend removing this endpoint or implementing a safe abstraction that only allows predefined queries or parameterized inputs. Would you like assistance in refactoring this to enhance security?


let json = json!({
"service": "torii",
"success": true
Expand Down
Loading