Add FIDO2/WebAuthn passkey authentication

Phase 14: Full WebAuthn support for passwordless passkey login and
hardware security key 2FA.

- go-webauthn/webauthn v0.16.1 dependency
- WebAuthnConfig with RPID/RPOrigin/DisplayName validation
- Migration 000009: webauthn_credentials table
- DB CRUD with ownership checks and admin operations
- internal/webauthn adapter: encrypt/decrypt at rest with AES-256-GCM
- REST: register begin/finish, login begin/finish, list, delete
- Web UI: profile enrollment, login passkey button, admin management
- gRPC: ListWebAuthnCredentials, RemoveWebAuthnCredential RPCs
- mciasdb: webauthn list/delete/reset subcommands
- OpenAPI: 6 new endpoints, WebAuthnCredentialInfo schema
- Policy: self-service enrollment rule, admin remove via wildcard
- Tests: DB CRUD, adapter round-trip, interface compliance
- Docs: ARCHITECTURE.md §22, PROJECT_PLAN.md Phase 14

Security: Credential IDs and public keys encrypted at rest with
AES-256-GCM via vault master key. Challenge ceremonies use 128-bit
nonces with 120s TTL in sync.Map. Sign counter validated on each
assertion to detect cloned authenticators. Password re-auth required
for registration (SEC-01 pattern). No credential material in API
responses or logs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-16 16:12:59 -07:00
parent 19fa0c9a8e
commit 25417b24f4
42 changed files with 4214 additions and 84 deletions

View File

