Enhancing Multi-Tenant Authentication: Preventing Ambiguous Logins
In the motos-max-cordialidad project, we recently addressed a critical security concern related to our multi-tenant authentication mechanism. The goal was to ensure a robust and deterministic user login experience, especially when a tenantId was not explicitly provided during the authentication attempt.
The Problem
Our system allows users to exist across multiple tenants, such as different workshops, with email as a primary identifier. Critically, the unique constraint for user emails was defined as @@unique([tenantId, email]), meaning an email address is only unique within a specific tenant. This design choice, while valid, exposed a vulnerability when a login request was made without specifying a tenantId.
Previously, a tenant-less login would invoke a findByEmail method. If the same email happened to exist in multiple tenants, this query could silently authenticate the user against an arbitrary tenant's account by using a findFirst logic. This led to two significant issues:
- Unpredictable Logins: Users could inadvertently log into an unintended tenant, leading to confusion and potential data access issues.
- Email Probing: An attacker could potentially probe for registered email addresses across the entire system by observing which emails resulted in an arbitrary, yet successful, login versus a direct rejection.
The Solution
To rectify this, we refactored the authentication flow to be strictly deterministic. Now, when a login request lacks an explicit tenantId, the system no longer makes assumptions. Instead, it performs a broader query across all tenants for accounts matching the provided email address.
The login process will only proceed if exactly one user account matches the email across the entire system. If zero accounts match, or if multiple accounts match (indicating ambiguity), the system returns a generic 'Invalid credentials' error. This approach ensures:
- Users are never authenticated against an unintended tenant.
- The possibility of using ambiguous matches for probing registered emails is eliminated.
- Single-tenant logins (the current deployment model) remain unaffected, as they inherently result in exactly one match.
Implementation Details
This solution leveraged our existing Repository Pattern within the Hexagonal Architecture. We enhanced the UserRepository interface by introducing a new method, findManyByEmail, specifically designed to fetch all user records across different tenants that match a given email address. This allowed the authentication service to gather all potential matches before applying the strict one-match-only rule.
Here's an illustrative example of how the repository might be structured and used:
interface UserRepository {
findByEmail(email: string, tenantId?: string): Promise<User | null>;
findManyByEmail(email: string): Promise<User[]>; // New method for multi-tenant search
// ... other methods
}
class PrismaUserRepository implements UserRepository {
constructor(private readonly prisma: PrismaService) {}
async findByEmail(email: string, tenantId?: string): Promise<User | null> {
return this.prisma.user.findFirst({
where: { email, tenantId },
});
}
async findManyByEmail(email: string): Promise<User[]> {
return this.prisma.user.findMany({
where: { email },
});
}
}
The authentication service then incorporates this new method to handle tenant-less logins deterministically:
// Inside an authentication service method
async validateUser(email: string, pass: string, tenantId?: string): Promise<any> {
if (tenantId) {
// Existing single-tenant login flow, explicit tenantId provided
const user = await this.userRepository.findByEmail(email, tenantId);
// ... validate password for this specific user
if (user && user.password === pass) { return user; }
} else {
// New multi-tenant login flow without explicit tenantId
const users = await this.userRepository.findManyByEmail(email);
if (users.length === 1) {
const user = users[0];
// ... validate password for this uniquely identified user
if (user && user.password === pass) { return user; }
} else {
// Zero or multiple matches -> ambiguous or not found
throw new UnauthorizedException('Invalid credentials');
}
}
throw new UnauthorizedException('Invalid credentials');
}
Tests and Validation
To ensure the robustness and correctness of this fix, we implemented three new use-case tests:
- Single-match success: Verifying successful authentication when exactly one account matches the email.
- Ambiguous-refusal: Confirming that login is refused when multiple accounts match the email across different tenants.
- No-match-refusal: Ensuring login is refused when no account matches the email.
These tests rigorously validate that the deterministic behavior is correctly enforced under all relevant scenarios.
Key Takeaway
The critical lesson here is the paramount importance of explicit and deterministic logic in multi-tenant authentication systems. Relying on implicit behavior or arbitrary selections can introduce subtle yet significant security vulnerabilities and lead to poor user experiences. By actively handling ambiguity and enforcing a strict one-match policy, we've substantially hardened our authentication mechanism against both accidental mis-authentication and potential probing attacks, making our motos-max-cordialidad project more secure and reliable.
Generated with Gitvlg.com