• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daycry / auth / 44317717916

18 Nov 2026 01:49PM UTC coverage: 82.894% (+4.4%) from 78.462%
44317717916

Pull #79

github

web-flow
Merge 7c781daeb into 55dbf61d2
Pull Request #79: feat: security fixes, extension points and auth completion

1214 of 1370 new or added lines in 67 files covered. (88.61%)

12 existing lines in 5 files now uncovered.

6663 of 8038 relevant lines covered (82.89%)

97.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.77
/src/Controllers/WebAuthnController.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of Daycry Auth.
7
 *
8
 * (c) Daycry <daycry9@proton.me>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace Daycry\Auth\Controllers;
15

16
use CodeIgniter\HTTP\ResponseInterface;
17
use Daycry\Auth\Authentication\Authenticators\Session;
18
use Daycry\Auth\Exceptions\WebAuthnDuplicateCredentialException;
19
use Daycry\Auth\Exceptions\WebAuthnException;
20
use Daycry\Auth\Interfaces\WebAuthnManagerInterface;
21

22
/**
23
 * JSON endpoints for the WebAuthn ceremonies. All methods 404 when the feature
24
 * is globally disabled (defense in depth on top of Auth::routes() gating).
25
 */
26
class WebAuthnController extends BaseAuthController
27
{
28
    /**
29
     * This controller exposes only JSON ceremony endpoints; it does not use
30
     * the form-validation flow that BaseAuthController otherwise requires.
31
     */
32
    protected function getValidationRules(): array
×
33
    {
34
        return [];
×
35
    }
36

37
    /**
38
     * Whether passkeys are enabled (`AuthSecurity::$webauthnEnabled`).
39
     */
40
    protected function enabled(): bool
9 ✔
41
    {
42
        return (bool) (setting('AuthSecurity.webauthnEnabled') ?? false);
9 ✔
43
    }
44

45
    /**
46
     * The ceremony manager (`service('webAuthnManager')`).
47
     */
48
    protected function manager(): WebAuthnManagerInterface
7 ✔
49
    {
50
        return service('webAuthnManager');
7 ✔
51
    }
52

53
    /**
54
     * A JSON error response carrying a fresh CSRF token.
55
     */
56
    protected function error(string $message, int $status, string $code = 'error'): ResponseInterface
8 ✔
57
    {
58
        return $this->response->setStatusCode($status)->setJSON([
8 ✔
59
            'status'  => 'error',
8 ✔
60
            'error'   => $code,
8 ✔
61
            'message' => $message,
8 ✔
62
            'token'   => csrf_hash(),
8 ✔
63
        ]);
8 ✔
64
    }
65

66
    /**
67
     * Adds the freshly-rotated CSRF token to a JSON payload so the reference
68
     * ceremony JS can carry it into the follow-up request (CI4 regenerates the
69
     * token per request when csrf.regenerate is enabled). Harmless for the
70
     * WebAuthn option objects: the browser ignores unknown top-level keys.
71
     *
72
     * @param array<string, mixed> $payload
73
     *
74
     * @return array<string, mixed>
75
     */
76
    protected function withToken(array $payload): array
6 ✔
77
    {
78
        $payload['token'] = csrf_hash();
6 ✔
79

80
        return $payload;
6 ✔
81
    }
82

83
    /**
84
     * Required MFA cannot be replaced or enrolled using only a remembered session.
85
     */
86
    protected function registrationGuard(): ?ResponseInterface
5 ✔
87
    {
88
        $user   = auth()->user();
5 ✔
89
        $policy = service('mfaPolicy');
5 ✔
90
        if (! $policy->requires($user)) {
5 ✔
91
            return null;
4 ✔
92
        }
93
        if ($policy->hasFactor($user)) {
1 ✔
94
            return $policy->verified($user) ? null : $this->error(lang('Auth.mfaVerificationRequired'), 403, 'mfa_verification_required');
1 ✔
95
        }
96
        $interactive = (int) session(Session::AUTHENTICATED_AT_KEY);
1 ✔
97
        $confirmed   = (string) session('auth_step_up_user') === (string) $user->id ? (int) session('password_confirmed_at') : 0;
1 ✔
98
        $latest      = max($interactive, $confirmed);
1 ✔
99
        $lifetime    = (int) (setting('AuthSecurity.passwordConfirmationLifetime') ?? 0);
1 ✔
100
        if ($latest <= 0 || $latest > time() || $lifetime <= 0 || time() - $latest >= $lifetime) {
1 ✔
101
            return $this->error(lang('Auth.passwordConfirmRequired'), 403, 'confirmation_required');
1 ✔
102
        }
103

104
        return null;
1 ✔
105
    }
106

107
    public function registerOptions(): ResponseInterface
6 ✔
108
    {
109
        if (! $this->enabled()) {
6 ✔
110
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
×
111
        }
112
        if (! auth()->loggedIn()) {
6 ✔
113
            return $this->error(lang('Auth.notLoggedIn'), 403, 'forbidden');
1 ✔
114
        }
115
        if (($denied = $this->registrationGuard()) !== null) {
5 ✔
116
            return $denied;
1 ✔
117
        }
118

119
        $body = $this->request->is('json') ? $this->request->getJSON(true) : $this->request->getPost();
5 ✔
120
        if ((bool) ($body['conditional'] ?? false)) {
5 ✔
121
            $authenticatedAt = (int) session(Session::AUTHENTICATED_AT_KEY);
1 ✔
122
            $lifetime        = (int) (setting('AuthSecurity.passwordConfirmationLifetime') ?? 0);
1 ✔
123
            if (! (bool) setting('AuthSecurity.webauthnAutoUpgrade') || $authenticatedAt <= 0 || $authenticatedAt > time() || $lifetime <= 0 || time() - $authenticatedAt >= $lifetime) {
1 ✔
124
                return $this->error(lang('Auth.passwordConfirmRequired'), 403, 'confirmation_required');
1 ✔
125
            }
126
        }
127

128
        try {
129
            $name    = $body['name'] ?? null;
5 ✔
130
            $options = $this->manager()->startRegistration(auth()->user(), is_string($name) && $name !== '' ? $name : null);
5 ✔
131
        } catch (WebAuthnException $e) {
×
132
            return $this->error($e->getMessage(), 409, 'conflict');
×
133
        }
134

135
        return $this->response->setJSON($this->withToken($options));
5 ✔
136
    }
137

138
    public function registerVerify(): ResponseInterface
4 ✔
139
    {
140
        if (! $this->enabled()) {
4 ✔
141
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
×
142
        }
143
        if (! auth()->loggedIn()) {
4 ✔
144
            return $this->error(lang('Auth.notLoggedIn'), 403, 'forbidden');
×
145
        }
146
        if (($denied = $this->registrationGuard()) !== null) {
4 ✔
NEW
147
            return $denied;
×
148
        }
149

150
        $json = $this->credentialJson();
4 ✔
151
        if ($json === null) {
4 ✔
152
            return $this->error(lang('Auth.webauthnVerificationFailed'), 400, 'bad_request');
×
153
        }
154

155
        try {
156
            $entity = $this->manager()->finishRegistration(auth()->user(), $json);
4 ✔
157
        } catch (WebAuthnDuplicateCredentialException $e) {
1 ✔
158
            return $this->error($e->getMessage(), 409, 'conflict');
1 ✔
159
        } catch (WebAuthnException $e) {
×
160
            return $this->error($e->getMessage(), 422, 'unprocessable');
×
161
        }
162

163
        return $this->response->setStatusCode(201)->setJSON($this->withToken([
4 ✔
164
            'status'     => 'ok',
4 ✔
165
            'credential' => ['uuid' => $entity->uuid, 'name' => $entity->name],
4 ✔
166
        ]));
4 ✔
167
    }
168

169
    public function loginOptions(): ResponseInterface
4 ✔
170
    {
171
        if (! $this->enabled()) {
4 ✔
172
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
1 ✔
173
        }
174

175
        $body    = $this->request->is('json') ? $this->request->getJSON(true) : $this->request->getPost();
3 ✔
176
        $email   = $body['email'] ?? null;
3 ✔
177
        $options = $this->manager()->startLogin(is_string($email) && $email !== '' ? $email : null);
3 ✔
178

179
        return $this->response->setJSON($this->withToken($options));
3 ✔
180
    }
181

182
    public function loginVerify(): ResponseInterface
3 ✔
183
    {
184
        if (! $this->enabled()) {
3 ✔
185
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
×
186
        }
187

188
        $json = $this->credentialJson();
3 ✔
189
        if ($json === null) {
3 ✔
190
            return $this->error(lang('Auth.webauthnVerificationFailed'), 400, 'bad_request');
×
191
        }
192

193
        try {
194
            $user = $this->manager()->finishLogin($json);
3 ✔
195
        } catch (WebAuthnException $e) {
×
196
            return $this->error($e->getMessage(), 422, 'unprocessable');
×
197
        }
198

199
        // Password login refuses banned users in checkLogin(); login() does not.
200
        if ($user->isBanned()) {
3 ✔
201
            return $this->error($user->getBanMessage() ?? lang('Auth.bannedUser'), 403, 'banned');
1 ✔
202
        }
203

204
        // A verified passkey (with user verification) is multi-factor: complete
205
        // the session directly without re-running the 'login' Action pipeline.
206
        $assertion    = json_decode($json, true);
2 ✔
207
        $encoded      = $assertion['response']['authenticatorData'] ?? '';
2 ✔
208
        $bytes        = is_string($encoded) ? base64_decode(strtr($encoded, '-_', '+/'), true) : false;
2 ✔
209
        $userVerified = is_string($bytes) && strlen($bytes) > 32 && (ord($bytes[32]) & 0x04) !== 0;
2 ✔
210
        if (service('mfaPolicy')->requires($user) && ! $userVerified) {
2 ✔
211
            return $this->error(lang('Auth.mfaVerificationRequired'), 403, 'mfa_verification_required');
1 ✔
212
        }
213
        auth()->login($user, false);
1 ✔
214
        if ($userVerified) {
1 ✔
215
            service('mfaPolicy')->markVerified($user);
1 ✔
216
        }
217

218
        return $this->response->setJSON($this->withToken([
1 ✔
219
            'status'   => 'ok',
1 ✔
220
            'redirect' => config('Auth')->loginRedirect(),
1 ✔
221
        ]));
1 ✔
222
    }
223

224
    public function twoFactorOptions(): ResponseInterface
×
225
    {
226
        if (! $this->enabled()) {
×
227
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
×
228
        }
229

230
        $pending = auth()->getPendingUser();
×
231
        if ($pending === null) {
×
232
            return $this->error(lang('Auth.webauthnVerificationFailed'), 422, 'unprocessable');
×
233
        }
234

235
        return $this->response->setJSON($this->withToken($this->manager()->startTwoFactor($pending)));
×
236
    }
237

238
    public function deleteCredential(string $uuid): ResponseInterface
×
239
    {
240
        if (! $this->enabled()) {
×
241
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
×
242
        }
243
        if (! auth()->loggedIn()) {
×
244
            return $this->error(lang('Auth.notLoggedIn'), 403, 'forbidden');
×
245
        }
246

NEW
247
        $user = auth()->user();
×
NEW
248
        if (service('mfaPolicy')->requires($user) && ! $user->hasTotpEnabled() && count($user->webAuthnCredentials()) <= 1) {
×
NEW
249
            return $this->error(lang('Auth.mfaLastFactorRequired'), 409, 'last_factor');
×
250
        }
251

NEW
252
        $ok = $user->revokeWebAuthnCredential($uuid);
×
253

254
        return $this->response->setStatusCode($ok ? 200 : 404)->setJSON($this->withToken(['status' => $ok ? 'ok' : 'not_found']));
×
255
    }
256

257
    /**
258
     * Browser credential synchronization is restricted to the current account.
259
     */
260
    public function credentialSignals(): ResponseInterface
1 ✔
261
    {
262
        if (! $this->enabled()) {
1 ✔
NEW
263
            return $this->error(lang('Auth.webauthnDisabled'), 404, 'disabled');
×
264
        }
265
        if (! auth()->loggedIn()) {
1 ✔
266
            return $this->error(lang('Auth.notLoggedIn'), 403, 'forbidden');
1 ✔
267
        }
268

269
        return $this->response->setHeader('Cache-Control', 'no-store')->setJSON($this->manager()->credentialSignals(auth()->user()));
1 ✔
270
    }
271

272
    /**
273
     * Extracts the browser PublicKeyCredential JSON from the request body
274
     * (accepts a `credential` field or the raw body).
275
     */
276
    protected function credentialJson(): ?string
5 ✔
277
    {
278
        $body = $this->request->getJSON(true);
5 ✔
279
        if (is_array($body) && isset($body['credential'])) {
5 ✔
280
            return json_encode($body['credential'], JSON_THROW_ON_ERROR);
5 ✔
281
        }
282
        $posted = $this->request->getPost('credential');
×
283
        if (is_string($posted) && $posted !== '') {
×
284
            return $posted;
×
285
        }
286
        $raw = (string) $this->request->getBody();
×
287

288
        return $raw !== '' ? $raw : null;
×
289
    }
290
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc