From 664642ab5b2ae3f64af021bd9d1d2807849cda1d Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <mths.dev@pm.me>
Date: Fri, 24 Jan 2025 15:37:36 -0300
Subject: [PATCH v1] Redact user password on pg_stat_statements

Previously when using the pg_stat_statements extension and logging level is set
to DDL and an e.g CREATE USER or ALTER ROLE was executed, the entire SQL was
being logged into the pg_stat_statements view, including the user
password.

To replace hard coded values on SQL with $#, the node must have a
location field, so when JumbleQuery is executed, the location of these
nodes are stored on JumbleState.

This commit adds a location field on String type that is used to
represent the password, so that it can be redacted from logs. The
grammar for was also changed to fill the location value
{ CREATE|ALTER} {USER|ROLE|GROUP } identifier { [WITH] [ENCRYPTED]
PASSWORD 'value' }
---
 src/backend/nodes/value.c |  1 +
 src/backend/parser/gram.y | 10 ++++++++--
 src/include/nodes/value.h |  2 ++
 3 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/src/backend/nodes/value.c b/src/backend/nodes/value.c
index 5a8c1ce2478..c79a3c0a202 100644
--- a/src/backend/nodes/value.c
+++ b/src/backend/nodes/value.c
@@ -65,6 +65,7 @@ makeString(char *str)
 	String	   *v = makeNode(String);
 
 	v->sval = str;
+	v->location = -1;
 	return v;
 }
 
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 7d99c9355c6..5950e873e81 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -1199,8 +1199,11 @@ AlterOptRoleList:
 AlterOptRoleElem:
 			PASSWORD Sconst
 				{
+					String *str = makeString($2);
+					str->location = @2;
+
 					$$ = makeDefElem("password",
-									 (Node *) makeString($2), @1);
+									 (Node *) str, @1);
 				}
 			| PASSWORD NULL_P
 				{
@@ -1213,8 +1216,11 @@ AlterOptRoleElem:
 					 * form, so there is no difference between PASSWORD and
 					 * ENCRYPTED PASSWORD.
 					 */
+					String *str = makeString($3);
+					str->location = @3;
+
 					$$ = makeDefElem("password",
-									 (Node *) makeString($3), @1);
+									 (Node *) str, @1);
 				}
 			| UNENCRYPTED PASSWORD Sconst
 				{
diff --git a/src/include/nodes/value.h b/src/include/nodes/value.h
index 3ee3b976b8f..2227d75f4b5 100644
--- a/src/include/nodes/value.h
+++ b/src/include/nodes/value.h
@@ -66,6 +66,8 @@ typedef struct String
 
 	NodeTag		type;
 	char	   *sval;
+
+	ParseLoc	location pg_node_attr(query_jumble_location);
 } String;
 
 typedef struct BitString
-- 
2.39.5 (Apple Git-154)

