passerby 0.9.0__py3-none-any.whl

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.
Files changed (214) hide show
  1. passerby/.DS_Store +0 -0
  2. passerby/__init__.py +0 -0
  3. passerby/accounts/__init__.py +1 -0
  4. passerby/accounts/models.py +246 -0
  5. passerby/accounts/oidc.py +259 -0
  6. passerby/accounts/roles.py +96 -0
  7. passerby/accounts/sessions.py +68 -0
  8. passerby/accounts/users.py +95 -0
  9. passerby/alerts/__init__.py +2 -0
  10. passerby/alerts/models.py +69 -0
  11. passerby/alerts/reports.py +240 -0
  12. passerby/alerts/send.py +304 -0
  13. passerby/cli.py +511 -0
  14. passerby/config.py +171 -0
  15. passerby/db.py +117 -0
  16. passerby/demo/__init__.py +3 -0
  17. passerby/demo/sites.py +411 -0
  18. passerby/demo/traffic.py +565 -0
  19. passerby/filtering/__init__.py +1 -0
  20. passerby/filtering/data/crawler_user_agents.txt +37 -0
  21. passerby/filtering/data/hosting_asns.txt +65 -0
  22. passerby/filtering/data/referrer_spam.txt +2360 -0
  23. passerby/filtering/models.py +42 -0
  24. passerby/filtering/rules.py +205 -0
  25. passerby/housekeeping/__init__.py +1 -0
  26. passerby/housekeeping/health.py +368 -0
  27. passerby/housekeeping/reapply.py +114 -0
  28. passerby/housekeeping/retention.py +90 -0
  29. passerby/imports/__init__.py +1 -0
  30. passerby/imports/base.py +373 -0
  31. passerby/imports/csvfile.py +136 -0
  32. passerby/imports/matomo.py +254 -0
  33. passerby/imports/umami.py +180 -0
  34. passerby/layout.toml +13 -0
  35. passerby/liveness/__init__.py +1 -0
  36. passerby/liveness/checks.py +189 -0
  37. passerby/liveness/domains.py +81 -0
  38. passerby/liveness/models.py +43 -0
  39. passerby/liveness/status.py +154 -0
  40. passerby/mail.py +40 -0
  41. passerby/migrations/env.py +91 -0
  42. passerby/migrations/script.py.mako +27 -0
  43. passerby/migrations/versions/20261111_0becea1ce756_project_icon.py +43 -0
  44. passerby/migrations/versions/20261111_23c2f6f76d71_event_excluded_flag.py +47 -0
  45. passerby/migrations/versions/20261111_53c53abf5f6d_user_timezone.py +37 -0
  46. passerby/migrations/versions/20261111_7ad858a7d3b3_baseline.py +375 -0
  47. passerby/migrations/versions/20261111_ee008225e276_project_retention.py +33 -0
  48. passerby/migrations/versions/20261111_eeb3643f2c09_event_referrer_host.py +65 -0
  49. passerby/migrations/versions/20261112_0889b3c5c142_project_stars.py +69 -0
  50. passerby/migrations/versions/20261112_1a1ae69ded81_hosting_networks.py +51 -0
  51. passerby/migrations/versions/20261112_1b5be2c5a6e0_project_viewers.py +69 -0
  52. passerby/migrations/versions/20261112_4e7a1c2b9d30_lowercase_emails.py +43 -0
  53. passerby/migrations/versions/20261112_6b2898bf913b_dismissed_problems.py +56 -0
  54. passerby/migrations/versions/20261112_78725731e933_user_sessions_valid_after.py +34 -0
  55. passerby/migrations/versions/20261112_8d3f5a1e6c27_superusers_are_staff.py +28 -0
  56. passerby/migrations/versions/20261112_97bbd8425a29_share_links.py +59 -0
  57. passerby/migrations/versions/20261112_dbb0e00c7f0e_instance_blocked_countries_and_spam_.py +62 -0
  58. passerby/migrations/versions/20261113_3ffa02de0f80_store_entries_for_shared_rate_limits.py +56 -0
  59. passerby/migrations/versions/20261113_b7e2c4d91a05_keep_only_utm_parameters.py +73 -0
  60. passerby/migrations/versions/20261114_882422b477b9_entry_and_exit_pages_on_visits.py +73 -0
  61. passerby/migrations/versions/20261114_b4fb13573a5c_goals.py +68 -0
  62. passerby/migrations/versions/20261114_d3b8e4fd9083_archived_sites.py +40 -0
  63. passerby/migrations/versions/20261116_1b50500b1915_consent_exempt_projects.py +40 -0
  64. passerby/migrations/versions/20261116_5891c4e9db51_webhook_alerts.py +92 -0
  65. passerby/migrations/versions/20261116_5b9870b14026_opt_out_seen_on_sites.py +42 -0
  66. passerby/migrations/versions/20261116_6264cf0316ee_annotations.py +67 -0
  67. passerby/migrations/versions/20261116_b400707f57d8_liveness_checks.py +133 -0
  68. passerby/migrations/versions/20261116_e1a183071097_email_alerts_and_reports.py +126 -0
  69. passerby/migrations/versions/20261117_5301de8306c2_page_measures_and_visit_facts.py +72 -0
  70. passerby/migrations/versions/20261117_5972834e4337_funnels.py +61 -0
  71. passerby/migrations/versions/20261117_6e8ff6a86c82_segments.py +61 -0
  72. passerby/migrations/versions/20261118_1d5c0e7a9b42_embeds.py +28 -0
  73. passerby/migrations/versions/20261118_2d363b6d81df_roles_on_neozen.py +144 -0
  74. passerby/migrations/versions/20261118_ae826b8acf38_accounts_on_neozen.py +142 -0
  75. passerby/migrations/versions/20261120_5c1e0a7d9b42_index_excluded_visits.py +33 -0
  76. passerby/migrations/versions/20261124_7c3d9e21f0ab_project_labels.py +59 -0
  77. passerby/migrations/versions/20261124_c41d8f0a6b27_organizations.py +335 -0
  78. passerby/migrations/versions/20261126_a8b07f3e7527_liveness_check_latest.py +29 -0
  79. passerby/migrations/versions/20261129_3f6a2d8c1b94_site_per_project.py +31 -0
  80. passerby/migrations/versions/20261203_5b1e7c0d9a42_webhook_secret.py +49 -0
  81. passerby/migrations/versions/20261203_8d24f6a1c0e3_report_recipients.py +68 -0
  82. passerby/migrations/versions/20261203_a1f0d93c6b57_api_token_writes.py +33 -0
  83. passerby/migrations/versions/20261203_c7a35e9b2d18_share_link_password.py +33 -0
  84. passerby/migrations/versions/20261203_e4b9c2f17a60_public_pages.py +41 -0
  85. passerby/net.py +112 -0
  86. passerby/organizations/__init__.py +1 -0
  87. passerby/organizations/access.py +187 -0
  88. passerby/organizations/members.py +326 -0
  89. passerby/projects/__init__.py +1 -0
  90. passerby/projects/icons.py +343 -0
  91. passerby/projects/models.py +264 -0
  92. passerby/py.typed +0 -0
  93. passerby/reporting/__init__.py +1 -0
  94. passerby/reporting/attention.py +329 -0
  95. passerby/reporting/filters.py +113 -0
  96. passerby/reporting/models.py +90 -0
  97. passerby/reporting/periods.py +278 -0
  98. passerby/reporting/stats.py +1709 -0
  99. passerby/sharing/__init__.py +1 -0
  100. passerby/sharing/models.py +42 -0
  101. passerby/text.py +50 -0
  102. passerby/tracking/__init__.py +1 -0
  103. passerby/tracking/geoip.py +173 -0
  104. passerby/tracking/ingest.py +453 -0
  105. passerby/tracking/models.py +190 -0
  106. passerby/web/__init__.py +1 -0
  107. passerby/web/auth/__init__.py +18 -0
  108. passerby/web/auth/api_auth.py +80 -0
  109. passerby/web/auth/guards.py +103 -0
  110. passerby/web/auth/identity.py +75 -0
  111. passerby/web/auth/middleware.py +39 -0
  112. passerby/web/auth/session.py +60 -0
  113. passerby/web/di.py +270 -0
  114. passerby/web/exports.py +46 -0
  115. passerby/web/forms.py +311 -0
  116. passerby/web/main.py +326 -0
  117. passerby/web/pages.py +482 -0
  118. passerby/web/repositories.py +47 -0
  119. passerby/web/routes/__init__.py +72 -0
  120. passerby/web/routes/account.py +270 -0
  121. passerby/web/routes/admin.py +334 -0
  122. passerby/web/routes/annotations.py +92 -0
  123. passerby/web/routes/api.py +332 -0
  124. passerby/web/routes/attention.py +105 -0
  125. passerby/web/routes/auth.py +183 -0
  126. passerby/web/routes/dashboard.py +224 -0
  127. passerby/web/routes/dto.py +195 -0
  128. passerby/web/routes/filtering.py +204 -0
  129. passerby/web/routes/goals.py +245 -0
  130. passerby/web/routes/home.py +62 -0
  131. passerby/web/routes/mcp.py +225 -0
  132. passerby/web/routes/members.py +301 -0
  133. passerby/web/routes/projects.py +896 -0
  134. passerby/web/routes/public.py +236 -0
  135. passerby/web/routes/reports.py +209 -0
  136. passerby/web/routes/share.py +361 -0
  137. passerby/web/routes/sharing.py +325 -0
  138. passerby/web/routes/tracker.py +220 -0
  139. passerby/web/routes/visits.py +168 -0
  140. passerby/web/security.py +141 -0
  141. passerby/web/service.py +40 -0
  142. passerby/web/static/ads/ads.css +3622 -0
  143. passerby/web/static/ads/restore.js +31 -0
  144. passerby/web/static/ads/shell.js +248 -0
  145. passerby/web/static/ads/situ.css +108 -0
  146. passerby/web/static/app.js +497 -0
  147. passerby/web/static/favicon.png +0 -0
  148. passerby/web/static/fonts/OFL-barlow.txt +93 -0
  149. passerby/web/static/fonts/OFL-figtree.txt +93 -0
  150. passerby/web/static/fonts/barlow-condensed-500.woff2 +0 -0
  151. passerby/web/static/fonts/barlow-condensed-600.woff2 +0 -0
  152. passerby/web/static/fonts/figtree.woff2 +0 -0
  153. passerby/web/static/icons.json +84 -0
  154. passerby/web/static/passerby.svg +8 -0
  155. passerby/web/static/t.js +367 -0
  156. passerby/web/static/t.min.js +2 -0
  157. passerby/web/static/theme.css +464 -0
  158. passerby/web/static/world.svg +1 -0
  159. passerby/web/static_files.py +50 -0
  160. passerby/web/stores.py +115 -0
  161. passerby/web/templates/_macros.html +137 -0
  162. passerby/web/templates/account.html +120 -0
  163. passerby/web/templates/admin/health.html +26 -0
  164. passerby/web/templates/admin/rules.html +107 -0
  165. passerby/web/templates/admin/users.html +89 -0
  166. passerby/web/templates/ads/form.html +98 -0
  167. passerby/web/templates/ads/nav.html +52 -0
  168. passerby/web/templates/ads/shell.html +132 -0
  169. passerby/web/templates/attention.html +56 -0
  170. passerby/web/templates/auth/login.html +26 -0
  171. passerby/web/templates/base.html +89 -0
  172. passerby/web/templates/dashboard/index.html +165 -0
  173. passerby/web/templates/demo.html +16 -0
  174. passerby/web/templates/error.html +14 -0
  175. passerby/web/templates/home.html +11 -0
  176. passerby/web/templates/invitation.html +25 -0
  177. passerby/web/templates/members.html +120 -0
  178. passerby/web/templates/projects/_details.html +88 -0
  179. passerby/web/templates/projects/_flow.html +39 -0
  180. passerby/web/templates/projects/_privacy_notice.html +20 -0
  181. passerby/web/templates/projects/_report.html +445 -0
  182. passerby/web/templates/projects/create.html +28 -0
  183. passerby/web/templates/projects/details.html +11 -0
  184. passerby/web/templates/projects/filtering.html +183 -0
  185. passerby/web/templates/projects/flow.html +10 -0
  186. passerby/web/templates/projects/live.html +52 -0
  187. passerby/web/templates/projects/report.html +27 -0
  188. passerby/web/templates/projects/search.html +27 -0
  189. passerby/web/templates/projects/settings/_fields.html +104 -0
  190. passerby/web/templates/projects/settings/_page.html +23 -0
  191. passerby/web/templates/projects/settings/alerts.html +34 -0
  192. passerby/web/templates/projects/settings/general.html +88 -0
  193. passerby/web/templates/projects/settings/monitoring.html +77 -0
  194. passerby/web/templates/projects/settings/privacy.html +29 -0
  195. passerby/web/templates/projects/settings/sharing.html +123 -0
  196. passerby/web/templates/projects/settings/tracking.html +76 -0
  197. passerby/web/templates/projects/unclaimed.html +43 -0
  198. passerby/web/templates/projects/visits.html +61 -0
  199. passerby/web/templates/public.html +25 -0
  200. passerby/web/templates/public_status.html +59 -0
  201. passerby/web/templates/report_stop.html +17 -0
  202. passerby/web/templates/share/base.html +36 -0
  203. passerby/web/templates/share/details.html +6 -0
  204. passerby/web/templates/share/flow.html +6 -0
  205. passerby/web/templates/share/locked.html +20 -0
  206. passerby/web/templates/share/report.html +6 -0
  207. passerby/web/transactions.py +52 -0
  208. passerby/web/ui.py +701 -0
  209. passerby/worker.py +209 -0
  210. passerby-0.9.0.dist-info/METADATA +31 -0
  211. passerby-0.9.0.dist-info/RECORD +214 -0
  212. passerby-0.9.0.dist-info/WHEEL +4 -0
  213. passerby-0.9.0.dist-info/entry_points.txt +9 -0
  214. passerby-0.9.0.dist-info/licenses/LICENSE +201 -0
passerby/.DS_Store ADDED
Binary file
passerby/__init__.py ADDED
File without changes
@@ -0,0 +1 @@
1
+ """Who signs in: users, their passwords and API tokens."""
@@ -0,0 +1,246 @@
1
+ """Accounts: who signs in, as NeoZen keeps them (`Subject`: the email, the
2
+ password's hash, the active flag, and the sessions), and what analytics
3
+ knows of them (`User`: the username, the timezone). This module is where the
4
+ two meet: the rest of the app reads a `User`, and of NeoZen's, what
5
+ `passerby.organizations` makes of it."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import re
11
+ import secrets
12
+ from datetime import UTC, datetime, timedelta
13
+ from uuid import uuid4
14
+
15
+ from advanced_alchemy.base import UUIDAuditBase
16
+ from neozen.core.authz.models import ScopeType
17
+ from neozen.core.crypto import generate_token
18
+ from neozen.storage.sqlalchemy.models import RoleAssignment, Subject
19
+ from pwdlib import PasswordHash
20
+ from pwdlib.exceptions import UnknownHashError
21
+ from sqlalchemy import ForeignKey, Select, String, and_, false, select
22
+ from sqlalchemy.orm import Mapped, foreign, mapped_column, relationship
23
+
24
+ from passerby.accounts.roles import ROLE_IDS, Role
25
+ from passerby.db import utcnow
26
+
27
+ # Argon2id. Hashes from before 2026-09-14 (PBKDF2) that no sign-in upgraded
28
+ # since don't verify: an administrator resets those passwords.
29
+ PASSWORDS = PasswordHash.recommended()
30
+
31
+
32
+ def hash_api_token(token: str) -> str:
33
+ """Hash an API token using SHA256."""
34
+ return hashlib.sha256(token.encode()).hexdigest()
35
+
36
+
37
+ def as_utc(moment: datetime) -> datetime:
38
+ """A time from NeoZen's tables: SQLite gives it back without its UTC."""
39
+ return moment if moment.tzinfo else moment.replace(tzinfo=UTC)
40
+
41
+
42
+ def normalize_email(email: str) -> str:
43
+ """An email as stored, and as looked up: trimmed, in lower case."""
44
+ return email.strip().lower()
45
+
46
+
47
+ MAX_EMAIL = 254
48
+
49
+
50
+ def parse_email(text: str) -> str:
51
+ """An email as stored; ValueError for one that isn't."""
52
+ email = normalize_email(text)
53
+ if len(email) > MAX_EMAIL or not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
54
+ msg = "Invalid email address"
55
+ raise ValueError(msg)
56
+ return email
57
+
58
+
59
+ class User(UUIDAuditBase):
60
+ # Who signs in: the email, the password and the active flag are the
61
+ # subject's, and nowhere else. Loaded with the user, always.
62
+ subject_id: Mapped[str] = mapped_column(
63
+ ForeignKey(Subject.id, ondelete="CASCADE"), unique=True
64
+ )
65
+ subject: Mapped[Subject] = relationship(Subject, lazy="joined", innerjoin=True)
66
+
67
+ username: Mapped[str] = mapped_column(String(150), unique=True)
68
+
69
+ # API token stored as SHA256 hash (plaintext never stored)
70
+ api_token_hash: Mapped[str | None] = mapped_column(String(64), default=None)
71
+ api_token_expires_at: Mapped[datetime | None] = mapped_column(default=None)
72
+ # Whether the token may write (import history, add notes), or only read.
73
+ api_token_writes: Mapped[bool] = mapped_column(
74
+ default=False, server_default=false()
75
+ )
76
+
77
+ # The subject's roles on the instance, NeoZen's assignments: loaded with
78
+ # the user, as every page's menu asks. Those in organizations and on
79
+ # projects are passerby.organizations'.
80
+ role_assignments: Mapped[list[RoleAssignment]] = relationship(
81
+ RoleAssignment,
82
+ primaryjoin=lambda: and_(
83
+ User.subject_id == foreign(RoleAssignment.subject_id),
84
+ RoleAssignment.scope_type == ScopeType.GLOBAL,
85
+ ),
86
+ lazy="selectin",
87
+ cascade="all, delete-orphan",
88
+ )
89
+
90
+ # IANA name of the timezone the user's browser reports. Calendar views
91
+ # (days, "yesterday", "this month") are in this timezone.
92
+ timezone: Mapped[str] = mapped_column(
93
+ String(64), default="UTC", server_default="UTC"
94
+ )
95
+
96
+ @classmethod
97
+ def new(
98
+ cls,
99
+ email: str,
100
+ username: str,
101
+ password: str | None = None,
102
+ *,
103
+ roles: tuple[Role, ...] = (),
104
+ **fields: object,
105
+ ) -> User:
106
+ """A new account, with its subject and roles: not added to any
107
+ session. Without a password, no password signs it in. Raises
108
+ ValueError for an email that isn't one."""
109
+ email = parse_email(email)
110
+ user_id = uuid4()
111
+ # The same id on both sides: one less thing to tell apart in the
112
+ # database. Nothing relies on it: the link is `subject_id`.
113
+ user = cls(
114
+ id=user_id,
115
+ username=username,
116
+ subject=Subject(id=str(user_id), email=email, is_active=True),
117
+ **fields,
118
+ )
119
+ if password is not None:
120
+ user.set_password(password)
121
+ for role in roles:
122
+ user.grant(role)
123
+ return user
124
+
125
+ def _assignment(self, role: Role) -> RoleAssignment | None:
126
+ """NeoZen keeps one per role, expired or not."""
127
+ return next(
128
+ (
129
+ a
130
+ for a in self.role_assignments
131
+ if a.role_id == ROLE_IDS[role] and a.scope_type == ScopeType.GLOBAL
132
+ ),
133
+ None,
134
+ )
135
+
136
+ def has_role(self, role: Role) -> bool:
137
+ """Whether the account holds the role on the instance, unexpired."""
138
+ held = self._assignment(role)
139
+ return held is not None and (
140
+ held.expires_at is None or as_utc(held.expires_at) > utcnow()
141
+ )
142
+
143
+ @property
144
+ def is_superuser(self) -> bool:
145
+ """An administrator: manages accounts and the instance's rules."""
146
+ return self.has_role(Role.ADMINISTRATOR)
147
+
148
+ @property
149
+ def is_staff(self) -> bool:
150
+ """Sees the staff pages; administrators do too."""
151
+ return self.is_superuser or self.has_role(Role.STAFF)
152
+
153
+ def grant(self, role: Role) -> None:
154
+ """Give the account a role on the instance; an expired one again."""
155
+ if self.has_role(role):
156
+ return
157
+ held = self._assignment(role)
158
+ if held is not None:
159
+ held.granted_at, held.expires_at = utcnow(), None
160
+ return
161
+ # As NeoZen's RoleService.assign_role makes them.
162
+ self.role_assignments.append(
163
+ RoleAssignment(
164
+ id=generate_token(prefix="role_"),
165
+ role_id=ROLE_IDS[role],
166
+ scope_type=ScopeType.GLOBAL,
167
+ granted_at=utcnow(),
168
+ )
169
+ )
170
+
171
+ def revoke(self, role: Role) -> None:
172
+ """Take a role on the instance back from the account."""
173
+ held = self._assignment(role)
174
+ if held is not None:
175
+ self.role_assignments.remove(held)
176
+
177
+ @property
178
+ def email(self) -> str:
179
+ return self.subject.email
180
+
181
+ @property
182
+ def is_active(self) -> bool:
183
+ """Whether the account may sign in, and its sessions count."""
184
+ return self.subject.is_active
185
+
186
+ @is_active.setter
187
+ def is_active(self, active: bool) -> None:
188
+ self.subject.is_active = active
189
+
190
+ @property
191
+ def has_password(self) -> bool:
192
+ """Whether a password can sign the account in: one made through the
193
+ identity provider has none until it is given one."""
194
+ return self.subject.hashed_password is not None
195
+
196
+ def set_password(self, password: str) -> None:
197
+ """Set the user's password (hashed). Ending the account's other
198
+ sessions is the caller's: see `passerby.accounts.sessions`."""
199
+ self.subject.hashed_password = PASSWORDS.hash(password)
200
+ self.subject.password_changed_at = utcnow()
201
+
202
+ def check_password(self, password: str) -> bool:
203
+ """Whether this is the user's password. A hash in a format no
204
+ longer read (PBKDF2) matches nothing."""
205
+ hashed = self.subject.hashed_password
206
+ if hashed is None:
207
+ return False
208
+ try:
209
+ return PASSWORDS.verify(password, hashed)
210
+ except UnknownHashError:
211
+ return False
212
+
213
+ def generate_api_token(
214
+ self, expires_in_days: int = 365, *, writes: bool = False
215
+ ) -> str:
216
+ """Generate a new API token, that only reads unless it `writes`.
217
+
218
+ The plaintext token is returned once and should be shown to the user.
219
+ Only the hash is stored in the database.
220
+ """
221
+ token = secrets.token_urlsafe(32)
222
+ self.api_token_hash = hash_api_token(token)
223
+ self.api_token_expires_at = utcnow() + timedelta(days=expires_in_days)
224
+ self.api_token_writes = writes
225
+ return token
226
+
227
+ def revoke_api_token(self) -> None:
228
+ """Revoke the current API token."""
229
+ self.api_token_hash = None
230
+ self.api_token_expires_at = None
231
+ self.api_token_writes = False
232
+
233
+ def __repr__(self) -> str:
234
+ return f"<User {self.username}>"
235
+
236
+
237
+ def user_with_email(email: str) -> Select[tuple[User]]:
238
+ """The account with this email, to look up (emails are unique)."""
239
+ return (
240
+ select(User).join(User.subject).where(Subject.email == normalize_email(email))
241
+ )
242
+
243
+
244
+ def users_by_email() -> Select[tuple[User]]:
245
+ """Every account, in the order of their emails."""
246
+ return select(User).join(User.subject).order_by(Subject.email)
@@ -0,0 +1,259 @@
1
+ """Signing in through the instance's identity provider (OpenID Connect).
2
+
3
+ NeoZen does the protocol: the state, the code's exchange, the ID token's
4
+ verification. The rules here are ours: which account an identity opens.
5
+
6
+ - An identity already linked to an account opens it, whatever its email has
7
+ become: the provider's own identifier is what counts.
8
+ - Else its email does, if the provider verified it and its domain is one the
9
+ settings allow: either alone would let in whoever can type an address. It
10
+ opens the account with that email, or a new one, and is linked to it.
11
+ - Never an administrator's, nor staff's: whoever runs the provider would
12
+ become one. They link their identity themselves, from their account page.
13
+
14
+ Nothing is written before the last check: a refused sign-in commits too (the
15
+ state it spent), with the redirect that says why.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import logging
22
+ from enum import StrEnum
23
+ from typing import TYPE_CHECKING
24
+
25
+ from neozen.core.oauth_client import (
26
+ OAuthClientError,
27
+ OAuthClientService,
28
+ OIDCProvider,
29
+ )
30
+ from neozen.core.utils import hex_id
31
+ from neozen.storage.sqlalchemy.repositories import (
32
+ OAuthStateRepository,
33
+ SocialAccountRepository,
34
+ )
35
+ from sqlalchemy import select
36
+
37
+ from passerby.accounts.models import User, normalize_email, user_with_email
38
+ from passerby.accounts.users import create_user
39
+
40
+ if TYPE_CHECKING:
41
+ import httpx
42
+ from neozen.core.oauth_client import (
43
+ AuthorizationResult,
44
+ CallbackResult,
45
+ OAuthUserInfo,
46
+ )
47
+ from neozen.storage.sqlalchemy.models import SocialAccount
48
+ from sqlalchemy.ext.asyncio import AsyncSession
49
+
50
+ from passerby.config import Settings
51
+
52
+ log = logging.getLogger(__name__)
53
+
54
+ CALLBACK_PATH = "/auth/oidc/callback"
55
+
56
+
57
+ class Refusal(StrEnum):
58
+ """Why a sign-in through the provider, or a link to it, is refused."""
59
+
60
+ FAILED = "failed"
61
+ UNVERIFIED = "unverified"
62
+ DOMAIN = "domain"
63
+ STAFF = "staff"
64
+ INACTIVE = "inactive"
65
+ OTHER_IDENTITY = "other-identity"
66
+ OTHER_ACCOUNT = "other-account"
67
+
68
+
69
+ # As the person reads them; {name} is the provider's (OIDC_NAME).
70
+ REASONS = {
71
+ Refusal.FAILED: "Signing in with {name} didn't work: try again.",
72
+ Refusal.UNVERIFIED: "Signing in with {name} gave no verified email address.",
73
+ Refusal.DOMAIN: "Your email address is outside the domains that may sign in with {name}. An administrator can create an account for you.",
74
+ Refusal.STAFF: "This account has administration rights: sign in with its password, then link {name} from its account page.",
75
+ Refusal.INACTIVE: "This account is deactivated.",
76
+ Refusal.OTHER_IDENTITY: "This account is linked to another identity of {name}: unlink that one first, from its account page.",
77
+ Refusal.OTHER_ACCOUNT: "This identity of {name} opens another account.",
78
+ }
79
+
80
+
81
+ class SignInRefusedError(Exception):
82
+ """The identity opens no account; the reason says why."""
83
+
84
+ def __init__(self, reason: Refusal) -> None:
85
+ super().__init__(reason)
86
+ self.reason = reason
87
+
88
+
89
+ def provider_id(issuer: str) -> str:
90
+ """What NeoZen stores identities under, 32 characters at most. It names
91
+ the issuer: an identifier means nothing at another, where it may be
92
+ someone else's."""
93
+ return f"oidc-{hashlib.sha256(issuer.encode()).hexdigest()[:24]}"
94
+
95
+
96
+ class IdentityProvider:
97
+ """The provider the settings name. Its discovery document is read once
98
+ per process, at the first sign-in, and so are its keys, until a token is
99
+ signed with a new one."""
100
+
101
+ def __init__(self, settings: Settings, http: httpx.AsyncClient) -> None:
102
+ self._settings = settings
103
+ self._http = http
104
+ self._discovered: OIDCProvider | None = None
105
+ self.id = provider_id(settings.oidc_issuer)
106
+
107
+ async def discovered(self) -> OIDCProvider:
108
+ """OAuthClientError if it can't be reached, or isn't that issuer."""
109
+ if self._discovered is None:
110
+ self._discovered = await OIDCProvider.discover(
111
+ self._settings.oidc_issuer,
112
+ self._settings.oidc_client_id,
113
+ self._settings.oidc_client_secret,
114
+ http_client=self._http,
115
+ provider_id=self.id,
116
+ scopes=["openid", "email"],
117
+ trust_email=self._settings.oidc_trust_email,
118
+ )
119
+ return self._discovered
120
+
121
+
122
+ class Identities:
123
+ """The accounts' identities at the provider, in the caller's database
124
+ session."""
125
+
126
+ def __init__(
127
+ self, db: AsyncSession, settings: Settings, provider: IdentityProvider
128
+ ) -> None:
129
+ self._db = db
130
+ self._settings = settings
131
+ self._provider = provider
132
+ self._links = SocialAccountRepository(session=db)
133
+ self._service = OAuthClientService(
134
+ state_repository=OAuthStateRepository(session=db),
135
+ social_account_repository=self._links,
136
+ )
137
+
138
+ async def begin(self, *, link_to: User | None = None) -> AuthorizationResult:
139
+ """Where to send the browser, and the state it must bring back: to
140
+ sign in, or to link the identity to an account."""
141
+ try:
142
+ await self._discover()
143
+ except OAuthClientError as e:
144
+ raise self._failed(e) from e
145
+ return await self._service.begin_authorization(
146
+ self._provider.id,
147
+ self._settings.public_url.rstrip("/") + CALLBACK_PATH,
148
+ existing_subject_id=link_to.subject_id if link_to else None,
149
+ )
150
+
151
+ async def receive(
152
+ self, code: str, state: str, *, browser_state: str | None, error: str
153
+ ) -> CallbackResult:
154
+ """Who the provider says this is, once its answer is verified."""
155
+ try:
156
+ await self._discover()
157
+ return await self._service.handle_callback(
158
+ self._provider.id,
159
+ code,
160
+ state,
161
+ browser_state=browser_state,
162
+ error=error,
163
+ )
164
+ except OAuthClientError as e:
165
+ raise self._failed(e) from e
166
+
167
+ async def account_of(self, who: OAuthUserInfo) -> User:
168
+ """The active account the identity opens; linked to it, from its
169
+ first sign-in on."""
170
+ user = await self._linked_user(who)
171
+ if user is None:
172
+ return await self._first_sign_in(who)
173
+ if not user.is_active:
174
+ raise SignInRefusedError(Refusal.INACTIVE)
175
+ return user
176
+
177
+ async def link(self, signed_in: User | None, result: CallbackResult) -> None:
178
+ """Have the identity open the account that asked for it: the one
179
+ still signed in, or the link would be another person's doing."""
180
+ if signed_in is None or signed_in.subject_id != result.existing_subject_id:
181
+ raise SignInRefusedError(Refusal.FAILED)
182
+ linked = await self._linked_user(result.user_info)
183
+ if linked is None:
184
+ await self._add_link(signed_in, result.user_info)
185
+ elif linked.id != signed_in.id:
186
+ raise SignInRefusedError(Refusal.OTHER_ACCOUNT)
187
+
188
+ async def linked(self, user: User) -> SocialAccount | None:
189
+ """The account's identity at the provider, if it has one."""
190
+ return await self._links.get_one_or_none(
191
+ subject_id=user.subject_id, provider_id=self._provider.id
192
+ )
193
+
194
+ async def unlink(self, user: User) -> None:
195
+ await self._service.unlink_account(user.subject_id, self._provider.id)
196
+
197
+ async def _discover(self) -> None:
198
+ self._service.register_provider_instance(await self._provider.discovered())
199
+
200
+ async def _linked_user(self, who: OAuthUserInfo) -> User | None:
201
+ link = await self._links.get_one_or_none(
202
+ provider_id=self._provider.id, provider_user_id=who.provider_user_id
203
+ )
204
+ if link is None:
205
+ return None
206
+ return await self._db.scalar(
207
+ select(User).where(User.subject_id == link.subject_id)
208
+ )
209
+
210
+ async def _first_sign_in(self, who: OAuthUserInfo) -> User:
211
+ email = self._trusted_email(who)
212
+ user = await self._db.scalar(user_with_email(email))
213
+ if user is None:
214
+ user = await self._new_account(email)
215
+ elif not user.is_active:
216
+ raise SignInRefusedError(Refusal.INACTIVE)
217
+ elif user.is_staff:
218
+ raise SignInRefusedError(Refusal.STAFF)
219
+ await self._add_link(user, who)
220
+ return user
221
+
222
+ def _trusted_email(self, who: OAuthUserInfo) -> str:
223
+ """The identity's email, as one that may open an account."""
224
+ if not who.email or not who.email_verified:
225
+ raise SignInRefusedError(Refusal.UNVERIFIED)
226
+ email = normalize_email(who.email)
227
+ if email.rpartition("@")[2] not in self._settings.oidc_domains:
228
+ raise SignInRefusedError(Refusal.DOMAIN)
229
+ return email
230
+
231
+ async def _new_account(self, email: str) -> User:
232
+ """An account without a password. Its username is the email's local
233
+ part, or all of it if that is taken."""
234
+ local_part = email.partition("@")[0]
235
+ taken = await self._db.scalar(
236
+ select(User.id).where(User.username == local_part)
237
+ )
238
+ return await create_user(
239
+ self._db, email, None, username=email if taken else local_part
240
+ )
241
+
242
+ async def _add_link(self, user: User, who: OAuthUserInfo) -> None:
243
+ """Only which identity it is: NeoZen's `link_account` would keep the
244
+ provider's tokens too, which the app has no use for."""
245
+ if await self.linked(user):
246
+ raise SignInRefusedError(Refusal.OTHER_IDENTITY)
247
+ await self._links.create(
248
+ id=hex_id(),
249
+ subject_id=user.subject_id,
250
+ provider_id=self._provider.id,
251
+ provider_user_id=who.provider_user_id,
252
+ email=who.email,
253
+ )
254
+
255
+ def _failed(self, error: OAuthClientError) -> SignInRefusedError:
256
+ """For the operator, what failed; for the person, that it did. As a
257
+ repr: some of it may come from the request."""
258
+ log.warning("sign-in with %s failed: %r", self._settings.oidc_issuer, error)
259
+ return SignInRefusedError(Refusal.FAILED)
@@ -0,0 +1,96 @@
1
+ """The roles, as NeoZen keeps them: the instance's, held everywhere, and
2
+ those held in an organization, or on one project."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from enum import StrEnum
7
+ from typing import TypedDict
8
+
9
+ from neozen.core.authz.models import BUILTIN_ROLES, OWNER_ROLE
10
+
11
+
12
+ class Role(StrEnum):
13
+ """The instance's roles. They run the instance, and open no project: an
14
+ administrator reads those of the organizations they belong to, as anyone
15
+ does. (NeoZen's own `superuser` would open every one: nobody holds it.)"""
16
+
17
+ STAFF = "staff" # sees how the instance runs (/admin/health)
18
+ ADMINISTRATOR = "administrator" # and manages accounts and the rules
19
+
20
+
21
+ class MemberRole(StrEnum):
22
+ """The roles in an organization, over all its projects. A viewer's may
23
+ be given on one project too, to someone outside the organization."""
24
+
25
+ VIEWER = "viewer"
26
+ EDITOR = "editor"
27
+ OWNER = OWNER_ROLE
28
+
29
+
30
+ class Permission(StrEnum):
31
+ """What a role lets one do: with a project, or in an organization."""
32
+
33
+ READ = "project:read" # its report
34
+ UPDATE = "project:update" # its settings, visit log and share links
35
+ CREATE = "project:create"
36
+ DELETE = "project:delete"
37
+ INVITE = "member:invite"
38
+ RENAME = "organization:update"
39
+
40
+
41
+ class StoredRole(TypedDict):
42
+ """A row of NeoZen's `roles` table."""
43
+
44
+ id: str
45
+ name: str
46
+ description: str
47
+ permissions: str # separated by commas
48
+ is_system: bool
49
+
50
+
51
+ def _row(
52
+ role: StrEnum, description: str, *permissions: str, is_system: bool
53
+ ) -> StoredRole:
54
+ return {
55
+ "id": f"analytics:{role}",
56
+ "name": str(role),
57
+ "description": description,
58
+ "permissions": ",".join(permissions),
59
+ "is_system": is_system,
60
+ }
61
+
62
+
63
+ _OWNER = BUILTIN_ROLES[OWNER_ROLE]
64
+
65
+ # The rows of NeoZen's `roles` table for them: the migrations add them, as do
66
+ # the tests' tables. A system role is one NeoZen gives in no organization.
67
+ ROLE_ROWS: list[StoredRole] = [
68
+ _row(
69
+ Role.ADMINISTRATOR,
70
+ "Manages the instance",
71
+ "instance:read",
72
+ "instance:manage",
73
+ is_system=True,
74
+ ),
75
+ _row(Role.STAFF, "Sees how the instance runs", "instance:read", is_system=True),
76
+ _row(MemberRole.VIEWER, "Reads the reports", Permission.READ, is_system=False),
77
+ _row(
78
+ MemberRole.EDITOR,
79
+ "Creates and sets up projects, and shares them",
80
+ Permission.READ,
81
+ Permission.UPDATE,
82
+ Permission.CREATE,
83
+ "access:grant",
84
+ "access:revoke",
85
+ is_system=False,
86
+ ),
87
+ # NeoZen's, and every permission on the projects.
88
+ {
89
+ "id": _OWNER.id,
90
+ "name": _OWNER.name,
91
+ "description": _OWNER.description,
92
+ "permissions": ",".join([*sorted(_OWNER.permissions), "project:*"]),
93
+ "is_system": True,
94
+ },
95
+ ]
96
+ ROLE_IDS = {row["name"]: row["id"] for row in ROLE_ROWS}
@@ -0,0 +1,68 @@
1
+ """Sign-in sessions: NeoZen's, as rows in the database, in the caller's
2
+ own database session (the request's, or the command line's), so that they
3
+ commit, or not, with the rest of its work."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from contextlib import suppress
8
+ from datetime import timedelta
9
+ from typing import TYPE_CHECKING
10
+
11
+ from neozen.core.session.service import SessionError, SessionNotFoundError
12
+ from neozen.storage.sqlalchemy.factories import session_service
13
+ from sqlalchemy import select
14
+
15
+ from passerby.accounts.models import User
16
+
17
+ if TYPE_CHECKING:
18
+ from sqlalchemy.ext.asyncio import AsyncSession
19
+
20
+ from passerby.config import Settings
21
+
22
+
23
+ class Sessions:
24
+ """Beginning, reading and ending accounts' sessions. A token is what the
25
+ browser's cookie holds; the database keeps its hash."""
26
+
27
+ def __init__(self, db: AsyncSession, settings: Settings) -> None:
28
+ self._db = db
29
+ self._service = session_service(
30
+ db,
31
+ settings.secret_key,
32
+ lifetime=timedelta(seconds=settings.auth_session_timeout),
33
+ )
34
+
35
+ async def begin(
36
+ self,
37
+ user: User,
38
+ *,
39
+ ip_address: str | None = None,
40
+ user_agent: str | None = None,
41
+ ) -> str:
42
+ """A new session for the user: its token."""
43
+ return await self._service.create_session(
44
+ user.subject_id, ip_address=ip_address, user_agent=user_agent
45
+ )
46
+
47
+ async def user_of(self, token: str) -> User | None:
48
+ """The active account a token signs in, or None: unknown, expired or
49
+ ended, or the account is deactivated. Reading a session writes
50
+ nothing (no sliding expiry), so a page view costs no write."""
51
+ try:
52
+ session = await self._service.validate_session(token, update_activity=False)
53
+ except SessionError:
54
+ return None
55
+ user = await self._db.scalar(
56
+ select(User).where(User.subject_id == session.subject_id)
57
+ )
58
+ return user if user is not None and user.is_active else None
59
+
60
+ async def end(self, token: str) -> None:
61
+ """End one session (signing out). An unknown one is already over."""
62
+ with suppress(SessionNotFoundError):
63
+ await self._service.revoke_session_by_token(token)
64
+
65
+ async def end_all(self, user: User) -> int:
66
+ """End every session of the user: after a password change, a
67
+ reset, or "sign out everywhere". How many were ended."""
68
+ return await self._service.revoke_all_sessions(user.subject_id)