aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/models.py
blob: 33f27d1b52ba7adc521377cc644b475534752582 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Define database models for users and incoming and outgoing Webmentions."""

import json
from datetime import UTC, datetime
from enum import StrEnum
from hashlib import sha256
from typing import Never
from uuid import UUID, uuid7

import sqlalchemy as sa
from flask_login import UserMixin
from sqlalchemy import (
    Boolean,
    DateTime,
    Enum,
    ForeignKey,
    Index,
    Integer,
    String,
    Text,
    UniqueConstraint,
    Uuid,
)
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import Mapped, mapped_column, relationship, validates
from werkzeug.security import check_password_hash, generate_password_hash

from .extensions import Base


class ReceivedStatus(StrEnum):
    """Persisted lifecycle state of an incoming Webmention."""

    RECEIVED = "received"
    VERIFYING = "verifying"
    VERIFIED = "verified"
    FAILED = "failed"
    DELETED = "deleted"


class SentWebmentionStatus(StrEnum):
    """Represent the outcome of a Webmention send attempt."""

    SENT = "sent"
    UNSUPPORTED = "unsupported"
    FAILED = "failed"


class User(UserMixin, Base):
    """Represent an authenticated application user."""

    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(Text(), index=True, unique=True)
    password_hash: Mapped[str] = mapped_column(Text(), nullable=False)

    def __repr__(self) -> str:
        """Represent the user by username."""
        return f"<User {self.username}>"

    @property
    def password(self) -> Never:
        """Prevent access to the user's plain-text password.

        :raises AttributeError: Always, because the password is write-only.
        """
        raise AttributeError("Password is write-only")

    @password.setter
    def password(self, password: str) -> None:
        """Hash and store a new password.

        :param password: Plain-text password to hash.
        """
        self.password_hash = generate_password_hash(password)

    def get_id(self) -> str:
        """Bind the login session to the current stored password hash.

        Only a one-way fingerprint is placed in Flask's signed cookie, never
        the password hash itself. Rehashing the password invalidates all
        previously issued session identifiers without a schema change.

        :returns: Session identifier combining the user ID and password-hash
                  fingerprint.
        """
        fingerprint = sha256(self.password_hash.encode("utf-8")).hexdigest()
        return f"{self.id}:{fingerprint}"

    def check_password(self, password: str) -> bool:
        """Check a plain-text password against the stored password hash.

        :param password: Plain-text password to check.
        :returns: Whether the password matches the stored hash.
        """
        return check_password_hash(self.password_hash, password)


class ReceivedWebmention(Base):
    """Represent a Webmention received for verification."""

    __tablename__ = "received_webmentions"

    uuid: Mapped[UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True)

    source: Mapped[str] = mapped_column(Text(), nullable=False)
    target: Mapped[str] = mapped_column(Text(), nullable=False)
    url_digest: Mapped[str] = mapped_column(String(64), nullable=False)

    @validates("source", "target")
    def _update_url_digest(self, key: str, value: str) -> str:
        source = value if key == "source" else self.__dict__.get("source")
        target = value if key == "target" else self.__dict__.get("target")
        if source is not None and target is not None:
            self.url_digest = received_url_digest(source, target)
        return value

    status: Mapped[ReceivedStatus] = mapped_column(
        Enum(
            ReceivedStatus,
            name="received_webmention_status",
            values_callable=lambda enum_type: [member.value for member in enum_type],
            native_enum=False,
        ),
        nullable=False,
        default=ReceivedStatus.RECEIVED,
    )
    # Counts stale-row requeues, not Huey's bounded in-task retries. A fresh
    # explicit submission resets this counter.
    recovery_attempts: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, server_default="0"
    )
    failure_reason: Mapped[str | None] = mapped_column(
        Text(), nullable=True, default=None
    )

    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        default=lambda: datetime.now(UTC),
        onupdate=lambda: datetime.now(UTC),
        nullable=False,
    )

    notification_sent_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, default=None
    )

    __table_args__ = (
        UniqueConstraint("url_digest", name="uq_webmention_url_digest"),
        Index("ix_received_webmentions_status_updated_at", "status", "updated_at"),
    )

    def __repr__(self) -> str:
        """Represent the received Webmention by source and target."""
        return f"<ReceivedWebmention {self.source!r} -> {self.target!r}>"

    @staticmethod
    def verification_reset_values(
        *, at: datetime, recoveries: int = 0
    ) -> dict[str, object]:
        """Return the columns to reset when verification is explicitly reopened.

        :param at: Timestamp to record for the newly opened verification.
        :param recoveries: Number of stale-lease recovery attempts to retain.
        :returns: Column values for resetting the verification state.
        """
        return {
            "status": ReceivedStatus.RECEIVED,
            "failure_reason": None,
            "recovery_attempts": recoveries,
            "updated_at": at,
        }

    def reset_for_verification(self) -> None:
        """Reopen an existing row for manual verification.

        Clear the previous outcome and restore the received state with a fresh
        timestamp.
        """
        for key, value in self.verification_reset_values(at=datetime.now(UTC)).items():
            setattr(self, key, value)

    @property
    def verified(self) -> bool:
        """Return whether the Webmention has been successfully verified."""
        return self.status == ReceivedStatus.VERIFIED

    @property
    def created_at(self) -> datetime:
        """Return the creation time encoded in the Webmention UUID."""
        return uuid7_to_datetime(self.uuid)


class Source(Base):
    """Represent a generated source document containing outgoing Webmentions."""

    __tablename__ = "sources"

    uuid: Mapped[UUID] = mapped_column(
        Uuid(as_uuid=True), primary_key=True, default=uuid7
    )

    path: Mapped[str] = mapped_column(Text(), nullable=False, unique=True)
    url: Mapped[str] = mapped_column(Text(), nullable=False, unique=True)

    content_hash: Mapped[str] = mapped_column(String(32), nullable=False)
    revision: Mapped[int] = mapped_column(Integer(), nullable=False, default=1)

    last_seen_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False
    )
    revised_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False
    )
    deleted_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, default=None
    )

    sent_webmentions: Mapped[list[SentWebmention]] = relationship(
        back_populates="source", cascade="all, delete-orphan"
    )

    def __repr__(self) -> str:
        """Represent the source by its public URL."""
        return f"<Source {self.url!r}>"

    @property
    def created_at(self) -> datetime:
        """Return the creation time encoded in the source UUID."""
        return uuid7_to_datetime(self.uuid)


class SentWebmention(Base):
    """Represent an outgoing Webmention associated with a source."""

    __tablename__ = "sent_webmentions"

    uuid: Mapped[UUID] = mapped_column(
        Uuid(as_uuid=True), primary_key=True, default=uuid7
    )

    source_id: Mapped[UUID] = mapped_column(
        Uuid(as_uuid=True),
        ForeignKey("sources.uuid", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    target: Mapped[str] = mapped_column(Text(), nullable=False)
    target_digest: Mapped[str] = mapped_column(String(64), nullable=False)

    @validates("target")
    def _update_target_digest(self, key: str, value: str) -> str:
        self.target_digest = sent_target_digest(value)
        return value

    active: Mapped[bool] = mapped_column(Boolean(), nullable=False, default=True)

    desired_revision: Mapped[int] = mapped_column(Integer(), nullable=False)
    processed_revision: Mapped[int | None] = mapped_column(
        Integer(), nullable=True, default=None
    )
    sent_revision: Mapped[int | None] = mapped_column(
        Integer(), nullable=True, default=None
    )

    status: Mapped[SentWebmentionStatus | None] = mapped_column(
        Enum(
            SentWebmentionStatus,
            name="sent_webmention_status",
            values_callable=lambda enum_type: [member.value for member in enum_type],
            native_enum=False,
        ),
        nullable=True,
        default=None,
    )

    failure_reason: Mapped[str | None] = mapped_column(
        Text(), nullable=True, default=None
    )

    endpoint: Mapped[str | None] = mapped_column(Text(), nullable=True, default=None)
    response_status: Mapped[int | None] = mapped_column(
        Integer(), nullable=True, default=None
    )
    status_url: Mapped[str | None] = mapped_column(Text(), nullable=True, default=None)

    # Retry state belongs to the desired revision, not to the target forever.
    attempt_count: Mapped[int] = mapped_column(Integer(), nullable=False, default=0)
    next_retry_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, default=None
    )

    last_attempted_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, default=None
    )
    last_sent_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, default=None
    )

    source: Mapped[Source] = relationship(back_populates="sent_webmentions")

    __table_args__ = (
        UniqueConstraint(
            "source_id", "target_digest", name="uq_sent_webmention_source_target_digest"
        ),
    )

    def __repr__(self) -> str:
        """Represent the sent Webmention by its target URL."""
        return f"<SentWebmention {self.target!r}>"

    def reopen(self, revision: int, active: bool) -> None:
        """Reopen delivery for a revision while preserving send history.

        :param revision: Source revision to make the desired delivery revision.
        :param active: Whether the target still appears in the current source.
        """
        self.desired_revision = revision
        self.active = active
        self.attempt_count = 0
        self.next_retry_at = None

    def resend(self) -> None:
        """Retry the current revision, clearing its previous delivery result.

        Reset attempt and response state without changing the desired source revision.
        """
        self.reopen(self.desired_revision, self.active)
        self.processed_revision = None
        self.status = None
        self.failure_reason = None
        self.endpoint = None
        self.response_status = None
        self.status_url = None

    @hybrid_property
    def pending(self) -> bool:
        """Return whether the Webmention has an unprocessed source revision."""
        return (
            self.processed_revision is None
            or self.processed_revision < self.desired_revision
        )

    @pending.inplace.expression
    @classmethod
    def _pending_expression(cls) -> sa.ColumnElement[bool]:
        """Express pending-revision status in database queries.

        :returns: SQLAlchemy expression selecting unprocessed source revisions.
        """
        return sa.or_(
            cls.processed_revision.is_(None),
            cls.processed_revision < cls.desired_revision,
        )

    @property
    def created_at(self) -> datetime:
        """Return the creation time encoded in the Webmention UUID."""
        return uuid7_to_datetime(self.uuid)


def uuid7_to_datetime(identifier: UUID) -> datetime:
    """Convert a UUID version 7 timestamp to a datetime.

    :param identifier: UUID whose embedded timestamp should be converted.
    :returns: Timestamp as a timezone-aware UTC datetime.
    """
    return datetime.fromtimestamp(identifier.time / 1000, tz=UTC)


def received_url_digest(source: str, target: str) -> str:
    """Fingerprint an unambiguous, ordered source/target pair.

    :param source: Webmention source URL.
    :param target: Webmention target URL.
    :returns: SHA-256 hexadecimal digest of the ordered URL pair.
    """
    encoded = json.dumps(
        [source, target], ensure_ascii=False, separators=(",", ":")
    ).encode("utf-8")
    return sha256(encoded).hexdigest()


def sent_target_digest(target: str) -> str:
    """Fingerprint an outgoing target (unique within each source ID).

    :param target: Outgoing Webmention target URL.
    :returns: SHA-256 hexadecimal digest of the target URL.
    """
    return sha256(target.encode("utf-8")).hexdigest()