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

Fix invalid json escaping #224

Merged
merged 3 commits into from
Jul 16, 2021
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ jobs:
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/points1_source.sql
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/points2_source.sql
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/function_source.sql
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/function_source_query_params.sql
env:
POSTGRES_HOST: localhost
POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }}
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/grcov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ jobs:
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/points1_source.sql
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/points2_source.sql
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/function_source.sql
psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U postgres -d test -f tests/fixtures/function_source_query_params.sql
env:
POSTGRES_HOST: localhost
POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }}
Expand Down
27 changes: 19 additions & 8 deletions src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,26 @@ pub fn mock_table_sources() -> Option<TableSources> {
}

pub fn mock_function_sources() -> Option<FunctionSources> {
let id = "public.function_source";
let source = FunctionSource {
id: id.to_owned(),
schema: "public".to_owned(),
function: "function_source".to_owned(),
};

let mut function_sources: FunctionSources = HashMap::new();
function_sources.insert(id.to_owned(), Box::new(source));

function_sources.insert(
"public.function_source".to_owned(),
Box::new(FunctionSource {
id: "public.function_source".to_owned(),
schema: "public".to_owned(),
function: "function_source".to_owned(),
}),
);

function_sources.insert(
"public.function_source_query_params".to_owned(),
Box::new(FunctionSource {
id: "public.function_source_query_params".to_owned(),
schema: "public".to_owned(),
function: "function_source_query_params".to_owned(),
}),
);

Some(function_sources)
}

Expand Down
10 changes: 4 additions & 6 deletions src/function_source.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use postgres::types::{Json, Type};
use postgres::types::Type;
use postgres_protocol::escape::escape_identifier;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand All @@ -7,7 +7,7 @@ use tilejson::{TileJSON, TileJSONBuilder};

use crate::db::Connection;
use crate::source::{Query, Source, Tile, Xyz};
use crate::utils::query_to_json_string;
use crate::utils::query_to_json;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FunctionSource {
Expand Down Expand Up @@ -42,8 +42,7 @@ impl Source for FunctionSource {
let empty_query = HashMap::new();
let query = query.as_ref().unwrap_or(&empty_query);

let query_json_string = query_to_json_string(&query)
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
let query_json = query_to_json(query);

// Query preparation : the schema and function can't be part of a prepared query, so they
// need to be escaped by hand.
Expand All @@ -69,9 +68,8 @@ impl Source for FunctionSource {
)
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;

let json = Json(query_json_string);
let tile = conn
.query_one(&query, &[&xyz.x, &xyz.y, &xyz.z, &json])
.query_one(&query, &[&xyz.x, &xyz.y, &xyz.z, &query_json])
.map(|row| row.get(self.function.as_str()))
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;

Expand Down
8 changes: 5 additions & 3 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::collections::HashMap;

use crate::source::{Query, Xyz};
use postgres::types::Json;
use serde_json::Value;

pub fn prettify_error<E: std::fmt::Display>(message: &'static str) -> impl Fn(E) -> std::io::Error {
move |error| std::io::Error::new(std::io::ErrorKind::Other, format!("{}: {}", message, error))
Expand Down Expand Up @@ -38,16 +40,16 @@ pub fn json_to_hashmap(value: &serde_json::Value) -> HashMap<String, String> {
hashmap
}

pub fn query_to_json_string(query: &Query) -> Result<String, serde_json::Error> {
pub fn query_to_json(query: &Query) -> Json<HashMap<String, Value>> {
let mut query_as_json = HashMap::new();
for (k, v) in query.iter() {
let json_value: serde_json::Value =
serde_json::from_str(v).unwrap_or_else(|_| serde_json::Value::String(v.clone()));

query_as_json.insert(k, json_value);
query_as_json.insert(k.clone(), json_value);
}

serde_json::to_string(&query_as_json)
Json(query_as_json)
}

pub fn get_bounds_cte(srid_bounds: String) -> String {
Expand Down
21 changes: 21 additions & 0 deletions tests/fixtures/function_source_query_params.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
DROP FUNCTION IF EXISTS public.function_source_query_params;
CREATE OR REPLACE FUNCTION public.function_source_query_params(z integer, x integer, y integer, query_params json) RETURNS bytea AS $$
DECLARE
mvt bytea;
BEGIN
RAISE DEBUG 'query_params: %', query_params;

IF (query_params->>'token')::varchar IS NULL THEN
RAISE EXCEPTION 'the `token` json parameter does not exist in `query_params`';
END IF;

SELECT INTO mvt ST_AsMVT(tile, 'public.function_source_query_params', 4096, 'geom') FROM (
SELECT
ST_AsMVTGeom(ST_Transform(geom, 3857), TileBBox(z, x, y, 3857), 4096, 64, true) AS geom
FROM public.table_source
WHERE geom && TileBBox(z, x, y, 4326)
) as tile WHERE geom IS NOT NULL;

RETURN mvt;
END
$$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;
1 change: 1 addition & 0 deletions tests/initdb-martin.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ echo "Loading Martin fixtures into $POSTGRES_DB"
psql --dbname="$POSTGRES_DB" -f /fixtures/TileBBox.sql
psql --dbname="$POSTGRES_DB" -f /fixtures/table_source.sql
psql --dbname="$POSTGRES_DB" -f /fixtures/function_source.sql
psql --dbname="$POSTGRES_DB" -f /fixtures/function_source_query_params.sql

psql --dbname="$POSTGRES_DB" -f /fixtures/points1_source.sql
psql --dbname="$POSTGRES_DB" -f /fixtures/points2_source.sql
23 changes: 23 additions & 0 deletions tests/server_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,29 @@ async fn test_get_function_source_tile_ok() {
assert!(response.status().is_success());
}

#[actix_rt::test]
async fn test_get_function_source_query_params_ok() {
init();

let state = mock_state(None, mock_function_sources(), false);
let mut app = test::init_service(App::new().data(state).configure(router)).await;

let req = test::TestRequest::get()
.uri("/rpc/public.function_source_query_params/0/0/0.pbf")
.to_request();

let response = test::call_service(&mut app, req).await;
println!("response.status = {:?}", response.status());
assert!(response.status().is_server_error());

let req = test::TestRequest::get()
.uri("/rpc/public.function_source_query_params/0/0/0.pbf?token=martin")
.to_request();

let response = test::call_service(&mut app, req).await;
assert!(response.status().is_success());
}

#[actix_rt::test]
async fn test_get_health_returns_ok() {
init();
Expand Down