Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .bumpversion.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "1.21.0+261122"
current_version = "1.21.1+261122"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)\\+(?P<build>\\d+)"
serialize = ["{major}.{minor}.{patch}+{build}"]
search = "{current_version}"
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "rasenmaeher_api"
version = "1.21.0+261122"
version = "1.21.1+261122"
description = "python-rasenmaeher-api"
authors = [
{ name = "Aciid", email = "703382+Aciid@users.noreply.github.com" },
Expand Down
2 changes: 1 addition & 1 deletion src/rasenmaeher_api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""python-rasenmaeher-api"""

__version__ = "1.21.0+261122" # NOTE Use `bump-my-version` to bump versions correctly
__version__ = "1.21.1+261122" # NOTE Use `bump-my-version` to bump versions correctly
17 changes: 8 additions & 9 deletions src/rasenmaeher_api/db/acme.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from sqlmodel import Session, col, delete, select
from sqlmodel.sql.expression import SelectOfScalar

from ..cert.acme import ACMEError, validate_device_csr
from ..cert.acme import ACMEError, b64url, validate_device_csr
from .engine import EngineWrapper
from .enrollments import ACME_CLIENT_IDENTIFIER_KEY, ACME_ORDER_KEY, Enrollment, EnrollmentState
from .errors import BackendError, CallsignReserved
Expand All @@ -25,15 +25,14 @@
ACCOUNT_PREFIX = "acme-account:"


def issue_nonce(prune: bool = False) -> str:
"""Mint a short-lived nonce shared by every API worker."""
now = datetime.datetime.now(datetime.UTC)
nonce = f"{int(now.timestamp()):010d}-{secrets.token_urlsafe(24)}"
def issue_nonce() -> str:
"""Mint a canonical nonce and discard expired ACME nonces, including on POST responses."""
nonce = b64url(secrets.token_bytes(32))
cutoff = datetime.datetime.now(datetime.UTC) - NONCE_LIFETIME
with EngineWrapper.get_session() as session:
if prune:
cutoff = int((now - NONCE_LIFETIME).timestamp())
token = col(SeenToken.token)
session.exec(delete(SeenToken).where(token >= NONCE_PREFIX, token < f"{NONCE_PREFIX}{cutoff:010d}-"))
session.exec(
delete(SeenToken).where(col(SeenToken.token).startswith(NONCE_PREFIX), col(SeenToken.created) <= cutoff)
)
session.add(SeenToken(token=f"{NONCE_PREFIX}{nonce}"))
session.commit()
return nonce
Expand Down
2 changes: 1 addition & 1 deletion src/rasenmaeher_api/web/api/acme/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async def directory() -> dict[str, str]:
@router.get("/new-nonce", status_code=204, response_class=Response)
async def new_nonce(response: Response) -> None:
"""Issue the first replay nonce for an ACME request."""
response.headers["Replay-Nonce"] = acme.issue_nonce(prune=True)
response.headers["Replay-Nonce"] = acme.issue_nonce()


@router.post("/new-account")
Expand Down
53 changes: 51 additions & 2 deletions tests/test_acme.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import plistlib
import secrets
import uuid
from typing import Any
from urllib.parse import urlsplit

Expand All @@ -16,13 +17,14 @@
from cryptography.x509.oid import ExtendedKeyUsageOID
from fastapi import FastAPI

from rasenmaeher_api.cert.acme import b64url
from rasenmaeher_api.cert.acme import ACMEError, b64url, decode_b64url
from rasenmaeher_api.cert.backend import sign_csr
from rasenmaeher_api.cert.errors import CertError
from rasenmaeher_api.db import EngineWrapper, Enrollment, EnrollmentState, Person
from rasenmaeher_api.db import EngineWrapper, Enrollment, EnrollmentState, Person, acme
from rasenmaeher_api.db import people as people_db
from rasenmaeher_api.db.enrollments import ACME_AUTHORIZATION_LIFETIME
from rasenmaeher_api.db.errors import NotFound
from rasenmaeher_api.db.nonces import SeenToken

ORIGIN = "https://localmaeher.dev.pvarki.fi"

Expand Down Expand Up @@ -73,6 +75,7 @@ async def send(
headers={"Content-Type": "application/jose+json"},
)
self.nonce = response.headers["Replay-Nonce"]
assert b64url(decode_b64url(self.nonce)) == self.nonce
return response

async def register(self) -> httpx.Response:
Expand All @@ -95,6 +98,52 @@ def csr(callsign: str, key: ec.EllipticCurvePrivateKey, san: x509.GeneralName |
return {"csr": b64url(builder.sign(key, hashes.SHA256()).public_bytes(serialization.Encoding.DER))}


@pytest.mark.asyncio(loop_scope="session")
@pytest.mark.usefixtures("dbinit_sess")
@pytest.mark.parametrize("app_instance", ["RSA"], indirect=True)
async def test_acme_nonce_cleanup(app_instance: FastAPI, monkeypatch: pytest.MonkeyPatch) -> None:
"""POST errors prune expired nonces without deleting accounts or other replay records."""
expired = datetime.datetime.now(datetime.UTC) - acme.NONCE_LIFETIME - datetime.timedelta(seconds=1)
suffix = str(uuid.uuid4())
expired_nonce = f"{acme.NONCE_PREFIX}expired-{suffix}"
remaining = (f"{acme.NONCE_PREFIX}live-{suffix}", f"{acme.ACCOUNT_PREFIX}{suffix}", f"other-{suffix}")
tokens = [
SeenToken(token=expired_nonce, created=expired),
SeenToken(token=remaining[0]),
SeenToken(token=remaining[1], created=expired),
SeenToken(token=remaining[2], created=expired),
]
with EngineWrapper.get_session() as session:
session.add_all(tokens)
session.commit()

async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app_instance), base_url=ORIGIN) as client:
# This suffix exposes the old concatenated nonce's nonzero base64 padding bits.
with monkeypatch.context() as patch:
patch.setattr(secrets, "token_urlsafe", lambda _: "B" * 32)
patch.setattr(secrets, "token_bytes", lambda _: b"\x01" * 32)
response = await client.post(
"/api/v1/acme/new-account", content=b"invalid", headers={"Content-Type": "application/jose+json"}
)
assert response.status_code == 400
nonce = response.headers["Replay-Nonce"]
assert b64url(decode_b64url(nonce)) == nonce
assert len(nonce) == 43
with pytest.raises(NotFound):
await SeenToken.by_token(expired_nonce)
for token in remaining:
assert (await SeenToken.by_token(token)).token == token

acme.consume_nonce(nonce)
with pytest.raises(ACMEError, match="Unknown, expired, or already used"):
acme.consume_nonce(nonce)

for method in ("GET", "HEAD"):
response = await client.request(method, "/api/v1/acme/new-nonce")
nonce = response.headers["Replay-Nonce"]
assert b64url(decode_b64url(nonce)) == nonce


@pytest.mark.asyncio(loop_scope="session")
@pytest.mark.usefixtures("dbinit_sess")
@pytest.mark.parametrize("app_instance", ["RSA"], indirect=True)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_rasenmaeher_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

def test_version() -> None:
"""Make sure version matches expected"""
assert __version__ == "1.21.0+261122"
assert __version__ == "1.21.1+261122"


@pytest.mark.asyncio(loop_scope="session")
Expand Down
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading