jigkit 0.4.0__tar.gz → 0.5.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.4.0 → jigkit-0.5.0}/PKG-INFO +6 -1
- {jigkit-0.4.0 → jigkit-0.5.0}/README.md +2 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/pyproject.toml +7 -2
- jigkit-0.5.0/src/jigkit/auth/__init__.py +30 -0
- jigkit-0.5.0/src/jigkit/auth/cookies.py +55 -0
- jigkit-0.5.0/src/jigkit/auth/passwords.py +48 -0
- jigkit-0.5.0/src/jigkit/auth/sessions.py +118 -0
- jigkit-0.5.0/src/jigkit/auth/setup.py +34 -0
- jigkit-0.5.0/src/jigkit/auth/throttle.py +70 -0
- jigkit-0.5.0/tests/test_auth.py +327 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/.gitignore +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/LICENSE +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/__init__.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/db.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/delivery.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/healthcheck.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/heartbeat.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/influx/__init__.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/influx/lineprotocol.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/influx/sink.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/logging.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/migrations.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/models.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/notify.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/py.typed +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/ratelimit.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/scheduler.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/secrets.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/settings.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/sinks.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/spool.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/testing/__init__.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/testing/http.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/testing/migrations.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/testing/notify.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/web/__init__.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/web/guard.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/web/health.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/web/manifest.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/web/server.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/src/jigkit/web/spa.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/conftest.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/sample_app/alembic/env.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/sample_app/alembic/script.py.mako +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/sample_app/alembic/versions/0001_initial.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/sample_app/alembic.ini +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/sample_app/sample_schema.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_db.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_delivery.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_healthcheck.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_heartbeat.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_influx_lineprotocol.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_influx_read.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_influx_sink.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_logging.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_migrations.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_models.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_notify.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_ratelimit.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_scheduler.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_secrets.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_settings.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_sinks.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_spool.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_testing_plugin.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_version.py +0 -0
- {jigkit-0.4.0 → jigkit-0.5.0}/tests/test_web.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: jigkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.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
|
|
@@ -18,6 +18,8 @@ Requires-Python: >=3.14
|
|
|
18
18
|
Requires-Dist: pydantic-settings>=2.15
|
|
19
19
|
Requires-Dist: pydantic>=2.13
|
|
20
20
|
Requires-Dist: tzdata>=2026.5
|
|
21
|
+
Provides-Extra: auth
|
|
22
|
+
Requires-Dist: argon2-cffi>=25.1; extra == 'auth'
|
|
21
23
|
Provides-Extra: db
|
|
22
24
|
Requires-Dist: aiosqlite>=0.22; extra == 'db'
|
|
23
25
|
Requires-Dist: alembic>=1.19; extra == 'db'
|
|
@@ -26,6 +28,7 @@ Provides-Extra: dev
|
|
|
26
28
|
Requires-Dist: aiosqlite>=0.22; extra == 'dev'
|
|
27
29
|
Requires-Dist: alembic>=1.19; extra == 'dev'
|
|
28
30
|
Requires-Dist: apprise>=1.9; extra == 'dev'
|
|
31
|
+
Requires-Dist: argon2-cffi>=25.1; extra == 'dev'
|
|
29
32
|
Requires-Dist: build>=1.3; extra == 'dev'
|
|
30
33
|
Requires-Dist: fastapi<0.144,>=0.141; extra == 'dev'
|
|
31
34
|
Requires-Dist: httpx2>=2.13; extra == 'dev'
|
|
@@ -83,6 +86,8 @@ pip install "jigkit[db]"
|
|
|
83
86
|
| `jigkit.scheduler` | — | `TickLoop`: in-process work on a fixed tick |
|
|
84
87
|
| `jigkit.notify` | `notify` | Apprise delivery off the event loop, and URL redaction for logs |
|
|
85
88
|
| `jigkit.ratelimit` | — | `RateLimiter`: a token bucket per client with bounded memory |
|
|
89
|
+
| `jigkit.auth` | `auth` | Argon2id passwords, a bounded failed-login throttle, the first-run setup token, the session cookie |
|
|
90
|
+
| `jigkit.auth.sessions` | `auth`, `db` | logins in the database as hashed, revocable tokens with a sliding expiry |
|
|
86
91
|
| `jigkit.testing` | `testing` | a pytest plugin (`data_dir`, `no_network`), migration checks run through the application's own `env.py`, and a recording stand-in HTTP server |
|
|
87
92
|
|
|
88
93
|
PostgreSQL is supported through the `postgres` extra. Python 3.14 or newer.
|
|
@@ -25,6 +25,8 @@ pip install "jigkit[db]"
|
|
|
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
|
+
| `jigkit.auth` | `auth` | Argon2id passwords, a bounded failed-login throttle, the first-run setup token, the session cookie |
|
|
29
|
+
| `jigkit.auth.sessions` | `auth`, `db` | logins in the database as hashed, revocable tokens with a sliding expiry |
|
|
28
30
|
| `jigkit.testing` | `testing` | a pytest plugin (`data_dir`, `no_network`), migration checks run through the application's own `env.py`, and a recording stand-in HTTP server |
|
|
29
31
|
|
|
30
32
|
PostgreSQL is supported through the `postgres` extra. Python 3.14 or newer.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "jigkit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.5.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,6 +57,11 @@ web = [
|
|
|
57
57
|
notify = [
|
|
58
58
|
"apprise>=1.9",
|
|
59
59
|
]
|
|
60
|
+
# Logging people in: password hashes, the login throttle, cookies, first-run setup. Database
|
|
61
|
+
# sessions (jigkit.auth.sessions) also need `db`.
|
|
62
|
+
auth = [
|
|
63
|
+
"argon2-cffi>=25.1",
|
|
64
|
+
]
|
|
60
65
|
# The pytest plugin: fixtures and migration checks for applications built on jigkit.
|
|
61
66
|
testing = [
|
|
62
67
|
"pytest>=9.1",
|
|
@@ -64,7 +69,7 @@ testing = [
|
|
|
64
69
|
]
|
|
65
70
|
# Everything this repository's own checks need.
|
|
66
71
|
dev = [
|
|
67
|
-
"jigkit[db,heartbeat,influx,notify,testing,web]",
|
|
72
|
+
"jigkit[auth,db,heartbeat,influx,notify,testing,web]",
|
|
68
73
|
"httpx>=0.28",
|
|
69
74
|
"pytest-cov>=7.1",
|
|
70
75
|
"ruff>=0.16",
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Logging people in (extra ``auth``): passwords, the login throttle, cookies, first-run setup.
|
|
2
|
+
|
|
3
|
+
Database sessions are in :mod:`jigkit.auth.sessions`, which also needs the ``db`` extra.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from jigkit.auth.cookies import clear_session_cookie, cookie_secure, issue_session_cookie
|
|
7
|
+
from jigkit.auth.passwords import (
|
|
8
|
+
MIN_PASSWORD_LENGTH,
|
|
9
|
+
PasswordTooShort,
|
|
10
|
+
burn_password_check,
|
|
11
|
+
hash_password,
|
|
12
|
+
verify_password,
|
|
13
|
+
)
|
|
14
|
+
from jigkit.auth.setup import SETUP_TOKEN_DISABLED, resolve_setup_token, setup_token_matches
|
|
15
|
+
from jigkit.auth.throttle import LoginThrottle
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"MIN_PASSWORD_LENGTH",
|
|
19
|
+
"SETUP_TOKEN_DISABLED",
|
|
20
|
+
"LoginThrottle",
|
|
21
|
+
"PasswordTooShort",
|
|
22
|
+
"burn_password_check",
|
|
23
|
+
"clear_session_cookie",
|
|
24
|
+
"cookie_secure",
|
|
25
|
+
"hash_password",
|
|
26
|
+
"issue_session_cookie",
|
|
27
|
+
"resolve_setup_token",
|
|
28
|
+
"setup_token_matches",
|
|
29
|
+
"verify_password",
|
|
30
|
+
]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""The cookie a logged-in browser carries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from fastapi import Request, Response
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def cookie_secure(request: Request, override: bool | None) -> bool:
|
|
12
|
+
"""Whether the session cookie gets the Secure flag: as configured, else for HTTPS requests.
|
|
13
|
+
|
|
14
|
+
The scheme is the request's own, which uvicorn takes from X-Forwarded-Proto only when the
|
|
15
|
+
proxy is one it believes (``FORWARDED_ALLOW_IPS``); the header itself is never read here,
|
|
16
|
+
since any client can send it. Following the scheme lets an instance on a private network be
|
|
17
|
+
used over plain HTTP, where a Secure cookie would be dropped and login would look broken.
|
|
18
|
+
"""
|
|
19
|
+
if override is not None:
|
|
20
|
+
return override
|
|
21
|
+
return request.url.scheme == "https"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def issue_session_cookie(
|
|
25
|
+
response: Response,
|
|
26
|
+
request: Request,
|
|
27
|
+
*,
|
|
28
|
+
name: str,
|
|
29
|
+
token: str,
|
|
30
|
+
max_age_seconds: int,
|
|
31
|
+
secure: bool | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
"""Put a session token in the browser.
|
|
34
|
+
|
|
35
|
+
HttpOnly, so no script can read it; SameSite=Lax, so a page elsewhere cannot send it with a
|
|
36
|
+
write, while a link to the application from an email still arrives logged in.
|
|
37
|
+
"""
|
|
38
|
+
response.set_cookie(
|
|
39
|
+
name,
|
|
40
|
+
token,
|
|
41
|
+
max_age=max_age_seconds,
|
|
42
|
+
httponly=True,
|
|
43
|
+
samesite="lax",
|
|
44
|
+
secure=cookie_secure(request, secure),
|
|
45
|
+
path="/",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clear_session_cookie(
|
|
50
|
+
response: Response, request: Request, *, name: str, secure: bool | None = None
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Remove the session token from the browser."""
|
|
53
|
+
response.delete_cookie(
|
|
54
|
+
name, httponly=True, samesite="lax", secure=cookie_secure(request, secure), path="/"
|
|
55
|
+
)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Password hashes: Argon2id at the library's defaults, and a length floor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
|
|
7
|
+
from argon2 import PasswordHasher
|
|
8
|
+
from argon2.exceptions import Argon2Error, InvalidHashError
|
|
9
|
+
|
|
10
|
+
#: The shortest password :func:`hash_password` accepts unless told otherwise.
|
|
11
|
+
MIN_PASSWORD_LENGTH = 10
|
|
12
|
+
|
|
13
|
+
# The library's defaults are memory-hard, and move with the library rather than with a number
|
|
14
|
+
# pinned here that nobody revisits.
|
|
15
|
+
_hasher = PasswordHasher()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PasswordTooShort(ValueError):
|
|
19
|
+
"""A new password is shorter than the minimum."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def hash_password(password: str, *, min_length: int = MIN_PASSWORD_LENGTH) -> str:
|
|
23
|
+
"""An Argon2id hash of ``password``, which must be at least ``min_length`` characters.
|
|
24
|
+
|
|
25
|
+
A length floor is the one rule enforced in code: an application reachable from the internet
|
|
26
|
+
has a short password as its whole attack surface.
|
|
27
|
+
"""
|
|
28
|
+
if len(password) < min_length:
|
|
29
|
+
raise PasswordTooShort(f"a password needs at least {min_length} characters")
|
|
30
|
+
return _hasher.hash(password)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def verify_password(password_hash: str, password: str) -> bool:
|
|
34
|
+
"""Whether ``password`` matches the hash; a malformed hash simply does not match."""
|
|
35
|
+
try:
|
|
36
|
+
return _hasher.verify(password_hash, password)
|
|
37
|
+
except Argon2Error, InvalidHashError:
|
|
38
|
+
return False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
#: Verified against when a login names nobody, so an unknown login takes as long to refuse as a
|
|
42
|
+
#: wrong password and timing does not reveal which logins exist.
|
|
43
|
+
_DUMMY_HASH = _hasher.hash(secrets.token_urlsafe(16))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def burn_password_check(password: str) -> None:
|
|
47
|
+
"""Spend the time a real password check takes, for a login that names nobody."""
|
|
48
|
+
verify_password(_DUMMY_HASH, password)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Logins kept in the database (extras ``auth`` and ``db``): revocable, and only hashed.
|
|
2
|
+
|
|
3
|
+
An application declares its session table with :class:`SessionMixin` and its own owner column::
|
|
4
|
+
|
|
5
|
+
class Session(SessionMixin, Base):
|
|
6
|
+
__tablename__ = "session"
|
|
7
|
+
person_id: Mapped[int] = mapped_column(ForeignKey("person.id", ondelete="CASCADE"))
|
|
8
|
+
|
|
9
|
+
SESSIONS = SessionStore(Session, owner="person_id")
|
|
10
|
+
|
|
11
|
+
The browser keeps the token; the table keeps only its SHA-256, so a copy of the database cannot
|
|
12
|
+
be replayed as logins. Ending a session deletes its row, so logging out really ends it.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
import secrets
|
|
19
|
+
from datetime import datetime, timedelta
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from sqlalchemy import Integer, String, delete, select
|
|
23
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
24
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
25
|
+
|
|
26
|
+
from jigkit.models import UtcDateTime, utcnow
|
|
27
|
+
|
|
28
|
+
#: How long a login lasts without being used; each use extends it.
|
|
29
|
+
SESSION_LIFETIME = timedelta(days=90)
|
|
30
|
+
#: How stale a session's expiry may grow before a request writes a new one, so an active browser
|
|
31
|
+
#: does not cost a write on every request.
|
|
32
|
+
SESSION_REFRESH = timedelta(days=1)
|
|
33
|
+
#: The longest user agent kept, to tell a person's sessions apart.
|
|
34
|
+
USER_AGENT_LENGTH = 300
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def token_digest(token: str) -> str:
|
|
38
|
+
"""The SHA-256 a session token is stored as."""
|
|
39
|
+
return hashlib.sha256(token.encode()).hexdigest()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SessionMixin:
|
|
43
|
+
"""The columns of a session table; the application adds the owner's foreign key."""
|
|
44
|
+
|
|
45
|
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
46
|
+
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
|
|
47
|
+
created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=utcnow)
|
|
48
|
+
last_seen_at: Mapped[datetime] = mapped_column(UtcDateTime, default=utcnow)
|
|
49
|
+
expires_at: Mapped[datetime] = mapped_column(UtcDateTime)
|
|
50
|
+
user_agent: Mapped[str] = mapped_column(String(USER_AGENT_LENGTH), default="")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SessionStore:
|
|
54
|
+
"""Opens, finds and ends the sessions in one table.
|
|
55
|
+
|
|
56
|
+
``owner`` names the table's column holding who the session logs in.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
model: type[Any],
|
|
62
|
+
*,
|
|
63
|
+
owner: str,
|
|
64
|
+
lifetime: timedelta = SESSION_LIFETIME,
|
|
65
|
+
refresh: timedelta = SESSION_REFRESH,
|
|
66
|
+
) -> None:
|
|
67
|
+
self.model = model
|
|
68
|
+
self.owner = owner
|
|
69
|
+
self.lifetime = lifetime
|
|
70
|
+
self.refresh = refresh
|
|
71
|
+
|
|
72
|
+
async def open(self, db: AsyncSession, owner_id: int, user_agent: str = "") -> str:
|
|
73
|
+
"""Start a session for ``owner_id`` and return its token, which only the browser keeps."""
|
|
74
|
+
token = secrets.token_urlsafe(32)
|
|
75
|
+
now = utcnow()
|
|
76
|
+
db.add(
|
|
77
|
+
self.model(
|
|
78
|
+
token_hash=token_digest(token),
|
|
79
|
+
created_at=now,
|
|
80
|
+
last_seen_at=now,
|
|
81
|
+
expires_at=now + self.lifetime,
|
|
82
|
+
user_agent=user_agent[:USER_AGENT_LENGTH],
|
|
83
|
+
**{self.owner: owner_id},
|
|
84
|
+
)
|
|
85
|
+
)
|
|
86
|
+
await db.flush()
|
|
87
|
+
return token
|
|
88
|
+
|
|
89
|
+
async def find(self, db: AsyncSession, token: str, now: datetime | None = None) -> Any | None:
|
|
90
|
+
"""The live session ``token`` belongs to, its expiry extended once it is stale, or None."""
|
|
91
|
+
now = now or utcnow()
|
|
92
|
+
session = (
|
|
93
|
+
await db.execute(select(self.model).where(self.model.token_hash == token_digest(token)))
|
|
94
|
+
).scalar_one_or_none()
|
|
95
|
+
if session is None or session.expires_at <= now:
|
|
96
|
+
return None
|
|
97
|
+
if now - session.last_seen_at >= self.refresh:
|
|
98
|
+
session.last_seen_at = now
|
|
99
|
+
session.expires_at = now + self.lifetime
|
|
100
|
+
return session
|
|
101
|
+
|
|
102
|
+
async def end(self, db: AsyncSession, token: str) -> None:
|
|
103
|
+
"""End the session ``token`` belongs to, if there is one."""
|
|
104
|
+
await db.execute(delete(self.model).where(self.model.token_hash == token_digest(token)))
|
|
105
|
+
|
|
106
|
+
async def end_all(self, db: AsyncSession, owner_id: int, *, keep: int | None = None) -> None:
|
|
107
|
+
"""End every session of ``owner_id``, except the one with id ``keep`` when given."""
|
|
108
|
+
statement = delete(self.model).where(getattr(self.model, self.owner) == owner_id)
|
|
109
|
+
if keep is not None:
|
|
110
|
+
statement = statement.where(self.model.id != keep)
|
|
111
|
+
await db.execute(statement)
|
|
112
|
+
|
|
113
|
+
async def prune(self, db: AsyncSession, now: datetime | None = None) -> int:
|
|
114
|
+
"""Delete every expired session, and return how many there were."""
|
|
115
|
+
result = await db.execute(
|
|
116
|
+
delete(self.model).where(self.model.expires_at <= (now or utcnow()))
|
|
117
|
+
)
|
|
118
|
+
return result.rowcount or 0
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""First-run setup: the token that guards creating the first administrator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
import secrets
|
|
7
|
+
|
|
8
|
+
#: The value that turns the setup token off, for an instance nobody else can reach.
|
|
9
|
+
SETUP_TOKEN_DISABLED = "off"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def resolve_setup_token(configured: str | None) -> str | None:
|
|
13
|
+
"""The token the first-run setup will ask for, or None when it is switched off.
|
|
14
|
+
|
|
15
|
+
Generated when none is configured, so an instance reachable from the internet before anyone
|
|
16
|
+
has set it up cannot be claimed by whoever finds its address first. Log a generated token
|
|
17
|
+
where the operator will see it; it is needed once, and never after setup.
|
|
18
|
+
"""
|
|
19
|
+
if configured == SETUP_TOKEN_DISABLED:
|
|
20
|
+
return None
|
|
21
|
+
return configured or secrets.token_urlsafe(9)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def setup_token_matches(expected: str | None, given: str | None) -> bool:
|
|
25
|
+
"""Whether ``given`` is the setup token, compared in constant time.
|
|
26
|
+
|
|
27
|
+
With the token switched off (``expected`` None) anything matches. Compared as UTF-8 bytes, so
|
|
28
|
+
a token with non-ASCII characters is refused rather than raising.
|
|
29
|
+
"""
|
|
30
|
+
if expected is None:
|
|
31
|
+
return True
|
|
32
|
+
if given is None:
|
|
33
|
+
return False
|
|
34
|
+
return hmac.compare_digest(expected.encode(), given.encode())
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Slowing down a run of guessed passwords."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections import OrderedDict, deque
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
|
|
9
|
+
#: How far back failures count, in seconds.
|
|
10
|
+
WINDOW_SECONDS = 60.0
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class LoginThrottle:
|
|
14
|
+
"""Failed logins per client address in a sliding minute; past the limit, logins are refused.
|
|
15
|
+
|
|
16
|
+
Only failures count, so a person who logs in, out and in again is never refused; a success
|
|
17
|
+
forgets the address's failures. Addresses are kept in least-recently-used order and the
|
|
18
|
+
oldest is forgotten beyond ``max_clients``, so a run of logins from many addresses cannot grow
|
|
19
|
+
it without bound. In memory: a restart forgets it, which gives an attacker nothing waiting a
|
|
20
|
+
minute would not.
|
|
21
|
+
|
|
22
|
+
The address must be the client's own. Behind a reverse proxy that takes uvicorn believing the
|
|
23
|
+
proxy's X-Forwarded-For (``FORWARDED_ALLOW_IPS``); otherwise every client shares the proxy's
|
|
24
|
+
address, and one person's failures lock everyone out.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
per_minute: int,
|
|
30
|
+
*,
|
|
31
|
+
max_clients: int = 10_000,
|
|
32
|
+
clock: Callable[[], float] = time.monotonic,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.per_minute = per_minute
|
|
35
|
+
self.max_clients = max_clients
|
|
36
|
+
self._clock = clock
|
|
37
|
+
self._failures: OrderedDict[str, deque[float]] = OrderedDict()
|
|
38
|
+
|
|
39
|
+
def _recent(self, address: str) -> deque[float] | None:
|
|
40
|
+
"""The address's failures within the window, without adding the address."""
|
|
41
|
+
window = self._failures.get(address)
|
|
42
|
+
if window is None:
|
|
43
|
+
return None
|
|
44
|
+
cutoff = self._clock() - WINDOW_SECONDS
|
|
45
|
+
while window and window[0] <= cutoff:
|
|
46
|
+
window.popleft()
|
|
47
|
+
if not window:
|
|
48
|
+
del self._failures[address]
|
|
49
|
+
return None
|
|
50
|
+
return window
|
|
51
|
+
|
|
52
|
+
def blocked(self, address: str) -> bool:
|
|
53
|
+
"""Whether ``address`` has used up its failed attempts for now."""
|
|
54
|
+
window = self._recent(address)
|
|
55
|
+
return window is not None and len(window) >= self.per_minute
|
|
56
|
+
|
|
57
|
+
def failed(self, address: str) -> None:
|
|
58
|
+
"""Count a failed login from ``address``."""
|
|
59
|
+
window = self._recent(address)
|
|
60
|
+
if window is None:
|
|
61
|
+
window = self._failures[address] = deque()
|
|
62
|
+
else:
|
|
63
|
+
self._failures.move_to_end(address)
|
|
64
|
+
window.append(self._clock())
|
|
65
|
+
while len(self._failures) > self.max_clients:
|
|
66
|
+
self._failures.popitem(last=False)
|
|
67
|
+
|
|
68
|
+
def succeeded(self, address: str) -> None:
|
|
69
|
+
"""Forget ``address``'s failures after it logs in."""
|
|
70
|
+
self._failures.pop(address, None)
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Passwords, the login throttle, first-run setup, the session cookie and database sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from datetime import UTC, datetime, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
import pytest
|
|
11
|
+
from fastapi import FastAPI, Request, Response
|
|
12
|
+
from sqlalchemy import ForeignKey, String, func, select
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
14
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
15
|
+
|
|
16
|
+
from jigkit.auth import (
|
|
17
|
+
SETUP_TOKEN_DISABLED,
|
|
18
|
+
LoginThrottle,
|
|
19
|
+
PasswordTooShort,
|
|
20
|
+
burn_password_check,
|
|
21
|
+
clear_session_cookie,
|
|
22
|
+
cookie_secure,
|
|
23
|
+
hash_password,
|
|
24
|
+
issue_session_cookie,
|
|
25
|
+
resolve_setup_token,
|
|
26
|
+
setup_token_matches,
|
|
27
|
+
verify_password,
|
|
28
|
+
)
|
|
29
|
+
from jigkit.auth.sessions import SessionMixin, SessionStore, token_digest
|
|
30
|
+
from jigkit.db import create_engine, create_sessionmaker, session_scope
|
|
31
|
+
from jigkit.models import Base
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TestPasswords:
|
|
35
|
+
def test_a_password_verifies_against_its_own_hash_only(self) -> None:
|
|
36
|
+
stored = hash_password("correct horse battery")
|
|
37
|
+
|
|
38
|
+
assert stored.startswith("$argon2id$")
|
|
39
|
+
assert verify_password(stored, "correct horse battery")
|
|
40
|
+
assert not verify_password(stored, "correct horse battery!")
|
|
41
|
+
|
|
42
|
+
def test_a_short_password_is_refused(self) -> None:
|
|
43
|
+
with pytest.raises(PasswordTooShort, match="at least 10"):
|
|
44
|
+
hash_password("short")
|
|
45
|
+
assert hash_password("abcd", min_length=4)
|
|
46
|
+
|
|
47
|
+
def test_a_malformed_hash_simply_does_not_match(self) -> None:
|
|
48
|
+
assert not verify_password("not-a-hash", "anything at all")
|
|
49
|
+
|
|
50
|
+
def test_burning_a_check_for_nobody_returns_nothing(self) -> None:
|
|
51
|
+
assert burn_password_check("whatever was typed") is None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Clock:
|
|
55
|
+
"""A clock a test moves by hand."""
|
|
56
|
+
|
|
57
|
+
def __init__(self) -> None:
|
|
58
|
+
self.now = 0.0
|
|
59
|
+
|
|
60
|
+
def __call__(self) -> float:
|
|
61
|
+
return self.now
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TestLoginThrottle:
|
|
65
|
+
def test_failures_past_the_limit_block_the_address(self) -> None:
|
|
66
|
+
throttle = LoginThrottle(3, clock=Clock())
|
|
67
|
+
for _ in range(3):
|
|
68
|
+
assert not throttle.blocked("a")
|
|
69
|
+
throttle.failed("a")
|
|
70
|
+
|
|
71
|
+
assert throttle.blocked("a")
|
|
72
|
+
assert not throttle.blocked("b")
|
|
73
|
+
|
|
74
|
+
def test_failures_older_than_a_minute_no_longer_count(self) -> None:
|
|
75
|
+
clock = Clock()
|
|
76
|
+
throttle = LoginThrottle(2, clock=clock)
|
|
77
|
+
throttle.failed("a")
|
|
78
|
+
throttle.failed("a")
|
|
79
|
+
assert throttle.blocked("a")
|
|
80
|
+
|
|
81
|
+
clock.now = 60.0
|
|
82
|
+
|
|
83
|
+
assert not throttle.blocked("a")
|
|
84
|
+
|
|
85
|
+
def test_a_success_forgets_the_failures(self) -> None:
|
|
86
|
+
throttle = LoginThrottle(2, clock=Clock())
|
|
87
|
+
throttle.failed("a")
|
|
88
|
+
throttle.failed("a")
|
|
89
|
+
|
|
90
|
+
throttle.succeeded("a")
|
|
91
|
+
|
|
92
|
+
assert not throttle.blocked("a")
|
|
93
|
+
|
|
94
|
+
def test_asking_never_adds_an_address(self) -> None:
|
|
95
|
+
throttle = LoginThrottle(2, clock=Clock())
|
|
96
|
+
|
|
97
|
+
for i in range(100):
|
|
98
|
+
throttle.blocked(f"10.0.0.{i}")
|
|
99
|
+
|
|
100
|
+
assert len(throttle._failures) == 0
|
|
101
|
+
|
|
102
|
+
def test_the_oldest_addresses_are_forgotten_beyond_the_bound(self) -> None:
|
|
103
|
+
throttle = LoginThrottle(1, max_clients=2, clock=Clock())
|
|
104
|
+
throttle.failed("a")
|
|
105
|
+
throttle.failed("b")
|
|
106
|
+
throttle.failed("a")
|
|
107
|
+
throttle.failed("c")
|
|
108
|
+
|
|
109
|
+
assert list(throttle._failures) == ["a", "c"]
|
|
110
|
+
assert throttle.blocked("a")
|
|
111
|
+
assert not throttle.blocked("b")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class TestSetupToken:
|
|
115
|
+
def test_a_configured_token_is_used(self) -> None:
|
|
116
|
+
assert resolve_setup_token("let-me-in") == "let-me-in"
|
|
117
|
+
|
|
118
|
+
def test_one_is_generated_when_none_is_configured(self) -> None:
|
|
119
|
+
first, second = resolve_setup_token(None), resolve_setup_token("")
|
|
120
|
+
|
|
121
|
+
assert first and second and first != second
|
|
122
|
+
|
|
123
|
+
def test_it_can_be_switched_off(self) -> None:
|
|
124
|
+
assert resolve_setup_token(SETUP_TOKEN_DISABLED) is None
|
|
125
|
+
|
|
126
|
+
@pytest.mark.parametrize(
|
|
127
|
+
("expected", "given", "matches"),
|
|
128
|
+
[
|
|
129
|
+
("token", "token", True),
|
|
130
|
+
("token", "tokeN", False),
|
|
131
|
+
("token", None, False),
|
|
132
|
+
("token", "tökén", False),
|
|
133
|
+
(None, None, True),
|
|
134
|
+
(None, "anything", True),
|
|
135
|
+
],
|
|
136
|
+
)
|
|
137
|
+
def test_matching(self, expected: str | None, given: str | None, matches: bool) -> None:
|
|
138
|
+
assert setup_token_matches(expected, given) is matches
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def cookie_app() -> FastAPI:
|
|
142
|
+
"""An application that logs in and out with the session cookie."""
|
|
143
|
+
app = FastAPI()
|
|
144
|
+
|
|
145
|
+
@app.post("/login")
|
|
146
|
+
async def login(request: Request, response: Response, secure: str = "") -> dict[str, str]:
|
|
147
|
+
override = {"yes": True, "no": False}.get(secure)
|
|
148
|
+
issue_session_cookie(
|
|
149
|
+
response, request, name="sid", token="t0k", max_age_seconds=3600, secure=override
|
|
150
|
+
)
|
|
151
|
+
return {}
|
|
152
|
+
|
|
153
|
+
@app.post("/logout")
|
|
154
|
+
async def logout(request: Request, response: Response) -> dict[str, str]:
|
|
155
|
+
clear_session_cookie(response, request, name="sid")
|
|
156
|
+
return {}
|
|
157
|
+
|
|
158
|
+
return app
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def post(base_url: str, path: str) -> httpx.Response:
|
|
162
|
+
transport = httpx.ASGITransport(app=cookie_app())
|
|
163
|
+
async with httpx.AsyncClient(transport=transport, base_url=base_url) as client:
|
|
164
|
+
return await client.post(path)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class TestSessionCookie:
|
|
168
|
+
async def test_the_cookie_is_http_only_lax_and_lasts_its_lifetime(self) -> None:
|
|
169
|
+
cookie = (await post("http://app.test", "/login")).headers["set-cookie"]
|
|
170
|
+
|
|
171
|
+
assert cookie.startswith("sid=t0k;")
|
|
172
|
+
for part in ("HttpOnly", "Max-Age=3600", "Path=/", "SameSite=lax"):
|
|
173
|
+
assert part in cookie
|
|
174
|
+
assert "Secure" not in cookie
|
|
175
|
+
|
|
176
|
+
async def test_https_requests_get_a_secure_cookie(self) -> None:
|
|
177
|
+
assert "Secure" in (await post("https://app.test", "/login")).headers["set-cookie"]
|
|
178
|
+
|
|
179
|
+
@pytest.mark.parametrize(("flag", "secure"), [("yes", True), ("no", False)])
|
|
180
|
+
async def test_the_configured_flag_wins(self, flag: str, secure: bool) -> None:
|
|
181
|
+
base = "http://app.test" if secure else "https://app.test"
|
|
182
|
+
cookie = (await post(base, f"/login?secure={flag}")).headers["set-cookie"]
|
|
183
|
+
|
|
184
|
+
assert ("Secure" in cookie) is secure
|
|
185
|
+
|
|
186
|
+
async def test_a_forged_forwarded_proto_does_not_count(self) -> None:
|
|
187
|
+
# Only uvicorn, believing a trusted proxy, may turn the header into the request's scheme.
|
|
188
|
+
transport = httpx.ASGITransport(app=cookie_app())
|
|
189
|
+
async with httpx.AsyncClient(transport=transport, base_url="http://app.test") as client:
|
|
190
|
+
response = await client.post("/login", headers={"X-Forwarded-Proto": "https"})
|
|
191
|
+
|
|
192
|
+
assert "Secure" not in response.headers["set-cookie"]
|
|
193
|
+
|
|
194
|
+
async def test_logging_out_clears_the_cookie(self) -> None:
|
|
195
|
+
cookie = (await post("http://app.test", "/logout")).headers["set-cookie"]
|
|
196
|
+
|
|
197
|
+
assert cookie.startswith('sid="";') and "Max-Age=0" in cookie
|
|
198
|
+
|
|
199
|
+
def test_cookie_secure(self) -> None:
|
|
200
|
+
scope = {
|
|
201
|
+
"type": "http",
|
|
202
|
+
"scheme": "https",
|
|
203
|
+
"server": ("app.test", 443),
|
|
204
|
+
"headers": [],
|
|
205
|
+
"path": "/",
|
|
206
|
+
"query_string": b"",
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
assert cookie_secure(Request(scope), None) is True
|
|
210
|
+
assert cookie_secure(Request(scope), False) is False
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class Account(Base):
|
|
214
|
+
"""Whom the sessions in these tests log in."""
|
|
215
|
+
|
|
216
|
+
__tablename__ = "test_auth_accounts"
|
|
217
|
+
|
|
218
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
219
|
+
name: Mapped[str] = mapped_column(String(20))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class AccountSession(SessionMixin, Base):
|
|
223
|
+
"""The sessions table these tests use."""
|
|
224
|
+
|
|
225
|
+
__tablename__ = "test_auth_sessions"
|
|
226
|
+
|
|
227
|
+
account_id: Mapped[int] = mapped_column(ForeignKey("test_auth_accounts.id", ondelete="CASCADE"))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@pytest.fixture
|
|
231
|
+
async def engine(tmp_path: Path) -> AsyncIterator[AsyncEngine]:
|
|
232
|
+
engine = create_engine(f"sqlite+aiosqlite:///{tmp_path / 'auth.db'}")
|
|
233
|
+
async with engine.begin() as connection:
|
|
234
|
+
await connection.run_sync(
|
|
235
|
+
Base.metadata.create_all, tables=[Account.__table__, AccountSession.__table__]
|
|
236
|
+
)
|
|
237
|
+
await connection.execute(
|
|
238
|
+
Account.__table__.insert(), [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
|
|
239
|
+
)
|
|
240
|
+
yield engine
|
|
241
|
+
await engine.dispose()
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
STORE = SessionStore(AccountSession, owner="account_id")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class TestSessions:
|
|
248
|
+
async def test_a_session_opens_and_is_found_by_its_token(self, engine: AsyncEngine) -> None:
|
|
249
|
+
factory = create_sessionmaker(engine)
|
|
250
|
+
async with session_scope(factory) as db:
|
|
251
|
+
token = await STORE.open(db, 1, "Firefox " + "x" * 400)
|
|
252
|
+
async with session_scope(factory) as db:
|
|
253
|
+
found = await STORE.find(db, token)
|
|
254
|
+
|
|
255
|
+
assert found is not None and found.account_id == 1
|
|
256
|
+
assert found.token_hash == token_digest(token) != token
|
|
257
|
+
assert len(found.user_agent) == 300
|
|
258
|
+
assert found.expires_at - found.created_at == timedelta(days=90)
|
|
259
|
+
|
|
260
|
+
async def test_an_unknown_or_expired_token_finds_nothing(self, engine: AsyncEngine) -> None:
|
|
261
|
+
factory = create_sessionmaker(engine)
|
|
262
|
+
async with session_scope(factory) as db:
|
|
263
|
+
token = await STORE.open(db, 1)
|
|
264
|
+
later = datetime.now(UTC) + timedelta(days=91)
|
|
265
|
+
async with session_scope(factory) as db:
|
|
266
|
+
assert await STORE.find(db, "not-a-token") is None
|
|
267
|
+
assert await STORE.find(db, token, now=later) is None
|
|
268
|
+
|
|
269
|
+
async def test_a_stale_session_is_extended_and_a_fresh_one_left_alone(
|
|
270
|
+
self, engine: AsyncEngine
|
|
271
|
+
) -> None:
|
|
272
|
+
factory = create_sessionmaker(engine)
|
|
273
|
+
async with session_scope(factory) as db:
|
|
274
|
+
token = await STORE.open(db, 1)
|
|
275
|
+
async with session_scope(factory) as db:
|
|
276
|
+
session = await STORE.find(db, token)
|
|
277
|
+
opened = session.expires_at
|
|
278
|
+
soon = datetime.now(UTC) + timedelta(hours=1)
|
|
279
|
+
async with session_scope(factory) as db:
|
|
280
|
+
assert (await STORE.find(db, token, now=soon)).expires_at == opened
|
|
281
|
+
later = datetime.now(UTC) + timedelta(days=2)
|
|
282
|
+
async with session_scope(factory) as db:
|
|
283
|
+
await STORE.find(db, token, now=later)
|
|
284
|
+
async with session_scope(factory) as db:
|
|
285
|
+
session = await STORE.find(db, token, now=later)
|
|
286
|
+
|
|
287
|
+
assert session.last_seen_at == later
|
|
288
|
+
assert session.expires_at == later + timedelta(days=90)
|
|
289
|
+
|
|
290
|
+
async def test_ending_a_session_ends_only_that_one(self, engine: AsyncEngine) -> None:
|
|
291
|
+
factory = create_sessionmaker(engine)
|
|
292
|
+
async with session_scope(factory) as db:
|
|
293
|
+
first, second = await STORE.open(db, 1), await STORE.open(db, 1)
|
|
294
|
+
async with session_scope(factory) as db:
|
|
295
|
+
await STORE.end(db, first)
|
|
296
|
+
async with session_scope(factory) as db:
|
|
297
|
+
assert await STORE.find(db, first) is None
|
|
298
|
+
assert await STORE.find(db, second) is not None
|
|
299
|
+
|
|
300
|
+
async def test_ending_all_of_an_owners_sessions_can_keep_one(self, engine: AsyncEngine) -> None:
|
|
301
|
+
factory = create_sessionmaker(engine)
|
|
302
|
+
async with session_scope(factory) as db:
|
|
303
|
+
mine = [await STORE.open(db, 1) for _ in range(3)]
|
|
304
|
+
theirs = await STORE.open(db, 2)
|
|
305
|
+
async with session_scope(factory) as db:
|
|
306
|
+
kept = await STORE.find(db, mine[0])
|
|
307
|
+
await STORE.end_all(db, 1, keep=kept.id)
|
|
308
|
+
async with session_scope(factory) as db:
|
|
309
|
+
assert await STORE.find(db, mine[0]) is not None
|
|
310
|
+
assert await STORE.find(db, mine[1]) is None
|
|
311
|
+
assert await STORE.find(db, theirs) is not None
|
|
312
|
+
await STORE.end_all(db, 1)
|
|
313
|
+
async with session_scope(factory) as db:
|
|
314
|
+
assert await STORE.find(db, mine[0]) is None
|
|
315
|
+
|
|
316
|
+
async def test_pruning_deletes_only_expired_sessions(self, engine: AsyncEngine) -> None:
|
|
317
|
+
factory = create_sessionmaker(engine)
|
|
318
|
+
async with session_scope(factory) as db:
|
|
319
|
+
await STORE.open(db, 1)
|
|
320
|
+
await STORE.open(db, 2)
|
|
321
|
+
async with session_scope(factory) as db:
|
|
322
|
+
assert await STORE.prune(db) == 0
|
|
323
|
+
assert await STORE.prune(db, now=datetime.now(UTC) + timedelta(days=91)) == 2
|
|
324
|
+
async with session_scope(factory) as db:
|
|
325
|
+
count = (await db.execute(select(func.count()).select_from(AccountSession))).scalar()
|
|
326
|
+
|
|
327
|
+
assert count == 0
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|