@@ -86,6 +86,54 @@ components:
type: boolean
description: Whether TOTP is enrolled and required for this account.
example: false
webauthn_enabled:
type: boolean
description: Whether at least one WebAuthn credential is registered.
example: false
webauthn_count:
type: integer
description: Number of registered WebAuthn credentials.
example: 0
WebAuthnCredentialInfo:
type: object
required: [id, name, sign_count, discoverable, created_at]
properties:
id:
type: integer
format: int64
description: Database row ID.
example: 1
name:
type: string
description: User-supplied label for the credential.
example: "YubiKey 5"
aaguid:
type: string
description: Authenticator Attestation GUID.
example: "2fc0579f-8113-47ea-b116-bb5a8db9202a"
sign_count:
type: integer
format: uint32
description: Signature counter (used to detect cloned authenticators).
example: 42
discoverable:
type: boolean
description: Whether this is a discoverable (passkey/resident) credential.
example: true
transports:
type: string
description: Comma-separated transport hints (usb, nfc, ble, internal).
example: "usb,nfc"
created_at:
type: string
format: date-time
example: "2026-03-11T09:00:00Z"
last_used_at:
type: string
format: date-time
nullable: true
example: "2026-03-15T14:30:00Z"
AuditEvent:
type: object
@@ -847,6 +895,213 @@ paths:
"404":
$ref: "#/components/responses/NotFound"
# ── WebAuthn ──────────────────────────────────────────────────────────────
/v1/auth/webauthn/register/begin:
post:
summary: Begin WebAuthn registration
description: |
Start a WebAuthn credential registration ceremony. Requires the current
password for re-authentication (same security model as TOTP enrollment).
Returns PublicKeyCredentialCreationOptions for the browser WebAuthn API.
operationId: beginWebAuthnRegister
tags: [Auth]
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [password]
properties:
password:
type: string
description: Current password for re-authentication.
name:
type: string
description: Optional label for the credential (e.g. "YubiKey 5").
example: "YubiKey 5"
responses:
"200":
description: Registration options for navigator.credentials.create().
content:
application/json:
schema:
type: object
description: PublicKeyCredentialCreationOptions (WebAuthn spec).
"401":
$ref: "#/components/responses/Unauthorized"
"429":
description: Account temporarily locked.
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/v1/auth/webauthn/register/finish:
post:
summary: Finish WebAuthn registration
description: |
Complete the WebAuthn credential registration ceremony. The request body
contains the authenticator's response from navigator.credentials.create().
The credential is encrypted at rest with AES-256-GCM.
operationId: finishWebAuthnRegister
tags: [Auth]
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
type: object
description: AuthenticatorAttestationResponse (WebAuthn spec).
responses:
"200":
description: Credential registered.
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: ok
"400":
$ref: "#/components/responses/BadRequest"
"401":
$ref: "#/components/responses/Unauthorized"
/v1/auth/webauthn/login/begin:
post:
summary: Begin WebAuthn login
description: |
Start a WebAuthn authentication ceremony. Public RPC — no auth required.
With a username: returns allowCredentials for the account's registered
credentials. Without a username: starts a discoverable (passkey) flow.
operationId: beginWebAuthnLogin
tags: [Public]
requestBody:
content:
application/json:
schema:
type: object
properties:
username:
type: string
description: Optional. If omitted, starts a discoverable (passkey) flow.
example: alice
responses:
"200":
description: Assertion options for navigator.credentials.get().
content:
application/json:
schema:
type: object
description: PublicKeyCredentialRequestOptions (WebAuthn spec).
"429":
$ref: "#/components/responses/RateLimited"
/v1/auth/webauthn/login/finish:
post:
summary: Finish WebAuthn login
description: |
Complete the WebAuthn authentication ceremony. Validates the assertion,
checks the sign counter, and issues a JWT. Public RPC — no auth required.
operationId: finishWebAuthnLogin
tags: [Public]
requestBody:
required: true
content:
application/json:
schema:
type: object
description: AuthenticatorAssertionResponse (WebAuthn spec).
responses:
"200":
description: Login successful.
content:
application/json:
schema:
$ref: "#/components/schemas/TokenResponse"
"401":
$ref: "#/components/responses/Unauthorized"
"429":
$ref: "#/components/responses/RateLimited"
/v1/accounts/{id}/webauthn:
get:
summary: List WebAuthn credentials (admin)
description: |
Returns metadata for all WebAuthn credentials registered to an account.
Credential material (IDs, public keys) is never included.
operationId: listWebAuthnCredentials
tags: [Admin — Accounts]
security:
- bearerAuth: []
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
description: Account UUID.
responses:
"200":
description: Credential metadata list.
content:
application/json:
schema:
type: object
properties:
credentials:
type: array
items:
$ref: "#/components/schemas/WebAuthnCredentialInfo"
"401":
$ref: "#/components/responses/Unauthorized"
"403":
$ref: "#/components/responses/Forbidden"
"404":
$ref: "#/components/responses/NotFound"
/v1/accounts/{id}/webauthn/{credentialId}:
delete:
summary: Remove WebAuthn credential (admin)
description: |
Remove a specific WebAuthn credential from an account. Admin only.
operationId: deleteWebAuthnCredential
tags: [Admin — Accounts]
security:
- bearerAuth: []
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
description: Account UUID.
- name: credentialId
in: path
required: true
schema:
type: integer
format: int64
description: Credential database row ID.
responses:
"204":
description: Credential removed.
"401":
$ref: "#/components/responses/Unauthorized"
"403":
$ref: "#/components/responses/Forbidden"
"404":
$ref: "#/components/responses/NotFound"
/v1/token/issue:
post:
summary: Issue service account token (admin)

215
web/static/webauthn.js Normal file
View File

