@@ -91,13 +91,7 @@ def __init__(
9191
9292 def record_principal (self , user : str , database : str ) -> None :
9393 """Records a PostgreSQL (user, database) pair observed on an IAM connection."""
94- if not user :
95- return
96- if not database :
97- database = user
98- pair = (user , database )
99- if pair not in self ._iam_principals :
100- self ._iam_principals .append (pair )
94+ _append_iam_principal (self ._iam_principals , user , database )
10195
10296 @property
10397 def conn_name (self ) -> ConnectionName :
@@ -164,91 +158,14 @@ async def _perform_refresh(self) -> ConnectionInfo:
164158
165159 async def _probe_connection (self , conn_info : ConnectionInfo ) -> None :
166160 """Proactively probes the database to refresh IAM tokens on server-side MCP."""
167- targets : list [str ] = []
168- if self ._conn_name .domain_name :
169- targets .append (self ._conn_name .domain_name )
170- else :
171- if self ._ip_type .value in conn_info .ip_addrs :
172- targets .extend (conn_info .ip_addrs [self ._ip_type .value ])
173-
174- if not targets :
175- logger .debug (
176- f"['{ self ._conn_name } ']: Proactive IAM token refresh probe skipped: no target IP addresses"
177- )
178- return
179-
180- port = SERVER_PROXY_PORT
181- try :
182- ssl_context = await conn_info .create_ssl_context (self ._enable_iam_auth )
183- except Exception as e : # noqa: BLE001
184- logger .debug (
185- f"['{ self ._conn_name } ']: Failed to create SSL context for probe: { e !s} "
186- )
187- return
188-
189- principals : list [tuple [str , str ] | None ] = []
190- if (
191- conn_info .database_version .startswith ("POSTGRES" )
192- and self ._iam_principals
193- ):
194- principals .extend (self ._iam_principals )
195- else :
196- principals .append (None )
197-
198- all_succeeded = True
199- for principal in principals :
200- probed_principal = False
201- for target in targets :
202- try :
203- logger .debug (
204- f"['{ self ._conn_name } ']: Probing IAM token refresh on { target } :{ port } "
205- )
206- reader , writer = await asyncio .wait_for (
207- asyncio .open_connection (
208- host = target ,
209- port = port ,
210- ssl = ssl_context ,
211- server_hostname = (
212- self ._conn_name .domain_name
213- if self ._conn_name .domain_name
214- else None
215- ),
216- ),
217- timeout = float (self ._timeout ),
218- )
219- try :
220- if principal is not None :
221- user , database = principal
222- writer .write (
223- _build_postgres_startup_packet (user , database )
224- )
225- await writer .drain ()
226- await asyncio .wait_for (
227- reader .read (1024 ),
228- timeout = float (self ._timeout ),
229- )
230- writer .write (b"X\x00 \x00 \x00 \x04 " )
231- await writer .drain ()
232- finally :
233- writer .close ()
234- await writer .wait_closed ()
235- probed_principal = True
236- break
237- except Exception as e : # noqa: BLE001
238- logger .debug (
239- f"['{ self ._conn_name } ']: Probing IAM token refresh on { target } :{ port } failed: { e !s} "
240- )
241- if not probed_principal :
242- all_succeeded = False
243-
244- if all_succeeded :
245- logger .debug (
246- f"['{ self ._conn_name } ']: Proactive IAM token refresh probe successful"
247- )
248- else :
249- logger .debug (
250- f"['{ self ._conn_name } ']: Proactive IAM token refresh probe encountered error across all targets"
251- )
161+ await _probe_instance_connection (
162+ self ._conn_name ,
163+ conn_info ,
164+ self ._enable_iam_auth ,
165+ self ._ip_type ,
166+ self ._timeout ,
167+ self ._iam_principals ,
168+ )
252169
253170 def _schedule_refresh (self , delay : int ) -> asyncio .Task :
254171 """
@@ -337,6 +254,112 @@ async def close(self) -> None:
337254 self ._closed = True
338255
339256
257+ def _append_iam_principal (
258+ principals : list [tuple [str , str ]], user : str , database : str
259+ ) -> None :
260+ """Appends (user, database) to principals if not already present."""
261+ if not user :
262+ return
263+ if not database :
264+ database = user
265+ pair = (user , database )
266+ if pair not in principals :
267+ principals .append (pair )
268+
269+
270+ async def _probe_instance_connection (
271+ conn_name : ConnectionName ,
272+ conn_info : ConnectionInfo ,
273+ enable_iam_auth : bool ,
274+ ip_type : IPTypes ,
275+ timeout : int ,
276+ iam_principals : list [tuple [str , str ]],
277+ ) -> None :
278+ """Proactively probes the database to refresh IAM tokens on server-side MCP."""
279+ targets : list [str ] = []
280+ if conn_name .domain_name :
281+ targets .append (conn_name .domain_name )
282+ else :
283+ if ip_type .value in conn_info .ip_addrs :
284+ targets .extend (conn_info .ip_addrs [ip_type .value ])
285+
286+ if not targets :
287+ logger .debug (
288+ f"['{ conn_name } ']: Proactive IAM token refresh probe skipped: no target IP addresses"
289+ )
290+ return
291+
292+ port = SERVER_PROXY_PORT
293+ try :
294+ ssl_context = await conn_info .create_ssl_context (enable_iam_auth )
295+ except Exception as e : # noqa: BLE001
296+ logger .debug (
297+ f"['{ conn_name } ']: Failed to create SSL context for probe: { e !s} "
298+ )
299+ return
300+
301+ principals : list [tuple [str , str ] | None ] = []
302+ if conn_info .database_version .startswith ("POSTGRES" ) and iam_principals :
303+ principals .extend (iam_principals )
304+ else :
305+ principals .append (None )
306+
307+ all_succeeded = True
308+ for principal in principals :
309+ probed_principal = False
310+ for target in targets :
311+ try :
312+ logger .debug (
313+ f"['{ conn_name } ']: Probing IAM token refresh on { target } :{ port } "
314+ )
315+ reader , writer = await asyncio .wait_for (
316+ asyncio .open_connection (
317+ host = target ,
318+ port = port ,
319+ ssl = ssl_context ,
320+ server_hostname = (
321+ conn_name .domain_name
322+ if conn_name .domain_name
323+ else None
324+ ),
325+ ),
326+ timeout = float (timeout ),
327+ )
328+ try :
329+ if principal is not None :
330+ user , database = principal
331+ writer .write (
332+ _build_postgres_startup_packet (user , database )
333+ )
334+ await writer .drain ()
335+ await asyncio .wait_for (
336+ reader .read (1024 ),
337+ timeout = float (timeout ),
338+ )
339+ writer .write (b"X\x00 \x00 \x00 \x04 " )
340+ await writer .drain ()
341+ finally :
342+ writer .close ()
343+ await writer .wait_closed ()
344+ probed_principal = True
345+ break
346+ except Exception as e : # noqa: BLE001
347+ logger .debug (
348+ f"['{ conn_name } ']: Probing IAM token refresh on { target } :{ port } failed: { e !s} "
349+ )
350+ if not probed_principal :
351+ all_succeeded = False
352+
353+ if all_succeeded :
354+ logger .debug (
355+ f"['{ conn_name } ']: Proactive IAM token refresh probe successful"
356+ )
357+ else :
358+ logger .debug (
359+ f"['{ conn_name } ']: Proactive IAM token refresh probe encountered error across all targets"
360+ )
361+
362+
340363def _build_postgres_startup_packet (user : str , database : str ) -> bytes :
341364 """Builds a PostgreSQL v3.0 StartupMessage for (user, database)."""
342365 if not database :
0 commit comments