|
21 | 21 |
|
22 | 22 | from google.auth import exceptions |
23 | 23 | from google.auth.aio import credentials |
| 24 | +from google.auth.aio import transport |
24 | 25 | from google.auth.aio.transport import sessions |
25 | 26 |
|
26 | 27 | # This is the valid "workload" format the library expects |
@@ -140,3 +141,37 @@ def mock_callback(): |
140 | 141 | await session.configure_mtls_channel(client_cert_callback=mock_callback) |
141 | 142 |
|
142 | 143 | assert session._is_mtls is True |
| 144 | + |
| 145 | + @pytest.mark.asyncio |
| 146 | + async def test_configure_mtls_channel_custom_request(self): |
| 147 | + """ |
| 148 | + Tests that if _auth_request is not an AiohttpRequest, _is_mtls is set to False |
| 149 | + because we can't configure the custom request with mTLS. |
| 150 | + """ |
| 151 | + with mock.patch.dict( |
| 152 | + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"} |
| 153 | + ), mock.patch("os.path.exists") as mock_exists, mock.patch( |
| 154 | + "builtins.open", mock.mock_open(read_data=json.dumps(VALID_WORKLOAD_CONFIG)) |
| 155 | + ), mock.patch( |
| 156 | + "google.auth.aio.transport.mtls.get_client_cert_and_key" |
| 157 | + ) as mock_helper, mock.patch( |
| 158 | + "google.auth.aio.transport.mtls.make_client_cert_ssl_context" |
| 159 | + ) as mock_make_context: |
| 160 | + mock_exists.return_value = True |
| 161 | + mock_helper.return_value = (True, b"fake_cert_data", b"fake_key_data") |
| 162 | + |
| 163 | + mock_context = mock.Mock(spec=ssl.SSLContext) |
| 164 | + mock_make_context.return_value = mock_context |
| 165 | + |
| 166 | + mock_creds = mock.AsyncMock(spec=credentials.Credentials) |
| 167 | + mock_auth_request = mock.AsyncMock(spec=transport.Request) |
| 168 | + session = sessions.AsyncAuthorizedSession(mock_creds, auth_request=mock_auth_request) |
| 169 | + |
| 170 | + await session.configure_mtls_channel() |
| 171 | + |
| 172 | + # If the request handler is not an AiohttpRequest, the library cannot configure |
| 173 | + # the connection to use mTLS, so _is_mtls must be False to reflect this unconfigured state. |
| 174 | + assert session._is_mtls is False |
| 175 | + mock_make_context.assert_called_once_with( |
| 176 | + b"fake_cert_data", b"fake_key_data" |
| 177 | + ) |
0 commit comments