AOSSIE-Org / AOSSIE-Org/Devr.AI

BUG: Missing await keyword in authentication dependency causes crash for logged-in users

Abierto
#177 2 comentarios 0 reacciones 1 asignado Reclamado por @OmShukla-07 Ver en GitHub
bug
Lenguaje dominante
Python
Estrellas
102
Forks
137
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

### Is there an existing issue for this?

- [x] I have searched the existing issues

### What happened?

# 🐞 Bug Report: Two Critical Bugs Fixed in PR

## Is there an existing issue for this?
- ✅ I have searched the existing issues

## 📌 Issue Overview
This PR fixes **TWO separate critical bugs** that were breaking the backend:

1. **Authentication Bug** - Missing `await` keyword crashes logged-in users
2. **Startup Crash Bug** - Weaviate connection failure prevents backend from starting

---

## 🔍 Steps to Reproduce

### Bug 1: Authentication Crash (dependencies.py)
1. Go to `http://localhost:5173/login`
2. Create an account and log in successfully
3. Navigate to `/integrations` page
4. See the error: `AttributeError: 'coroutine' object has no attribute 'user'`

### Bug 2: Startup Crash (main.py)
1. Ensure Weaviate is slow to start or has network issues
2. Run `poetry run python main.py` in backend directory
3. Backend crashes with `httpcore.ConnectTimeout` error
4. See backend fails to start completely

---

## 🎯 Expected Behavior

### Bug 1: Authentication
- Logged-in users should successfully access `/integrations` page
- Integration status should load without crashing
- No `AttributeError: 'coroutine'` in logs

### Bug 2: Startup
- Backend should start even if Weaviate connection times out
- Show warning message instead of crashing
- Other features (Discord bot, API) should work normally

---

## 🚨 Actual Behavior

### Bug 1: Authentication
```
AttributeError: 'coroutine' object has no attribute 'user'
INFO: 127.0.0.1:62135 - "GET /v1/integrations/status/discord HTTP/1.1" 401 Unauthorized
```
**Result**: Integration page completely broken for logged-in users

### Bug 2: Startup
```
ERROR - Failed to connect to Weaviate: httpcore.ConnectTimeout
Traceback (most recent call last):
File "D:\FSOCIETY\GSOC\Devr.AI\backend\main.py", line 70, in test_weaviate_connection
raise
```
**Result**: Backend won't start, all services unavailable

---

## 📷 Screenshot

**Before Fix:**
```
Terminal: Backend crashes during startup
Browser: Cannot access integrations page (if backend somehow starts)
```

**After Fix:**
```
Terminal:
✅ Weaviate connection successful OR
⚠️ Failed to connect to Weaviate during startup: [error]
⚠️ Continuing without Weaviate - some features may not work
✅ Discord bot logged in as Devr.AI#5824
✅ Uvicorn running on http://0.0.0.0:8000

Browser:
✅ Integration page loads successfully for logged-in users
✅ No AttributeError crashes
```

---

## 💡 Suggested Improvements (Already Implemented)

### Fix 1: Add Missing `await` Keyword
**File**: `backend/app/core/dependencies.py`
**Line**: 50

```python
# BEFORE (Broken):
user_response = supabase.auth.get_user(token)

# AFTER (Fixed):
user_response = await supabase.auth.get_user(token)
```

**Why needed:**
- Supabase uses `AsyncClient` - all auth methods are async
- Without `await`, Python tries to access `.user` attribute before data loads
- Bug was introduced by CodeRabbit AI in commit `cedaad3` (Oct 16, 2025)

### Fix 2: Make Weaviate Connection Non-Blocking
**File**: `backend/main.py`
**Lines**: 68-72

```python
# BEFORE (Broken):
except Exception as e:
logger.error(f"Failed to connect to Weaviate: {e}")
raise # ❌ This crashes entire backend

# AFTER (Fixed):
except Exception as e:
logger.warning(f"Failed to connect to Weaviate during startup: {e}")
logger.warning("Continuing without Weaviate - some features may not work")
# Don't raise - allow backend to start even if Weaviate is unavailable
```

**Why needed:**
- Weaviate client tries to connect to PyPI for version checks during init
- Network timeouts or slow connections would crash entire backend
- Backend should gracefully degrade instead of completely failing
- Discord bot, API endpoints, and other services don't depend on Weaviate to start

---

## 🔗 Root Cause Analysis

### Bug 1: Authentication
**Introduced by**: CodeRabbit AI automated refactoring

**Commit**: `cedaad3194a4c2fcd7c5d76aa6f096e17db11f78`

**Date**: October 16, 2025

**Original correct code**: Commit `ee34c94` had `await` keyword

Git history proof:
```bash
$ git show cedaad3 backend/app/core/dependencies.py
- user_response = await supabase.auth.get_user(token) # Original (correct)
+ user_response = supabase.auth.get_user(token) # Bug introduced
```

### Bug 2: Weaviate Startup
**Design issue**: Original implementation treated Weaviate connection failure as fatal

**Problem**: Weaviate tries to connect to `https://pypi.org/pypi/weaviate-client/json` during startup

**Result**: Network issues or slow connections crash entire backend

**Why not caught earlier:**
- Weaviate usually starts quickly in Docker
- Most testing done in environments with good network connectivity
- Bug only appears when Weaviate is slow or network has issues

---

## 📊 Impact Assessment

### Bug 1: Authentication
**Severity**: 🔴 Critical
**Affected users**: All logged-in dashboard users
**Broken features**:
- Integration status page
- Integration management
- Settings page
- Any authenticated API endpoint

**Working features** (unaffected):
- Discord bot commands
- Public landing page
- User registration
- Login (authentication itself)

### Bug 2: Weaviate Startup
**Severity**: 🔴 Critical
**Affected users**: Everyone (backend won't start)
**Broken features**:
- Entire backend unavailable
- Discord bot can't connect
- All API endpoints down
- Frontend can't fetch data

---

## Record

- ✅ I agree to follow this project's Code of Conduct
- ✅ I want to work on this issue (already fixed in PR)

---

### Related Files
- `backend/app/core/dependencies.py` - Authentication fix
- `backend/main.py` - Startup robustness fix
- `backend/app/database/supabase/client.py` - AsyncClient usage
- `docs/issues/ISSUE_002_Missing_Await_In_Auth_Dependency.md` - Detailed documentation

### References
- Supabase Python AsyncClient: https://supabase.com/docs/reference/python/introduction
- Python Async/Await: https://docs.python.org/3/library/asyncio-task.html
- Weaviate Python Client: https://weaviate.io/developers/weaviate/client-libraries/python
- FastAPI Dependencies: https://fastapi.tiangolo.com/tutorial/dependencies/

---

**Report created by**: Om Shukla (@OmShukla-07)
**Date**: December 1, 2025

### Record

- [x] I agree to follow this project's Code of Conduct
- [x] I want to work on this issue

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.