Commit ·
952cf47
1
Parent(s): ed723a3
fixing project id env variable loading
Browse files83 unmodified lines848586878889909188 unmodified lines18018118218318418526 unmodified lines212213214215216217268 unmodified lines4864874884894904914924934944954964974984995005015025035045055065075085095105115125135147 unmodified lines5225235245255265271 unmodified line52953053153253353453553653753853954083 unmodified linesdef save_credentials(creds, project_id=None):global credentials_from_env# Don't save to file if credentials came from environment variableif credentials_from_env:returncreds_data = {88 unmodified linescredentials = Credentials.from_authorized_user_info(creds_data, SCOPES)credentials_from_env = True # Mark as environment credentials# Try to refresh if expired and refresh token existsif credentials.expired and credentials.refresh_token:try:26 unmodified linescredentials = Credentials.from_authorized_user_info(minimal_creds_data, SCOPES)credentials_from_env = True # Mark as environment credentials# Force refresh since we don't have a valid tokentry:logging.info("Refreshing minimal environment credentials...")268 unmodified linesif user_project_id:return user_project_idenv_project_id = os.getenv("GOOGLE_CLOUD_PROJECT")if env_project_id:user_project_id = env_project_idsave_credentials(creds, user_project_id)return user_project_idif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:creds_data = json.load(f)cached_project_id = creds_data.get("project_id")if cached_project_id:user_project_id = cached_project_idreturn user_project_idexcept Exception as e:passif creds.expired and creds.refresh_token:try:creds.refresh(GoogleAuthRequest())save_credentials(creds)except Exception as e:raise Exception(f"Failed to refresh credentials while getting project ID: {str(e)}")headers = {"Authorization": f"Bearer {creds.token}",7 unmodified linestry:import requestsresp = requests.post(f"{CODE_ASSIST_ENDPOINT}/v1internal:loadCodeAssist",data=json.dumps(probe_payload),1 unmodified line)resp.raise_for_status()data = resp.json()user_project_id = data.get("cloudaicompanionProject")if not user_project_id:raise ValueError("Could not find 'cloudaicompanionProject' in loadCodeAssist response.")save_credentials(creds, user_project_id)return user_project_idexcept requests.exceptions.HTTPError as e:raise83 unmodified lines8485868788899091929394959697989910010110210310488 unmodified lines19319419519619719819920020120220320426 unmodified lines231232233234235236237238239240241242268 unmodified lines5115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505517 unmodified lines5595605615625635645651 unmodified line56756856957057157257357457557657757857958058158258358458558683 unmodified linesdef save_credentials(creds, project_id=None):global credentials_from_env# Don't save credentials to file if they came from environment variable,# but still save project_id if provided and no file exists or file lacks project_idif credentials_from_env:if project_id and os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:existing_data = json.load(f)# Only update project_id if it's missing from the fileif "project_id" not in existing_data:existing_data["project_id"] = project_idwith open(CREDENTIAL_FILE, "w") as f:json.dump(existing_data, f, indent=2)logging.info(f"Added project_id {project_id} to existing credential file")except Exception as e:logging.warning(f"Could not update project_id in credential file: {e}")returncreds_data = {88 unmodified linescredentials = Credentials.from_authorized_user_info(creds_data, SCOPES)credentials_from_env = True # Mark as environment credentials# Extract project_id from environment credentials if availableif "project_id" in raw_env_creds_data:global user_project_iduser_project_id = raw_env_creds_data["project_id"]logging.info(f"Extracted project_id from environment credentials: {user_project_id}")# Try to refresh if expired and refresh token existsif credentials.expired and credentials.refresh_token:try:26 unmodified linescredentials = Credentials.from_authorized_user_info(minimal_creds_data, SCOPES)credentials_from_env = True # Mark as environment credentials# Extract project_id from environment credentials if availableif "project_id" in raw_env_creds_data:global user_project_iduser_project_id = raw_env_creds_data["project_id"]logging.info(f"Extracted project_id from minimal environment credentials: {user_project_id}")# Force refresh since we don't have a valid tokentry:logging.info("Refreshing minimal environment credentials...")268 unmodified linesif user_project_id:return user_project_id# Priority 1: Check environment variable firstenv_project_id = os.getenv("GOOGLE_CLOUD_PROJECT")if env_project_id:logging.info(f"Using project ID from GOOGLE_CLOUD_PROJECT environment variable: {env_project_id}")user_project_id = env_project_idsave_credentials(creds, user_project_id)return user_project_id# Priority 2: Check cached project ID in credential fileif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:creds_data = json.load(f)cached_project_id = creds_data.get("project_id")if cached_project_id:logging.info(f"Using cached project ID from credential file: {cached_project_id}")user_project_id = cached_project_idreturn user_project_idexcept Exception as e:logging.warning(f"Could not read project_id from credential file: {e}")# Priority 3: Make API call to discover project ID# Ensure we have valid credentials for the API callif creds.expired and creds.refresh_token:try:logging.info("Refreshing credentials before project ID discovery...")creds.refresh(GoogleAuthRequest())save_credentials(creds)logging.info("Credentials refreshed successfully for project ID discovery")except Exception as e:logging.error(f"Failed to refresh credentials while getting project ID: {e}")# Continue with existing credentials - they might still workif not creds.token:raise Exception("No valid access token available for project ID discovery")headers = {"Authorization": f"Bearer {creds.token}",7 unmodified linestry:import requestslogging.info("Attempting to discover project ID via API call...")resp = requests.post(f"{CODE_ASSIST_ENDPOINT}/v1internal:loadCodeAssist",data=json.dumps(probe_payload),1 unmodified line)resp.raise_for_status()data = resp.json()discovered_project_id = data.get("cloudaicompanionProject")if not discovered_project_id:raise ValueError("Could not find 'cloudaicompanionProject' in loadCodeAssist response.")logging.info(f"Discovered project ID via API: {discovered_project_id}")user_project_id = discovered_project_idsave_credentials(creds, user_project_id)return user_project_idexcept requests.exceptions.HTTPError as e:logging.error(f"HTTP error during project ID discovery: {e}")if hasattr(e, 'response') and e.response:logging.error(f"Response status: {e.response.status_code}, body: {e.response.text}")raise Exception(f"Failed to discover project ID via API: {e}")except Exception as e:logging.error(f"Unexpected error during project ID discovery: {e}")raise Exception(f"Failed to discover project ID: {e}")
src/auth.py+52-6