Repository: All-Hands-AI/OpenHands
File: enterprise/server/routes/api_keys.py (Python)

Code before:
        True if the key is valid, False otherwise
    """
    if not (LITE_LLM_API_URL and byor_key):
        return False

    try:
        async with httpx.AsyncClient(
            verify=httpx_verify_option(),
            timeout=5.0,  # Short timeout for lightweight verification
        ) as client:
            # Make a lightweight request to verify the key
            # Using /v1/models endpoint as it's lightweight and requires authentication
            response = await client.get(
                f'{LITE_LLM_API_URL}/v1/models',
                headers={
                    'Authorization': f'Bearer {byor_key}',
                },
            )

            # If we get a 401 or 403, the key is invalid
            if response.status_code in (401, 403):
                logger.warning(
                    'BYOR key verification failed - authentication error',
                    extra={
                        'user_id': user_id,
                        'status_code': response.status_code,
                        'key_prefix': byor_key[:10] + '...'
                        if len(byor_key) > 10
                        else byor_key,
                    },
                )
                return False

            # If we get a successful response (200) or other non-auth errors, consider it valid
            # Other errors (like 500) might be temporary, so we err on the side of considering it valid
            if response.status_code == 200:
                logger.debug(
                    'BYOR key verification successful',
                    extra={'user_id': user_id},
                )
                return True

            # For other status codes, log but consider it valid to avoid false negatives
            logger.warning(
                'BYOR key verification returned unexpected status code',
                extra={
                    'user_id': user_id,
                    'status_code': response.status_code,
                },
            )
            return True  # Consider valid to avoid false negatives

Review comment (suggestion):
Would `response.is_success` make more sense here? (Just as a general principle - it means that we don't cut off other responses like 301, 201, etc...)

Code after:
        byor_key: The BYOR key to verify
        user_id: The user ID for logging purposes

    Returns:
        True if the key is verified as valid, False if verification fails or key is invalid.
        Returns False on network errors/timeouts to ensure we don't return potentially invalid keys.
    """
    if not (LITE_LLM_API_URL and byor_key):
        return False

    try:
        async with httpx.AsyncClient(
            verify=httpx_verify_option(),
            timeout=BYOR_KEY_VERIFICATION_TIMEOUT,
        ) as client:
            # Make a lightweight request to verify the key
            # Using /v1/models endpoint as it's lightweight and requires authentication
            response = await client.get(
                f'{LITE_LLM_API_URL}/v1/models',
                headers={
                    'Authorization': f'Bearer {byor_key}',
                },
            )

            # Only 200 status code indicates valid key
            if response.status_code == 200:
                logger.debug(
                    'BYOR key verification successful',
                    extra={'user_id': user_id},
                )
                return True

            # All other status codes (401, 403, 500, etc.) are treated as invalid
            # This includes authentication errors and server errors
            logger.warning(
                'BYOR key verification failed - treating as invalid',
                extra={
                    'user_id': user_id,
                    'status_code': response.status_code,
                    'key_prefix': byor_key[:10] + '...'
                    if len(byor_key) > 10
                    else byor_key,
                },
            )
            return False

    except (httpx.TimeoutException, Exception) as e:
        # Any exception (timeout, network error, etc.) means we can't verify
        # Return False to trigger regeneration rather than returning potentially invalid key
        logger.warning(
            'BYOR key verification error - treating as invalid to ensure key validity',