|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +import os |
| 17 | +import socket |
| 18 | +import ssl |
| 19 | +import tempfile |
| 20 | +import threading |
| 21 | +from typing import Any, TYPE_CHECKING |
| 22 | + |
| 23 | +if TYPE_CHECKING: |
| 24 | + import psycopg |
| 25 | + |
| 26 | +logger = logging.getLogger(name=__name__) |
| 27 | + |
| 28 | +_CHUNK_SIZE = 8 * 1024 # bytes per recv() call inside the proxy forwarding loop |
| 29 | + |
| 30 | + |
| 31 | +def _proxy(local: socket.socket, remote: "ssl.SSLSocket") -> None: |
| 32 | + """Bidirectionally proxy bytes between a local Unix socket and a remote |
| 33 | + SSL socket. |
| 34 | +
|
| 35 | + Spawns one daemon thread for the remote→local direction and runs the |
| 36 | + local→remote direction in the calling thread. Blocks until the calling |
| 37 | + thread's direction reaches EOF or a socket error, at which point both |
| 38 | + sockets are closed so the other thread also unblocks and exits. |
| 39 | +
|
| 40 | + Args: |
| 41 | + local: The Unix domain socket connected to the database driver. |
| 42 | + remote: The SSL socket connected to the AlloyDB proxy server. |
| 43 | + """ |
| 44 | + |
| 45 | + def forward(src: Any, dst: Any) -> None: |
| 46 | + buf = bytearray(_CHUNK_SIZE) |
| 47 | + view = memoryview(buf) |
| 48 | + try: |
| 49 | + while True: |
| 50 | + n = src.recv_into(view) |
| 51 | + if n == 0: |
| 52 | + logger.debug("psycopg proxy: EOF on %s, closing both sockets", src) |
| 53 | + break |
| 54 | + dst.sendall(view[:n]) |
| 55 | + except (OSError, ssl.SSLError) as e: |
| 56 | + logger.debug("psycopg proxy: socket error on %s: %s", src, e) |
| 57 | + finally: |
| 58 | + # Close both ends so the sibling thread also unblocks. |
| 59 | + for s in (local, remote): |
| 60 | + try: |
| 61 | + # shutdown is required on POSIX systems to forcefully |
| 62 | + # interrupt the sibling thread's blocking recv_into() call. |
| 63 | + # Simply closing the socket does not interrupt the system |
| 64 | + # call and leads to leaked threads. |
| 65 | + s.shutdown(socket.SHUT_RDWR) |
| 66 | + except OSError: |
| 67 | + pass |
| 68 | + try: |
| 69 | + s.close() |
| 70 | + except OSError: |
| 71 | + pass |
| 72 | + |
| 73 | + threading.Thread(target=forward, args=(remote, local), daemon=True).start() |
| 74 | + forward(local, remote) # run in calling thread rather than spawning a third |
| 75 | + |
| 76 | + |
| 77 | +def connect(remote_sock: "ssl.SSLSocket", **kwargs: Any) -> "psycopg.Connection": |
| 78 | + """Create a psycopg DBAPI connection object. |
| 79 | +
|
| 80 | + Because psycopg does not accept a pre-connected socket, this function |
| 81 | + creates a temporary Unix domain socket, tells psycopg to connect there, |
| 82 | + and runs a background proxy that forwards bytes between that socket and |
| 83 | + the already-established AlloyDB TLS connection. |
| 84 | +
|
| 85 | + Args: |
| 86 | + remote_sock (ssl.SSLSocket): SSL/TLS secure socket stream connected to the |
| 87 | + AlloyDB proxy server. |
| 88 | +
|
| 89 | + Returns: |
| 90 | + psycopg.Connection: A psycopg Connection object for the AlloyDB instance. |
| 91 | + """ |
| 92 | + try: |
| 93 | + import psycopg |
| 94 | + except ImportError: |
| 95 | + raise ImportError( |
| 96 | + 'Unable to import module "psycopg." Please install and try again.' |
| 97 | + ) |
| 98 | + |
| 99 | + tmpdir = tempfile.mkdtemp() |
| 100 | + socket_path = os.path.join(tmpdir, ".s.PGSQL.5432") |
| 101 | + logger.debug("psycopg: created Unix socket at %s", socket_path) |
| 102 | + |
| 103 | + local_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 104 | + local_sock.bind(socket_path) |
| 105 | + local_sock.listen(1) |
| 106 | + |
| 107 | + def _accept_and_proxy() -> None: |
| 108 | + """Accept one connection then proxy bytes until the connection closes.""" |
| 109 | + try: |
| 110 | + unix_conn, _ = local_sock.accept() |
| 111 | + local_sock.close() |
| 112 | + logger.debug("psycopg proxy: accepted connection, starting proxy") |
| 113 | + except OSError as e: |
| 114 | + logger.debug("psycopg proxy: accept failed: %s", e) |
| 115 | + try: |
| 116 | + remote_sock.close() |
| 117 | + except OSError: |
| 118 | + pass |
| 119 | + return |
| 120 | + _proxy(unix_conn, remote_sock) |
| 121 | + |
| 122 | + threading.Thread(target=_accept_and_proxy, daemon=True).start() |
| 123 | + |
| 124 | + user = kwargs.pop("user") |
| 125 | + db = kwargs.pop("db") |
| 126 | + passwd = kwargs.pop("password", None) |
| 127 | + # SSL is already handled by the underlying SSLSocket; disable it on the |
| 128 | + # Unix socket so psycopg does not attempt a second TLS handshake. |
| 129 | + kwargs.pop("sslmode", None) |
| 130 | + |
| 131 | + logger.debug("psycopg: connecting as user=%s dbname=%s", user, db) |
| 132 | + try: |
| 133 | + conn = psycopg.connect( |
| 134 | + user=user, |
| 135 | + dbname=db, |
| 136 | + password=passwd, |
| 137 | + host=tmpdir, |
| 138 | + port=5432, |
| 139 | + sslmode="disable", |
| 140 | + **kwargs, |
| 141 | + ) |
| 142 | + logger.debug("psycopg: connection established") |
| 143 | + return conn |
| 144 | + except Exception as e: |
| 145 | + logger.debug("psycopg: connection failed: %s", e) |
| 146 | + # psycopg never connected (or failed mid-handshake); close the server |
| 147 | + # socket so the proxy thread unblocks and exits cleanly. |
| 148 | + try: |
| 149 | + local_sock.close() |
| 150 | + except OSError: |
| 151 | + pass |
| 152 | + try: |
| 153 | + remote_sock.close() |
| 154 | + except OSError: |
| 155 | + pass |
| 156 | + raise |
| 157 | + finally: |
| 158 | + # The socket file and its parent directory are only needed during the |
| 159 | + # initial connect() call; remove them now regardless of outcome. |
| 160 | + try: |
| 161 | + os.remove(socket_path) |
| 162 | + except OSError: |
| 163 | + pass |
| 164 | + try: |
| 165 | + os.rmdir(tmpdir) |
| 166 | + except OSError: |
| 167 | + pass |
0 commit comments