1616
1717# Custom utils import
1818from google .cloud .sql .connector .refresh_utils import _get_ephemeral , _get_metadata
19+ from google .cloud .sql .connector .utils import write_to_file
1920from google .cloud .sql .connector .version import __version__ as version
2021
2122# Importing libraries
2728import google .auth .transport .requests
2829import ssl
2930import socket
30- from tempfile import NamedTemporaryFile
31+ from tempfile import TemporaryDirectory
3132from typing import (
3233 Any ,
3334 Awaitable ,
3435 Coroutine ,
35- IO ,
3636 Optional ,
3737 TYPE_CHECKING ,
3838 Union ,
@@ -67,9 +67,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
6767
6868class InstanceMetadata :
6969 ip_address : str
70- _ca_fileobject : IO
71- _cert_fileobject : IO
72- _key_fileobject : IO
7370 context : ssl .SSLContext
7471
7572 def __init__ (
@@ -80,27 +77,17 @@ def __init__(
8077 server_ca_cert : str ,
8178 ) -> None :
8279 self .ip_address = ip_address
83-
84- self ._ca_fileobject = NamedTemporaryFile (suffix = ".pem" )
85- self ._cert_fileobject = NamedTemporaryFile (suffix = ".pem" )
86- self ._key_fileobject = NamedTemporaryFile (suffix = ".pem" )
87-
88- # Write each file and reset to beginning
89- # TODO: Write tests on Windows and convert writing of temp
90- # files to be compatible with Windows.
91- self ._ca_fileobject .write (server_ca_cert .encode ())
92- self ._cert_fileobject .write (ephemeral_cert .encode ())
93- self ._key_fileobject .write (private_key )
94-
95- self ._ca_fileobject .seek (0 )
96- self ._cert_fileobject .seek (0 )
97- self ._key_fileobject .seek (0 )
98-
9980 self .context = ConnectionSSLContext ()
100- self .context .load_cert_chain (
101- self ._cert_fileobject .name , keyfile = self ._key_fileobject .name
102- )
103- self .context .load_verify_locations (cafile = self ._ca_fileobject .name )
81+
82+ # tmpdir and its contents are automatically deleted after the CA cert
83+ # and ephemeral cert are loaded into the SSLcontext. The values
84+ # need to be written to files in order to be loaded by the SSLContext
85+ with TemporaryDirectory () as tmpdir :
86+ ca_filename , cert_filename , key_filename = write_to_file (
87+ tmpdir , server_ca_cert , ephemeral_cert , private_key
88+ )
89+ self .context .load_cert_chain (cert_filename , keyfile = key_filename )
90+ self .context .load_verify_locations (cafile = ca_filename )
10491
10592
10693class CloudSQLConnectionError (Exception ):
0 commit comments