I’m experiencing an intermittent authentication issue with the Google Cloud Vision API when running in production. The service, uses a service account json file for authentication and then perform text detection API via Python’s ImageAnnotatorClient. This works fine on both localhost and the development server. However, in production, it occasionally fails with an authentication error.
2024-08-18 07:16:35,315 - uvicorn - ERROR - Response Message: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [reason: "ACCESS_TOKEN_EXPIRED" domain: "googleapis.com" metadata { key: "service" value: "vision.googleapis.com" } metadata { key: "method" value: "google.cloud.vision.v1.ImageAnnotator.BatchAnnotateImages"
Details:
Service Environment: FastAPI service running on a production server (ubuntu vm, python 3.10)
Problem: The API sometimes returns authentication errors. The issue is intermittent but appears only in the production environment.
Working Conditions: The same service account JSON file works without issues on localhost and dev servers.
Additional Context:
- I have validated that the service account credentials and API configurations are correct.
- Network issues have been ruled out as the server is capable of making other network requests reliably.
CODE:
Relevant part of the code in the api.
def setup_client(self):
main_key = Utils.main_key_compile(self.first_key_part_file,self.second_key_part_file,self.third_key_part_file)
# Create a Fernet cipher using the main key
cipher_suite = Fernet(main_key)
with open(self.gvk_file_path, "rb") as file:
encrypted_data = file.read()
# Read the encrypted content from the JSON file you want to decrypt
decrypted_data = cipher_suite.decrypt(encrypted_data)
# client = vision.ImageAnnotatorClient()
json_str = decrypted_data.decode("utf-8") # Decode the bytes to a string
api_key_dict = json.loads(json_str) # Parse the JSON string into a Python dictionary
my_credentials = service_account.Credentials.from_service_account_info(api_key_dict)
self.client = vision.ImageAnnotatorClient(credentials=my_credentials)
def extract_text_google(self, image):
success, encoded_image = cv2.imencode('.png', image)
content = encoded_image.tobytes()
image = vision.Image(content=content)
image_context = types.ImageContext(language_hints=["en"])
max_retries = 2
retry_delay = 2 # seconds
for attempt in range(max_retries):
try:
response = self.client.text_detection(image=image,image_context=image_context)
# check if response.text_annotations is empty
if len(response.text_annotations) == 0:
text_results = {}
else:
text_results = response.text_annotations[0].description
return text_results
except google.api_core.exceptions.Unauthenticated as e:
self.logger.error(f"Authentication error: {e}")
# Optionally, reinitialize the client here if needed
self.setup_client()
except google.api_core.exceptions.GoogleAPIError as e:
self.logger.error(f"API error: {e}")
if attempt < max_retries:
time.sleep(retry_delay)
else:
raise
except Exception as e:
self.logger.error(f"Unexpected error: {e}")
if attempt < max_retries:
time.sleep(retry_delay)
else:
raise
return {}
Also rarely face the following issue as well
gunicorn[3784527]: google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.181.74:443: Failed to connect to remote host: FD Shutdown
Troubleshooting Steps Taken:
- Verified that the service account JSON file is correctly configured.
- Attempted to resolve the issue by creating multiple service accounts, but the problem persists.
- Ran a simple test on the prod server, by creating a vision client on python and hitting the api with service account credentials, this time continuously received failed authentication.
TroubleShooting_Simple_API_Hit_Client
I expected that direct call with client should work atleast sometime, since calls from within fastapi service sometimes worked, but this time got authentication issue every single time.