Skip to content

Commit 9052d62

Browse files
committed
test(auth): Add integration tests for logins waiting for a second factor
Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Carl Schwan <carl@carlschwan.eu>
1 parent a21c731 commit 9052d62

3 files changed

Lines changed: 265 additions & 0 deletions

File tree

‎build/integration/features/bootstrap/FeatureContext.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class FeatureContext implements Context, SnippetAcceptingContext {
1919
use Search;
2020
use WebDav;
2121
use Trashbin;
22+
use TwoFactorAuth;
2223

2324
protected function resetAppConfigs(): void {
2425
$this->deleteServerConfig('bruteForce', 'whitelist_0');
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
<?php
2+
3+
/**
4+
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
5+
* SPDX-License-Identifier: AGPL-3.0-or-later
6+
*/
7+
use Behat\Hook\AfterScenario;
8+
use Behat\Step\Given;
9+
use Behat\Step\Then;
10+
use Behat\Step\When;
11+
use GuzzleHttp\Client;
12+
use PHPUnit\Framework\Assert;
13+
14+
require __DIR__ . '/autoload.php';
15+
16+
/**
17+
* Steps for logins that are waiting for their second factor
18+
*
19+
* Needs the OccRunner, Auth and Sharing traits.
20+
*/
21+
trait TwoFactorAuth {
22+
private bool $twoFactorEnforced = false;
23+
/** @var array<string, string> */
24+
private array $appPasswords = [];
25+
26+
#[Given('two-factor authentication is enforced for group :group')]
27+
public function twoFactorAuthenticationIsEnforcedForGroup(string $group): void {
28+
$this->enforceTwoFactorAuthentication(['--on', '--group', $group]);
29+
}
30+
31+
/**
32+
* The admin group stays excluded, the admin account is used for the setup and cleanup of scenarios
33+
*/
34+
#[Given('two-factor authentication is enforced for all users except group :group')]
35+
public function twoFactorAuthenticationIsEnforcedExceptForGroup(string $group): void {
36+
$this->enforceTwoFactorAuthentication(['--on', '--exclude', 'admin', '--exclude', $group]);
37+
}
38+
39+
#[Given('two-factor authentication is not enforced')]
40+
public function twoFactorAuthenticationIsNotEnforced(): void {
41+
$this->enforceTwoFactorAuthentication(['--off']);
42+
}
43+
44+
private function enforceTwoFactorAuthentication(array $options): void {
45+
$this->runOcc(array_merge(['twofactorauth:enforce'], $options));
46+
Assert::assertSame(0, $this->lastCode, $this->lastStdOut . $this->lastStdErr);
47+
$this->twoFactorEnforced = true;
48+
}
49+
50+
#[AfterScenario]
51+
public function resetTwoFactorEnforcement(): void {
52+
if ($this->twoFactorEnforced) {
53+
$this->runOcc(['twofactorauth:enforce', '--off']);
54+
$this->twoFactorEnforced = false;
55+
}
56+
$this->appPasswords = [];
57+
}
58+
59+
#[Given('user :user has an app password')]
60+
public function userHasAnAppPassword(string $user): void {
61+
putenv('NC_PASS=' . $this->regularUser);
62+
$this->runOcc(['user:auth-tokens:add', '--password-from-env', $user]);
63+
putenv('NC_PASS');
64+
Assert::assertSame(0, $this->lastCode, $this->lastStdOut . $this->lastStdErr);
65+
66+
$lines = explode("\n", trim($this->lastStdOut));
67+
$this->appPasswords[$user] = end($lines);
68+
}
69+
70+
#[When('requesting :url with :method using the app password of :user')]
71+
public function requestingWithAppPassword(string $url, string $method, string $user): void {
72+
$this->sendRequest($url, $method, 'basic ' . base64_encode($user . ':' . $this->appPasswords[$user]));
73+
}
74+
75+
#[When('requesting :url with :method using the app password of :user and the browser session')]
76+
public function requestingWithAppPasswordAndBrowserSession(string $url, string $method, string $user): void {
77+
$this->sendRequest($url, $method, 'basic ' . base64_encode($user . ':' . $this->appPasswords[$user]), true);
78+
}
79+
80+
#[When('submitting the login form as :user using the browser session')]
81+
public function submittingTheLoginFormAs(string $user): void {
82+
$this->submitLoginForm($user, []);
83+
}
84+
85+
/**
86+
* A timezone offset that is not valid UTF-8 makes saving the session fail
87+
* after the session token of the login was created
88+
*/
89+
#[When('logging in using web as :user with a timezone offset that is not valid UTF-8')]
90+
public function loggingInUsingWebWithInvalidTimezoneOffset(string $user): void {
91+
$this->submitLoginForm($user, [
92+
'timezone' => 'Europe/Berlin',
93+
'timezone_offset' => "\xFF",
94+
]);
95+
}
96+
97+
/**
98+
* Submits the login form without following the redirect to the challenge
99+
*/
100+
private function submitLoginForm(string $user, array $formParams): void {
101+
$loginUrl = $this->getServerUrl() . '/index.php/login';
102+
$client = new Client();
103+
$this->extracRequestTokenFromResponse($client->get($loginUrl, ['cookies' => $this->cookieJar]));
104+
105+
// Without http_errors the cookies of a failed login are kept
106+
$this->response = $client->post($loginUrl, [
107+
'form_params' => [
108+
'user' => $user,
109+
'password' => $this->regularUser,
110+
'requesttoken' => $this->requestToken,
111+
] + $formParams,
112+
'cookies' => $this->cookieJar,
113+
'headers' => ['Origin' => $this->getServerUrl()],
114+
'allow_redirects' => false,
115+
'http_errors' => false,
116+
]);
117+
}
118+
119+
#[When('the password :password of the last link share is sent as an anonymous request using the browser session')]
120+
public function thePasswordOfTheLastLinkShareIsSent(string $password): void {
121+
$client = new Client();
122+
$authenticateUrl = $this->getServerUrl() . '/index.php/s/' . $this->lastShareData->data[0]->token . '/authenticate/showShare';
123+
// Keeps the request anonymous although the session cookie belongs to a login
124+
$headers = ['X-Nextcloud-Federation' => '1'];
125+
126+
$this->extracRequestTokenFromResponse($client->get($authenticateUrl, [
127+
'cookies' => $this->cookieJar,
128+
'headers' => $headers,
129+
]));
130+
131+
$this->response = $client->post($authenticateUrl, [
132+
'form_params' => [
133+
'password' => $password,
134+
'requesttoken' => $this->requestToken,
135+
],
136+
'cookies' => $this->cookieJar,
137+
'headers' => $headers + ['Origin' => $this->getServerUrl()],
138+
'allow_redirects' => false,
139+
'http_errors' => false,
140+
]);
141+
}
142+
143+
#[Then('the response redirects to :path')]
144+
public function theResponseRedirectsTo(string $path): void {
145+
Assert::assertContains($this->response->getStatusCode(), [302, 303]);
146+
Assert::assertSame($path, parse_url($this->response->getHeaderLine('Location'), PHP_URL_PATH));
147+
}
148+
149+
#[Then('the browser session has access to the account of :user')]
150+
public function theBrowserSessionHasAccessToTheAccountOf(string $user): void {
151+
Assert::assertSame($user, $this->getBrowserSessionUser(), 'The browser session is not logged in as ' . $user);
152+
}
153+
154+
#[Then('the browser session has no access to the account of :user')]
155+
public function theBrowserSessionHasNoAccessToTheAccountOf(string $user): void {
156+
Assert::assertNotSame($user, $this->getBrowserSessionUser(), 'The browser session is logged in as ' . $user);
157+
}
158+
159+
/**
160+
* The user the browser session is fully logged in as, without following
161+
* a redirect to a two-factor challenge
162+
*/
163+
private function getBrowserSessionUser(): ?string {
164+
$client = new Client();
165+
$this->response = $client->get($this->getServerUrl() . '/ocs/v2.php/cloud/user?format=json', [
166+
'cookies' => $this->cookieJar,
167+
'headers' => ['OCS-APIRequest' => 'true'],
168+
'allow_redirects' => false,
169+
'http_errors' => false,
170+
]);
171+
172+
if ($this->response->getStatusCode() !== 200) {
173+
return null;
174+
}
175+
return json_decode($this->response->getBody()->getContents())->ocs->data->id;
176+
}
177+
178+
private function getServerUrl(): string {
179+
return substr($this->baseUrl, 0, -5);
180+
}
181+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
2+
# SPDX-License-Identifier: AGPL-3.0-or-later
3+
Feature: two-factor-auth
4+
5+
Background:
6+
Given user "user0" exists
7+
And user "user1" exists
8+
And As an "admin"
9+
And creating the group "twofactor"
10+
And user "user0" belongs to group "twofactor"
11+
And two-factor authentication is enforced for group "twofactor"
12+
And the cookie jar is reset
13+
14+
Scenario: a login is redirected to the challenge selection
15+
When submitting the login form as "user0" using the browser session
16+
Then the response redirects to "/index.php/login/selectchallenge"
17+
And the browser session has no access to the account of "user0"
18+
19+
Scenario: a user outside the enforced group logs in without a second factor
20+
When submitting the login form as "user1" using the browser session
21+
Then the HTTP status code should be "303"
22+
And the browser session has access to the account of "user1"
23+
24+
Scenario: a user in an excluded group logs in without a second factor
25+
Given creating the group "notwofactor"
26+
And user "user1" belongs to group "notwofactor"
27+
And two-factor authentication is enforced for all users except group "notwofactor"
28+
When submitting the login form as "user1" using the browser session
29+
Then the HTTP status code should be "303"
30+
And the browser session has access to the account of "user1"
31+
32+
Scenario: a user outside an excluded group has to pass a second factor
33+
Given creating the group "notwofactor"
34+
And two-factor authentication is enforced for all users except group "notwofactor"
35+
When submitting the login form as "user1" using the browser session
36+
Then the response redirects to "/index.php/login/selectchallenge"
37+
And the browser session has no access to the account of "user1"
38+
39+
Scenario: a login is complete when two-factor authentication is no longer enforced
40+
Given two-factor authentication is not enforced
41+
When submitting the login form as "user0" using the browser session
42+
Then the HTTP status code should be "303"
43+
And the browser session has access to the account of "user0"
44+
45+
Scenario: WebDAV refuses the login password of a user who has to pass a second factor
46+
When requesting "/remote.php/dav/files/user0/" with "PROPFIND" using basic auth
47+
Then the HTTP status code should be "401"
48+
49+
Scenario: WebDAV accepts an app password of a user who has to pass a second factor
50+
Given user "user0" has an app password
51+
When requesting "/remote.php/dav/files/user0/" with "PROPFIND" using the app password of "user0"
52+
Then the HTTP status code should be "207"
53+
54+
Scenario: a login whose session could not be saved still needs its second factor
55+
When logging in using web as "user0" with a timezone offset that is not valid UTF-8
56+
Then the HTTP status code should be "500"
57+
And the browser session has no access to the account of "user0"
58+
59+
Scenario: the app password of another user in the session does not replace the second factor
60+
Given user "user1" has an app password
61+
And requesting "/ocs/v2.php/cloud/user" with "GET" using the app password of "user1" and the browser session
62+
And the HTTP status code should be "200"
63+
When submitting the login form as "user0" using the browser session
64+
Then the HTTP status code should be "303"
65+
And the browser session has no access to the account of "user0"
66+
67+
Scenario: a session whose session token belongs to another user is logged out
68+
Given Logging in using web as "user1"
69+
When logging in using web as "user0" with a timezone offset that is not valid UTF-8
70+
Then the HTTP status code should be "500"
71+
And the browser session has no access to the account of "user1"
72+
73+
Scenario: renewing the session token of a login keeps its pending second factor
74+
Given User "user1" uploads file with content "shared note" to "/note.txt"
75+
And as "user1" creating a share with
76+
| path | note.txt |
77+
| shareType | 3 |
78+
| password | Link-password-2fa-test |
79+
And logging in using web as "user0" with a timezone offset that is not valid UTF-8
80+
And the HTTP status code should be "500"
81+
When the password "Link-password-2fa-test" of the last link share is sent as an anonymous request using the browser session
82+
Then the HTTP status code should be "303"
83+
And the browser session has no access to the account of "user0"

0 commit comments

Comments
 (0)