From 8943f057036a187fcc7c09662e3f0cea66f7e1e6 Mon Sep 17 00:00:00 2001 From: Marc Brinkmann Date: Tue, 9 Apr 2024 13:08:20 +0200 Subject: [PATCH] Update role creation code to not use bind params --- src/postgres.rs | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/src/postgres.rs b/src/postgres.rs index 77a2849..5b51816 100644 --- a/src/postgres.rs +++ b/src/postgres.rs @@ -103,10 +103,8 @@ impl PostgresConnection { .is_none() { // User does not exist, ensure we create it. - let create_role_sql = format!("CREATE ROLE {} NOCREATEDB NOCREATEROLE NOINHERIT LOGIN NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 8 PASSWORD $1;", role_name); - self.client - .execute(&create_role_sql, &[&role_name, &role_password]) - .await?; + let create_role_sql = format!("CREATE ROLE {} NOCREATEDB NOCREATEROLE NOINHERIT LOGIN NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 8 PASSWORD '{}'", role_name, single_quote_escape(role_password)); + self.client.execute(&create_role_sql, &[]).await?; }; // Same for database, only create if not existent yet. @@ -149,6 +147,10 @@ fn assert_valid_ident(input: &str) -> Result<(), Error> { } } +fn single_quote_escape(input: &str) -> String { + input.replace('\'', "''") +} + #[cfg(test)] mod tests { use super::PostgresDb; @@ -180,12 +182,23 @@ mod tests { su.create_database("unittest", "unittest") .expect("should be able to create db"); - let db = dbg!(PostgresDb::new( - pg.as_user("unittest", "unittest").uri("postgres") - )); + let db = PostgresDb::new(pg.as_user("unittest", "unittest").uri("postgres")); let con = db.connect().await.expect("failed to connect"); con.run_self_check() .await .expect_err("self-check should fail"); } + + #[tokio::test] + async fn can_create_db_for_instance() { + let pg = mk_pg(); + let su = pg.as_superuser(); + + let db = PostgresDb::new(su.uri("postgres")); + + let con = db.connect().await.expect("failed to connect"); + con.create_instance("myrole", "mypw", "mydb") + .await + .expect("failed to create instance"); + } }