Skip to content

Commit 6056518

Browse files
committed
Tolerate OTP that are slighlty early or late #9677
Because some clients have mobile devices with a poorly synced time, we must be tolerant and allow them to be either a bit early or a bit late. Now the total window to accept an OTP is of 87 seconds.
1 parent 3be7ad8 commit 6056518

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/Model/Traits/HasOtp.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,6 @@ public function verifyOtp(string $received): bool
9999
}
100100
$otp = OTPHP\Factory::loadFromProvisioningUri($this->otpUri);
101101

102-
return $otp->verify($received);
102+
return $otp->verify($received, null, 29);
103103
}
104104
}

tests/Model/Traits/HasOtpTest.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ public function testVerifySecret(): void
8989

9090
$otp = Factory::loadFromProvisioningUri($uri);
9191
self::assertInstanceOf(TOTPInterface::class, $otp);
92-
self::assertTrue($this->user->verifyOtp($otp->now()), 'Correct OTP given');
92+
93+
// This is very time sensitive, and test might be flaky if the generated OTP is on the last
94+
// millisecond of a second, and the verification happens on the first millisecond of the next second.
95+
// To limit flakiness, we test with a slightly shorter time period than what is actually allowed.
96+
self::assertTrue($this->user->verifyOtp($otp->at(time())), 'Correct OTP given');
97+
self::assertTrue($this->user->verifyOtp($otp->at(time() - 27)), 'Even accept correct past OTP, in case of mobile device clock sync failure');
98+
self::assertTrue($this->user->verifyOtp($otp->at(time() + 27)), 'Even accept correct future OTP, in case of mobile device clock sync failure');
9399
}
94100
}

0 commit comments

Comments
 (0)