@@ -0,0 +1,215 @@
// webauthn.js — WebAuthn/passkey helpers for the MCIAS web UI.
// CSP-compliant: loaded as an external script, no inline code.
(function () {
'use strict';
// Base64URL encode/decode helpers for WebAuthn ArrayBuffer <-> JSON transport.
function base64urlEncode(buffer) {
var bytes = new Uint8Array(buffer);
var str = '';
for (var i = 0; i < bytes.length; i++) {
str += String.fromCharCode(bytes[i]);
}
return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function base64urlDecode(str) {
str = str.replace(/-/g, '+').replace(/_/g, '/');
while (str.length % 4) { str += '='; }
var binary = atob(str);
var bytes = new Uint8Array(binary.length);
for (var i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
// Get the CSRF token from the cookie for mutating requests.
function getCSRFToken() {
var match = document.cookie.match(/(?:^|;\s*)mcias_csrf=([^;]+)/);
return match ? match[1] : '';
}
function showError(id, msg) {
var el = document.getElementById(id);
if (el) { el.textContent = msg; el.style.display = ''; }
}
function hideError(id) {
var el = document.getElementById(id);
if (el) { el.style.display = 'none'; el.textContent = ''; }
}
// mciasWebAuthnRegister initiates a passkey/security-key registration.
window.mciasWebAuthnRegister = function (password, name, onSuccess, onError) {
if (!window.PublicKeyCredential) {
onError('WebAuthn is not supported in this browser.');
return;
}
var csrf = getCSRFToken();
var savedNonce = '';
fetch('/profile/webauthn/begin', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf },
body: JSON.stringify({ password: password, name: name })
})
.then(function (resp) {
if (!resp.ok) return resp.text().then(function (t) { throw new Error(t || 'Registration failed'); });
return resp.json();
})
.then(function (data) {
savedNonce = data.nonce;
var opts = data.options;
opts.publicKey.challenge = base64urlDecode(opts.publicKey.challenge);
if (opts.publicKey.user && opts.publicKey.user.id) {
opts.publicKey.user.id = base64urlDecode(opts.publicKey.user.id);
}
if (opts.publicKey.excludeCredentials) {
for (var i = 0; i < opts.publicKey.excludeCredentials.length; i++) {
opts.publicKey.excludeCredentials[i].id = base64urlDecode(opts.publicKey.excludeCredentials[i].id);
}
}
return navigator.credentials.create(opts);
})
.then(function (credential) {
if (!credential) throw new Error('Registration cancelled');
var credJSON = {
id: credential.id,
rawId: base64urlEncode(credential.rawId),
type: credential.type,
response: {
attestationObject: base64urlEncode(credential.response.attestationObject),
clientDataJSON: base64urlEncode(credential.response.clientDataJSON)
}
};
if (credential.response.getTransports) {
credJSON.response.transports = credential.response.getTransports();
}
return fetch('/profile/webauthn/finish', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf },
body: JSON.stringify({ nonce: savedNonce, name: name, credential: credJSON })
});
})
.then(function (resp) {
if (!resp.ok) return resp.text().then(function (t) { throw new Error(t || 'Registration failed'); });
return resp.json();
})
.then(function (result) { onSuccess(result); })
.catch(function (err) { onError(err.message || 'Registration failed'); });
};
// mciasWebAuthnLogin initiates a passkey login.
window.mciasWebAuthnLogin = function (username, onSuccess, onError) {
if (!window.PublicKeyCredential) {
onError('WebAuthn is not supported in this browser.');
return;
}
var savedNonce = '';
fetch('/login/webauthn/begin', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: username || '' })
})
.then(function (resp) {
if (!resp.ok) return resp.text().then(function (t) { throw new Error(t || 'Login failed'); });
return resp.json();
})
.then(function (data) {
savedNonce = data.nonce;
var opts = data.options;
opts.publicKey.challenge = base64urlDecode(opts.publicKey.challenge);
if (opts.publicKey.allowCredentials) {
for (var i = 0; i < opts.publicKey.allowCredentials.length; i++) {
opts.publicKey.allowCredentials[i].id = base64urlDecode(opts.publicKey.allowCredentials[i].id);
}
}
return navigator.credentials.get(opts);
})
.then(function (assertion) {
if (!assertion) throw new Error('Login cancelled');
var credJSON = {
id: assertion.id,
rawId: base64urlEncode(assertion.rawId),
type: assertion.type,
response: {
authenticatorData: base64urlEncode(assertion.response.authenticatorData),
clientDataJSON: base64urlEncode(assertion.response.clientDataJSON),
signature: base64urlEncode(assertion.response.signature)
}
};
if (assertion.response.userHandle) {
credJSON.response.userHandle = base64urlEncode(assertion.response.userHandle);
}
return fetch('/login/webauthn/finish', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nonce: savedNonce, credential: credJSON })
});
})
.then(function (resp) {
if (!resp.ok) return resp.text().then(function (t) { throw new Error(t || 'Login failed'); });
return resp.json();
})
.then(function () { onSuccess(); })
.catch(function (err) { onError(err.message || 'Login failed'); });
};
// Auto-wire the profile page enrollment button.
document.addEventListener('DOMContentLoaded', function () {
var enrollBtn = document.getElementById('webauthn-enroll-btn');
if (enrollBtn) {
enrollBtn.addEventListener('click', function () {
var pw = document.getElementById('webauthn-password').value;
var name = document.getElementById('webauthn-name').value || 'Passkey';
hideError('webauthn-enroll-error');
hideError('webauthn-enroll-success');
if (!pw) {
showError('webauthn-enroll-error', 'Password is required.');
return;
}
enrollBtn.disabled = true;
enrollBtn.textContent = 'Waiting for authenticator...';
window.mciasWebAuthnRegister(pw, name, function () {
enrollBtn.disabled = false;
enrollBtn.textContent = 'Add Passkey';
document.getElementById('webauthn-password').value = '';
var msg = document.getElementById('webauthn-enroll-success');
if (msg) { msg.textContent = 'Passkey registered successfully.'; msg.style.display = ''; }
// Reload the credentials list.
window.location.reload();
}, function (err) {
enrollBtn.disabled = false;
enrollBtn.textContent = 'Add Passkey';
showError('webauthn-enroll-error', err);
});
});
}
// Auto-wire the login page passkey button.
var loginBtn = document.getElementById('webauthn-login-btn');
if (loginBtn) {
loginBtn.addEventListener('click', function () {
hideError('webauthn-login-error');
loginBtn.disabled = true;
loginBtn.textContent = 'Waiting for authenticator...';
window.mciasWebAuthnLogin('', function () {
window.location.href = '/dashboard';
}, function (err) {
loginBtn.disabled = false;
loginBtn.textContent = 'Sign in with passkey';
showError('webauthn-login-error', err);
});
});
}
});
})();

View File

@@ -15,6 +15,7 @@
<dt class="text-muted">Status</dt>
<dd id="status-cell">{{template "account_status" .}}</dd>
<dt class="text-muted">TOTP</dt><dd>{{if .Account.TOTPRequired}}Enabled{{else}}Disabled{{end}}</dd>
{{if .WebAuthnEnabled}}<dt class="text-muted">Passkeys</dt><dd>{{len .WebAuthnCreds}} registered</dd>{{end}}
<dt class="text-muted">Created</dt><dd class="text-small">{{formatTime .Account.CreatedAt}}</dd>
<dt class="text-muted">Updated</dt><dd class="text-small">{{formatTime .Account.UpdatedAt}}</dd>
</dl>
@@ -44,6 +45,12 @@
<div id="token-delegates-section">{{template "token_delegates" .}}</div>
</div>
{{end}}
{{if .WebAuthnEnabled}}
<div class="card">
<h2 style="font-size:1rem;font-weight:600;margin-bottom:1rem">Passkeys</h2>
{{template "webauthn_credentials" .}}
</div>
{{end}}
<div class="card">
<h2 style="font-size:1rem;font-weight:600;margin-bottom:1rem">Tags</h2>
<div id="tags-editor">{{template "tags_editor" .}}</div>

View File

