Skip to content

[HWC MOBILE] Fix Thread-Unsafe Global Token Storage in Authentication Interceptors #127

@Tomeshwari-02

Description

@Tomeshwari-02

🔐 [CRITICAL] Fix Thread-Unsafe Global Token Storage in Authentication Interceptors

🚨 Problem

The application uses global mutable state (companion objects) to store authentication tokens, which leads to race conditions when multiple threads access or modify the token simultaneously.

📍 File:
app/src/main/java/org/piramalswasthya/cho/network/interceptors/TokenInsertTmcInterceptor.kt (Lines 9–28)


🔍 Current Implementation

class TokenInsertTmcInterceptor : Interceptor {
    companion object {
        private var TOKEN: String = ""      // ❌ GLOBAL MUTABLE
        private var JWT: String = ""        // ❌ GLOBAL MUTABLE
        
        fun setToken(iToken: String) { TOKEN = iToken }
        fun setJwt(iJWT: String) { JWT = iJWT }
    }
    
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder()
            .addHeader("Authorization", TOKEN)  // ❌ UNSAFE READ
            .addHeader("Jwttoken", JWT)         // ❌ UNSAFE READ
            .build()

        return chain.proceed(request)
    }
}

⚠️ Race Condition Scenario

Thread A: Syncing patient data
→ TokenInsertTmcInterceptor.setToken("TOKEN_A")

Thread B: User logout  
→ TokenInsertTmcInterceptor.setToken("")

Thread C: Syncing vitals (reads empty token)
→ API call fails with 401 Unauthorized
→ Patient data sync fails silently
→ Data loss

❗ Impact

  • Affects 100% of network operations:

    • Patient registration
    • Vitals sync
    • Lab reports
    • Prescriptions
  • Silent data loss in critical healthcare workflows

  • Unreliable authentication behavior

  • Difficult/impossible to unit test due to static companion objects


✅ Expected Behavior

  • Token storage should be thread-safe and consistent
  • All threads should read the correct token value
  • No failures due to concurrent modifications
  • Architecture should support testability and maintainability

💡 Proposed Solution

  • Replace global mutable state with a thread-safe AuthTokenManager

  • Ensure safe concurrent access using:

    • Mutex (for coroutines) OR
    • AtomicReference
  • Use Dependency Injection (Hilt) to provide token manager

  • Move token logic to a single source of truth

  • Expose tokens via safe APIs (e.g., suspend functions)


🛠️ Tasks

  • Create AuthTokenManager with Mutex protection
  • Update TokenInsertTmcInterceptor to use Dependency Injection (DI)
  • Write concurrent access tests
  • Migrate TokenInsertAbhaInterceptor and `TokenESanjeevaniIn

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions