jigkit 0.6.0__tar.gz → 0.8.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {jigkit-0.6.0 → jigkit-0.8.0}/.gitignore +4 -2
- {jigkit-0.6.0 → jigkit-0.8.0}/PKG-INFO +8 -3
- {jigkit-0.6.0 → jigkit-0.8.0}/README.md +3 -2
- {jigkit-0.6.0 → jigkit-0.8.0}/pyproject.toml +8 -3
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/auth/__init__.py +2 -1
- jigkit-0.8.0/src/jigkit/auth/passkeys.py +337 -0
- jigkit-0.8.0/src/jigkit/testing/passkeys.py +149 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/web/__init__.py +5 -0
- jigkit-0.8.0/src/jigkit/web/access.py +99 -0
- jigkit-0.8.0/tests/test_access.py +146 -0
- jigkit-0.8.0/tests/test_passkeys.py +402 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/LICENSE +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/__init__.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/auth/cookies.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/auth/passwords.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/auth/sessions.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/auth/throttle.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/db.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/delivery.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/healthcheck.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/heartbeat.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/influx/__init__.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/influx/lineprotocol.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/influx/sink.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/logging.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/migrations.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/models.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/notify.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/py.typed +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/ratelimit.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/scheduler.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/secrets.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/settings.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/sinks.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/spool.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/testing/__init__.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/testing/http.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/testing/migrations.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/testing/notify.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/web/guard.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/web/health.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/web/manifest.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/web/server.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/src/jigkit/web/spa.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/conftest.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/sample_app/alembic/env.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/sample_app/alembic/script.py.mako +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/sample_app/alembic/versions/0001_initial.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/sample_app/alembic.ini +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/sample_app/sample_schema.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_auth.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_db.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_delivery.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_healthcheck.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_heartbeat.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_influx_lineprotocol.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_influx_read.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_influx_sink.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_logging.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_migrations.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_models.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_notify.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_ratelimit.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_scheduler.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_secrets.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_settings.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_sinks.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_spool.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_testing_plugin.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_version.py +0 -0
- {jigkit-0.6.0 → jigkit-0.8.0}/tests/test_web.py +0 -0
|
@@ -17,8 +17,6 @@ junit/
|
|
|
17
17
|
.ruff_cache/
|
|
18
18
|
# Staging directory the coverage publish step assembles (CI only)
|
|
19
19
|
coverage-upload/
|
|
20
|
-
# Shared coverage tooling, fetched on demand by `make coverage`
|
|
21
|
-
.coverage-report.py
|
|
22
20
|
|
|
23
21
|
# Editor and OS
|
|
24
22
|
.idea/
|
|
@@ -28,3 +26,7 @@ coverage-upload/
|
|
|
28
26
|
|
|
29
27
|
# Claude Code local settings
|
|
30
28
|
.claude/settings.local.json
|
|
29
|
+
|
|
30
|
+
# npm package
|
|
31
|
+
node_modules/
|
|
32
|
+
js/coverage/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: jigkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.0
|
|
4
4
|
Summary: The shared foundations of small self-hosted web apps: settings, database, migrations, logging, health checks and test fixtures
|
|
5
5
|
Project-URL: Homepage, https://github.com/jmerhar/jigkit
|
|
6
6
|
Project-URL: Changelog, https://github.com/jmerhar/jigkit/blob/main/CHANGELOG.md
|
|
@@ -40,12 +40,16 @@ Requires-Dist: ruff>=0.16; extra == 'dev'
|
|
|
40
40
|
Requires-Dist: sqlalchemy[asyncio]>=2.0.52; extra == 'dev'
|
|
41
41
|
Requires-Dist: twine>=6.2; extra == 'dev'
|
|
42
42
|
Requires-Dist: uvicorn[standard]>=0.30; extra == 'dev'
|
|
43
|
+
Requires-Dist: webauthn<4,>=3.0; extra == 'dev'
|
|
43
44
|
Provides-Extra: heartbeat
|
|
44
45
|
Requires-Dist: httpx2>=2.13; extra == 'heartbeat'
|
|
45
46
|
Provides-Extra: influx
|
|
46
47
|
Requires-Dist: httpx2>=2.13; extra == 'influx'
|
|
47
48
|
Provides-Extra: notify
|
|
48
49
|
Requires-Dist: apprise>=1.9; extra == 'notify'
|
|
50
|
+
Provides-Extra: passkeys
|
|
51
|
+
Requires-Dist: argon2-cffi>=25.1; extra == 'passkeys'
|
|
52
|
+
Requires-Dist: webauthn<4,>=3.0; extra == 'passkeys'
|
|
49
53
|
Provides-Extra: postgres
|
|
50
54
|
Requires-Dist: aiosqlite>=0.22; extra == 'postgres'
|
|
51
55
|
Requires-Dist: alembic>=1.19; extra == 'postgres'
|
|
@@ -82,13 +86,14 @@ pip install "jigkit[db]"
|
|
|
82
86
|
| `jigkit.spool`, `jigkit.delivery` | — | a bounded on-disk queue per destination, and write-now-or-spool-and-replay |
|
|
83
87
|
| `jigkit.influx` | `influx` | InfluxDB 3 and 2.x sinks: line protocol in each batch's precision, and SQL reads from InfluxDB 3 |
|
|
84
88
|
| `jigkit.heartbeat` | `heartbeat` | a push-monitor heartbeat after delivered writes, at most once per interval |
|
|
85
|
-
| `jigkit.web` | `web` | FastAPI building blocks: write guard, security headers, SPA serving, health router, PWA manifest, `serve()` |
|
|
89
|
+
| `jigkit.web` | `web` | FastAPI building blocks: a fail-closed access policy, write guard, security headers, SPA serving, health router, PWA manifest, `serve()` |
|
|
86
90
|
| `jigkit.scheduler` | — | `TickLoop`: in-process work on a fixed tick |
|
|
87
91
|
| `jigkit.notify` | `notify` | Apprise delivery off the event loop, and URL redaction for logs |
|
|
88
92
|
| `jigkit.ratelimit` | — | `RateLimiter`: a token bucket per client with bounded memory |
|
|
89
93
|
| `jigkit.auth` | `auth` | Argon2id passwords, a bounded failed-login throttle, the session cookie |
|
|
90
94
|
| `jigkit.auth.sessions` | `auth`, `db` | logins in the database as hashed, revocable tokens with a sliding expiry |
|
|
91
|
-
| `jigkit.
|
|
95
|
+
| `jigkit.auth.passkeys` | `passkeys`, `db` | WebAuthn ceremonies to add a passkey and log in with one, a bounded in-memory challenge store, `PasskeyMixin` |
|
|
96
|
+
| `jigkit.testing` | `testing` | a pytest plugin (`data_dir`, `no_network`), migration checks run through the application's own `env.py`, a recording stand-in HTTP server, and a software passkey authenticator (with `passkeys`) |
|
|
92
97
|
|
|
93
98
|
PostgreSQL is supported through the `postgres` extra. Python 3.14 or newer.
|
|
94
99
|
|
|
@@ -21,13 +21,14 @@ pip install "jigkit[db]"
|
|
|
21
21
|
| `jigkit.spool`, `jigkit.delivery` | — | a bounded on-disk queue per destination, and write-now-or-spool-and-replay |
|
|
22
22
|
| `jigkit.influx` | `influx` | InfluxDB 3 and 2.x sinks: line protocol in each batch's precision, and SQL reads from InfluxDB 3 |
|
|
23
23
|
| `jigkit.heartbeat` | `heartbeat` | a push-monitor heartbeat after delivered writes, at most once per interval |
|
|
24
|
-
| `jigkit.web` | `web` | FastAPI building blocks: write guard, security headers, SPA serving, health router, PWA manifest, `serve()` |
|
|
24
|
+
| `jigkit.web` | `web` | FastAPI building blocks: a fail-closed access policy, write guard, security headers, SPA serving, health router, PWA manifest, `serve()` |
|
|
25
25
|
| `jigkit.scheduler` | — | `TickLoop`: in-process work on a fixed tick |
|
|
26
26
|
| `jigkit.notify` | `notify` | Apprise delivery off the event loop, and URL redaction for logs |
|
|
27
27
|
| `jigkit.ratelimit` | — | `RateLimiter`: a token bucket per client with bounded memory |
|
|
28
28
|
| `jigkit.auth` | `auth` | Argon2id passwords, a bounded failed-login throttle, the session cookie |
|
|
29
29
|
| `jigkit.auth.sessions` | `auth`, `db` | logins in the database as hashed, revocable tokens with a sliding expiry |
|
|
30
|
-
| `jigkit.
|
|
30
|
+
| `jigkit.auth.passkeys` | `passkeys`, `db` | WebAuthn ceremonies to add a passkey and log in with one, a bounded in-memory challenge store, `PasskeyMixin` |
|
|
31
|
+
| `jigkit.testing` | `testing` | a pytest plugin (`data_dir`, `no_network`), migration checks run through the application's own `env.py`, a recording stand-in HTTP server, and a software passkey authenticator (with `passkeys`) |
|
|
31
32
|
|
|
32
33
|
PostgreSQL is supported through the `postgres` extra. Python 3.14 or newer.
|
|
33
34
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "jigkit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.8.0"
|
|
8
8
|
description = "The shared foundations of small self-hosted web apps: settings, database, migrations, logging, health checks and test fixtures"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.14"
|
|
@@ -57,11 +57,16 @@ web = [
|
|
|
57
57
|
notify = [
|
|
58
58
|
"apprise>=1.9",
|
|
59
59
|
]
|
|
60
|
-
# Logging people in: password hashes, the login throttle
|
|
60
|
+
# Logging people in: password hashes, the login throttle and the session cookie. Database
|
|
61
61
|
# sessions (jigkit.auth.sessions) also need `db`.
|
|
62
62
|
auth = [
|
|
63
63
|
"argon2-cffi>=25.1",
|
|
64
64
|
]
|
|
65
|
+
# Passkeys (jigkit.auth.passkeys), on top of `auth`; their table also needs `db`.
|
|
66
|
+
passkeys = [
|
|
67
|
+
"jigkit[auth]",
|
|
68
|
+
"webauthn>=3.0,<4",
|
|
69
|
+
]
|
|
65
70
|
# The pytest plugin: fixtures and migration checks for applications built on jigkit.
|
|
66
71
|
testing = [
|
|
67
72
|
"pytest>=9.1",
|
|
@@ -69,7 +74,7 @@ testing = [
|
|
|
69
74
|
]
|
|
70
75
|
# Everything this repository's own checks need.
|
|
71
76
|
dev = [
|
|
72
|
-
"jigkit[auth,db,heartbeat,influx,notify,testing,web]",
|
|
77
|
+
"jigkit[auth,db,heartbeat,influx,notify,passkeys,testing,web]",
|
|
73
78
|
"httpx>=0.28",
|
|
74
79
|
"pytest-cov>=7.1",
|
|
75
80
|
"ruff>=0.16",
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Logging people in (extra ``auth``): passwords, the login throttle and the session cookie.
|
|
2
2
|
|
|
3
|
-
Database sessions are in :mod:`jigkit.auth.sessions`, which also needs the ``db`` extra
|
|
3
|
+
Database sessions are in :mod:`jigkit.auth.sessions`, which also needs the ``db`` extra, and
|
|
4
|
+
passkeys in :mod:`jigkit.auth.passkeys`, which needs the ``passkeys`` and ``db`` extras.
|
|
4
5
|
"""
|
|
5
6
|
|
|
6
7
|
from jigkit.auth.cookies import clear_session_cookie, cookie_secure, issue_session_cookie
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Passkeys (extras ``passkeys`` and ``db``): adding one to an account, and logging in with one.
|
|
2
|
+
|
|
3
|
+
A WebAuthn ceremony is two requests. The server hands out options carrying a fresh challenge;
|
|
4
|
+
the browser passes them to an authenticator and comes back with its answer. Between the two, the
|
|
5
|
+
challenge waits in :class:`Ceremonies`, in memory, under a random key the browser holds in a
|
|
6
|
+
short-lived cookie (:func:`hold_ceremony`). The functions here wrap the ``webauthn`` library so
|
|
7
|
+
that an application's routes deal only in JSON, bytes and :class:`PasskeyRejected`::
|
|
8
|
+
|
|
9
|
+
class Passkey(PasskeyMixin, Base):
|
|
10
|
+
__tablename__ = "passkey"
|
|
11
|
+
person_id: Mapped[int] = mapped_column(ForeignKey("person.id", ondelete="CASCADE"))
|
|
12
|
+
|
|
13
|
+
Registration: :func:`registration_options`, then :func:`verify_registration`, which returns the
|
|
14
|
+
:class:`NewPasskey` to store. Logging in: :func:`authentication_options`, then
|
|
15
|
+
:func:`parse_login` to learn which passkey answered, then :func:`verify_login` against it, which
|
|
16
|
+
returns the signature counter to store.
|
|
17
|
+
|
|
18
|
+
Passkeys are discoverable, so a login names nobody up front: the authenticator offers whichever
|
|
19
|
+
of its passkeys belong to the site, and the answer says which one it used.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import secrets
|
|
26
|
+
import time
|
|
27
|
+
from collections.abc import Callable, Iterable
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from datetime import datetime
|
|
30
|
+
from typing import TYPE_CHECKING, Any
|
|
31
|
+
from urllib.parse import urlsplit
|
|
32
|
+
|
|
33
|
+
from sqlalchemy import JSON, Integer, LargeBinary, String
|
|
34
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
35
|
+
from webauthn import (
|
|
36
|
+
generate_authentication_options,
|
|
37
|
+
generate_registration_options,
|
|
38
|
+
options_to_json,
|
|
39
|
+
verify_authentication_response,
|
|
40
|
+
verify_registration_response,
|
|
41
|
+
)
|
|
42
|
+
from webauthn.helpers import parse_authentication_credential_json
|
|
43
|
+
from webauthn.helpers.exceptions import WebAuthnException
|
|
44
|
+
from webauthn.helpers.structs import (
|
|
45
|
+
AuthenticationCredential,
|
|
46
|
+
AuthenticatorSelectionCriteria,
|
|
47
|
+
PublicKeyCredentialDescriptor,
|
|
48
|
+
ResidentKeyRequirement,
|
|
49
|
+
UserVerificationRequirement,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
from jigkit.auth.cookies import cookie_secure
|
|
53
|
+
from jigkit.models import UtcDateTime, utcnow
|
|
54
|
+
|
|
55
|
+
if TYPE_CHECKING:
|
|
56
|
+
from fastapi import Request, Response
|
|
57
|
+
|
|
58
|
+
#: How long a ceremony may take between its two requests.
|
|
59
|
+
CEREMONY_SECONDS = 300
|
|
60
|
+
#: The most ceremonies kept waiting at once; beyond it the oldest are forgotten, so requests
|
|
61
|
+
#: that start ceremonies and never finish them cannot grow the process without bound.
|
|
62
|
+
MAX_CEREMONIES = 10_000
|
|
63
|
+
#: The longest label a person can give a passkey.
|
|
64
|
+
LABEL_LENGTH = 100
|
|
65
|
+
|
|
66
|
+
#: What parsing and verifying raise for an answer that does not hold up: the library's own
|
|
67
|
+
#: failures, and malformed base64 in a field it decodes without wrapping the error.
|
|
68
|
+
_REJECTED = (WebAuthnException, ValueError)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class PasskeyRejected(Exception):
|
|
72
|
+
"""An authenticator's answer that is malformed or does not verify."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class Party:
|
|
77
|
+
"""Who passkeys belong to: the site's host name, and the origin answers must come from."""
|
|
78
|
+
|
|
79
|
+
rp_id: str
|
|
80
|
+
origin: str
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def relying_party(public_url: str | None, scheme: str, host: str) -> Party:
|
|
84
|
+
"""The relying party for a request: the configured public URL's, else the request's own.
|
|
85
|
+
|
|
86
|
+
A passkey is bound to the host name it was made for, so a deployment behind a proxy needs its
|
|
87
|
+
public URL set for passkeys made there to keep working. ``host`` is the request's Host
|
|
88
|
+
header, port included.
|
|
89
|
+
"""
|
|
90
|
+
if public_url:
|
|
91
|
+
parts = urlsplit(public_url)
|
|
92
|
+
return Party(rp_id=parts.hostname or "", origin=f"{parts.scheme}://{parts.netloc}")
|
|
93
|
+
return Party(rp_id=urlsplit(f"//{host}").hostname or "", origin=f"{scheme}://{host}")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def request_party(request: Request, public_url: str | None) -> Party:
|
|
97
|
+
""":func:`relying_party` for a FastAPI request."""
|
|
98
|
+
return relying_party(public_url, request.url.scheme, request.headers.get("host", ""))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Ceremony:
|
|
103
|
+
"""A challenge handed out, and whose ceremony it is: None for a login, which names nobody."""
|
|
104
|
+
|
|
105
|
+
challenge: bytes
|
|
106
|
+
owner_id: int | None
|
|
107
|
+
expires: float
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Ceremonies:
|
|
111
|
+
"""Challenges waiting for their answer. Each is used once; an expired one is forgotten.
|
|
112
|
+
|
|
113
|
+
Held in memory, so a ceremony in flight across a restart has to be started again, and an
|
|
114
|
+
application running several processes needs its ceremony requests to reach the same one.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
*,
|
|
120
|
+
lifetime_seconds: float = CEREMONY_SECONDS,
|
|
121
|
+
max_waiting: int = MAX_CEREMONIES,
|
|
122
|
+
clock: Callable[[], float] = time.monotonic,
|
|
123
|
+
) -> None:
|
|
124
|
+
self._lifetime = lifetime_seconds
|
|
125
|
+
self._max_waiting = max_waiting
|
|
126
|
+
self._clock = clock
|
|
127
|
+
self._waiting: dict[str, Ceremony] = {}
|
|
128
|
+
|
|
129
|
+
def __len__(self) -> int:
|
|
130
|
+
return len(self._waiting)
|
|
131
|
+
|
|
132
|
+
def start(self, challenge: bytes, owner_id: int | None) -> str:
|
|
133
|
+
"""Keep a challenge for its answer, and return the key the browser holds."""
|
|
134
|
+
self._forget_expired()
|
|
135
|
+
while len(self._waiting) >= self._max_waiting:
|
|
136
|
+
del self._waiting[next(iter(self._waiting))]
|
|
137
|
+
key = secrets.token_urlsafe(24)
|
|
138
|
+
self._waiting[key] = Ceremony(challenge, owner_id, self._clock() + self._lifetime)
|
|
139
|
+
return key
|
|
140
|
+
|
|
141
|
+
def finish(self, key: str | None) -> Ceremony | None:
|
|
142
|
+
"""The ceremony a key belongs to, if it is still waiting; it can be finished only once."""
|
|
143
|
+
self._forget_expired()
|
|
144
|
+
return self._waiting.pop(key, None) if key else None
|
|
145
|
+
|
|
146
|
+
def _forget_expired(self) -> None:
|
|
147
|
+
"""Drop every ceremony past its expiry; they are kept in the order they expire."""
|
|
148
|
+
now = self._clock()
|
|
149
|
+
while self._waiting:
|
|
150
|
+
key = next(iter(self._waiting))
|
|
151
|
+
if self._waiting[key].expires > now:
|
|
152
|
+
return
|
|
153
|
+
del self._waiting[key]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def hold_ceremony(
|
|
157
|
+
response: Response,
|
|
158
|
+
request: Request,
|
|
159
|
+
key: str,
|
|
160
|
+
*,
|
|
161
|
+
name: str,
|
|
162
|
+
path: str = "/",
|
|
163
|
+
max_age_seconds: int = CEREMONY_SECONDS,
|
|
164
|
+
secure: bool | None = None,
|
|
165
|
+
) -> None:
|
|
166
|
+
"""Give the browser a ceremony's key, for the request that finishes it.
|
|
167
|
+
|
|
168
|
+
HttpOnly and SameSite=Strict: the ceremony is finished by the application's own page, so the
|
|
169
|
+
cookie never needs to travel with a request from anywhere else. ``path`` can narrow it to the
|
|
170
|
+
routes that finish ceremonies.
|
|
171
|
+
"""
|
|
172
|
+
response.set_cookie(
|
|
173
|
+
name,
|
|
174
|
+
key,
|
|
175
|
+
max_age=max_age_seconds,
|
|
176
|
+
httponly=True,
|
|
177
|
+
samesite="strict",
|
|
178
|
+
secure=cookie_secure(request, secure),
|
|
179
|
+
path=path,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def clear_ceremony(response: Response, *, name: str, path: str = "/") -> None:
|
|
184
|
+
"""Remove a finished ceremony's key from the browser."""
|
|
185
|
+
response.delete_cookie(name, path=path, httponly=True, samesite="strict")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class PasskeyMixin:
|
|
189
|
+
"""The columns of a passkey table; the application adds the owner's foreign key."""
|
|
190
|
+
|
|
191
|
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
192
|
+
credential_id: Mapped[bytes] = mapped_column(LargeBinary(1024), unique=True)
|
|
193
|
+
public_key: Mapped[bytes] = mapped_column(LargeBinary(2048))
|
|
194
|
+
#: The authenticator's signature counter; one that goes backwards betrays a cloned key.
|
|
195
|
+
sign_count: Mapped[int] = mapped_column(Integer, default=0)
|
|
196
|
+
transports: Mapped[list[str]] = mapped_column(JSON, default=list)
|
|
197
|
+
label: Mapped[str] = mapped_column(String(LABEL_LENGTH))
|
|
198
|
+
created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=utcnow)
|
|
199
|
+
last_used_at: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@dataclass(frozen=True)
|
|
203
|
+
class Options:
|
|
204
|
+
"""What a ceremony's first request returns: the options as the browser's API takes them, and
|
|
205
|
+
the challenge in them, for :class:`Ceremonies` to keep."""
|
|
206
|
+
|
|
207
|
+
public_key: dict[str, Any]
|
|
208
|
+
challenge: bytes
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@dataclass(frozen=True)
|
|
212
|
+
class NewPasskey:
|
|
213
|
+
"""A verified passkey, ready to store."""
|
|
214
|
+
|
|
215
|
+
credential_id: bytes
|
|
216
|
+
public_key: bytes
|
|
217
|
+
sign_count: int
|
|
218
|
+
transports: list[str]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class LoginAnswer:
|
|
223
|
+
"""An authenticator's answer to a login, parsed but not yet verified."""
|
|
224
|
+
|
|
225
|
+
#: Which passkey answered, to look up in the passkey table.
|
|
226
|
+
credential_id: bytes
|
|
227
|
+
#: The account handle the passkey was made for, when the authenticator gives it; it must
|
|
228
|
+
#: match the handle of the account the credential is stored under.
|
|
229
|
+
user_handle: bytes | None
|
|
230
|
+
credential: AuthenticationCredential
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def new_user_handle() -> bytes:
|
|
234
|
+
"""A random account handle for passkeys to carry, in place of anything that identifies the
|
|
235
|
+
person: an authenticator may show it, and it outlives a change of login name."""
|
|
236
|
+
return secrets.token_bytes(32)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def registration_options(
|
|
240
|
+
party: Party,
|
|
241
|
+
*,
|
|
242
|
+
rp_name: str,
|
|
243
|
+
user_handle: bytes,
|
|
244
|
+
user_name: str,
|
|
245
|
+
display_name: str,
|
|
246
|
+
exclude: Iterable[bytes] = (),
|
|
247
|
+
) -> Options:
|
|
248
|
+
"""Start adding a passkey: the options a browser hands its authenticator.
|
|
249
|
+
|
|
250
|
+
The passkey is discoverable, so it can log in without a login name typed first, and the
|
|
251
|
+
authenticator is told which credentials (``exclude``) the account already holds, so it does
|
|
252
|
+
not make a second passkey where it has one. ``rp_name`` is what the site is called on the
|
|
253
|
+
person's device.
|
|
254
|
+
"""
|
|
255
|
+
options = generate_registration_options(
|
|
256
|
+
rp_id=party.rp_id,
|
|
257
|
+
rp_name=rp_name,
|
|
258
|
+
user_id=user_handle,
|
|
259
|
+
user_name=user_name,
|
|
260
|
+
user_display_name=display_name,
|
|
261
|
+
authenticator_selection=AuthenticatorSelectionCriteria(
|
|
262
|
+
resident_key=ResidentKeyRequirement.REQUIRED,
|
|
263
|
+
user_verification=UserVerificationRequirement.PREFERRED,
|
|
264
|
+
),
|
|
265
|
+
exclude_credentials=[PublicKeyCredentialDescriptor(id=c) for c in exclude],
|
|
266
|
+
)
|
|
267
|
+
return Options(json.loads(options_to_json(options)), options.challenge)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def verify_registration(party: Party, credential: dict[str, Any], challenge: bytes) -> NewPasskey:
|
|
271
|
+
"""Finish adding a passkey: check the authenticator's answer to ``challenge``.
|
|
272
|
+
|
|
273
|
+
``credential`` is the browser's JSON for the new credential. Raises :class:`PasskeyRejected`
|
|
274
|
+
if it is malformed, answers another challenge, or comes from another origin.
|
|
275
|
+
"""
|
|
276
|
+
try:
|
|
277
|
+
verified = verify_registration_response(
|
|
278
|
+
credential=credential,
|
|
279
|
+
expected_challenge=challenge,
|
|
280
|
+
expected_rp_id=party.rp_id,
|
|
281
|
+
expected_origin=party.origin,
|
|
282
|
+
)
|
|
283
|
+
except _REJECTED as error:
|
|
284
|
+
raise PasskeyRejected(str(error)) from error
|
|
285
|
+
response = credential.get("response")
|
|
286
|
+
transports = response.get("transports") if isinstance(response, dict) else None
|
|
287
|
+
return NewPasskey(
|
|
288
|
+
credential_id=verified.credential_id,
|
|
289
|
+
public_key=verified.credential_public_key,
|
|
290
|
+
sign_count=verified.sign_count,
|
|
291
|
+
transports=[t for t in transports or [] if isinstance(t, str)],
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def authentication_options(party: Party) -> Options:
|
|
296
|
+
"""Start logging in with a passkey. Names nobody: the authenticator offers whichever of its
|
|
297
|
+
passkeys belong to this site."""
|
|
298
|
+
options = generate_authentication_options(
|
|
299
|
+
rp_id=party.rp_id, user_verification=UserVerificationRequirement.PREFERRED
|
|
300
|
+
)
|
|
301
|
+
return Options(json.loads(options_to_json(options)), options.challenge)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def parse_login(credential: dict[str, Any]) -> LoginAnswer:
|
|
305
|
+
"""Read which passkey answered a login, before looking it up to verify the answer.
|
|
306
|
+
|
|
307
|
+
Raises :class:`PasskeyRejected` if the answer is malformed.
|
|
308
|
+
"""
|
|
309
|
+
try:
|
|
310
|
+
parsed = parse_authentication_credential_json(credential)
|
|
311
|
+
except _REJECTED as error:
|
|
312
|
+
raise PasskeyRejected(str(error)) from error
|
|
313
|
+
return LoginAnswer(parsed.raw_id, parsed.response.user_handle or None, parsed)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def verify_login(
|
|
317
|
+
party: Party, answer: LoginAnswer, challenge: bytes, *, public_key: bytes, sign_count: int
|
|
318
|
+
) -> int:
|
|
319
|
+
"""Check a login answer against the stored passkey, and return its new signature counter.
|
|
320
|
+
|
|
321
|
+
Raises :class:`PasskeyRejected` if the signature does not verify, answers another challenge,
|
|
322
|
+
comes from another origin, or carries a counter that has not moved past ``sign_count``, the
|
|
323
|
+
mark of a cloned key. An authenticator that keeps no counter sends zero every time, which
|
|
324
|
+
passes.
|
|
325
|
+
"""
|
|
326
|
+
try:
|
|
327
|
+
verified = verify_authentication_response(
|
|
328
|
+
credential=answer.credential,
|
|
329
|
+
expected_challenge=challenge,
|
|
330
|
+
expected_rp_id=party.rp_id,
|
|
331
|
+
expected_origin=party.origin,
|
|
332
|
+
credential_public_key=public_key,
|
|
333
|
+
credential_current_sign_count=sign_count,
|
|
334
|
+
)
|
|
335
|
+
except _REJECTED as error:
|
|
336
|
+
raise PasskeyRejected(str(error)) from error
|
|
337
|
+
return verified.new_sign_count
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""A software authenticator, answering WebAuthn ceremonies as a phone or a security key would.
|
|
2
|
+
|
|
3
|
+
Needs the ``passkeys`` extra, whose ``webauthn`` brings ``cbor2`` and ``cryptography``. It makes
|
|
4
|
+
real ES256 key pairs and real CBOR, so the server's verification runs exactly as it does for a
|
|
5
|
+
device; only the person's touch is skipped::
|
|
6
|
+
|
|
7
|
+
authenticator = SoftAuthenticator(origin="http://myapp.test")
|
|
8
|
+
options = (await client.post("/api/auth/passkeys/options")).json()
|
|
9
|
+
await client.post("/api/auth/passkeys", json={"credential": authenticator.register(options)})
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import secrets
|
|
17
|
+
import struct
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import cbor2
|
|
22
|
+
from cryptography.hazmat.primitives import hashes
|
|
23
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
24
|
+
from webauthn.helpers import base64url_to_bytes, bytes_to_base64url
|
|
25
|
+
|
|
26
|
+
FLAG_USER_PRESENT = 0x01
|
|
27
|
+
FLAG_USER_VERIFIED = 0x04
|
|
28
|
+
FLAG_ATTESTED = 0x40
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Credential:
|
|
33
|
+
"""One passkey the authenticator holds."""
|
|
34
|
+
|
|
35
|
+
id: bytes
|
|
36
|
+
key: ec.EllipticCurvePrivateKey
|
|
37
|
+
rp_id: str
|
|
38
|
+
user_handle: bytes
|
|
39
|
+
sign_count: int = 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class SoftAuthenticator:
|
|
44
|
+
"""Holds passkeys and answers a server's options with them, from ``origin``."""
|
|
45
|
+
|
|
46
|
+
origin: str
|
|
47
|
+
credentials: list[Credential] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
def register(
|
|
50
|
+
self,
|
|
51
|
+
options: dict[str, Any],
|
|
52
|
+
*,
|
|
53
|
+
origin: str | None = None,
|
|
54
|
+
credential: Credential | None = None,
|
|
55
|
+
) -> dict[str, Any]:
|
|
56
|
+
"""Make a passkey for the options' site and user, and return the browser's JSON for it.
|
|
57
|
+
|
|
58
|
+
With ``credential``, offer that existing passkey again instead; with ``origin``, answer
|
|
59
|
+
as if from another site.
|
|
60
|
+
"""
|
|
61
|
+
rp_id = options["rp"]["id"]
|
|
62
|
+
if credential is None:
|
|
63
|
+
credential = Credential(
|
|
64
|
+
secrets.token_bytes(32),
|
|
65
|
+
ec.generate_private_key(ec.SECP256R1()),
|
|
66
|
+
rp_id,
|
|
67
|
+
base64url_to_bytes(options["user"]["id"]),
|
|
68
|
+
)
|
|
69
|
+
self.credentials.append(credential)
|
|
70
|
+
numbers = credential.key.public_key().public_numbers()
|
|
71
|
+
cose_key = cbor2.dumps(
|
|
72
|
+
{
|
|
73
|
+
1: 2, # key type: EC2
|
|
74
|
+
3: -7, # algorithm: ES256
|
|
75
|
+
-1: 1, # curve: P-256
|
|
76
|
+
-2: numbers.x.to_bytes(32, "big"),
|
|
77
|
+
-3: numbers.y.to_bytes(32, "big"),
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
auth_data = (
|
|
81
|
+
hashlib.sha256(rp_id.encode()).digest()
|
|
82
|
+
+ bytes([FLAG_USER_PRESENT | FLAG_USER_VERIFIED | FLAG_ATTESTED])
|
|
83
|
+
+ struct.pack(">I", 0)
|
|
84
|
+
+ bytes(16) # AAGUID: none
|
|
85
|
+
+ struct.pack(">H", len(credential.id))
|
|
86
|
+
+ credential.id
|
|
87
|
+
+ cose_key
|
|
88
|
+
)
|
|
89
|
+
attestation = cbor2.dumps({"fmt": "none", "attStmt": {}, "authData": auth_data})
|
|
90
|
+
client_data = self._client_data("webauthn.create", options["challenge"], origin)
|
|
91
|
+
return {
|
|
92
|
+
"id": bytes_to_base64url(credential.id),
|
|
93
|
+
"rawId": bytes_to_base64url(credential.id),
|
|
94
|
+
"type": "public-key",
|
|
95
|
+
"response": {
|
|
96
|
+
"clientDataJSON": bytes_to_base64url(client_data),
|
|
97
|
+
"attestationObject": bytes_to_base64url(attestation),
|
|
98
|
+
"transports": ["internal", "hybrid"],
|
|
99
|
+
},
|
|
100
|
+
"clientExtensionResults": {},
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
def authenticate(
|
|
104
|
+
self,
|
|
105
|
+
options: dict[str, Any],
|
|
106
|
+
*,
|
|
107
|
+
credential: Credential | None = None,
|
|
108
|
+
origin: str | None = None,
|
|
109
|
+
) -> dict[str, Any]:
|
|
110
|
+
"""Sign the options' challenge with a passkey for its site, and return the browser's JSON.
|
|
111
|
+
|
|
112
|
+
Uses the first passkey held for the site unless ``credential`` names one; each signature
|
|
113
|
+
moves that passkey's counter on by one.
|
|
114
|
+
"""
|
|
115
|
+
if credential is None:
|
|
116
|
+
credential = next(c for c in self.credentials if c.rp_id == options["rpId"])
|
|
117
|
+
credential.sign_count += 1
|
|
118
|
+
auth_data = (
|
|
119
|
+
hashlib.sha256(credential.rp_id.encode()).digest()
|
|
120
|
+
+ bytes([FLAG_USER_PRESENT | FLAG_USER_VERIFIED])
|
|
121
|
+
+ struct.pack(">I", credential.sign_count)
|
|
122
|
+
)
|
|
123
|
+
client_data = self._client_data("webauthn.get", options["challenge"], origin)
|
|
124
|
+
signature = credential.key.sign(
|
|
125
|
+
auth_data + hashlib.sha256(client_data).digest(), ec.ECDSA(hashes.SHA256())
|
|
126
|
+
)
|
|
127
|
+
return {
|
|
128
|
+
"id": bytes_to_base64url(credential.id),
|
|
129
|
+
"rawId": bytes_to_base64url(credential.id),
|
|
130
|
+
"type": "public-key",
|
|
131
|
+
"response": {
|
|
132
|
+
"clientDataJSON": bytes_to_base64url(client_data),
|
|
133
|
+
"authenticatorData": bytes_to_base64url(auth_data),
|
|
134
|
+
"signature": bytes_to_base64url(signature),
|
|
135
|
+
"userHandle": bytes_to_base64url(credential.user_handle),
|
|
136
|
+
},
|
|
137
|
+
"clientExtensionResults": {},
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
def _client_data(self, kind: str, challenge: str, origin: str | None) -> bytes:
|
|
141
|
+
"""The client data a browser signs over: the ceremony, its challenge and the origin."""
|
|
142
|
+
return json.dumps(
|
|
143
|
+
{
|
|
144
|
+
"type": kind,
|
|
145
|
+
"challenge": challenge,
|
|
146
|
+
"origin": origin or self.origin,
|
|
147
|
+
"crossOrigin": False,
|
|
148
|
+
}
|
|
149
|
+
).encode()
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
Each is applied to an application the app builds itself, so an application keeps its own
|
|
4
4
|
factory and lifespan and takes only the pieces it wants:
|
|
5
5
|
|
|
6
|
+
- :class:`AccessPolicy`: every API route needs a credential unless it is declared open;
|
|
6
7
|
- :func:`install_write_guard`: writes under the API only from the application's own pages;
|
|
7
8
|
- :func:`install_security_headers`: nosniff, a same-origin referrer, no framing;
|
|
8
9
|
- :func:`mount_spa`: the built single-page app, with its client-side routes and cache headers;
|
|
@@ -11,6 +12,7 @@ factory and lifespan and takes only the pieces it wants:
|
|
|
11
12
|
- :func:`serve`: uvicorn, believing forwarded headers only from the configured proxies.
|
|
12
13
|
"""
|
|
13
14
|
|
|
15
|
+
from jigkit.web.access import AccessPolicy, Route, route_templates
|
|
14
16
|
from jigkit.web.guard import (
|
|
15
17
|
WRITE_HEADER,
|
|
16
18
|
WRITES,
|
|
@@ -27,7 +29,9 @@ __all__ = [
|
|
|
27
29
|
"IMMUTABLE",
|
|
28
30
|
"WRITES",
|
|
29
31
|
"WRITE_HEADER",
|
|
32
|
+
"AccessPolicy",
|
|
30
33
|
"Health",
|
|
34
|
+
"Route",
|
|
31
35
|
"health_router",
|
|
32
36
|
"install_security_headers",
|
|
33
37
|
"install_write_guard",
|
|
@@ -35,6 +39,7 @@ __all__ = [
|
|
|
35
39
|
"mount_spa",
|
|
36
40
|
"origin_allowed",
|
|
37
41
|
"preferred_language",
|
|
42
|
+
"route_templates",
|
|
38
43
|
"serve",
|
|
39
44
|
"web_manifest",
|
|
40
45
|
]
|