@@ -0,0 +1,30 @@
{{define "webauthn_credentials"}}
<div id="webauthn-credentials-section">
{{if .WebAuthnCreds}}
<table class="table" style="font-size:.85rem;margin-bottom:1rem">
<thead>
<tr><th>Name</th><th>Created</th><th>Last Used</th><th>Sign Count</th><th></th></tr>
</thead>
<tbody>
{{range .WebAuthnCreds}}
<tr>
<td>{{.Name}}{{if .Discoverable}} <span class="badge" title="Passkey (discoverable)">passkey</span>{{end}}</td>
<td class="text-small">{{formatTime .CreatedAt}}</td>
<td class="text-small">{{if .LastUsedAt}}{{formatTime (derefTime .LastUsedAt)}}{{else}}Never{{end}}</td>
<td>{{.SignCount}}</td>
<td>
<button class="btn btn-sm btn-danger"
hx-delete="{{$.DeletePrefix}}/{{.ID}}"
hx-target="#webauthn-credentials-section"
hx-swap="outerHTML"
hx-confirm="Remove this passkey?">Remove</button>
</td>
</tr>
{{end}}
</tbody>
</table>
{{else}}
<p class="text-muted text-small">No passkeys registered.</p>
{{end}}
</div>
{{end}}

View File

@@ -0,0 +1,19 @@
{{define "webauthn_enroll"}}
<div id="webauthn-enroll-section">
<div id="webauthn-enroll-error" class="alert alert-error" style="display:none" role="alert"></div>
<div id="webauthn-enroll-success" class="alert alert-success" style="display:none" role="alert"></div>
<div class="form-group">
<label for="webauthn-name">Passkey Name</label>
<input class="form-control" type="text" id="webauthn-name" placeholder="e.g. YubiKey 5" value="Passkey">
</div>
<div class="form-group">
<label for="webauthn-password">Current Password</label>
<input class="form-control" type="password" id="webauthn-password" autocomplete="current-password">
</div>
<div class="form-actions">
<button class="btn btn-primary" type="button" id="webauthn-enroll-btn">
Add Passkey
</button>
</div>
</div>
{{end}}

View File

@@ -29,10 +29,24 @@
<button class="btn btn-primary" type="submit" style="width:100%">Sign in</button>
</div>
</form>
{{if .WebAuthnEnabled}}
<div style="margin-top:1rem;text-align:center">
<div style="display:flex;align-items:center;gap:.75rem;margin-bottom:.75rem">
<hr style="flex:1;border:0;border-top:1px solid #ddd">
<span class="text-muted text-small">or</span>
<hr style="flex:1;border:0;border-top:1px solid #ddd">
</div>
<div id="webauthn-login-error" class="alert alert-error" style="display:none" role="alert"></div>
<button class="btn btn-secondary" type="button" id="webauthn-login-btn" style="width:100%">
Sign in with passkey
</button>
</div>
{{end}}
</div>
</div>
</div>
<script src="/static/htmx.min.js"></script>
{{if .WebAuthnEnabled}}<script src="/static/webauthn.js"></script>{{end}}
</body>
</html>
{{end}}

View File

@@ -4,6 +4,18 @@
<div class="page-header">
<h1>Profile</h1>
</div>
{{if .WebAuthnEnabled}}
<div class="card">
<h2 style="font-size:1rem;font-weight:600;margin-bottom:1rem">Passkeys</h2>
<p class="text-muted text-small" style="margin-bottom:.75rem">
Passkeys let you sign in without a password using your device's biometrics or a security key.
</p>
{{template "webauthn_credentials" .}}
<h3 style="font-size:.9rem;font-weight:600;margin:1rem 0 .5rem">Add a Passkey</h3>
{{template "webauthn_enroll" .}}
</div>
<script src="/static/webauthn.js"></script>
{{end}}
<div class="card">
<h2 style="font-size:1rem;font-weight:600;margin-bottom:1rem">Change Password</h2>
<p class="text-muted text-small" style="margin-bottom:.75rem">