Compare commits
272
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
146bfaf45e | ||
|
|
b761136dd9 | ||
|
|
ac39740acb | ||
|
|
a4b6aa5357 | ||
|
|
d7c812ba07 | ||
|
|
34f2eeddd7 | ||
|
|
347f2cf720 | ||
|
|
3c36bdf2a9 | ||
|
|
3ed4d75898 | ||
|
|
637a8aed13 | ||
|
|
f24f0c32f4 | ||
|
|
66b765d81d | ||
|
|
504200e011 | ||
|
|
f39a84ac14 | ||
|
|
dc7c381bd8 | ||
|
|
96c0866c67 | ||
|
|
3a2d6088f2 | ||
|
|
c57dbdb62e | ||
|
|
ac2ba4d2c1 | ||
|
|
a215b5f9c9 | ||
|
|
4554bf3251 | ||
|
|
89e5ae6273 | ||
|
|
90b94904e8 | ||
|
|
c9726f4029 | ||
|
|
5a0a3decbe | ||
|
|
59d228b8d3 | ||
|
|
816494aee0 | ||
|
|
5f3519d0af | ||
|
|
1ea7cfc773 | ||
|
|
649392d2e8 | ||
|
|
1f1d555125 | ||
|
|
4af22ca4c4 | ||
|
|
6b46dfee90 | ||
|
|
e4d9d7bf49 | ||
|
|
cddab4d759 | ||
|
|
0ae9634f70 | ||
|
|
e6db73c6bb | ||
|
|
58b9a52e01 | ||
|
|
9023496e94 | ||
|
|
549a86a48c | ||
|
|
f7f6946207 | ||
|
|
a814a5f7f9 | ||
|
|
a135560899 | ||
|
|
1216d9a873 | ||
|
|
9b90f89135 | ||
|
|
78bd79a933 | ||
|
|
d941961549 | ||
|
|
422bb1862a | ||
|
|
ea0f728af2 | ||
|
|
d51fa55a1d | ||
|
|
ffe62d3c78 | ||
|
|
35735d67a5 | ||
|
|
af4135ac36 | ||
|
|
85e8e62e5b | ||
|
|
265fae993f | ||
|
|
27b0ea564a | ||
|
|
6041c0cdb2 | ||
|
|
e9d0fd259a | ||
|
|
34547075cf | ||
|
|
bed7f03063 | ||
|
|
6f6261eb1f | ||
|
|
0a6939fe07 | ||
|
|
5c494cb261 | ||
|
|
b1022eb02a | ||
|
|
66a770ae10 | ||
|
|
64d1ea5093 | ||
|
|
a98db6e36e | ||
|
|
2cde368c1e | ||
|
|
0458e8e5a5 | ||
|
|
9c10e627fc | ||
|
|
cbf5a6870b | ||
|
|
5a7380686c | ||
|
|
27929987b2 | ||
|
|
241ac800c6 | ||
|
|
b1f5a30272 | ||
|
|
2a77b0c988 | ||
|
|
e15a01c338 | ||
|
|
9af0604f47 | ||
|
|
0d5ffede05 | ||
|
|
b30e2c8080 | ||
|
|
c92d8979eb | ||
|
|
c13880cfab | ||
|
|
c0ef046b0d | ||
|
|
1c1fced5ba | ||
|
|
dac8f2c9ea | ||
|
|
e2eaa7ae40 | ||
|
|
bb0a02dcd9 | ||
|
|
06e7ae0ea5 | ||
|
|
bf1e5f013b | ||
|
|
13b6131652 | ||
|
|
f258a22aa3 | ||
|
|
eaaabf3763 | ||
|
|
d117da3dc6 | ||
|
|
9f7934121f | ||
|
|
2e40387245 | ||
|
|
6c82d7d689 | ||
|
|
c174fa2ffe | ||
|
|
711371f9d7 | ||
|
|
f2b6153aa6 | ||
|
|
d69c518b47 | ||
|
|
5868ca82e8 | ||
|
|
32e744d9ee | ||
|
|
9c53e5e727 | ||
|
|
f45e4ef305 | ||
|
|
5705d02792 | ||
|
|
0e825e6d61 | ||
|
|
de0f5c13c4 | ||
|
|
3c64b150db | ||
|
|
afffd52dec | ||
|
|
cad5897e9a | ||
|
|
8405fd9157 | ||
|
|
cf3dbb7489 | ||
|
|
022e193cc2 | ||
|
|
58214be0db | ||
|
|
62a59477c6 | ||
|
|
9494ed6d0c | ||
|
|
2954fe609f | ||
|
|
1d102a4754 | ||
|
|
88ca8bfe18 | ||
|
|
f592e5b7b5 | ||
|
|
285aa66525 | ||
|
|
f1a86d9d76 | ||
|
|
6be8e2d632 | ||
|
|
0f12c63f5e | ||
|
|
6f5e479900 | ||
|
|
3493227880 | ||
|
|
ed50031663 | ||
|
|
7a63b3a728 | ||
|
|
6220812e08 | ||
|
|
0293d66c1e | ||
|
|
93184b6011 | ||
|
|
27f9cc06b2 | ||
|
|
8af8e39c0b | ||
|
|
526d98be17 | ||
|
|
40fb75a34b | ||
|
|
9c441dc0aa | ||
|
|
e704123f22 | ||
|
|
0b0bdaab6f | ||
|
|
0bc3cd65e7 | ||
|
|
c6eb2b44e8 | ||
|
|
103766eb74 | ||
|
|
6d9074eefe | ||
|
|
73d8c61aa7 | ||
|
|
2d2d191e11 | ||
|
|
f44c4bb6bd | ||
|
|
dcce9fcb35 | ||
|
|
3cc2fad1dd | ||
|
|
ed66d73327 | ||
|
|
a88ca860d4 | ||
|
|
8720d623ea | ||
|
|
00f60f1374 | ||
|
|
1127b41ba3 | ||
|
|
ce1bc7bee6 | ||
|
|
8a9222033d | ||
|
|
d63f702ec3 | ||
|
|
2b501b75be | ||
|
|
b9561a49d2 | ||
|
|
0f32c3a868 | ||
|
|
22c0167978 | ||
|
|
f0d67e7efa | ||
|
|
e6ab177a05 | ||
|
|
48128ab97b | ||
|
|
6337bcfc24 | ||
|
|
11a74d955e | ||
|
|
e103e6779b | ||
|
|
ed1e361b14 | ||
|
|
db64dac235 | ||
|
|
c468b61d3e | ||
|
|
f7bbec8a0a | ||
|
|
17329c5d6f | ||
|
|
120a24678d | ||
|
|
947e4d3cf2 | ||
|
|
8c85c912e8 | ||
|
|
ee7ed77697 | ||
|
|
f1945aaf53 | ||
|
|
97da432bd4 | ||
|
|
a8200fdf54 | ||
|
|
36b7c2f77e | ||
|
|
a984a443e1 | ||
|
|
86e77a0ad4 | ||
|
|
ced8c4f082 | ||
|
|
75959e6045 | ||
|
|
5237e6352b | ||
|
|
f68e4fb652 | ||
|
|
a8bdb70e08 | ||
|
|
326fec9214 | ||
|
|
d878c32d68 | ||
|
|
ea4660690d | ||
|
|
f8b3eaacd6 | ||
|
|
985b55f6d9 | ||
|
|
ccce643b39 | ||
|
|
5da1981823 | ||
|
|
a89c464834 | ||
|
|
d5b4a2e03a | ||
|
|
c53112fbaf | ||
|
|
8bcb7ff049 | ||
|
|
ea648aab95 | ||
|
|
f45ca199cf | ||
|
|
8fc670b240 | ||
|
|
5f8bed33e6 | ||
|
|
ddeefdebe0 | ||
|
|
6a7eaf0ff8 | ||
|
|
b065b7301f | ||
|
|
abdc56e84c | ||
|
|
e1ec25f1e4 | ||
|
|
5beffaf7d5 | ||
|
|
6f6957c779 | ||
|
|
d2b6f1551f | ||
|
|
b998d8d535 | ||
|
|
c21421a89b | ||
|
|
7d2507a927 | ||
|
|
26be6156ae | ||
|
|
bb864055e6 | ||
|
|
d5fbb2ed84 | ||
|
|
49e79aadcc | ||
|
|
87e7c5b30e | ||
|
|
76d59b3fb6 | ||
|
|
6475a51067 | ||
|
|
e5c6b6060e | ||
|
|
9f198fcf4c | ||
|
|
a0040f52e0 | ||
|
|
592cf83656 | ||
|
|
b11552fa49 | ||
|
|
42cf43a125 | ||
|
|
42bdfa25d3 | ||
|
|
d5a7a72416 | ||
|
|
ceeaf277e2 | ||
|
|
a5410ac237 | ||
|
|
4a48529cbb | ||
|
|
8ee1c8cea5 | ||
|
|
3ee385de12 | ||
|
|
ac3d79a1df | ||
|
|
a0d15e30d8 | ||
|
|
e773c5097f | ||
|
|
0ae1404ab5 | ||
|
|
997d047323 | ||
|
|
8e9906d844 | ||
|
|
89593cfa74 | ||
|
|
af610fe25f | ||
|
|
5a9b0d2b0d | ||
|
|
27d30a1af2 | ||
|
|
acd01afc99 | ||
|
|
4ffadd223c | ||
|
|
6ab0554d00 | ||
|
|
1cf78c4e56 | ||
|
|
c5d5fa2fac | ||
|
|
27c32fc75f | ||
|
|
80de75672c | ||
|
|
70ae435867 | ||
|
|
403a773f53 | ||
|
|
452a27a778 | ||
|
|
c2369034ee | ||
|
|
5720a63958 | ||
|
|
e55d8a3f1e | ||
|
|
250ca6e8f0 | ||
|
|
9495daa701 | ||
|
|
7bb676eb68 | ||
|
|
ac0bdb6518 | ||
|
|
492019088e | ||
|
|
178a4aa360 | ||
|
|
e24c272e2e | ||
|
|
d8d80d9594 | ||
|
|
e4da4da2c6 | ||
|
|
42c664c076 | ||
|
|
fed4a7005e | ||
|
|
d87cbf9650 | ||
|
|
dcffbb1b98 | ||
|
|
394cccfbcb | ||
|
|
72614f8f19 | ||
|
|
5425efee1f | ||
|
|
fd13bc6ea2 | ||
|
|
97ebe69553 |
No files matched your search
@@ -0,0 +1,51 @@
|
|||||||
|
# Woodpecker CI pipeline for the member portal — THIN on purpose.
|
||||||
|
#
|
||||||
|
# Runs the portal's EXISTING test suites (tests/test_*.py, one self-contained
|
||||||
|
# script per regression, each with its own "WHY THIS EXISTS" docstring). No
|
||||||
|
# test logic lives here; any change to what is tested belongs in tests/.
|
||||||
|
#
|
||||||
|
# Gating: `push` fires the suite on every push (including branch pushes), so a
|
||||||
|
# red run blocks the merge via Gitea branch protection (status check
|
||||||
|
# `ci/woodpecker/push/main`). `manual` is kept so a run can be triggered by
|
||||||
|
# hand from the Woodpecker UI or API.
|
||||||
|
#
|
||||||
|
# Backend note (why there are no container images here):
|
||||||
|
# The co-op's Woodpecker agent is a Cloudron app with no Docker socket, so it
|
||||||
|
# runs the `local` backend — each step executes as a shell command INSIDE the
|
||||||
|
# agent container and the step's `image:` field selects the SHELL, not a
|
||||||
|
# container image. Every tool a step needs must be baked into the agent image
|
||||||
|
# (co-op/woodpecker-agent): python3 + pip, node, bash, git, git-lfs.
|
||||||
|
#
|
||||||
|
# Dependency note (why not `-r requirements.txt`):
|
||||||
|
# The agent image's Python is 3.14, where the app image's PINNED stack has no
|
||||||
|
# published wheels (pydantic 2.9.2 / psycopg2-binary 2.9.9). The tests import
|
||||||
|
# app.main, which at import time needs only the bounded ranges below; the
|
||||||
|
# heavier runtime deps (uvicorn, psycopg2) are lazy-imported and unneeded by
|
||||||
|
# the suites. Ranges, not floating, so a future major cannot silently change
|
||||||
|
# what CI proves — a major bump shows up as a red run here first.
|
||||||
|
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
- event: manual
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: tests
|
||||||
|
image: bash
|
||||||
|
commands:
|
||||||
|
# venv on the writable volume — the container rootfs is read-only and
|
||||||
|
# pip refuses to write /root/.local.
|
||||||
|
- python3 -m venv .venv
|
||||||
|
- .venv/bin/pip -q install 'fastapi>=0.115,<1' 'httpx>=0.27,<1' 'PyJWT>=2.9,<3' 'slowapi>=0.1.9,<1' 'cryptography>=44,<46'
|
||||||
|
# Run EVERY suite even when one fails, then fail the step — a single
|
||||||
|
# command chain would hide all failures after the first.
|
||||||
|
- |
|
||||||
|
fails=0
|
||||||
|
for f in tests/test_*.py; do
|
||||||
|
echo "== $f"
|
||||||
|
.venv/bin/python "$f" || fails=$((fails+1))
|
||||||
|
done
|
||||||
|
if [ "$fails" -ne 0 ]; then
|
||||||
|
echo "FAILED: $fails test file(s) red"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "all portal test suites green"
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# CI config is privileged: a change here can alter what runs in the shared
|
||||||
|
# Woodpecker agent container. Require an Owners review before merge.
|
||||||
|
^\.woodpecker\.yml$ @co-op/owners
|
||||||
+14
-9
@@ -14,17 +14,22 @@
|
|||||||
},
|
},
|
||||||
"sendmail": {},
|
"sendmail": {},
|
||||||
"scheduler": {
|
"scheduler": {
|
||||||
"membership_sweep": {
|
"membership_sweep": {
|
||||||
"schedule": "0 3 * * *",
|
"schedule": "0 3,11,19 * * *",
|
||||||
"command": "/app/code/sweep.sh"
|
"command": "/app/code/sweep.sh"
|
||||||
},
|
},
|
||||||
"rag_refresh": {
|
"service_sync": {
|
||||||
"schedule": "30 3 * * *",
|
"schedule": "*/5 * * * *",
|
||||||
"command": "/app/code/rag_refresh.py"
|
"command": "/app/code/service_sync.sh"
|
||||||
}
|
},
|
||||||
|
"metrics_snapshot": {
|
||||||
|
"schedule": "15 3 * * *",
|
||||||
|
"command": "/app/code/metrics_snapshot.py"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"manifestVersion": 2,
|
"manifestVersion": 2,
|
||||||
"website": "https://inference.coop",
|
"website": "https://inference.coop",
|
||||||
"contactEmail": "info@inference.coop"
|
"contactEmail": "info@inference.coop",
|
||||||
|
"dockerImage": "registry.inference.coop/code/member-portal:20261121-b761136"
|
||||||
}
|
}
|
||||||
+4
-3
@@ -9,8 +9,9 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|||||||
# Copy app
|
# Copy app
|
||||||
COPY app/ ./app/
|
COPY app/ ./app/
|
||||||
COPY sweep.sh /app/code/sweep.sh
|
COPY sweep.sh /app/code/sweep.sh
|
||||||
COPY rag_refresh.py /app/code/rag_refresh.py
|
COPY service_sync.sh /app/code/service_sync.sh
|
||||||
RUN chmod +x /app/code/sweep.sh /app/code/rag_refresh.py
|
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
|
||||||
|
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/metrics_snapshot.py
|
||||||
|
|
||||||
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
||||||
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
||||||
@@ -20,4 +21,4 @@ RUN mkdir -p /app/data
|
|||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
|
|
||||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--forwarded-allow-ips=172.18.0.1"]
|
||||||
@@ -30,7 +30,18 @@ LibreChat ──→ Member Portal ──→ LiteLLM ──→ backend
|
|||||||
## The three responsibilities
|
## The three responsibilities
|
||||||
|
|
||||||
1. **Webhook handler** (`POST /webhook/opencollective`) — listens for Open
|
1. **Webhook handler** (`POST /webhook/opencollective`) — listens for Open
|
||||||
Collective membership events and activates/deactivates members.
|
Collective membership events and activates/deactivates members. The same
|
||||||
|
endpoint carries credit-pack purchases, so a failure here can cost a member
|
||||||
|
money: it answers **503** (retryable) with an ERROR line naming the exception
|
||||||
|
when anything unexpected escapes, and **401** when the URL token is wrong —
|
||||||
|
that status means the webhook URL and `WEBHOOK_TOKEN` disagree, so it is
|
||||||
|
never swallowed by the error net. Any OC read it makes has an explicit
|
||||||
|
timeout and one retry (`_oc_graphql_post`); until 2026-11-13
|
||||||
|
`fetch_all_member_nodes` used httpx's 5-second default and a slow page became
|
||||||
|
an unhandled 500 on a paid purchase. The durable backstop — reconciling PAID
|
||||||
|
credit packs against `credit_ledger` on a schedule — is not built yet; see
|
||||||
|
the app repo's issue *"Backstop: reconcile PAID credit packs against the
|
||||||
|
ledger"*.
|
||||||
2. **Key injector** (`/v1/*`) — reads the member's email from the
|
2. **Key injector** (`/v1/*`) — reads the member's email from the
|
||||||
`X-User-Email` header, looks up their LiteLLM key, and forwards the
|
`X-User-Email` header, looks up their LiteLLM key, and forwards the
|
||||||
request to the gateway with that key.
|
request to the gateway with that key.
|
||||||
@@ -45,32 +56,109 @@ LibreChat ──→ Member Portal ──→ LiteLLM ──→ backend
|
|||||||
| `MEMBERS_GROUP_ID` | Cloudron group ID for members (grants chat access) |
|
| `MEMBERS_GROUP_ID` | Cloudron group ID for members (grants chat access) |
|
||||||
| `LITELLM_BASE` | LiteLLM gateway URL |
|
| `LITELLM_BASE` | LiteLLM gateway URL |
|
||||||
| `LITELLM_MASTER_KEY` | LiteLLM master key |
|
| `LITELLM_MASTER_KEY` | LiteLLM master key |
|
||||||
| `OPENCOLLECTIVE_WEBHOOK_SECRET` | Optional webhook signature secret |
|
| `PORTAL_KEK` | **Required.** Base64-encoded 32-byte key-encryption key. Member chat keys (`members.key_token`) are stored AES-256-GCM-encrypted at rest (`enc1:` prefix) and decrypted in memory only when served (dashboard, LibreChat key feed, LiteLLM management). Generate with `python3 -c "import base64,os;print(base64.b64encode(os.urandom(32)).decode())"`. If unset, the portal runs but refuses to encrypt new keys, keeps legacy plaintext, and logs CRITICAL. Rotating it requires re-encrypting every row (decrypt with the old key, encrypt with the new). |
|
||||||
|
| `ADMIN_TOKEN` | The portal's admin token (`X-Admin-Token` header) for the `/admin/*` endpoints the panel calls. Never the webhook URL token — that one cannot unlock `/admin/*` by design. |
|
||||||
|
| `ALLOWANCE_POLICY` | `report` (default) \| `on`. `report` computes every allowance decision and changes nothing; `on` performs renewals and sends the one reminder. Deactivation is gated separately by `ALLOWANCE_DEACTIVATE`. |
|
||||||
|
| `ALLOWANCE_DEACTIVATE` | `off` (default) \| `on`. When `on`, a member who was reminded and is still unpaid after the grace window is moved to the inactive group. **Defaults off so renewals/reminders can run before anyone loses access.** |
|
||||||
|
| `PAYMENT_GRACE_DAYS` | Days after the single reminder before an unpaid member is deactivated (default `7`). |
|
||||||
|
| `GUEST_BUDGET` | Guest-account credit in USD (default `2.0`). |
|
||||||
|
| `GUEST_DAYS` | Guest-account time box in days from provisioning (default `60`). The sweep deactivates an expired guest even with credits left. |
|
||||||
|
| `GUEST_PER_INVITER_DAYS` | Rolling window for the one-guest-per-inviter limit (default `30`). |
|
||||||
|
| `GUESTS_GROUP_ID` | Cloudron group ID for guest accounts. The chat and dashboard apps' access restrictions list BOTH the members and guests groups, so a guest reaches exactly those two apps. |
|
||||||
|
| `GUESTS_ENDED_GROUP_ID` | Cloudron group a SELF-CANCELLED guest's user lands in: out of guests (chat access ends) but still admitted by the dashboard app, so the ended state and Become-a-member stay visible. Unset → the shared inactive group (dashboard access ends too). |
|
||||||
|
|
||||||
## Tier budgets
|
## Guest accounts
|
||||||
|
|
||||||
Governance decision (set in Loomio). Defaults:
|
A member can give a friend access to the co-op with $2 of credits — no Open
|
||||||
|
Collective membership required. `POST /admin/provision-guest` (X-Admin-Token)
|
||||||
|
with `{"email", "name", "inviter": "<the guest access member's email>"}` runs the
|
||||||
|
guest pipeline: Cloudron user in the **guests** group, a LiteLLM team capped at
|
||||||
|
`GUEST_BUDGET` with **no monthly reset** (the cap is the guest's whole life), the
|
||||||
|
portal row marked `account_type='guest'` with the $2 held as non-expiring
|
||||||
|
credit, `guest_expires_at` set to now + `GUEST_DAYS`, the guest welcome email
|
||||||
|
(setup link, what they can use, Become-a-member, newsletter note), and a
|
||||||
|
**guests ledger** row (`guests` table: inviter → recipient, expiry, status) for
|
||||||
|
the abuse audit. Guards: one guest per inviter per `GUEST_PER_INVITER_DAYS`; one
|
||||||
|
guest per recipient ever; the inviter must be an active member; an existing
|
||||||
|
portal row under the recipient address is refused. Guests are subscribed to
|
||||||
|
the newsletter and invited to NOTHING else (no Loomio, no Matrix).
|
||||||
|
|
||||||
- `free` — $2/month of tokens
|
**Member self-serve invitations (provision immediately).** `POST /broker/guests`
|
||||||
- `member` — $15/month
|
(the member-dashboard broker identity — a guest identity fails it) lets a MEMBER
|
||||||
- `supporter` — $30/month
|
invite a guest from their dashboard: `{"email", "name"}`. The same guards run
|
||||||
|
BEFORE anything is created (`guest_request_guard`: everything above, plus the
|
||||||
|
recipient is never a `MANUAL_MEMBERS` address), and a valid invitation
|
||||||
|
**provisions immediately** — the approval gate was removed on 2026-11-08 as
|
||||||
|
operator policy; the remaining protections (active member, one guest per
|
||||||
|
inviter per rolling 30 days, one guest per recipient ever, the $2 cap and the
|
||||||
|
`GUEST_DAYS` box) were judged sufficient. `provision_guest_member` re-runs
|
||||||
|
every guard, so a moved-state refusal still refuses. The member sees their
|
||||||
|
invitation trail — each guest with its status and expiry — via
|
||||||
|
`GET /broker/guests`.
|
||||||
|
|
||||||
## LibreChat wiring
|
**Sweep safety.** `reconcile_memberships()` never deactivates a guest for
|
||||||
|
lacking an OC contribution. A guest lapses only by its own rules, handled by
|
||||||
|
`reconcile_guest_lifecycles()` inside the sweep: credits spent out (LiteLLM's
|
||||||
|
cap enforces the limit; the sweep retires the row) or the `GUEST_DAYS` time box.
|
||||||
|
Deactivation is the same semantics as a member's — guests group → inactive,
|
||||||
|
budget zeroed, row `active=0`, newsletter unsubscribed — and the account is
|
||||||
|
KEPT so a returning payer resumes cleanly.
|
||||||
|
|
||||||
Point LibreChat's custom endpoint at this portal (not directly at LiteLLM),
|
**Self-service cancellation (recipient-initiated).** `POST /broker/cancel-guest`
|
||||||
and add the identity header:
|
(dashboard broker identity) ends a guest account at the recipient's own
|
||||||
|
request: deactivation with the same kept-account semantics, the newsletter
|
||||||
|
unsubscribed, and — the part a lapse does not do — any UNSPENT credit
|
||||||
|
returned to the co-op as a negative `credit_ledger` row whose reason names
|
||||||
|
the cancellation and the original guest reference (`guest-return:<email>` is
|
||||||
|
the dedupe reference, so a repeat cancel can never double-return). The
|
||||||
|
guests-ledger row records the full trail: inviter → recipient → 'cancelled
|
||||||
|
by recipient'. The Cloudron user leaves the guests group for
|
||||||
|
`GUESTS_ENDED_GROUP_ID` — chat and API access end, while the dashboard app
|
||||||
|
(which lists that group in its access restriction) still admits them, so
|
||||||
|
`GET /broker/guest-status` can show the ended state: access ended, data
|
||||||
|
kept, Become-a-member still one contribution away. A paying member calling
|
||||||
|
either route gets a 403 — cancelling a membership means ending the Open
|
||||||
|
Collective contribution, and this endpoint is deliberately guest-only.
|
||||||
|
|
||||||
|
**Guest → member conversion (automatic).** When a guest's OC identity appears as
|
||||||
|
a live BACKER/ADMIN with the account's own email — via the webhook or the
|
||||||
|
nightly sweep — `provision_member()` routes the call to
|
||||||
|
`convert_guest_to_member()`: the Cloudron user moves guests → members, the
|
||||||
|
LiteLLM cap lifts to the member allowance + credits (unspent guest credit is
|
||||||
|
carried — it already lives in `credit_balance`), the row becomes a normal
|
||||||
|
member with the standard `MEMBER_BUDGET`, the anchor day (the guest's start
|
||||||
|
date) is kept and the reset pinned to it, the congratulations email goes out,
|
||||||
|
and the normal member onboarding runs (newsletter, Loomio + Matrix syncs,
|
||||||
|
docs-RAG group, held-credit grants). When the contribution arrives under a
|
||||||
|
DIFFERENT OC email it cannot auto-match: the operator links it with
|
||||||
|
`POST /admin/guest-convert` `{"email": "<guest account>", "oc_email": "<the OC
|
||||||
|
email the contribution is under>"}` — the row records `members.oc_email`, and
|
||||||
|
the sweep and webhook treat that address as an additional matcher from then on.
|
||||||
|
|
||||||
|
|
||||||
|
## Budget model
|
||||||
|
|
||||||
|
Governance decision (set in Loomio): a single sliding-scale Membership tier
|
||||||
|
($5–$20/month flexible) with a FLAT allowance for every member —
|
||||||
|
`MEMBER_BUDGET` (default `15`), reset on each membership payment and extendable
|
||||||
|
with non-expiring purchased credit packs. The per-tier budgets the portal once
|
||||||
|
shipped (free/member/supporter) are retired — there are no per-tier portal
|
||||||
|
settings; the single env knob is `MEMBER_BUDGET`.
|
||||||
|
|
||||||
|
## Chat wiring
|
||||||
|
|
||||||
|
LibreChat talks to the **gateway directly** with each member's own key; the
|
||||||
|
portal is not in the chat request path. (The old `/v1/*` key-injection proxy —
|
||||||
|
`X-Portal-Secret` + `X-User-Email` — was retired 2026-11-19. It let anyone with
|
||||||
|
that shared secret spend as any member, and nothing used it.)
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
# librechat-custom/librechat.yaml (excerpt)
|
||||||
endpoints:
|
endpoints:
|
||||||
custom:
|
custom:
|
||||||
- name: "Inference Cooperative"
|
- name: "Inference Cooperative"
|
||||||
apiKey: "${LITELLM_KEY}"
|
apiKey: "${INFERENCE_COOP_API_KEY}"
|
||||||
baseURL: "https://portal.inference.coop/v1"
|
baseURL: "https://gateway.inference.coop/v1"
|
||||||
headers:
|
|
||||||
X-User-Email: "{{LIBRECHAT_USER_EMAIL}}"
|
|
||||||
models:
|
|
||||||
default: ["deepseek-v4-flash", "gpt-oss-120b"]
|
|
||||||
fetch: true
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
@@ -92,19 +180,206 @@ points. Remaining work before production:
|
|||||||
|
|
||||||
## Scheduled tasks (scheduler addon)
|
## Scheduled tasks (scheduler addon)
|
||||||
|
|
||||||
Two jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
|
Four jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
|
||||||
|
|
||||||
- **membership_sweep** (nightly 3am) — `sweep.sh` calls the portal's own
|
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
|
||||||
`/admin/sweep` (auth: `X-Admin-Token` = `WEBHOOK_TOKEN`) to reconcile members
|
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
|
||||||
|
the portal's `ADMIN_TOKEN` — never `WEBHOOK_TOKEN`, which is the webhook's
|
||||||
|
URL token and returns 403 on `/admin/*`) to reconcile members
|
||||||
against the live Open Collective list: provisions missed signups, deactivates
|
against the live Open Collective list: provisions missed signups, deactivates
|
||||||
lapsed members, syncs Loomio + Matrix. Idempotent; a missed webhook
|
lapsed members, syncs Loomio + Matrix. Idempotent; a missed webhook
|
||||||
self-heals within 24 hours.
|
self-heals within a day. The same sweep also runs the payment-driven
|
||||||
- **rag_refresh** (nightly 3:30am) — `rag_refresh.py` pulls this repo's
|
allowance reconciliation (below) and the credit-pack reconciliation.
|
||||||
sibling docs from the Gitea raw API (public, no credentials), uploads changed
|
|
||||||
files to Open WebUI (`OWUI_API_KEY`), attaches them to the shared knowledge
|
**Credit-pack reconciliation** (`CREDIT_RECONCILE`, default `report`) — credits
|
||||||
collection (`DOCS_KNOWLEDGE_ID`), reindexes, and re-grants the members group.
|
are granted on exactly one path, the OC `order.processed` webhook, and that
|
||||||
State persists in `/app/data/rag_refresh_state.json`.
|
path can fail AFTER the money has moved: on 2026-11-13 a $50 pack's delivery
|
||||||
|
500'd on httpx's invisible 5-second default, and a $10 pack had no delivery in
|
||||||
|
the retained log at all. Neither left a ledger row and nothing noticed. This
|
||||||
|
pass reads OC's OWN order list (`fetch_collective_orders`, needs the `orders`
|
||||||
|
scope on `OC_PERSONAL_TOKEN`, granted 2026-11-13) and compares it with our
|
||||||
|
books over `CREDIT_RECONCILE_DAYS` (default 30 — days, not "whatever our log
|
||||||
|
still holds": the $10 gap was 11 hours old and the log had already lost the
|
||||||
|
whole morning). In `report` mode it logs findings and changes NOTHING; grants
|
||||||
|
happen only when `CREDIT_RECONCILE=on`. Every grant uses
|
||||||
|
`credit_pack_reference()` — the same per-order key the webhook writes — so a
|
||||||
|
late delivery and this pass cannot both credit one purchase. A buyer who is not
|
||||||
|
an active member is reported, never credited: those keep the hold-and-email
|
||||||
|
path. On demand: `POST /admin/credit-pack-reconcile` (`X-Admin-Token`), a dry
|
||||||
|
run unless `?apply=1` and the policy is `on`.
|
||||||
|
|
||||||
|
Matching caution: our own references are NOT uniform, so a bare
|
||||||
|
`oc:<slug>:<order.id>` test reports credited purchases as missing (it read 21
|
||||||
|
of them that way, all false). `credit_pack_accounted()` matches the exact
|
||||||
|
reference when one exists and otherwise requires a second signal — same member,
|
||||||
|
same tip-free amount, within days — and counts a `held_credits` row as
|
||||||
|
accounted for. Each candidate also carries its `nearby_book_rows` (the member's
|
||||||
|
own ledger/held rows within a week) because a manual grant can be real and carry
|
||||||
|
no reference at all: the 2026-09-28 launch-day packs were credited as `+20.00`
|
||||||
|
then corrected by `-10.75`, netting exactly 3 × $5.00 with no reference on any
|
||||||
|
row. A reviewer sees that, instead of a phantom victim.
|
||||||
|
|
||||||
|
**Webhook-failure report** — the portal records every delivery it does not
|
||||||
|
accept in `webhook_failures` (`record_webhook_failure()`, called from the
|
||||||
|
webhook wrapper, including the 401 that means the webhook URL and
|
||||||
|
`WEBHOOK_TOKEN` disagree) and the sweep emails `info@` **once per new batch**
|
||||||
|
via a marker in `portal_state`, so a wrong token does not mail every sweep while
|
||||||
|
the rows stay queryable. Each row carries the source IP and user-agent, and the
|
||||||
|
email names the source: Open Collective posts from its own hosts, so a refusal
|
||||||
|
from an unrelated address is a probe, not a purchase. This replaces the
|
||||||
|
log-scraping watcher that used to run
|
||||||
|
on the operator's machine: the portal handles every delivery, so the portal is
|
||||||
|
what must notice and report a failure. (It also removes the dependency on a log
|
||||||
|
buffer with only hours of memory — when the 2026-11-13 $10 purchase was
|
||||||
|
investigated, whole hours were missing from it.) Log-scraping jobs cannot be
|
||||||
|
the primary alert for a signal whose window they cannot see.
|
||||||
|
|
||||||
|
**Unmapped-backer check** — a contributor who pays but has no portal row never
|
||||||
|
gets an account, because `fetch_members()` drops every member node with no
|
||||||
|
email and an OC Organization never exposes one (the mmoya case, found weeks late
|
||||||
|
by the member asking). `reconcile_unmapped_backers()` reads the RAW member nodes
|
||||||
|
— including the ones the sweep must skip — and compares them with `members.db`,
|
||||||
|
reporting three classes because each needs a different action: an ORG account
|
||||||
|
(link it with `/admin/org-link`), a VISIBLE email (the sweep should have
|
||||||
|
provisioned it — check the token), and a HIDDEN email (fetch it out-of-band,
|
||||||
|
then `/admin/provision`). A node with no account object is attributed through
|
||||||
|
same-day current orders, and is never reported without a date to attribute it
|
||||||
|
against. On demand: `POST /admin/unmapped-check`.
|
||||||
|
|
||||||
|
**Spend-consistency check** — on 2026-11-05 the portal's all-time-spend aggregate
|
||||||
|
failed *soft*: its copy of the gateway's LiteLLM DB credential had gone stale, the
|
||||||
|
query returned nothing, and every surface showed $0 while looking clean — the
|
||||||
|
portal was the thing that was wrong. `check_spend_consistency()` compares two
|
||||||
|
genuinely independent reads — the portal's SpendLogs aggregate over its own DB
|
||||||
|
credential, and LiteLLM's own HTTP API (`/global/spend/teams`) over the master key
|
||||||
|
— **day by day over the window both sides cover**, which localises drift instead of
|
||||||
|
hiding it in a sum. Two traps are encoded here: LiteLLM's per-day view reaches back
|
||||||
|
only a fixed number of days (31) while our table holds everything, so a
|
||||||
|
sum-vs-all-time test reports the missing window as drift ($107.63 of it on
|
||||||
|
2026-11-13, against a real agreement of $0.07); and `/global/spend/keys` follows
|
||||||
|
each key's own budget cycle, so it is not an all-time figure either
|
||||||
|
(`/global/spend/report` would be, but is Enterprise-gated). An EMPTY/$0 portal
|
||||||
|
aggregate while LiteLLM reports real spend is a FAILURE named as the
|
||||||
|
stale-credential signature — judged *before* the window overlap, since in that
|
||||||
|
failure there are no shared days to compare. Silent when they agree; a read that
|
||||||
|
cannot be made is `skipped`, never clean. On demand: `POST /admin/spend-check`.
|
||||||
|
|
||||||
|
**Notice policy (all of the above):** email `info@` only when there is a
|
||||||
|
problem, and only about what is NEW. What a human has been told is a growing SET
|
||||||
|
of keys in `portal_state` (`order:grant` / `order:hold`, `slug:class`) — a set
|
||||||
|
that shrinks (a purchase granted, a finding fixed) mails nobody again, a failed
|
||||||
|
send retries on the next sweep instead of going quiet, a `notify=False` run is a
|
||||||
|
look and never consumes the alert, and a clean pass clears the marker so a
|
||||||
|
recurrence is news again.
|
||||||
|
|
||||||
|
**Service-invite triggers:** the sweep is the backstop, not the primary path.
|
||||||
|
Two faster triggers exist, because a member who has just set up their account
|
||||||
|
should not wait hours for forum + Space access:
|
||||||
|
1. **First-login activation hook** — when a member first presents themselves
|
||||||
|
on the broker identity path (the dashboard's first login), the portal
|
||||||
|
checks — only if their Loomio invite is still outstanding
|
||||||
|
(`loomio_invited_at` is null) — that their Cloudron account is now
|
||||||
|
activated (`inviteAccepted`), and if so fires the same idempotent Loomio +
|
||||||
|
Matrix syncs as a background task. Established members cost one SELECT; the
|
||||||
|
response never waits on Loomio or Matrix; failures are logged and
|
||||||
|
non-fatal; unactivated accounts are never invited (the check fails closed).
|
||||||
|
2. **service_sync** (below) — the scheduled tick that covers members who never
|
||||||
|
open the dashboard.
|
||||||
|
- **service_sync** (every 5 minutes) — `service_sync.sh` calls the portal's own
|
||||||
|
`/admin/service-sync` (same `X-Admin-Token` auth as the sweep). WHY: a new
|
||||||
|
member is provisioned with an UNACTIVATED Cloudron account, and the syncs
|
||||||
|
deliberately skip an unactivated account (never invite a half-created one) —
|
||||||
|
so nobody on our side is watching at the moment the member actually activates.
|
||||||
|
This job fires the same idempotent Loomio + Matrix syncs the sweep runs, but
|
||||||
|
ONLY while some member is still awaiting their invites (one indexed SELECT
|
||||||
|
when nobody is, so it costs nothing in the steady state), and it deliberately
|
||||||
|
is NOT `/admin/sweep`: it never touches Open Collective, allowance logic or
|
||||||
|
member mail. An in-process guard drops an overlapping run.
|
||||||
|
Net effect: a member who has just set up their account waits minutes at most.
|
||||||
|
- **metrics_snapshot** (daily 3:15am UTC) — `metrics_snapshot.py` records one row per
|
||||||
|
day into the `metrics_daily` table: members, newsletter subscribers, Matrix
|
||||||
|
membership, spend, request counts, energy/CO₂, and the Open Collective
|
||||||
|
balance. Each run **completes yesterday's row** with its full-day
|
||||||
|
spend/requests/tokens/impact aggregates, then records today's row live (its
|
||||||
|
usage columns carry the hours so far and are completed by the next run's
|
||||||
|
completion pass). A source that cannot be read
|
||||||
|
yields NULL for that metric rather than a zero. `spend_usd` is the co-op-wide
|
||||||
|
total and deliberately spans every team, the co-op's own operator accounts
|
||||||
|
included; `operator_spend_usd` is the breakout of that portion, served through
|
||||||
|
`/broker/metrics` so the member dashboard can show the co-op's own share
|
||||||
|
alongside the total. `oc_balance_usd` is a daily snapshot of the collective's
|
||||||
|
OC balance (the OC API has no historical series, so balance history accrues
|
||||||
|
from these snapshots only — 2026-11-08 onward). `--backfill` rebuilds history
|
||||||
|
idempotently (balance history cannot be backfilled: past balances were never
|
||||||
|
recorded); `--backfill --since YYYY-MM-DD` repairs recent days' usage columns
|
||||||
|
only, leaving the membership curve as the nightly snapshots measured it.
|
||||||
|
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
|
||||||
|
|
||||||
Verify after any manifest change: the deploy log must show
|
Verify after any manifest change: the deploy log must show
|
||||||
`setupAddons: ... scheduler ...` listing both tasks, and each script must
|
`setupAddons: ... scheduler ...` listing all four tasks, and each script must
|
||||||
succeed when run manually inside the container.
|
succeed when run manually inside the container.
|
||||||
|
|
||||||
|
### Allowance renewal (payment-driven, join-day anchored)
|
||||||
|
|
||||||
|
Each member has a monthly allowance (`MEMBER_BUDGET`, currently $15). The
|
||||||
|
allowance renews on the day of the month the member *joined*, never on the day
|
||||||
|
Open Collective happened to charge them — OC aligns every member's charge onto
|
||||||
|
the collective's common billing day, so anchoring to the payment date let an
|
||||||
|
early charge move the boundary and skip a cycle entirely. The join day is stored
|
||||||
|
per member (`members.anchor_day`) and the reset is pinned there.
|
||||||
|
|
||||||
|
Whether the allowance renews is decided by asking Open Collective directly, on
|
||||||
|
the sweep's own schedule (not inferred from webhook delivery): a member with a
|
||||||
|
live recurring contribution (order status `ACTIVE` or `PROCESSING` — a payment
|
||||||
|
in flight is not a missed payment) renews; a member with no live recurring
|
||||||
|
contribution gets **one** reminder email, and is deactivated only after
|
||||||
|
`PAYMENT_GRACE_DAYS`. One-time payments are not an allowance cycle — they top up
|
||||||
|
the non-expiring credit balance and are untouched here. There are no annual
|
||||||
|
contributors (verified 2026-11-04: 104 orders, 87 MONTHLY, 17 ONETIME, zero
|
||||||
|
annual), so only the monthly case is implemented.
|
||||||
|
|
||||||
|
Every decision (renewed / reminded / deactivated, plus the payment date or its
|
||||||
|
absence) is written to `allowance_log` and answerable from that record. Run
|
||||||
|
`POST /admin/allowance?mode=report` (X-Admin-Token) for a no-op report that
|
||||||
|
changes nothing; `mode=send` performs renewals and sends the reminder and
|
||||||
|
requires `ALLOWANCE_POLICY=on`. Deactivation additionally requires
|
||||||
|
`ALLOWANCE_DEACTIVATE=on`.
|
||||||
|
|
||||||
|
### Allowance shortfall (a paid cycle OC truncated)
|
||||||
|
|
||||||
|
Open Collective aligns every recurring charge onto the collective's common
|
||||||
|
billing day, so a member who joins mid-month is charged again well before a full
|
||||||
|
month has elapsed — they pay for a full month and receive less than one. The
|
||||||
|
co-op's remedy: credit the missing **allowance** (the flat `MEMBER_BUDGET`
|
||||||
|
pro-rated for the days lost, `FULL_PAID_MONTH_DAYS = 30`, unrounded) as
|
||||||
|
non-expiring credits — the same balance that extends the allowance and is spent
|
||||||
|
only after it. It is never a share of what they paid.
|
||||||
|
|
||||||
|
The set is derived FROM DATA, on every sweep (`POST /admin/sweep` calls
|
||||||
|
`reconcile_allowance_shortfalls`, as does `POST /admin/shortfall-credits`):
|
||||||
|
each MONTHLY order's real charge history is read from Open Collective, and any
|
||||||
|
consecutive pair on the SAME order less than a full month apart is a truncated
|
||||||
|
cycle. Two subscriptions a member happens to hold are judged separately; a gap
|
||||||
|
whose dates cannot be determined is skipped and logged. Each credit is keyed to
|
||||||
|
the specific OC charge that caused it (`credit_ledger.reference` = the charge
|
||||||
|
`publicId`), so a re-run credits nothing twice — dedupe is on the charge, not
|
||||||
|
the member — and the ledger `reason` names the cycle so a member's question is
|
||||||
|
answerable from it.
|
||||||
|
|
||||||
|
Member notices ride the same pass, but default OFF
|
||||||
|
(`ALLOWANCE_SHORTFALL_EMAILS=off`); set it to `on` to send the staged notice,
|
||||||
|
at most once per charge (`shortfall_notices`). `mode=report` on
|
||||||
|
`/admin/shortfall-credits` previews the affected set and changes nothing.
|
||||||
|
|
||||||
|
### Energy & carbon metrics
|
||||||
|
|
||||||
|
The daily snapshot also computes energy (Wh) and carbon (gCO₂e) from output tokens,
|
||||||
|
using per-model factors whose provenance varies: measured for GreenPT, assumed equal
|
||||||
|
for one sibling model, and an explicit order-of-magnitude estimate for providers that
|
||||||
|
disclose nothing. Only output tokens count, and a day with no measured tokens is
|
||||||
|
recorded as NULL rather than zero.
|
||||||
|
|
||||||
|
[Energy and carbon metrics](docs/energy-metrics.md) documents the factor table, the
|
||||||
|
formulas, the tripwire that catches unit errors, the schedule, and — most importantly —
|
||||||
|
which parts are measurements and which are estimates. What members are told is in
|
||||||
|
`co-op/docs/energy.md`.
|
||||||
+8145
-525
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,197 @@
|
|||||||
|
# Energy and carbon metrics
|
||||||
|
|
||||||
|
How the portal's daily `energy_wh` and `co2e_g` figures are produced, what is
|
||||||
|
measured versus estimated, and how to change them. Written because the calculation
|
||||||
|
previously lived only in code comments (see `code/member-portal#3`).
|
||||||
|
|
||||||
|
For what members are told, see `co-op/docs/energy.md`. This document is the
|
||||||
|
developer-facing counterpart and is deliberately blunter about the limits.
|
||||||
|
|
||||||
|
## Where the numbers come from
|
||||||
|
|
||||||
|
**Input: output tokens only, per day, per model.**
|
||||||
|
|
||||||
|
- Source: LiteLLM's spend logs (`LiteLLM_SpendLogs`), column `completion_tokens`.
|
||||||
|
- Grouped on **`model_group`** — our alias, e.g. `greenpt/deepseek-v4.1-flash` —
|
||||||
|
**not** `model`, which carries the upstream name (`openai/deepseek-v4.1-flash`).
|
||||||
|
Grouping on the wrong column matches no factor and yields zeros for every day. That
|
||||||
|
mistake shipped once during development and is the reason this is called out.
|
||||||
|
|
||||||
|
**Only output tokens count**, matching the unit GreenPT publishes (mWh per 100 output
|
||||||
|
tokens). This is a deliberate choice to line up with the provider's own metric, not an
|
||||||
|
oversight — and it means these figures **understate total compute**, because input
|
||||||
|
tokens consume energy too. Treat the numbers as comparable and directionally true
|
||||||
|
rather than as a total energy accounting.
|
||||||
|
|
||||||
|
## The factor table
|
||||||
|
|
||||||
|
Factors live in `metrics_snapshot.py` (`IMPACT_FACTORS`, `IMPACT_PROXY`). Matching is
|
||||||
|
`str.startswith()`, so **the longest prefix must come first** — order matters.
|
||||||
|
|
||||||
|
| model prefix | Wh / 1k output tokens | gCO2e / kWh | provenance |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `greenpt/deepseek-v4.1-flash` | 0.3641 | 193.0 | MEASURED |
|
||||||
|
| `greenpt/glm-5.3-flash` | 1.0782 | 193.0 | MEASURED |
|
||||||
|
| `greenpt/glm-5.3` | 1.0782 | 193.0 | SAME_FAMILY |
|
||||||
|
| `greenpt/green-r` | 0.5535 | 23.6 | MEASURED |
|
||||||
|
| *anything else* | 0.5000 | 250.0 | ESTIMATED |
|
||||||
|
|
||||||
|
### The three provenance tiers
|
||||||
|
|
||||||
|
- **MEASURED** — fitted from live calls to GreenPT's API, which returns an `impact`
|
||||||
|
object on every request (energy in watt-milliseconds, emissions in µgCO2e). Energy
|
||||||
|
was regressed on output tokens across prompt sizes (R² ≥ 0.999); grid intensity is
|
||||||
|
what their own emissions figures imply. Fitted 2026-10-28.
|
||||||
|
- **SAME_FAMILY** — measured for `glm-5.3-flash` and assumed to hold for `glm-5.3`.
|
||||||
|
An assumption of similarity, not a measurement.
|
||||||
|
- **ESTIMATED** — the proxy row: an order-of-magnitude figure near the middle of the
|
||||||
|
measured range, with an EU grid average. It is applied to every provider that does
|
||||||
|
not disclose impact, **deliberately**, so that a day's total is never quietly
|
||||||
|
missing models. It is not a number we know.
|
||||||
|
|
||||||
|
**No tier is exposed on its own**, but every row now carries a *provenance* read
|
||||||
|
derived from the measured/estimated token split — see "Provenance in the API"
|
||||||
|
below. A consumer can tell how much of a day's figure rested on a measurement.
|
||||||
|
|
||||||
|
## Provenance in the API
|
||||||
|
|
||||||
|
Every row returned by `/admin/metrics/series` and `/broker/metrics` carries the
|
||||||
|
measured-vs-estimated split, so a consumer can tell how much of a day's figure
|
||||||
|
rested on a real measurement. Four fields:
|
||||||
|
|
||||||
|
| field | meaning |
|
||||||
|
|---|---|
|
||||||
|
| `tokens_measured` | output tokens that day attributed to a factor whose `source` is **MEASURED** — a direct provider measurement. |
|
||||||
|
| `tokens_estimated` | the rest: **SAME_FAMILY** (borrowed from a sibling) and the flat **proxy**. A borrowed or proxied factor is an assumption, so it is **not** counted as measured. |
|
||||||
|
| `factor_revision` | a short, stable hash of the factor table (`IMPACT_FACTORS` + `IMPACT_PROXY`) in effect when the row was computed. |
|
||||||
|
| `provenance` | the derived read, below. |
|
||||||
|
|
||||||
|
`tokens_measured + tokens_estimated = out_tokens` for any day with tokens. A day
|
||||||
|
with no output tokens has NULL in both (fail-closed, same rule as energy/carbon).
|
||||||
|
|
||||||
|
`provenance` is one of:
|
||||||
|
|
||||||
|
- **`measured`** — every token rested on a measured factor.
|
||||||
|
- **`estimated`** — every token rested on a non-measured factor (borrowed or proxy).
|
||||||
|
- **`mixed`** — both are present; the day's total is a blend.
|
||||||
|
- **`none`** — no provenance. This is **either** a day with no output tokens **or**
|
||||||
|
a row written before these columns existed (older rows keep NULL). It is
|
||||||
|
deliberately **not** `measured`: an unknown split must never read as a confident
|
||||||
|
measurement. This is the whole point of the indicator — failure reads as unknown.
|
||||||
|
|
||||||
|
`factor_revision` is a deterministic hash, **not a timestamp**: two runs against the
|
||||||
|
same table produce the same string. It changes if any factor value or source label
|
||||||
|
changes, or if the matching order changes (order is meaningful — longest prefix
|
||||||
|
first). It is "what the numbers were computed with", not "what was known then".
|
||||||
|
|
||||||
|
### Forward-only, then backfill
|
||||||
|
|
||||||
|
The columns are added by an **additive** migration — a guarded
|
||||||
|
`ALTER TABLE metrics_daily ADD COLUMN …`, the same idiom used when the impact
|
||||||
|
columns first arrived. On an existing database this is safe: it never errors,
|
||||||
|
existing rows survive untouched, and they simply keep NULL in the new columns.
|
||||||
|
Nothing is guessed for history on migration; those rows read as `provenance: "none"`.
|
||||||
|
|
||||||
|
To give past rows a real split, run `metrics_snapshot.py --backfill` (or re-run the
|
||||||
|
affected days). Backfill rewrites each day from the current LiteLLM token split and
|
||||||
|
the **current** factor table, so it also updates `factor_revision` to today's
|
||||||
|
revision — a backfilled historical row records the revision used to recompute it,
|
||||||
|
not the one that was current at the time. Honest for a chart label; not a historical
|
||||||
|
audit trail.
|
||||||
|
|
||||||
|
## Formulas
|
||||||
|
|
||||||
|
```
|
||||||
|
energy_wh = Σ_models ( out_tokens / 1000 × wh_per_1k_out )
|
||||||
|
|
||||||
|
co2e_g = Σ_models ( out_tokens / 1000 × wh_per_1k_out / 1000 × gco2e_per_kwh )
|
||||||
|
└────────────── Wh ──────────────┘ └─ Wh → kWh ─┘
|
||||||
|
```
|
||||||
|
|
||||||
|
Carbon was once understated by exactly 1000× here — a `/1e6` where `/1e3` was
|
||||||
|
intended — which is why the tripwire below exists.
|
||||||
|
|
||||||
|
## NULL, never zero
|
||||||
|
|
||||||
|
`impact_for()` returns an all-NULL impact block for a day with no measured tokens,
|
||||||
|
and the row is written with NULL energy and carbon. It never writes `0.0`:
|
||||||
|
|
||||||
|
> a zero reads as "the co-op used no energy", which is a claim we cannot support, and
|
||||||
|
> it would survive into a chart as a fact.
|
||||||
|
|
||||||
|
The first backfill shipped exactly that bug — it summed the wrong column, every model
|
||||||
|
totalled zero, and every day in history claimed to have used no energy.
|
||||||
|
|
||||||
|
A NULL day renders as a **bare gap in the charts, with nothing explaining it.** That is
|
||||||
|
deliberate: the surfaces carry no caveat text. Accepted knowingly.
|
||||||
|
|
||||||
|
The same fail-closed rule applies to every metric in the snapshot, not only energy:
|
||||||
|
an unreadable source (Listmonk, Matrix, LiteLLM) yields NULL for that metric and
|
||||||
|
prints to the log, rather than a number that looks real.
|
||||||
|
|
||||||
|
## The tripwire
|
||||||
|
|
||||||
|
After summing, `impact_for()` computes the grid intensity its own mix implies and
|
||||||
|
compares it against a plausible band:
|
||||||
|
|
||||||
|
```
|
||||||
|
implied = co2e_g / energy_wh × 1000 # gCO2e per kWh
|
||||||
|
if not (5.0 <= implied <= 500.0):
|
||||||
|
warn "suspect a unit error before trusting these numbers"
|
||||||
|
```
|
||||||
|
|
||||||
|
It warns; it never alters the numbers or suppresses the row. Its purpose is narrow and
|
||||||
|
earned: the 1000× carbon error kept the energy column plausible, so nothing looked
|
||||||
|
wrong, and a silent error of that kind would otherwise be found by a member rather
|
||||||
|
than by us.
|
||||||
|
|
||||||
|
## Schedule and backfill
|
||||||
|
|
||||||
|
- **`metrics_snapshot` runs daily at 03:15**, from Cloudron's scheduler addon
|
||||||
|
(`CloudronManifest.json` → `addons.scheduler`), via `/app/code/metrics_snapshot.py`.
|
||||||
|
It runs after `membership_sweep` (03:00) and `rag_refresh` (03:30).
|
||||||
|
- It writes **one row per day** into the `metrics_daily` table, in the same SQLite
|
||||||
|
database as the members table (`members.db`). Columns: `day`, `members_active`,
|
||||||
|
`members_total`, `members_new`, `newsletter_subs`, `matrix_space_members`,
|
||||||
|
`spend_usd`, `requests`, `out_tokens`, `energy_wh`, `co2e_g`, `tokens_measured`,
|
||||||
|
`tokens_estimated`, `factor_revision`, `recorded_at`.
|
||||||
|
- **Each 03:15 run completes YESTERDAY, then records today live.** The day that
|
||||||
|
just ended is rewritten with its FULL spend/requests/tokens/impact aggregates
|
||||||
|
(usage columns only — the membership columns are point-in-time measurements
|
||||||
|
that are not reconstructible afterwards). Today's row carries the first hours
|
||||||
|
of live data and is completed by the next run. (Until 2026-11-12 the run
|
||||||
|
wrote only today's partial and never revisited it, which froze every day at
|
||||||
|
its first ~3 hours — the November under-count.)
|
||||||
|
- **`metrics_snapshot.py --backfill` rebuilds history** from the sources and is
|
||||||
|
idempotent — it rewrites a day rather than duplicating it. It is the tool to run
|
||||||
|
after changing a factor, and the reason a published chart can move: history is
|
||||||
|
**rewritten**, not appended to. `--backfill --since YYYY-MM-DD` limits the
|
||||||
|
rewrite to days from that date and touches ONLY the usage/impact columns, so
|
||||||
|
a targeted repair of recent days cannot alter the published membership curve.
|
||||||
|
|
||||||
|
## What is measured, and what is not
|
||||||
|
|
||||||
|
Stated plainly, because a mixed total is easy to over-read:
|
||||||
|
|
||||||
|
- **Measured:** GreenPT models — the providers whose API reports impact.
|
||||||
|
- **Assumed equal to a measurement:** `greenpt/glm-5.3`, from its flash sibling.
|
||||||
|
- **Estimated:** everything else. Currently that means **all Tinfoil and Regolo
|
||||||
|
traffic**, which is a real share of co-op usage.
|
||||||
|
|
||||||
|
So a day's figure is a blend, and **the split is now recorded per day** —
|
||||||
|
`tokens_measured` and `tokens_estimated` say how much of the total rested on a
|
||||||
|
measurement, and the API derives a `provenance` read from them. Before those
|
||||||
|
columns existed the split was not recorded; such rows carry NULL and read as
|
||||||
|
`provenance: "none"`. See "Provenance in the API".
|
||||||
|
|
||||||
|
One consequence worth knowing: the proxy assumes a 250 gCO2e/kWh grid, while Regolo
|
||||||
|
runs on 100% renewable energy, so the proxy **overstates** Regolo's carbon. Per-provider
|
||||||
|
factors are a follow-up; until then, Regolo and Tinfoil figures should be read as upper
|
||||||
|
bounds rather than measurements.
|
||||||
|
|
||||||
|
## Changing the factors
|
||||||
|
|
||||||
|
Edit the table in `metrics_snapshot.py` and redeploy — refining a factor is a data
|
||||||
|
edit, not a code change. Then run `--backfill` if the change should apply to history.
|
||||||
|
The energy factors are also recorded in `co-op/docs/energy.md` for members, and the two
|
||||||
|
should not disagree.
|
||||||
+1037
File diff suppressed because it is too large.
Load diff
-117
@@ -1,117 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Nightly docs-RAG refresh — server-side (portal container).
|
|
||||||
|
|
||||||
Fetches the co-op docs from the Gitea raw API (public repo, no credentials),
|
|
||||||
uploads changed files to Open WebUI via the internal network (OWUI_API_KEY,
|
|
||||||
already in the portal env), attaches them to the shared knowledge collection,
|
|
||||||
reindexes, and keeps the members group grant intact.
|
|
||||||
|
|
||||||
Replaces the bot-hosted refresh script (same logic, no bot dependency).
|
|
||||||
Silent-ish: prints a one-line summary; exits non-zero on hard failure so the
|
|
||||||
Cloudron scheduler log captures it.
|
|
||||||
"""
|
|
||||||
import json, os, sys, time, hashlib, urllib.request, urllib.error
|
|
||||||
|
|
||||||
GITEA_RAW = "https://git.inference.coop/co-op/docs/raw/branch/main/"
|
|
||||||
OWUI_BASE = os.environ.get("OWUI_BASE", "http://chat:8080")
|
|
||||||
OWUI_KEY = os.environ.get("OWUI_API_KEY", "")
|
|
||||||
KB_ID = os.environ.get("DOCS_KNOWLEDGE_ID", "")
|
|
||||||
GID = "eb348e1a-059a-4a8f-8920-0f73942f6272" # OWUI members group
|
|
||||||
DOCS = ["README.md", "getting-started.md", "models.md", "api-access.md",
|
|
||||||
"terms-of-service.md", "privacy-policy.md", "charter.md",
|
|
||||||
"infrastructure.md", "open-questions.md"]
|
|
||||||
STATE_PATH = "/app/data/rag_refresh_state.json"
|
|
||||||
|
|
||||||
if not OWUI_KEY or not KB_ID:
|
|
||||||
print("rag_refresh: OWUI_API_KEY / DOCS_KNOWLEDGE_ID not set", file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
def api(path, body=None, method=None, key=None, base=None, timeout=180):
|
|
||||||
data = json.dumps(body).encode() if body is not None else None
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"{base or OWUI_BASE}{path}", data=data, method=method or ("POST" if data else "GET"),
|
|
||||||
headers={"Authorization": f"Bearer {key or OWUI_KEY}", "Content-Type": "application/json"})
|
|
||||||
try:
|
|
||||||
r = urllib.request.urlopen(req, timeout=timeout)
|
|
||||||
return r.status, json.loads(r.read())
|
|
||||||
except urllib.error.HTTPError as e:
|
|
||||||
return e.code, e.read().decode()[:200]
|
|
||||||
|
|
||||||
def multipart_upload(filename, content):
|
|
||||||
boundary = "----ragrefresh9x"
|
|
||||||
part = (f"--{boundary}\r\n"
|
|
||||||
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
|
|
||||||
f"Content-Type: text/markdown\r\n\r\n").encode() + content.encode() + \
|
|
||||||
f"\r\n--{boundary}--\r\n".encode()
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"{OWUI_BASE}/api/v1/files/", data=part, method="POST",
|
|
||||||
headers={"Authorization": f"Bearer {OWUI_KEY}",
|
|
||||||
"Content-Type": f"multipart/form-data; boundary={boundary}"})
|
|
||||||
r = urllib.request.urlopen(req, timeout=180)
|
|
||||||
return json.loads(r.read())
|
|
||||||
|
|
||||||
def fetch_doc(name):
|
|
||||||
req = urllib.request.Request(GITEA_RAW + name)
|
|
||||||
try:
|
|
||||||
return urllib.request.urlopen(req, timeout=30).read().decode()
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
state = {}
|
|
||||||
if os.path.exists(STATE_PATH):
|
|
||||||
try:
|
|
||||||
state = json.load(open(STATE_PATH))
|
|
||||||
except Exception:
|
|
||||||
state = {}
|
|
||||||
|
|
||||||
changed = 0
|
|
||||||
skipped = 0
|
|
||||||
for name in DOCS:
|
|
||||||
content = fetch_doc(name)
|
|
||||||
if content is None:
|
|
||||||
print(f"rag_refresh: WARN could not fetch {name}", file=sys.stderr)
|
|
||||||
continue
|
|
||||||
newhash = hashlib.sha256(content.encode()).hexdigest()
|
|
||||||
if state.get(name) == newhash:
|
|
||||||
skipped += 1
|
|
||||||
continue
|
|
||||||
|
|
||||||
# delete stale file rows with this name, then upload fresh + attach
|
|
||||||
code, files = api("/api/v1/files/?page=1")
|
|
||||||
if code == 200 and isinstance(files, dict):
|
|
||||||
files = files.get("items", []) # OWUI returns {items: [...]}
|
|
||||||
if code == 200 and isinstance(files, list):
|
|
||||||
for f in files:
|
|
||||||
if f.get("filename") == name:
|
|
||||||
api(f"/api/v1/files/{f['id']}", method="DELETE")
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp = multipart_upload(name, content)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"rag_refresh: upload failed for {name}: {e}", file=sys.stderr)
|
|
||||||
continue
|
|
||||||
fid = resp.get("id")
|
|
||||||
# attach can 400 transiently right after upload (file still processing) — retry
|
|
||||||
code = None
|
|
||||||
for attempt in range(3):
|
|
||||||
code, _ = api(f"/api/v1/knowledge/{KB_ID}/file/add", {"file_id": fid})
|
|
||||||
if code == 200:
|
|
||||||
break
|
|
||||||
time.sleep(5 * (attempt + 1))
|
|
||||||
if code != 200:
|
|
||||||
print(f"rag_refresh: attach failed for {name}: {code}", file=sys.stderr)
|
|
||||||
continue
|
|
||||||
state[name] = newhash
|
|
||||||
changed += 1
|
|
||||||
|
|
||||||
# reindex the KB (chunk copies at attach time go stale otherwise)
|
|
||||||
if changed:
|
|
||||||
api("/api/v1/knowledge/reindex", {"knowledge_id": KB_ID}, timeout=300)
|
|
||||||
|
|
||||||
# keep the members-group grant intact (guards against grant loss)
|
|
||||||
api(f"/api/v1/knowledge/{KB_ID}/access/update",
|
|
||||||
{"access_grants": [{"principal_type": "group", "principal_id": GID, "permission": "read"}]})
|
|
||||||
|
|
||||||
json.dump(state, open(STATE_PATH, "w"))
|
|
||||||
print(f"rag_refresh: changed={changed} skipped={skipped}")
|
|
||||||
sys.exit(0)
|
|
||||||
@@ -5,3 +5,4 @@ pydantic==2.9.2
|
|||||||
PyJWT==2.9.0
|
PyJWT==2.9.0
|
||||||
slowapi==0.1.9
|
slowapi==0.1.9
|
||||||
psycopg2-binary==2.9.9
|
psycopg2-binary==2.9.9
|
||||||
|
cryptography==44.0.2
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Frequent service-invite sync — run by the Cloudron scheduler addon every
|
||||||
|
# few minutes.
|
||||||
|
#
|
||||||
|
# WHY: a new member is provisioned with an UNACTIVATED Cloudron account, and
|
||||||
|
# the Loomio/Matrix syncs deliberately skip an unactivated account (never
|
||||||
|
# invite a half-created one). The member activates later, by following the
|
||||||
|
# setup link in their welcome email — and until this job existed, the next
|
||||||
|
# thing to look at them was the 3x/day membership sweep, so a brand-new member
|
||||||
|
# could sit without forum or Space access for hours.
|
||||||
|
#
|
||||||
|
# Calls the portal's own /admin/service-sync endpoint (localhost), which fires
|
||||||
|
# the same idempotent Loomio + Matrix syncs the sweep runs, but ONLY while some
|
||||||
|
# member is still awaiting their invites (one SELECT when nobody is).
|
||||||
|
#
|
||||||
|
# The ADMIN_TOKEN env var is shared with the main app (the scheduler runs in
|
||||||
|
# the same launch environment), so we use it to authenticate. Admin auth is a
|
||||||
|
# header, never a URL token.
|
||||||
|
#
|
||||||
|
# Deliberately NOT the full /admin/sweep: that reconciles against Open
|
||||||
|
# Collective, runs allowance logic and can send member mail. This job must only
|
||||||
|
# ever send the invites a member is owed.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [ -z "$ADMIN_TOKEN" ]; then
|
||||||
|
echo "service-sync: ADMIN_TOKEN is not set; aborting" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
python3 - "$ADMIN_TOKEN" <<'PY'
|
||||||
|
import sys, urllib.request, urllib.error
|
||||||
|
|
||||||
|
token = sys.argv[1]
|
||||||
|
url = "http://127.0.0.1:8000/admin/service-sync"
|
||||||
|
req = urllib.request.Request(url, method="POST", data=b"", headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Admin-Token": token,
|
||||||
|
})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=300) as resp:
|
||||||
|
print("service-sync:", resp.read().decode())
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
print(f"service-sync: HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"service-sync: request failed: {e}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
PY
|
||||||
@@ -5,19 +5,23 @@
|
|||||||
# the portal against the live Open Collective member list: provisions missing
|
# the portal against the live Open Collective member list: provisions missing
|
||||||
# members, deactivates lapsed members, and syncs Loomio.
|
# members, deactivates lapsed members, and syncs Loomio.
|
||||||
#
|
#
|
||||||
# The WEBHOOK_TOKEN env var is shared with the main app (scheduler runs in the
|
# The ADMIN_TOKEN env var is shared with the main app (scheduler runs in the
|
||||||
# same launch environment), so we use it to authenticate the call.
|
# same launch environment), so we use it to authenticate the call. Admin auth is
|
||||||
|
# a header, never a URL token (security fix 2026-10-27). The WEBHOOK_TOKEN
|
||||||
|
# fallback was removed when the cutover completed (ADMIN_TOKEN_LEGACY=0): the
|
||||||
|
# legacy token now gets 403 on /admin/*, so falling back to it would turn
|
||||||
|
# "ADMIN_TOKEN unset" into a confusing mid-run 403 instead of a clear abort.
|
||||||
#
|
#
|
||||||
# Uses Python (guaranteed present in the base image) rather than curl.
|
# Uses Python (guaranteed present in the base image) rather than curl.
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
if [ -z "$WEBHOOK_TOKEN" ]; then
|
if [ -z "$ADMIN_TOKEN" ]; then
|
||||||
echo "sweep: WEBHOOK_TOKEN not set; aborting" >&2
|
echo "sweep: ADMIN_TOKEN is not set; aborting" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
python3 - "$WEBHOOK_TOKEN" <<'PY'
|
python3 - "$ADMIN_TOKEN" <<'PY'
|
||||||
import sys, urllib.request, urllib.error
|
import sys, urllib.request, urllib.error
|
||||||
|
|
||||||
token = sys.argv[1]
|
token = sys.argv[1]
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for app.main.allowance_lapse_decision (grace/deactivation).
|
||||||
|
|
||||||
|
Self-contained and runnable:
|
||||||
|
|
||||||
|
* from the repo root: python3 tests/test_allowance_lapse.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_allowance_lapse.py
|
||||||
|
(the container has the app's own dependencies; the host usually does not)
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
Deactivation is gated OFF (ALLOWANCE_DEACTIVATE=off) and the flag must stay
|
||||||
|
off until the preview is trusted. That makes the live preview legitimately
|
||||||
|
show ZERO past-grace members right after a reminder, so this file proves the
|
||||||
|
decision logic on a SYNTHETIC reminder time instead of waiting a week — and
|
||||||
|
without altering any real member's rows.
|
||||||
|
|
||||||
|
The decision is a pure function (no DB, no network, no clock), so a past
|
||||||
|
reminder, a grace boundary and the "armed" case are all exercised directly:
|
||||||
|
|
||||||
|
- reminder 10 days ago, NOT authorised -> ("would_deactivate", deadline)
|
||||||
|
[the preview this change adds]
|
||||||
|
- reminder 3 days ago (inside grace) -> ("in_grace", None)
|
||||||
|
- reminder exactly at the grace edge -> ("would_deactivate", deadline)
|
||||||
|
- reminder one second inside the edge -> ("in_grace", None)
|
||||||
|
- reminder 10 days ago, AUTHORISED -> ("deactivated", deadline)
|
||||||
|
[the real path, unchanged: needs policy=on AND deactivate=on]
|
||||||
|
- no reminder at all -> ("in_grace", None)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
# Locate the app package: explicit env, the deployed path, or the repo root.
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.main import allowance_lapse_decision # noqa: E402
|
||||||
|
|
||||||
|
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=timezone.utc)
|
||||||
|
GRACE = 7.0
|
||||||
|
|
||||||
|
# (name, reminder_sent_at, acting, expected_decision, expected_deadline)
|
||||||
|
CASES = [
|
||||||
|
("reminder 10d ago, not authorised -> would_deactivate (preview)",
|
||||||
|
NOW - timedelta(days=10), False, "would_deactivate", NOW - timedelta(days=10) + timedelta(days=7)),
|
||||||
|
("reminder 3d ago (inside grace) -> in_grace",
|
||||||
|
NOW - timedelta(days=3), False, "in_grace", None),
|
||||||
|
("reminder exactly 7d ago (at the edge) -> would_deactivate",
|
||||||
|
NOW - timedelta(days=7), False, "would_deactivate", NOW),
|
||||||
|
("reminder 6d23h ago (one hour inside grace) -> in_grace",
|
||||||
|
NOW - timedelta(days=6, hours=23), False, "in_grace", None),
|
||||||
|
("reminder 10d ago, AUTHORISED -> deactivated (real path)",
|
||||||
|
NOW - timedelta(days=10), True, "deactivated", NOW - timedelta(days=10) + timedelta(days=7)),
|
||||||
|
("no reminder ever sent -> in_grace",
|
||||||
|
None, False, "in_grace", None),
|
||||||
|
]
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
for name, sent_at, acting, expect_dec, expect_dl in CASES:
|
||||||
|
decision, deadline = allowance_lapse_decision(sent_at, NOW, GRACE, acting)
|
||||||
|
dl_ok = (deadline == expect_dl)
|
||||||
|
ok = (decision == expect_dec) and dl_ok
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}\n"
|
||||||
|
f" decision={decision} (expected {expect_dec}) "
|
||||||
|
f"deadline={deadline} (expected {expect_dl}) acting={acting}")
|
||||||
|
|
||||||
|
print(f"\n{len(CASES) - failures}/{len(CASES)} passed")
|
||||||
|
sys.exit(1 if failures else 0)
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for the allowance-shortfall derivation (OC billing alignment).
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* from the repo root: python3 tests/test_allowance_shortfall.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_allowance_shortfall.py
|
||||||
|
(the container has the app's own dependencies; the host usually does not)
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
The shortfall credit must be derived FROM DATA and must never be paid twice.
|
||||||
|
`derive_shortfalls` is pure (no DB, no network, no clock), so the arithmetic,
|
||||||
|
the per-order boundary, the month-length boundary and the idempotence key are
|
||||||
|
all exercised directly on synthetic charge ladders.
|
||||||
|
|
||||||
|
Covered:
|
||||||
|
- a truncated first cycle -> one credit, pro-rated to the days lost
|
||||||
|
- a gap of exactly a full month -> NOT truncated (boundary)
|
||||||
|
- a gap LONGER than a full month -> NOT truncated (OC deferred a charge)
|
||||||
|
- credits are NEVER rounded -> 4.5 and 1.5 come out exact
|
||||||
|
- two orders are judged separately -> a cross-subscription pair is not
|
||||||
|
mistaken for one truncated cycle
|
||||||
|
- the reference is the EARLY charge -> it is the idempotence key
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# Locate the app package: explicit env, the deployed path, or the repo root.
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from datetime import datetime, timezone # noqa: E402
|
||||||
|
from app.main import ( # noqa: E402
|
||||||
|
derive_shortfalls, shortfall_reason, _usd, SHORTFALL_REMEDIATED,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def dt(s):
|
||||||
|
return datetime.fromisoformat(s + "T00:00:00+00:00")
|
||||||
|
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = got == want
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
# --- one truncated first cycle: joined/charged 11 Sep, re-aligned to 2 Oct (21d)
|
||||||
|
recs = [{"slug": "member-a", "order_id": "or_1",
|
||||||
|
"charges": [(dt("2026-09-11"), "tx_a1"), (dt("2026-10-02"), "tx_a2")]}]
|
||||||
|
got = derive_shortfalls(recs, budget=15.0)
|
||||||
|
check("truncated first cycle -> one credit",
|
||||||
|
[(g["prev"], g["cur"], g["gap_days"], g["days_lost"], g["amount"], g["reference"]) for g in got],
|
||||||
|
[("2026-09-11", "2026-10-02", 21, 9, 4.5, "tx_a2")])
|
||||||
|
|
||||||
|
# --- boundary: a gap of exactly 30 days is a full month -> nothing
|
||||||
|
recs = [{"slug": "member-b", "order_id": "or_2",
|
||||||
|
"charges": [(dt("2026-10-02"), "tx_b1"), (dt("2026-11-01"), "tx_b2")]}]
|
||||||
|
check("gap == full month -> no credit", derive_shortfalls(recs, budget=15.0), [])
|
||||||
|
|
||||||
|
# --- a gap LONGER than a month (OC deferred a charge) -> nothing
|
||||||
|
recs = [{"slug": "member-c", "order_id": "or_3",
|
||||||
|
"charges": [(dt("2026-09-28"), "tx_c1"), (dt("2026-11-02"), "tx_c2")]}]
|
||||||
|
check("gap > full month -> no credit", derive_shortfalls(recs, budget=15.0), [])
|
||||||
|
|
||||||
|
# --- no rounding: 24-day gap -> 6 days lost -> exact 3.0; 27-day -> 1.5
|
||||||
|
recs = [{"slug": "member-d", "order_id": "or_4",
|
||||||
|
"charges": [(dt("2026-10-09"), "tx_d1"), (dt("2026-11-02"), "tx_d2")]}]
|
||||||
|
check("exact pro-rate, no rounding", [g["amount"] for g in derive_shortfalls(recs, 15.0)], [3.0])
|
||||||
|
recs = [{"slug": "member-e", "order_id": "or_5",
|
||||||
|
"charges": [(dt("2026-10-06"), "tx_e1"), (dt("2026-11-02"), "tx_e2")]}]
|
||||||
|
check("half-dollar stays exact", [g["amount"] for g in derive_shortfalls(recs, 15.0)], [1.5])
|
||||||
|
|
||||||
|
# --- per-order boundary: two orders six days apart are NOT one truncated cycle
|
||||||
|
recs = [
|
||||||
|
{"slug": "member-f", "order_id": "or_6a", "charges": [(dt("2026-10-16"), "tx_f1")]},
|
||||||
|
{"slug": "member-f", "order_id": "or_6b", "charges": [(dt("2026-10-22"), "tx_f2")]},
|
||||||
|
]
|
||||||
|
check("two subscriptions are judged separately (no cross-order pair)",
|
||||||
|
derive_shortfalls(recs, budget=15.0), [])
|
||||||
|
|
||||||
|
# --- a later (non-first) cycle can be truncated too
|
||||||
|
recs = [{"slug": "member-g", "order_id": "or_7",
|
||||||
|
"charges": [(dt("2026-09-02"), "tx_g1"), (dt("2026-10-02"), "tx_g2"),
|
||||||
|
(dt("2026-10-20"), "tx_g3")]}]
|
||||||
|
check("a later cycle is caught too",
|
||||||
|
[(g["prev"], g["cur"], g["reference"]) for g in derive_shortfalls(recs, 15.0)],
|
||||||
|
[("2026-10-02", "2026-10-20", "tx_g3")])
|
||||||
|
|
||||||
|
# --- the reference is the EARLY charge (the idempotence key)
|
||||||
|
recs = [{"slug": "member-h", "order_id": "or_8",
|
||||||
|
"charges": [(dt("2026-10-15"), "tx_h1"), (dt("2026-11-02"), "tx_h2")]}]
|
||||||
|
check("reference is the truncating (second) charge",
|
||||||
|
[g["reference"] for g in derive_shortfalls(recs, 15.0)], ["tx_h2"])
|
||||||
|
|
||||||
|
# --- formatting and reason helpers
|
||||||
|
check("_usd keeps exact amounts", [_usd(2.0), _usd(4.5), _usd(1.5)], ["$2", "$4.5", "$1.5"])
|
||||||
|
check("reason names the cycle",
|
||||||
|
shortfall_reason("2026-10-07", "2026-11-02"),
|
||||||
|
"allowance shortfall, truncated paid cycle 2026-10-07→2026-11-02 (OC billing alignment)")
|
||||||
|
|
||||||
|
# --- the manual-remediation exclusion is keyed on the charge ref alone
|
||||||
|
# --- (no member PII in this public repo; identity/timeline live in ops docs;
|
||||||
|
# --- the OC tx id IS the reference key and was approved as such — see the
|
||||||
|
# --- commit that restored it to match the deployed image)
|
||||||
|
check("remediated charge excluded by reference",
|
||||||
|
"tx_Kr6n3rW577OSjr2bIt5IC" in SHORTFALL_REMEDIATED, True)
|
||||||
|
|
||||||
|
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
|
||||||
|
sys.exit(1 if failures else 0)
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: hostile tokens must be a clean 401/403, never a 500/503.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-20 a scanner (192.238.226.25) POSTed to the Open Collective webhook
|
||||||
|
URL with a path token containing a non-ASCII character. `secrets.compare_digest`
|
||||||
|
REFUSES str containing non-ASCII with
|
||||||
|
|
||||||
|
TypeError: comparing strings with non-ASCII characters is not supported
|
||||||
|
|
||||||
|
so the auth check crashed before rejecting the request. The wrapper turned that
|
||||||
|
into a 503, the portal recorded it as an OC delivery that might have cost a
|
||||||
|
member money, and the sweep emailed info@ a false money-critical alarm. The
|
||||||
|
same crash produced 500s on /admin/* and /broker/* from the same scanner.
|
||||||
|
|
||||||
|
The guards proven here:
|
||||||
|
|
||||||
|
COMPARISON
|
||||||
|
1. `_secret_eq` compares arbitrary UTF-8 input and returns a bool; the raw
|
||||||
|
`compare_digest` is proven to raise, so the regression is real.
|
||||||
|
2. Empty never matches (a missing secret fails closed).
|
||||||
|
|
||||||
|
STATUS CODES
|
||||||
|
3. A webhook token with non-ASCII chars answers 401 — not 503 — and does not
|
||||||
|
ask OC to retry.
|
||||||
|
4. Non-ASCII in the admin, broker and sync-token headers answers 401/403,
|
||||||
|
not 500.
|
||||||
|
|
||||||
|
ORIGIN RECORDING
|
||||||
|
5. The refused delivery is recorded with its source address and user-agent.
|
||||||
|
6. The failure report names the source in the email body and says a
|
||||||
|
non-OC source is a probe, not a purchase.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_auth_probe_hardening.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["WEBHOOK_TOKEN"] = "test-webhook-token"
|
||||||
|
os.environ["ADMIN_TOKEN"] = "test-admin-token"
|
||||||
|
os.environ["ADMIN_TOKEN_LEGACY"] = "0"
|
||||||
|
os.environ["BROKER_SECRET"] = "test-broker-secret"
|
||||||
|
os.environ["LIBRECHAT_SYNC_TOKEN"] = "test-sync-token"
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
REAL_ASYNC_CLIENT = httpx.AsyncClient
|
||||||
|
UA = "probe-test/1.0"
|
||||||
|
NON_ASCII = "tøken-ø"
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, ok))
|
||||||
|
|
||||||
|
|
||||||
|
SENT = []
|
||||||
|
|
||||||
|
|
||||||
|
def fake_send(to, subject, body, *a, **k):
|
||||||
|
SENT.append({"to": to, "subject": subject, "body": body})
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
|
||||||
|
# --- 1. The raw stdlib call really does raise: this is the bug. ---
|
||||||
|
raised = False
|
||||||
|
try:
|
||||||
|
secrets.compare_digest(NON_ASCII, NON_ASCII)
|
||||||
|
except TypeError:
|
||||||
|
raised = True
|
||||||
|
check("baseline: secrets.compare_digest raises on non-ASCII str", raised)
|
||||||
|
check("helper: identical ASCII secrets match", m._secret_eq("abc", "abc") is True)
|
||||||
|
check("helper: identical non-ASCII secrets match", m._secret_eq(NON_ASCII, NON_ASCII) is True)
|
||||||
|
check("helper: different non-ASCII secrets do not match",
|
||||||
|
m._secret_eq(NON_ASCII, "test-webhook-token") is False)
|
||||||
|
check("helper: empty never matches (fail closed)",
|
||||||
|
m._secret_eq("", "") is False and m._secret_eq("x", "") is False)
|
||||||
|
|
||||||
|
transport = httpx.ASGITransport(app=m.app, client=("192.238.226.25", 44321))
|
||||||
|
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
|
||||||
|
# --- 3. Hostile webhook token: 401, not 503. ---
|
||||||
|
r = await c.post(f"/webhook/opencollective/{NON_ASCII}",
|
||||||
|
json={"type": "order.processed", "data": {}},
|
||||||
|
headers={"user-agent": UA})
|
||||||
|
check(f"webhook: non-ASCII token answers 401 (got {r.status_code})",
|
||||||
|
r.status_code == 401)
|
||||||
|
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
||||||
|
check("webhook: the refusal does NOT ask OC to retry", body.get("retry") is not True)
|
||||||
|
|
||||||
|
# --- 5. The refusal is recorded with source + user-agent. ---
|
||||||
|
conn = m.get_db()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT status, detail, ip, user_agent FROM webhook_failures "
|
||||||
|
"ORDER BY id DESC LIMIT 1").fetchone()
|
||||||
|
conn.close()
|
||||||
|
check(f"record: the 401 is stored (got {row})", row is not None and row[0] == 401)
|
||||||
|
check("record: the row names the invalid token, not an exception",
|
||||||
|
row is not None and row[1] == "Invalid webhook token")
|
||||||
|
check(f"record: the source address is stored (got {row and row[2]!r})",
|
||||||
|
bool(row and row[2] == "192.238.226.25"))
|
||||||
|
check(f"record: the user-agent is stored (got {row and row[3]!r})",
|
||||||
|
bool(row and row[3] == UA))
|
||||||
|
|
||||||
|
# --- 4. Hostile header tokens: auth rejection, never 500. ---
|
||||||
|
for label, path, header in (
|
||||||
|
("admin", "/admin/aliases", "x-admin-token"),
|
||||||
|
("broker", "/broker/keys", "x-broker-secret"),
|
||||||
|
("sync", "/admin/librechat/keys", "x-sync-token"),
|
||||||
|
):
|
||||||
|
# httpx encodes str header values as ASCII and refuses non-ASCII;
|
||||||
|
# send the UTF-8 bytes, which is what a hostile client can send.
|
||||||
|
r = await c.get(path, headers=[
|
||||||
|
(header.encode("ascii"), NON_ASCII.encode("utf-8")),
|
||||||
|
(b"user-agent", UA.encode("utf-8")),
|
||||||
|
])
|
||||||
|
check(f"{label}: non-ASCII header token answers 401/403, not 500 "
|
||||||
|
f"(got {r.status_code})", r.status_code in (401, 403))
|
||||||
|
|
||||||
|
# --- 6. The report names the source and calls a non-OC source a probe. ---
|
||||||
|
SENT.clear()
|
||||||
|
m.send_email = fake_send
|
||||||
|
rep = m.webhook_failure_report()
|
||||||
|
check(f"report: reported the refused delivery (got {rep.get('status')})",
|
||||||
|
rep.get("status") == "reported")
|
||||||
|
text = SENT[0]["body"] if SENT else ""
|
||||||
|
check(f"report: the body names the source (got {text[:120]!r})",
|
||||||
|
"[source " in text)
|
||||||
|
check("report: the body distinguishes a probe from an OC purchase",
|
||||||
|
"probe, not a purchase" in text)
|
||||||
|
check("report: the body still explains the token-mismatch case",
|
||||||
|
"WEBHOOK_TOKEN" in text)
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for the OC-balance self-heal (the Nov 2026 chart hole).
|
||||||
|
|
||||||
|
Incident: the 03:15 snapshot on 2026-11-12 DID record oc_balance_usd=1357.39,
|
||||||
|
but a repair backfill run hours later rewrote the day through backfill()'s
|
||||||
|
full-row upsert — whose row dict carries no balance key — and ON CONFLICT wrote
|
||||||
|
NULL over it. Nothing revisited a day's balance afterwards, so the hole was
|
||||||
|
permanent and the money chart broke mid-line.
|
||||||
|
|
||||||
|
Fixes under test here:
|
||||||
|
* upsert() never erases a balance it did not measure (COALESCE on conflict);
|
||||||
|
* the nightly snapshot heals any RECENT day with a missing balance from OC's
|
||||||
|
transaction ledger (balance column ONLY — membership/usage never touched);
|
||||||
|
* days before the series' first recorded balance stay NULL by design;
|
||||||
|
* an OC failure is fail-soft: hole stays, next night retries, nothing raises.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* from the repo root: python3 tests/test_balance_backfill.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 tests/test_balance_backfill.py
|
||||||
|
"""
|
||||||
|
import datetime as dt
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="balance-heal-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE metrics_snapshot is imported
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"),
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "metrics_snapshot.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
import metrics_snapshot as ms # noqa: E402
|
||||||
|
|
||||||
|
TODAY = ms.today()
|
||||||
|
YESTERDAY = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=1)).isoformat()
|
||||||
|
DAY_MINUS2 = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=2)).isoformat()
|
||||||
|
DAY_MINUS5 = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=5)).isoformat()
|
||||||
|
|
||||||
|
FAILED = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, cond, detail=""):
|
||||||
|
if cond:
|
||||||
|
print(f" ok {name}")
|
||||||
|
else:
|
||||||
|
print(f" FAIL {name} {detail}")
|
||||||
|
FAILED.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def read_row(day):
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
try:
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn.execute("SELECT * FROM metrics_daily WHERE day = ?", (day,)).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def wipe():
|
||||||
|
ms.connect().close() # ensure the table exists (schema init)
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
conn.execute("DELETE FROM metrics_daily")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def stub_sources(**kw):
|
||||||
|
"""Replace every network source with fixed in-memory data."""
|
||||||
|
ms.from_sqlite = lambda: {"active": kw.get("active", 40), "total": kw.get("total", 71),
|
||||||
|
"joins": list(kw.get("joins", []))}
|
||||||
|
ms.from_listmonk = lambda: kw.get("subs", 71)
|
||||||
|
ms.listmonk_joins = lambda: list(kw.get("joins", []))
|
||||||
|
ms.from_matrix = lambda: kw.get("matrix", 65)
|
||||||
|
ms.oc_collective_balance = lambda: kw.get("balance", 123.45)
|
||||||
|
ms.spend_by_day = lambda since=None: dict(kw.get("spend", {}))
|
||||||
|
ms.operator_spend_by_day = lambda since=None: None if kw.get("op_spend") is None else dict(kw.get("op_spend") or {})
|
||||||
|
ms.tokens_by_day_model = lambda since=None: {k: dict(v) for k, v in (kw.get("tokens") or {}).items()}
|
||||||
|
|
||||||
|
|
||||||
|
def seed(day, **cols):
|
||||||
|
ms.upsert(day, {"spend_usd": None, "requests": None, "out_tokens": None,
|
||||||
|
"energy_wh": None, "co2e_g": None, "tokens_measured": None,
|
||||||
|
"tokens_estimated": None, "factor_revision": None, **cols})
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
print("1. REGRESSION: a full-row rewrite without a balance never erases one "
|
||||||
|
"(the 2026-11-12 incident)")
|
||||||
|
wipe()
|
||||||
|
# The day as the 03:15 snapshot wrote it: membership + usage + a live balance.
|
||||||
|
seed(TODAY, spend_usd=3.38, requests=674, members_active=113, members_total=113,
|
||||||
|
members_new=2, newsletter_subs=122, matrix_space_members=36, oc_balance_usd=1357.39)
|
||||||
|
# Full backfill (the shape the 2026-11-12 18:42 repair ran): its today-branch
|
||||||
|
# rewrites the day with a dict that has NO oc_balance_usd key.
|
||||||
|
stub_sources(joins=["2026-11-01"], spend={TODAY: (3.38, 674)}, op_spend={TODAY: 0.9},
|
||||||
|
tokens={TODAY: {"greenpt/glm-5.3-flash": 379040}})
|
||||||
|
ms.backfill()
|
||||||
|
t = read_row(TODAY)
|
||||||
|
check("backfill rewrote the day (test is live)", t["members_total"] == 71, t["members_total"])
|
||||||
|
check("the recorded balance SURVIVED the rewrite", t["oc_balance_usd"] == 1357.39,
|
||||||
|
t["oc_balance_usd"])
|
||||||
|
|
||||||
|
print("2. snapshot() with a failed OC read keeps a balance recorded earlier that day")
|
||||||
|
wipe()
|
||||||
|
seed(TODAY, spend_usd=0.5, requests=10, members_active=40, members_total=71,
|
||||||
|
oc_balance_usd=1357.39)
|
||||||
|
stub_sources(spend={YESTERDAY: (5.0, 100), TODAY: (0.7, 20)}, op_spend=None, tokens={},
|
||||||
|
balance=None)
|
||||||
|
ms.snapshot()
|
||||||
|
t = read_row(TODAY)
|
||||||
|
check("today's row still refreshed (spend updated)", t["spend_usd"] == 0.7, t["spend_usd"])
|
||||||
|
check("earlier balance kept when the fresh read failed", t["oc_balance_usd"] == 1357.39,
|
||||||
|
t["oc_balance_usd"])
|
||||||
|
|
||||||
|
print("3. self-heal reconstructs a missing day from the ledger — balance column ONLY")
|
||||||
|
wipe()
|
||||||
|
seed(DAY_MINUS2, spend_usd=1.0, requests=50, members_active=39, members_total=70,
|
||||||
|
oc_balance_usd=1200.0)
|
||||||
|
# The hole: yesterday's row exists, everything but the balance.
|
||||||
|
seed(YESTERDAY, spend_usd=2.0, requests=60, members_active=39, members_total=70,
|
||||||
|
newsletter_subs=71, matrix_space_members=65)
|
||||||
|
seed(TODAY, spend_usd=0.5, requests=10, members_active=40, members_total=71,
|
||||||
|
oc_balance_usd=1470.44)
|
||||||
|
READ_AT = TODAY + "T03:15:58.123Z"
|
||||||
|
# Ledger after the two cutoffs: yesterday +73.05, day-before +113.05 (all days
|
||||||
|
# cumulative toward the anchor). Signed as OC stores them: CREDIT +, DEBIT -.
|
||||||
|
ledger = [
|
||||||
|
{"createdAt": DAY_MINUS2 + "T10:00:00.000Z", "type": "CREDIT", "amount": {"valueInCents": 5000}},
|
||||||
|
{"createdAt": DAY_MINUS2 + "T10:00:00.200Z", "type": "DEBIT", "amount": {"valueInCents": -500}},
|
||||||
|
{"createdAt": YESTERDAY + "T12:00:00.000Z", "type": "CREDIT", "amount": {"valueInCents": 7805}},
|
||||||
|
{"createdAt": READ_AT, "type": "DEBIT", "amount": {"valueInCents": -1000}}, # exactly at read_at: in the (C, read_at] window
|
||||||
|
]
|
||||||
|
ms.oc_fetch_transactions = lambda date_from, date_to: list(ledger)
|
||||||
|
ms.heal_missing_balances(1470.44, READ_AT)
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
d2 = read_row(DAY_MINUS2)
|
||||||
|
t = read_row(TODAY)
|
||||||
|
check("hole filled: yesterday = anchor - net(yesterday 03:15 .. read_at)",
|
||||||
|
y["oc_balance_usd"] == 1470.44 - (7805 - 1000) / 100.0, y["oc_balance_usd"])
|
||||||
|
check("existing days untouched by the heal", d2["oc_balance_usd"] == 1200.0 and t["oc_balance_usd"] == 1470.44)
|
||||||
|
check("membership columns of the healed day intact",
|
||||||
|
y["members_active"] == 39 and y["members_total"] == 70 and y["newsletter_subs"] == 71)
|
||||||
|
check("usage columns of the healed day intact", y["spend_usd"] == 2.0 and y["requests"] == 60)
|
||||||
|
|
||||||
|
print("4. pre-history stays NULL — a hole BEFORE the first recorded day is not invented")
|
||||||
|
wipe()
|
||||||
|
seed(DAY_MINUS5, spend_usd=1.0, requests=5) # before the series' first balance
|
||||||
|
seed(DAY_MINUS2, spend_usd=1.0, requests=5, oc_balance_usd=1200.0)
|
||||||
|
seed(TODAY, oc_balance_usd=1470.44)
|
||||||
|
ms.oc_fetch_transactions = lambda date_from, date_to: []
|
||||||
|
ms.heal_missing_balances(1470.44, READ_AT)
|
||||||
|
d5 = read_row(DAY_MINUS5)
|
||||||
|
check("day before the first balance stays NULL (gap by design)", d5["oc_balance_usd"] is None,
|
||||||
|
d5["oc_balance_usd"])
|
||||||
|
|
||||||
|
print("5. OC ledger failure is fail-soft: hole stays, nothing raises, no zero written")
|
||||||
|
wipe()
|
||||||
|
seed(DAY_MINUS2, oc_balance_usd=1200.0)
|
||||||
|
seed(YESTERDAY, spend_usd=2.0, members_active=39, oc_balance_usd=None)
|
||||||
|
seed(TODAY, oc_balance_usd=1470.44)
|
||||||
|
def _boom(date_from, date_to):
|
||||||
|
raise RuntimeError("OC unreachable (test)")
|
||||||
|
ms.oc_fetch_transactions = _boom
|
||||||
|
ms.heal_missing_balances(1470.44, READ_AT) # must not raise
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
check("hole left NULL for the next night", y["oc_balance_usd"] is None, y["oc_balance_usd"])
|
||||||
|
check("no zero written on failure", y["oc_balance_usd"] != 0.0)
|
||||||
|
|
||||||
|
print("6. write_balance on a day with NO row inserts balance + NULL everything else")
|
||||||
|
wipe()
|
||||||
|
ms.write_balance(YESTERDAY, 1357.39)
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
check("balance written", y["oc_balance_usd"] == 1357.39)
|
||||||
|
check("membership/usage columns NULL (fail-closed, never zero)",
|
||||||
|
y["members_active"] is None and y["spend_usd"] is None and y["requests"] is None)
|
||||||
|
|
||||||
|
print("7. anchor=None (OC read failed this run) heals nothing")
|
||||||
|
wipe()
|
||||||
|
seed(DAY_MINUS2, oc_balance_usd=1200.0)
|
||||||
|
seed(YESTERDAY, oc_balance_usd=None)
|
||||||
|
seed(TODAY, oc_balance_usd=1470.44)
|
||||||
|
ms.oc_fetch_transactions = lambda date_from, date_to: list(ledger)
|
||||||
|
ms.heal_missing_balances(None, READ_AT)
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
check("no heal without an anchor balance", y["oc_balance_usd"] is None, y["oc_balance_usd"])
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILED:
|
||||||
|
print(f"FAILED: {len(FAILED)} check(s): {FAILED}")
|
||||||
|
sys.exit(1)
|
||||||
|
print("ALL CHECKS PASSED")
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for the per-member daily usage series (Nov 2026).
|
||||||
|
|
||||||
|
The member dashboard's usage chart needs per-day spend/requests for the
|
||||||
|
signed-in member, bounded by the days parameter. /broker/usage now carries a
|
||||||
|
`daily` series (additive — every existing field is untouched, so older
|
||||||
|
dashboards keep working), built by member_daily_usage (DB path) or
|
||||||
|
daily_series_from_rows (HTTP fallback). These tests pin:
|
||||||
|
|
||||||
|
1. the route->handler table for /broker/usage (a decorator landing on the
|
||||||
|
wrong handler is invisible to every check except a request);
|
||||||
|
2. the DB path's SQL: day convention matches the co-op daily series
|
||||||
|
(to_char("startTime", 'YYYY-MM-DD')), the window filter goes on the
|
||||||
|
column DIRECTLY (a COALESCE with '' on a timestamp column was the
|
||||||
|
silent-empty-window bug in the model leaderboard), and requests excludes
|
||||||
|
failed attempts;
|
||||||
|
3. daily_series_from_rows: team filtering happens BEFORE it is called, rows
|
||||||
|
without a parseable day are skipped, spend sums failures too, requests
|
||||||
|
does not, output is day-ascending;
|
||||||
|
4. broker_get_usage's response contract: `daily` present and fail-soft
|
||||||
|
(a daily-query failure degrades to [], never an error).
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_broker_usage_daily.py
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="usage-daily-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"),
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
ROOT = Path(_cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
import app.main as portal # noqa: E402
|
||||||
|
|
||||||
|
FAILED = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, cond, detail=""):
|
||||||
|
if cond:
|
||||||
|
print(f" ok {name}")
|
||||||
|
else:
|
||||||
|
print(f" FAIL {name} {detail}")
|
||||||
|
FAILED.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
# --- 1. route -> handler table (touched route AND its neighbours) ------------
|
||||||
|
src = (ROOT / "app" / "main.py").read_text()
|
||||||
|
|
||||||
|
def handler_for(path_literal):
|
||||||
|
m = re.search(
|
||||||
|
r'@app\.get\("' + re.escape(path_literal) + r'"\)\n(?:@[^\n]+\n)*async def (\w+)',
|
||||||
|
src,
|
||||||
|
)
|
||||||
|
return m.group(1) if m else None
|
||||||
|
|
||||||
|
check("/broker/usage -> broker_usage", handler_for("/broker/usage") == "broker_usage",
|
||||||
|
f"got {handler_for('/broker/usage')}")
|
||||||
|
check("/broker/metrics -> broker_metrics", handler_for("/broker/metrics") == "broker_metrics",
|
||||||
|
f"got {handler_for('/broker/metrics')}")
|
||||||
|
check("/broker/keys exists", handler_for("/broker/keys") is not None)
|
||||||
|
|
||||||
|
# --- 2. member_daily_usage SQL ------------------------------------------------
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
class _Cur:
|
||||||
|
def __init__(self, rows):
|
||||||
|
self._rows = rows
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def execute(self, sql, params):
|
||||||
|
captured["sql"] = sql
|
||||||
|
captured["params"] = list(params)
|
||||||
|
|
||||||
|
def fetchall(self):
|
||||||
|
return [("2026-11-10", 0.5, 3), ("2026-11-11", 1.25, 5)]
|
||||||
|
|
||||||
|
|
||||||
|
class _Conn:
|
||||||
|
def __init__(self, rows):
|
||||||
|
self._rows = rows
|
||||||
|
|
||||||
|
def cursor(self):
|
||||||
|
return _Cur(self._rows)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
orig_db_ready = portal.litellm_db_ready
|
||||||
|
orig_pg = portal._pg_connect
|
||||||
|
portal.litellm_db_ready = lambda: True
|
||||||
|
portal._pg_connect = lambda: _Conn(None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
out = portal.member_daily_usage(days=90, team_id="team-abc")
|
||||||
|
sql = re.sub(r"\s+", " ", captured["sql"])
|
||||||
|
check("day convention matches the co-op series",
|
||||||
|
"to_char(\"startTime\", 'YYYY-MM-DD')" in sql, sql[:120])
|
||||||
|
check("window filter on the column directly",
|
||||||
|
'"startTime" >= %s' in sql
|
||||||
|
and "COALESCE" not in sql.split("WHERE", 1)[-1], sql[:200])
|
||||||
|
check("failure rows excluded from requests",
|
||||||
|
"COUNT(*) FILTER (WHERE status IS DISTINCT FROM 'failure')" in sql)
|
||||||
|
check("team filter bound as parameter", captured["params"][-1] == "team-abc",
|
||||||
|
f"params={captured['params']}")
|
||||||
|
check("rows mapped to day/spend/requests",
|
||||||
|
out == [{"day": "2026-11-10", "spend": 0.5, "requests": 3},
|
||||||
|
{"day": "2026-11-11", "spend": 1.25, "requests": 5}], str(out))
|
||||||
|
|
||||||
|
# days=0 (no param) -> no window filter at all (backward-compatible default)
|
||||||
|
portal.member_daily_usage(days=0, team_id="team-abc")
|
||||||
|
check("days=0 means all time (no window predicate)",
|
||||||
|
'"startTime" >=' not in captured["sql"])
|
||||||
|
finally:
|
||||||
|
portal.litellm_db_ready = orig_db_ready
|
||||||
|
portal._pg_connect = orig_pg
|
||||||
|
|
||||||
|
# DB unconfigured must raise RuntimeError (the caller degrades to an empty
|
||||||
|
# series) — with the real litellm_db_ready restored and no stub.
|
||||||
|
db_ready_now = portal.litellm_db_ready()
|
||||||
|
if db_ready_now:
|
||||||
|
# A live DB on this host: re-stub to the unconfigured state for this check.
|
||||||
|
portal.litellm_db_ready = lambda: False
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
portal.member_daily_usage(days=30, team_id="t")
|
||||||
|
check("DB unconfigured raises RuntimeError", False, "no raise")
|
||||||
|
except RuntimeError:
|
||||||
|
check("DB unconfigured raises RuntimeError", True)
|
||||||
|
except Exception as e:
|
||||||
|
check("DB unconfigured raises RuntimeError", False, f"raised {type(e).__name__}: {e}")
|
||||||
|
finally:
|
||||||
|
portal.litellm_db_ready = orig_db_ready
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
portal.member_daily_usage(days=30, team_id="t")
|
||||||
|
check("DB unconfigured raises RuntimeError", False, "no raise")
|
||||||
|
except RuntimeError:
|
||||||
|
check("DB unconfigured raises RuntimeError", True)
|
||||||
|
except Exception as e:
|
||||||
|
check("DB unconfigured raises RuntimeError", False, f"raised {type(e).__name__}: {e}")
|
||||||
|
|
||||||
|
# --- 3. daily_series_from_rows ------------------------------------------------
|
||||||
|
rows = [
|
||||||
|
{"startTime": "2026-11-10 08:15:00+00", "spend": 0.10, "status": "success"},
|
||||||
|
{"startTime": "2026-11-10 09:00:00+00", "spend": 0.20, "status": "failure"},
|
||||||
|
{"startTime": "2026-11-11 00:05:00+00", "spend": 0.30, "status": "success"},
|
||||||
|
{"startTime": "", "spend": 9.99, "status": "success"}, # unparseable day: skipped
|
||||||
|
]
|
||||||
|
out = portal.daily_series_from_rows(rows)
|
||||||
|
check("fallback series: spend sums failures, requests does not",
|
||||||
|
out == [{"day": "2026-11-10", "spend": 0.3, "requests": 1},
|
||||||
|
{"day": "2026-11-11", "spend": 0.3, "requests": 1}], str(out))
|
||||||
|
check("fallback series ascending by day",
|
||||||
|
[r["day"] for r in out] == sorted(r["day"] for r in out))
|
||||||
|
check("fallback series on empty/None input", portal.daily_series_from_rows(None) == []
|
||||||
|
and portal.daily_series_from_rows([]) == [])
|
||||||
|
|
||||||
|
# Calendar fill: a day with no usage rows inside the measured span becomes an
|
||||||
|
# explicit zero (measured), so chart x-spacing is true; days outside the span
|
||||||
|
# are never invented.
|
||||||
|
gappy = portal.daily_series_from_rows([
|
||||||
|
{"startTime": "2026-11-08 10:00:00+00", "spend": 1.0, "status": "success"},
|
||||||
|
{"startTime": "2026-11-11 10:00:00+00", "spend": 2.0, "status": "success"},
|
||||||
|
])
|
||||||
|
check("calendar fill: interior zero days explicit, ends respected",
|
||||||
|
[r["day"] for r in gappy] == ["2026-11-08", "2026-11-09", "2026-11-10", "2026-11-11"]
|
||||||
|
and gappy[1] == {"day": "2026-11-09", "spend": 0.0, "requests": 0}
|
||||||
|
and gappy[0]["spend"] == 1.0 and gappy[3]["spend"] == 2.0, str(gappy))
|
||||||
|
|
||||||
|
# --- 4. broker_get_usage response contract ------------------------------------
|
||||||
|
check("DB path returns 'daily' key (source contract)",
|
||||||
|
'"daily": daily' in src)
|
||||||
|
check("daily query is fail-soft in the DB path",
|
||||||
|
re.search(r"daily usage query failed.*?\n\s*daily = \[\]", src, re.S) is not None)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILED:
|
||||||
|
print(f"FAILED: {len(FAILED)} check(s): " + ", ".join(FAILED))
|
||||||
|
sys.exit(1)
|
||||||
|
print("broker usage daily series: OK")
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: ONE definition of the co-op's all-time spend.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-13 the panel's card said $941.37 and the member dashboard's said
|
||||||
|
$900.51 — the same claim, two numbers. The panel used the portal's per-team
|
||||||
|
query; the dashboard summed the chart series IN THE BROWSER, which disagrees
|
||||||
|
with the server whenever a row is null, capped or stale. coop_spend_totals()
|
||||||
|
is now the single source, exposed to the panel's boot payload, the money
|
||||||
|
payload and the broker's metrics.
|
||||||
|
|
||||||
|
The split has to be the same split on every surface, and a failure to compute
|
||||||
|
it must NEVER look like "$0 spent": the safe wrapper returns {} so callers
|
||||||
|
omit the key instead of printing a zero that reads as fact.
|
||||||
|
"""
|
||||||
|
import pathlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(cond, msg):
|
||||||
|
print((" ok " if cond else " FAIL ") + msg)
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(msg)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeCursor:
|
||||||
|
def __init__(self, rows):
|
||||||
|
self._rows = rows
|
||||||
|
|
||||||
|
def execute(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def fetchall(self):
|
||||||
|
return self._rows
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConn:
|
||||||
|
def __init__(self, rows):
|
||||||
|
self._rows = rows
|
||||||
|
|
||||||
|
def cursor(self):
|
||||||
|
return FakeCursor(self._rows)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
ROWS = [
|
||||||
|
("member:alice@example.org", 10.005),
|
||||||
|
("member:bob@example.org", 5.005),
|
||||||
|
("agent:infrastructure-bot", 1.5),
|
||||||
|
("sandbox:throwaway", 0.02),
|
||||||
|
("", 1.07), # spend rows with no team at all
|
||||||
|
]
|
||||||
|
|
||||||
|
real_ready, real_connect = m.litellm_db_ready, m._pg_connect
|
||||||
|
try:
|
||||||
|
m.litellm_db_ready = lambda: True
|
||||||
|
m._pg_connect = lambda: FakeConn(ROWS)
|
||||||
|
t = m.coop_spend_totals()
|
||||||
|
|
||||||
|
print("1. the split adds up and covers every row")
|
||||||
|
check(t["member_all_time_spend"] == 15.01,
|
||||||
|
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
|
||||||
|
check(t["own_all_time_spend"] == 2.59,
|
||||||
|
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
|
||||||
|
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
|
||||||
|
"total == member + own, so no dollar is counted twice or dropped")
|
||||||
|
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
|
||||||
|
f"total is every SpendLogs row ({round(sum(r[1] for r in ROWS), 2)}), the same universe the money chart sums")
|
||||||
|
|
||||||
|
print("2. a failure to compute must not look like $0")
|
||||||
|
def boom():
|
||||||
|
raise RuntimeError("LiteLLM DB credentials not configured")
|
||||||
|
m._pg_connect = boom
|
||||||
|
check(m._coop_spend_totals_safe() == {},
|
||||||
|
"the safe wrapper returns {} so callers omit the key instead of showing a fake zero")
|
||||||
|
m.litellm_db_ready = lambda: False
|
||||||
|
check(m._coop_spend_totals_safe() == {},
|
||||||
|
"and it degrades the same way when the DB is simply not configured")
|
||||||
|
finally:
|
||||||
|
m.litellm_db_ready, m._pg_connect = real_ready, real_connect
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILS:
|
||||||
|
print(f"coop spend totals: {len(FAILS)} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("coop spend totals: OK — one definition, one number, no fake zeros")
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for credit-pack webhook idempotence (audit H1, 2026-11-05).
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* from the repo root: python3 tests/test_credit_pack_idempotence.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_credit_pack_idempotence.py
|
||||||
|
(the container has the app's own dependencies; the host usually does not)
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
The webhook credit-pack grant used to key its dedupe on `data.get('id')`,
|
||||||
|
which is absent from real OC deliveries — every recorded reference came out
|
||||||
|
`oc:<slug>:` (empty suffix), so the key could not distinguish two purchases
|
||||||
|
by the same member, and NO exists-check guarded the grant at all. One
|
||||||
|
re-delivered (or replayed, or forged-but-OC-resolvable) event then credits
|
||||||
|
the pack a second time.
|
||||||
|
|
||||||
|
Covered:
|
||||||
|
- the reference is built per-ORDER (per-purchase), non-empty
|
||||||
|
- a replayed order credits exactly once, even though the handler runs
|
||||||
|
twice (simulated by replaying the same grant sequence)
|
||||||
|
- a NEW order from the same member is never blocked by an earlier one
|
||||||
|
- a LEGACY empty-suffix ledger row neither matches nor rejects a new
|
||||||
|
grant (no re-shaping of historical rows — the invariant the fix
|
||||||
|
must respect)
|
||||||
|
- held_credits.oc_reference carries a UNIQUE index (one hold per
|
||||||
|
purchase; NULLs and distinct legacy refs stay legal)
|
||||||
|
- the DB starts with the unique index present even though legacy
|
||||||
|
rows exist (no duplicate live rows to violate it)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditpack-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
# Locate the app package: explicit env, the deployed path, or the repo root.
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.main import ( # noqa: E402
|
||||||
|
add_credits, credit_pack_reference, credit_reference_exists, get_credit_balance, get_db,
|
||||||
|
)
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = got == want
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def grant_once(email, amount, ref):
|
||||||
|
"""The exact grant sequence the webhook now runs (exists-check gates add)."""
|
||||||
|
if credit_reference_exists(ref):
|
||||||
|
return "already_credited"
|
||||||
|
add_credits(email, amount, reason="credit pack purchase (Open Collective)", reference=ref)
|
||||||
|
return "credits_added"
|
||||||
|
|
||||||
|
|
||||||
|
# --- reference building: per-order, non-empty, distinct per purchase ---
|
||||||
|
check("reference keyed on the order id",
|
||||||
|
credit_pack_reference("caseyg", {"idV2": "or_abc123"}), "oc:or_abc123")
|
||||||
|
check("two purchases differ even from one member",
|
||||||
|
credit_pack_reference("caseyg", {"idV2": "or_1"}) != credit_pack_reference("caseyg", {"idV2": "or_2"}),
|
||||||
|
True)
|
||||||
|
try:
|
||||||
|
credit_pack_reference("caseyg", {})
|
||||||
|
check("missing order idV2 refused (no ambiguous/empty reference)", False, True)
|
||||||
|
credit_pack_reference("caseyg", {"idV2": ""})
|
||||||
|
check("empty order idV2 refused", False, True)
|
||||||
|
except ValueError:
|
||||||
|
check("missing/empty order idV2 refused (no ambiguous/empty reference)", True, True)
|
||||||
|
|
||||||
|
# --- replay on a real (temporary) DB: one replay = exactly one credit ---
|
||||||
|
conn = get_db() # initializes schema (incl. the unique index) on the temp db
|
||||||
|
conn.execute("INSERT INTO members (email, key_token, active) VALUES ('p@example.com', '', 1)")
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
ref_a = credit_pack_reference("p", {"idV2": "or_test_a"})
|
||||||
|
r1 = grant_once("p@example.com", 10.0, ref_a) # first delivery
|
||||||
|
r2 = grant_once("p@example.com", 10.0, ref_a) # re-delivery of the SAME order
|
||||||
|
check("first delivery grants", r1, "credits_added")
|
||||||
|
check("replay of the same order is refused", r2, "already_credited")
|
||||||
|
n = conn.execute("SELECT COUNT(*) FROM credit_ledger WHERE reference = ?", (ref_a,)).fetchone()[0]
|
||||||
|
check("exactly ONE ledger row for the replayed order", n, 1)
|
||||||
|
check("balance credited once (10, not 20)", get_credit_balance("p@example.com"), 10.0)
|
||||||
|
|
||||||
|
# --- a NEW purchase from the same member is never blocked ---
|
||||||
|
ref_b = credit_pack_reference("p", {"idV2": "or_test_b"})
|
||||||
|
r3 = grant_once("p@example.com", 5.0, ref_b)
|
||||||
|
check("a different order still credits normally", r3, "credits_added")
|
||||||
|
check("balance includes the second purchase", get_credit_balance("p@example.com"), 15.0)
|
||||||
|
|
||||||
|
# --- legacy empty-suffix rows: never matched, never reshaped ---
|
||||||
|
grant_once("legacy@example.com", 23.0, "oc:caseyg:") # simulate a pre-fix ledger row
|
||||||
|
legacy_rows = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM credit_ledger WHERE reference = 'oc:caseyg:'").fetchone()[0]
|
||||||
|
check("legacy row stored exactly as it was written", legacy_rows, 1)
|
||||||
|
new_from_legacy_member = credit_pack_reference("caseyg", {"idV2": "or_new"})
|
||||||
|
check("a new purchase does NOT match the legacy empty-suffix row",
|
||||||
|
credit_reference_exists(new_from_legacy_member), False)
|
||||||
|
check("a new purchase by the legacy member credits normally",
|
||||||
|
grant_once("legacy@example.com", 15.0, new_from_legacy_member), "credits_added")
|
||||||
|
still = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM credit_ledger WHERE reference = 'oc:caseyg:'").fetchone()[0]
|
||||||
|
check("the legacy row was neither rejected nor re-shaped", still, 1)
|
||||||
|
|
||||||
|
# --- held_credits.oc_reference: UNIQUE index semantics ---
|
||||||
|
idx = conn.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_held_credits_oc_reference'"
|
||||||
|
).fetchone()
|
||||||
|
check("unique index exists on a fresh (and the live-shaped) db", bool(idx), True)
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('buyer-a', NULL, 'Buyer A', 20.0, 'oc:buyer-a:or_h1', 'held')")
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('buyer-a', NULL, 'Buyer A', 20.0, 'oc:buyer-a:or_h1', 'held')")
|
||||||
|
conn.commit()
|
||||||
|
check("second hold for the SAME order rejected by the unique index", False, True)
|
||||||
|
except sqlite3.IntegrityError:
|
||||||
|
conn.rollback()
|
||||||
|
check("second hold for the SAME order rejected by the unique index", True, True)
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('buyer-b', NULL, 'Buyer B', 10.0, 'oc:buyer-b:or_h2', 'held')")
|
||||||
|
conn.commit()
|
||||||
|
check("a different purchase still gets its own hold", True, True)
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('unknown', NULL, NULL, 10.0, NULL, 'held')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('unknown', NULL, NULL, 10.0, NULL, 'held')")
|
||||||
|
conn.commit()
|
||||||
|
check("NULL oc_reference rows stay legal (index does not overblock)", True, True)
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
|
||||||
|
sys.exit(1 if failures else 0)
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: credit-pack reconciliation (issue #7).
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
Credits are granted on exactly ONE path — the OC `order.processed` webhook —
|
||||||
|
and that path can fail AFTER the money has moved. On 2026-11-13 two purchases
|
||||||
|
did: a $50 pack whose delivery 500'd (httpx's invisible 5-second default), and
|
||||||
|
a $10 pack with no delivery in the retained log at all. Neither produced a
|
||||||
|
ledger row, and nothing on a schedule noticed. The reconcile pass reads OC's
|
||||||
|
OWN order list and compares it with our books.
|
||||||
|
|
||||||
|
The thing that makes this dangerous rather than merely absent is the matching:
|
||||||
|
our own stored references are NOT uniform, so the obvious
|
||||||
|
`oc:<slug>:<order.id>` test reported 21 already-credited purchases as missing
|
||||||
|
on its first run. A pass that "fixes" those would double-credit members. This
|
||||||
|
test pins down, case by case, what counts as accounted for:
|
||||||
|
|
||||||
|
* newer ledger rows carry the v2 id `oc:alice:or_…`
|
||||||
|
* older ledger rows carry a HYPHENATED id `oc:bob:8k03reyd-…`
|
||||||
|
* legacy rows carry an EMPTY suffix `oc:erin:`
|
||||||
|
* non-member purchases live in `held_credits`, not the ledger, and are
|
||||||
|
accounted for — they took the hold path on purpose
|
||||||
|
|
||||||
|
and that a purchase with NO such record is reported (dry run) or granted ONCE
|
||||||
|
(apply), using the same reference the webhook writes, so the two paths are
|
||||||
|
idempotent against each other in both directions.
|
||||||
|
|
||||||
|
Network is STUBBED; assertions are on our own recorded state.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_credit_pack_reconcile.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.ADMIN_TOKEN = "test-admin-token"
|
||||||
|
m.ADMIN_TOKEN_LEGACY = ""
|
||||||
|
m.CREDIT_RECONCILE = "report" # the shipped default
|
||||||
|
m.CREDIT_RECONCILE_DAYS = 30
|
||||||
|
|
||||||
|
NOW = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def iso(days_ago: float) -> str:
|
||||||
|
return (NOW - timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def stamp(days_ago: float) -> str:
|
||||||
|
return (NOW - timedelta(days=days_ago)).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
|
||||||
|
def order(oid, slug, amount, days_ago=1.0, tier="Credit pack", status="PAID",
|
||||||
|
frequency="ONETIME"):
|
||||||
|
return {"id": oid, "status": status, "createdAt": iso(days_ago),
|
||||||
|
"frequency": frequency, "amount": {"value": amount, "currency": "USD"},
|
||||||
|
"platformTipAmount": {"value": 0}, "totalAmount": {"value": amount},
|
||||||
|
"tier": {"name": tier, "slug": (tier or "").lower().replace(" ", "-")},
|
||||||
|
"fromAccount": {"slug": slug, "name": slug.title(), "type": "INDIVIDUAL"}}
|
||||||
|
|
||||||
|
|
||||||
|
ORDERS = [
|
||||||
|
# accounted by the EXACT v2 reference (and the ledger amount deliberately
|
||||||
|
# disagrees, to prove the exact match does not need the fuzzy second signal)
|
||||||
|
order("or_AAA", "alice", 50, 2.0),
|
||||||
|
# accounted only by the SECOND signal: older rows carry a hyphenated id
|
||||||
|
order("or_BBB", "bob", 50, 3.0),
|
||||||
|
# accounted only by the SECOND signal: a legacy EMPTY-suffix reference
|
||||||
|
order("or_EEE", "erin", 5, 4.0),
|
||||||
|
# accounted as HELD — a non-member purchase recorded on the hold path
|
||||||
|
order("or_HHH", "holdguy", 10, 5.0),
|
||||||
|
# GENUINELY UNACCOUNTED, and by an active member → the one real candidate
|
||||||
|
order("or_CCC", "carol", 10, 0.5),
|
||||||
|
# unaccounted, but the buyer is not an active member → hold path, not a grant
|
||||||
|
order("or_DDD", "dave", 10, 0.7),
|
||||||
|
# unaccounted and active, but outside the window → not this pass's business
|
||||||
|
order("or_FFF", "frank", 10, 100.0),
|
||||||
|
# not a credit pack / not paid / not one-time → never examined as a pack
|
||||||
|
order("or_G1", "carol", 15, 1.0, tier="Membership"),
|
||||||
|
order("or_G2", "carol", 10, 1.0, status="PENDING"),
|
||||||
|
order("or_G3", "carol", 10, 1.0, status="REFUNDED"),
|
||||||
|
order("or_G4", "carol", 10, 1.0, frequency="MONTHLY"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class Boom(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_orders(per_page=100, max_pages=3):
|
||||||
|
if FAIL_ORDERS:
|
||||||
|
raise Boom("OC said 500")
|
||||||
|
return list(ORDERS)
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_index():
|
||||||
|
if FAIL_INDEX:
|
||||||
|
raise Boom("member index unavailable")
|
||||||
|
return {e: {"slug": e.split("@")[0]} for e in
|
||||||
|
("alice@x.org", "bob@x.org", "carol@x.org", "dave@x.org",
|
||||||
|
"erin@x.org", "frank@x.org", "gina@x.org")}
|
||||||
|
|
||||||
|
|
||||||
|
BUDGET_PUSHES = []
|
||||||
|
SENT = []
|
||||||
|
|
||||||
|
|
||||||
|
def fake_send(to, subject, body, *a, **k):
|
||||||
|
SENT.append({"to": to, "subject": subject, "body": body})
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_budget(email):
|
||||||
|
BUDGET_PUSHES.append(email)
|
||||||
|
return 25.0
|
||||||
|
|
||||||
|
|
||||||
|
FAIL_ORDERS = False
|
||||||
|
FAIL_INDEX = False
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, bool(ok)))
|
||||||
|
|
||||||
|
|
||||||
|
def ledger_rows():
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.row_factory = __import__("sqlite3").Row
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT email, delta, reference, created_at FROM credit_ledger ORDER BY id")]
|
||||||
|
conn.close()
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def balance(email):
|
||||||
|
return m.get_credit_balance(email)
|
||||||
|
|
||||||
|
|
||||||
|
def seed():
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("DELETE FROM members")
|
||||||
|
conn.execute("DELETE FROM credit_ledger")
|
||||||
|
conn.execute("DELETE FROM held_credits")
|
||||||
|
# A fresh world: the report markers are part of the state under test, so a
|
||||||
|
# leftover fingerprint from an earlier section would silence a real notice.
|
||||||
|
conn.execute("DELETE FROM portal_state")
|
||||||
|
for email, slug, active in (("alice@x.org", "alice", 1), ("bob@x.org", "bob", 1),
|
||||||
|
("carol@x.org", "carol", 1), ("dave@x.org", "dave", 0),
|
||||||
|
("erin@x.org", "erin", 1), ("frank@x.org", "frank", 1)):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, slug, active, account_type, credit_balance) "
|
||||||
|
"VALUES (?, ?, ?, 'member', 0)", (email, slug, active))
|
||||||
|
# alice: the v2 form, with an amount that DISAGREES with the order ($48 ≠ $50)
|
||||||
|
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('alice@x.org', 48.0, 'credit pack', ?, ?)",
|
||||||
|
("oc:alice:or_AAA", stamp(2.0)))
|
||||||
|
# bob: the hyphenated legacy id for the SAME order (or_BBB)
|
||||||
|
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('bob@x.org', 50.0, 'credit pack', ?, ?)",
|
||||||
|
("oc:bob:8k03reyd-5agmq5x4-4nkplbwo-z7j4nxv9", stamp(3.0)))
|
||||||
|
# erin: the empty-suffix legacy form
|
||||||
|
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('erin@x.org', 5.0, 'credit pack', 'oc:erin:', ?)", (stamp(4.0),))
|
||||||
|
# holdguy: a non-member purchase held, never a ledger row
|
||||||
|
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference, "
|
||||||
|
"status, created_at) VALUES ('holdguy', 'hold@x.org', 'Hold Guy', 10.0, "
|
||||||
|
"'oc:holdguy:', 'pending', ?)", (stamp(5.0),))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def names(res):
|
||||||
|
return sorted(c["slug"] for c in res["candidates"])
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
global FAIL_ORDERS, FAIL_INDEX
|
||||||
|
m.fetch_collective_orders = fake_orders
|
||||||
|
m.fetch_member_index = fake_index
|
||||||
|
m.sync_team_budget_from_balance = fake_budget
|
||||||
|
m.send_email = fake_send
|
||||||
|
|
||||||
|
# ---------- dry run: report only, change nothing --------------------------
|
||||||
|
seed()
|
||||||
|
before = ledger_rows()
|
||||||
|
res = await m.reconcile_credit_packs(apply=False)
|
||||||
|
check(f"dry run reports ok (got {res.get('status')})", res.get("status") == "ok")
|
||||||
|
check("dry run is marked dry_run", res.get("dry_run") is True)
|
||||||
|
check(f"packs in window counted (got {res.get('packs_in_window')})",
|
||||||
|
res.get("packs_in_window") == 6)
|
||||||
|
check(f"only the unaccounted active-member pack is a candidate (got {names(res)})",
|
||||||
|
names(res) == ["carol"])
|
||||||
|
check(f"the inactive member's pack is a hold, not a grant (got {res['needs_hold']})",
|
||||||
|
[c["slug"] for c in res["needs_hold"]] == ["dave"])
|
||||||
|
check("dry run applied nothing", res.get("applied") == [])
|
||||||
|
check("dry run wrote no ledger row", ledger_rows() == before)
|
||||||
|
check(f"dry run left carol's balance alone (got {balance('carol@x.org')})",
|
||||||
|
balance("carol@x.org") == 0.0)
|
||||||
|
check("dry run pushed no budget", BUDGET_PUSHES == [])
|
||||||
|
|
||||||
|
# the three accounting shapes that a v2-only match would have called missing
|
||||||
|
for oid, slug, why in (("or_AAA", "alice", "exact v2 reference"),
|
||||||
|
("or_BBB", "bob", "hyphenated legacy id"),
|
||||||
|
("or_EEE", "erin", "empty-suffix legacy reference"),
|
||||||
|
("or_HHH", "holdguy", "held (non-member) purchase")):
|
||||||
|
o = next(x for x in ORDERS if x["id"] == oid)
|
||||||
|
ev = m.credit_pack_accounted(o, ledger_rows(), [
|
||||||
|
dict(r) for r in
|
||||||
|
conn_rows("SELECT id, slug, email, amount, oc_reference, status, created_at FROM held_credits")
|
||||||
|
])
|
||||||
|
check(f"accounted: {why} ({oid}) -> {ev}", ev is not None)
|
||||||
|
check("a genuinely unaccounted order stays unaccounted",
|
||||||
|
m.credit_pack_accounted(next(x for x in ORDERS if x["id"] == "or_CCC"),
|
||||||
|
ledger_rows(), []) is None)
|
||||||
|
|
||||||
|
# A manual grant with NO reference links to its member by EMAIL, and the slug
|
||||||
|
# and email local part routinely differ ("henry-smith" vs "h.smith@x.org").
|
||||||
|
# Matching only on the slug in the reference drops that row — which is how a
|
||||||
|
# hand-credited purchase comes to look like a gap.
|
||||||
|
henry = order("or_HH2", "henry-smith", 12, 1.0)
|
||||||
|
henry_rows = [{"email": "h.smith@x.org", "delta": 12.0, "reference": None,
|
||||||
|
"created_at": stamp(1.0), "reason": "manual application"}]
|
||||||
|
check("a reference-less manual grant is matched via the MEMBER EMAIL",
|
||||||
|
m.credit_pack_accounted(henry, henry_rows, [],
|
||||||
|
member_email="h.smith@x.org") is not None)
|
||||||
|
check("...and is NOT matched without it (the slug alone finds nothing)",
|
||||||
|
m.credit_pack_accounted(henry, henry_rows, []) is None)
|
||||||
|
|
||||||
|
# ---------- a read that fails is UNKNOWN, never 'nothing missing' ---------
|
||||||
|
FAIL_ORDERS = True
|
||||||
|
res = await m.reconcile_credit_packs(apply=False)
|
||||||
|
check(f"order fetch failure is skipped/order_fetch_failed (got {res})",
|
||||||
|
res.get("status") == "skipped" and res.get("reason") == "order_fetch_failed")
|
||||||
|
FAIL_ORDERS = False
|
||||||
|
FAIL_INDEX = True
|
||||||
|
res = await m.reconcile_credit_packs(apply=False)
|
||||||
|
check(f"member index failure is skipped/member_index_failed (got {res})",
|
||||||
|
res.get("status") == "skipped" and res.get("reason") == "member_index_failed")
|
||||||
|
FAIL_INDEX = False
|
||||||
|
|
||||||
|
# ---------- apply=1 while the policy is still 'report' --------------------
|
||||||
|
seed()
|
||||||
|
res = await m.reconcile_credit_packs(apply=True)
|
||||||
|
check("apply is IGNORED while CREDIT_RECONCILE != 'on'",
|
||||||
|
res.get("dry_run") is True and res.get("applied") == [])
|
||||||
|
check(f"and still nothing was credited (got {balance('carol@x.org')})",
|
||||||
|
balance("carol@x.org") == 0.0)
|
||||||
|
|
||||||
|
# ---------- CREDIT_RECONCILE=on: grant exactly once ----------------------
|
||||||
|
seed()
|
||||||
|
SENT.clear()
|
||||||
|
m.CREDIT_RECONCILE = "on"
|
||||||
|
res = await m.reconcile_credit_packs(apply=True)
|
||||||
|
check(f"apply grants the one candidate (got {res.get('applied')})",
|
||||||
|
[c["slug"] for c in res.get("applied", [])] == ["carol"])
|
||||||
|
check(f"carol credited $10 (got {balance('carol@x.org')})",
|
||||||
|
balance("carol@x.org") == 10.0)
|
||||||
|
ref = f"oc:carol:or_CCC"
|
||||||
|
check(f"the grant used the webhook's own reference ({ref})",
|
||||||
|
any(r["reference"] == ref for r in ledger_rows()))
|
||||||
|
check(f"exactly one ledger row was added (got {len(ledger_rows())})",
|
||||||
|
len(ledger_rows()) == 4)
|
||||||
|
check("the budget was pushed once", BUDGET_PUSHES == ["carol@x.org"])
|
||||||
|
check("the inactive member was NOT credited",
|
||||||
|
balance("dave@x.org") == 0.0)
|
||||||
|
check("the out-of-window member was NOT credited",
|
||||||
|
balance("frank@x.org") == 0.0)
|
||||||
|
|
||||||
|
# The money notice: someone is told when a purchase had to be recovered —
|
||||||
|
# and NOT told again about a set they have already heard about.
|
||||||
|
check(f"the grant mails a notice naming the order (got {len(SENT)})",
|
||||||
|
len(SENT) == 1 and "or_CCC" in SENT[0]["body"] and "carol" in SENT[0]["body"]
|
||||||
|
and SENT[0]["to"] == "info@inference.coop")
|
||||||
|
|
||||||
|
# the webhook and this pass must dedupe each other, whichever runs first
|
||||||
|
check("the webhook would now answer already_credited for this order",
|
||||||
|
m.credit_reference_exists(m.credit_pack_reference("carol", {"idV2": "or_CCC"})))
|
||||||
|
|
||||||
|
res = await m.reconcile_credit_packs(apply=True)
|
||||||
|
check(f"a second apply changes nothing (got {res.get('applied')})",
|
||||||
|
res.get("applied") == [] and res.get("candidates") == [])
|
||||||
|
check(f"carol's balance unchanged by the re-run (got {balance('carol@x.org')})",
|
||||||
|
balance("carol@x.org") == 10.0)
|
||||||
|
check(f"still one row for the order (got {len(ledger_rows())})",
|
||||||
|
len(ledger_rows()) == 4)
|
||||||
|
check(f"a re-run with nothing to report mails nothing (got {len(SENT)})", len(SENT) == 1)
|
||||||
|
|
||||||
|
# ---------- a candidate must SHOW the nearby rows a human needs ----------
|
||||||
|
# A manual grant can be real and carry no per-order reference: ntnsndr's three
|
||||||
|
# launch-day $5 packs were credited as +20.00 then corrected by -10.75, netting
|
||||||
|
# exactly 3 x $5.00, with no reference on any row. The matcher must NOT read
|
||||||
|
# that as accounted for (that would hide real gaps), so the candidate has to
|
||||||
|
# carry enough context for a reviewer to tell the two apart.
|
||||||
|
seed()
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT INTO members (email, slug, active, account_type, credit_balance) "
|
||||||
|
"VALUES ('gina@x.org', 'gina', 1, 'member', 0)")
|
||||||
|
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('gina@x.org', 7.5, 'manual application', NULL, ?)", (stamp(0.5),))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
async def only_gina(per_page=100, max_pages=3):
|
||||||
|
return [order("or_GGG", "gina", 10, 0.5)]
|
||||||
|
|
||||||
|
saved_orders = m.fetch_collective_orders
|
||||||
|
m.fetch_collective_orders = only_gina
|
||||||
|
res = await m.reconcile_credit_packs(apply=False)
|
||||||
|
cand = (res.get("candidates") or [{}])[0]
|
||||||
|
check(f"an unreferenced nearby grant is SURFACED on the candidate "
|
||||||
|
f"(got {cand.get('nearby_book_rows')})",
|
||||||
|
any(abs(float(n["delta"]) - 7.5) < 0.01
|
||||||
|
for n in cand.get("nearby_book_rows") or []))
|
||||||
|
check("a nearby unreferenced grant does NOT count as accounted for",
|
||||||
|
len(res.get("candidates") or []) == 1)
|
||||||
|
check(f"the pass still leaves the money alone (got {balance('gina@x.org')})",
|
||||||
|
balance("gina@x.org") == 0.0)
|
||||||
|
m.fetch_collective_orders = saved_orders
|
||||||
|
|
||||||
|
# ---------- the endpoint -------------------------------------------------
|
||||||
|
# Re-seed: the direct apply above already credited carol, so the endpoint
|
||||||
|
# would have no candidate and the check would pass for the wrong reason.
|
||||||
|
seed()
|
||||||
|
m.CREDIT_RECONCILE = "report"
|
||||||
|
|
||||||
|
async def endpoint_checks():
|
||||||
|
transport = httpx.ASGITransport(app=m.app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
|
||||||
|
r = await c.post("/admin/credit-pack-reconcile")
|
||||||
|
check(f"endpoint needs the admin token (got {r.status_code})",
|
||||||
|
r.status_code in (401, 403))
|
||||||
|
r = await c.post("/admin/credit-pack-reconcile",
|
||||||
|
headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
body = r.json()
|
||||||
|
check(f"endpoint defaults to a DRY RUN (got {body})",
|
||||||
|
r.status_code == 200 and body.get("dry_run") is True)
|
||||||
|
r = await c.post("/admin/credit-pack-reconcile?apply=1",
|
||||||
|
headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
body = r.json()
|
||||||
|
check("endpoint ?apply=1 is still a dry run while the policy is 'report'",
|
||||||
|
body.get("dry_run") is True and body.get("applied") == [])
|
||||||
|
m.CREDIT_RECONCILE = "on"
|
||||||
|
r = await c.post("/admin/credit-pack-reconcile?apply=1",
|
||||||
|
headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
body = r.json()
|
||||||
|
check(f"endpoint ?apply=1 grants once the policy is 'on' (got {body})",
|
||||||
|
body.get("dry_run") is False
|
||||||
|
and [x["slug"] for x in body.get("applied", [])] == ["carol"])
|
||||||
|
m.CREDIT_RECONCILE = "report"
|
||||||
|
|
||||||
|
await endpoint_checks()
|
||||||
|
|
||||||
|
|
||||||
|
def conn_rows(sql):
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.row_factory = __import__("sqlite3").Row
|
||||||
|
rows = conn.execute(sql).fetchall()
|
||||||
|
conn.close()
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import asyncio, os, sys, tempfile
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "sources.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, source) VALUES (?,?,?,?)",
|
||||||
|
("a@example.org", "slug-a", 1, "oc-incognito"))
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, source) VALUES (?,?,?,?)",
|
||||||
|
("b@example.org", "slug-b", 1, "oc-incognito"))
|
||||||
|
conn.commit(); conn.close()
|
||||||
|
|
||||||
|
m.fetch_member_index = lambda: [("a@example.org", "slug-a"), ("other@example.org", "slug-z")]
|
||||||
|
r = asyncio.run(m.derive_member_sources())
|
||||||
|
conn = m.get_db()
|
||||||
|
a = conn.execute("SELECT source, oc_email FROM members WHERE email='a@example.org'").fetchone()
|
||||||
|
b = conn.execute("SELECT source, oc_email FROM members WHERE email='b@example.org'").fetchone()
|
||||||
|
conn.close()
|
||||||
|
print(" flipped:", r["flipped"], "| a:", tuple(a), "| b:", tuple(b))
|
||||||
|
assert tuple(a) == ("oc", "a@example.org"), "visible email must flip the source and record it"
|
||||||
|
assert tuple(b) == ("oc-incognito", None), "a profile still hiding its email stays incognito"
|
||||||
|
print("DERIVE SOURCES OK: flips only where the profile now shows an email")
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Tests for app.main._current_dues (the member's CURRENT OC dues level).
|
||||||
|
|
||||||
|
The admin panel's "Dues" column shows what a member pays on Open Collective
|
||||||
|
(e.g. $10/mo). That figure is persisted by reconcile_allowances from the OC
|
||||||
|
orders it already fetches; this file pins the pure extraction rules:
|
||||||
|
|
||||||
|
* a live MONTHLY order -> its per-charge amount + 'MONTHLY';
|
||||||
|
* a live YEARLY order -> its amount + 'YEARLY' (no monthly normalization);
|
||||||
|
* ACTIVE and PROCESSING both count (a payment in flight is still the level);
|
||||||
|
* ONE-TIME orders never become dues — credit packs are purchases, not dues;
|
||||||
|
* CANCELLED / ERROR / PAST_DUE recurrences are not what the member pays now;
|
||||||
|
* no orders, an unparseable amount or a zero amount -> (None, None).
|
||||||
|
NULL is the ONLY honest answer; the code must never fall back to the $15
|
||||||
|
allowance or to a guessed tier.
|
||||||
|
|
||||||
|
python3 tests/test_dues_level.py
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.main import _current_dues # noqa: E402
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(cond, msg):
|
||||||
|
print((" ok " if cond else " FAIL ") + msg)
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def order(freq, status, amount, created="2026-11-17T01:52:56.450Z"):
|
||||||
|
return {"frequency": freq, "status": status,
|
||||||
|
"amount": {"value": amount, "currency": "USD"},
|
||||||
|
"totalAmount": {"value": amount, "currency": "USD"},
|
||||||
|
"createdAt": created, "lastChargedAt": created}
|
||||||
|
|
||||||
|
|
||||||
|
print("1. a live monthly subscription is the dues level")
|
||||||
|
check(_current_dues([order("MONTHLY", "ACTIVE", 10)]) == (10.0, "MONTHLY"),
|
||||||
|
"$10/month ACTIVE monthly -> (10.0, 'MONTHLY')")
|
||||||
|
check(_current_dues([order("MONTHLY", "PROCESSING", 12.5)]) == (12.5, "MONTHLY"),
|
||||||
|
"a PROCESSING monthly is still the current level (12.5, 'MONTHLY')")
|
||||||
|
|
||||||
|
print("2. yearly dues are reported as charged — not divided into months")
|
||||||
|
check(_current_dues([order("YEARLY", "ACTIVE", 120)]) == (120.0, "YEARLY"),
|
||||||
|
"$120/year ACTIVE yearly -> (120.0, 'YEARLY') (the panel appends '/yr')")
|
||||||
|
|
||||||
|
print("3. one-time orders are purchases, never a dues level")
|
||||||
|
check(_current_dues([order("ONETIME", "PAID", 10)]) == (None, None),
|
||||||
|
"a PAID $10 one-time order does not become dues")
|
||||||
|
check(_current_dues([order("ONETIME", "PAID", 10),
|
||||||
|
order("MONTHLY", "ACTIVE", 10)]) == (10.0, "MONTHLY"),
|
||||||
|
"a member with BOTH a one-time pack and a monthly subscription reads the monthly")
|
||||||
|
|
||||||
|
print("4. ended subscriptions do not report a stale level")
|
||||||
|
check(_current_dues([order("MONTHLY", "CANCELLED", 10)]) == (None, None),
|
||||||
|
"a CANCELLED monthly -> (None, None)")
|
||||||
|
check(_current_dues([order("MONTHLY", "ERROR", 10)]) == (None, None),
|
||||||
|
"an ERROR (failed charge) monthly -> (None, None)")
|
||||||
|
|
||||||
|
print("5. nothing readable -> NULL, never a guess")
|
||||||
|
check(_current_dues([]) == (None, None), "no orders -> (None, None)")
|
||||||
|
check(_current_dues(None) == (None, None), "a missing order list -> (None, None)")
|
||||||
|
check(_current_dues([{"frequency": "MONTHLY", "status": "ACTIVE"}]) == (None, None),
|
||||||
|
"a monthly with no totalAmount -> (None, None)")
|
||||||
|
check(_current_dues([order("MONTHLY", "ACTIVE", 0)]) == (None, None),
|
||||||
|
"a $0 monthly -> (None, None), not dues of zero")
|
||||||
|
check(_current_dues([{"frequency": "MONTHLY", "status": "ACTIVE",
|
||||||
|
"totalAmount": {"value": "not-a-number"}}]) == (None, None),
|
||||||
|
"an unparseable amount -> (None, None)")
|
||||||
|
|
||||||
|
print("6. stacked live monthlies are summed (not newest-only)")
|
||||||
|
old = order("MONTHLY", "ACTIVE", 5, "2024-01-01T00:00:00.000Z")
|
||||||
|
new = order("MONTHLY", "ACTIVE", 10, "2026-11-17T01:52:56.450Z")
|
||||||
|
check(_current_dues([new, old]) == (15.0, "MONTHLY"),
|
||||||
|
"two live monthly subscriptions are summed ($5 + $10 = $15)")
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILS:
|
||||||
|
print(f"dues level: {len(FAILS)} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("dues level: all checks passed")
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the first-login service-sync hook (activation path).
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
New members were deliberately skipped by the Loomio/Matrix syncs until their
|
||||||
|
Cloudron account was activated (never invite a half-created account), but
|
||||||
|
nothing fired the syncs at the moment they DID activate — the 3x/day sweep
|
||||||
|
was the pickup, so a member could wait hours for forum/space access. The
|
||||||
|
hook on the broker identity path closes that gap. The guards that must hold
|
||||||
|
are proven here on a FIXTURE db with the network STUBBED:
|
||||||
|
|
||||||
|
CHEAP GATE
|
||||||
|
1. An established member (loomio_invited_at set) schedules NOTHING and
|
||||||
|
triggers no Cloudron call — one SELECT, zero further work.
|
||||||
|
ACTIVATION FILTER (fail-closed)
|
||||||
|
2. A never-invited member whose Cloudron account is NOT activated fires no
|
||||||
|
sync — never invite a half-created account.
|
||||||
|
3. A member Cloudron does not know fires no sync.
|
||||||
|
4. An unreadable Cloudron user list fires no sync (fail-closed — unlike
|
||||||
|
the sweep's fail-open roster filter, the hook decides whether to fire
|
||||||
|
at all, so it must be sure).
|
||||||
|
FIRES
|
||||||
|
5. A never-invited member whose Cloudron account IS activated fires BOTH
|
||||||
|
syncs (Loomio then Matrix) exactly once, as a background task.
|
||||||
|
SAFETY
|
||||||
|
6. A sync failure is swallowed and logged; the inflight flag clears so a
|
||||||
|
later gate hit can retry (sweep remains the backstop).
|
||||||
|
7. While a sync is in flight, further gate hits schedule nothing (the
|
||||||
|
full-roster reconcile already covers every pending member).
|
||||||
|
8. The gate NEVER raises — even when its own DB read fails, the broker
|
||||||
|
response must be untouched.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_first_login_sync.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, ok))
|
||||||
|
|
||||||
|
|
||||||
|
async def drain():
|
||||||
|
"""Await every task the gate scheduled, so assertions are deterministic."""
|
||||||
|
cur = asyncio.current_task()
|
||||||
|
pending = [t for t in asyncio.all_tasks() if t is not cur]
|
||||||
|
if pending:
|
||||||
|
await asyncio.gather(*pending, return_exceptions=True)
|
||||||
|
|
||||||
|
|
||||||
|
CLOUDRON_USERS = [] # what the (stubbed) Cloudron user list returns
|
||||||
|
cloudron_calls = 0
|
||||||
|
sync_calls = [] # ("loomio"|"matrix") in fire order
|
||||||
|
sync_gate = None # optional asyncio.Event: hold the sync in flight
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_fetch_users(client=None):
|
||||||
|
global cloudron_calls
|
||||||
|
cloudron_calls += 1
|
||||||
|
if CLOUDRON_USERS is None:
|
||||||
|
return None
|
||||||
|
return CLOUDRON_USERS
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_loomio_sync():
|
||||||
|
sync_calls.append("loomio")
|
||||||
|
if sync_gate is not None:
|
||||||
|
await sync_gate.wait()
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_matrix_sync():
|
||||||
|
sync_calls.append("matrix")
|
||||||
|
|
||||||
|
|
||||||
|
async def boom_loomio_sync():
|
||||||
|
raise RuntimeError("simulated Loomio outage")
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
global CLOUDRON_USERS, cloudron_calls, sync_calls, sync_gate
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
for slug, email in (("est", "est@x.org"), ("new", "new@x.org"),
|
||||||
|
("pending", "pending@x.org"), ("ghost", "ghost@x.org")):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO members (email, slug, active) VALUES (?, ?, 1)",
|
||||||
|
(email, slug),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
m.cloudron_fetch_all_users = fake_fetch_users
|
||||||
|
m.sync_loomio_memberships = fake_loomio_sync
|
||||||
|
m.sync_matrix_space = fake_matrix_sync
|
||||||
|
|
||||||
|
# --- 1. CHEAP GATE: an established member schedules nothing at all. ---
|
||||||
|
m.mark_loomio_invited("est@x.org")
|
||||||
|
cloudron_calls = 0
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("est@x.org")
|
||||||
|
await drain()
|
||||||
|
check("established member: no sync scheduled", sync_calls == [])
|
||||||
|
check("established member: no Cloudron call", cloudron_calls == 0)
|
||||||
|
check("established member: inflight flag stays clear",
|
||||||
|
m._first_login_sync_inflight is False)
|
||||||
|
|
||||||
|
# --- 2. ACTIVATION FILTER: account not activated -> never fires. ---
|
||||||
|
CLOUDRON_USERS = [{"email": "new@x.org", "inviteAccepted": False}]
|
||||||
|
cloudron_calls = 0
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("new@x.org")
|
||||||
|
await drain()
|
||||||
|
check("not-activated member: no sync fired", sync_calls == [])
|
||||||
|
check("not-activated member: activation WAS checked", cloudron_calls == 1)
|
||||||
|
check("not-activated member: inflight flag cleared",
|
||||||
|
m._first_login_sync_inflight is False)
|
||||||
|
|
||||||
|
# --- 3. Unknown to Cloudron -> never fires. ---
|
||||||
|
CLOUDRON_USERS = [{"email": "other@x.org", "inviteAccepted": True}]
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("ghost@x.org")
|
||||||
|
await drain()
|
||||||
|
check("member unknown to Cloudron: no sync fired", sync_calls == [])
|
||||||
|
|
||||||
|
# --- 4. FAIL CLOSED: unreadable Cloudron user list -> never fires. ---
|
||||||
|
CLOUDRON_USERS = None
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("new@x.org")
|
||||||
|
await drain()
|
||||||
|
check("cloudron outage: no sync fired (fail-closed)", sync_calls == [])
|
||||||
|
check("cloudron outage: inflight flag cleared",
|
||||||
|
m._first_login_sync_inflight is False)
|
||||||
|
|
||||||
|
# --- 5. FIRES: activated + outstanding invites -> both syncs, once each. ---
|
||||||
|
CLOUDRON_USERS = [{"email": "NEW@x.org", "inviteAccepted": True}] # case-insensitive
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("new@x.org")
|
||||||
|
await drain()
|
||||||
|
check("activated member: Loomio sync fired first, then Matrix",
|
||||||
|
sync_calls == ["loomio", "matrix"])
|
||||||
|
check("activated member: inflight flag cleared after the run",
|
||||||
|
m._first_login_sync_inflight is False)
|
||||||
|
|
||||||
|
# --- 6. SAFETY: a sync failure is swallowed; the gate stays usable. ---
|
||||||
|
m.sync_loomio_memberships = boom_loomio_sync
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("new@x.org")
|
||||||
|
err = None
|
||||||
|
try:
|
||||||
|
await drain()
|
||||||
|
except Exception as e: # pragma: no cover
|
||||||
|
err = e
|
||||||
|
check("loomio outage: nothing escapes the background task", err is None)
|
||||||
|
check("loomio outage: matrix still attempted", sync_calls == ["matrix"])
|
||||||
|
check("loomio outage: inflight flag cleared for the next attempt",
|
||||||
|
m._first_login_sync_inflight is False)
|
||||||
|
m.sync_loomio_memberships = fake_loomio_sync
|
||||||
|
|
||||||
|
# --- 7. INFLIGHT: a second gate hit while a sync runs schedules nothing. ---
|
||||||
|
sync_gate = asyncio.Event()
|
||||||
|
sync_calls = []
|
||||||
|
m.maybe_first_login_service_sync("new@x.org") # task starts, blocks in loomio stub
|
||||||
|
await asyncio.sleep(0) # let it reach the blocking stub
|
||||||
|
check("inflight: flag is set while the sync runs",
|
||||||
|
m._first_login_sync_inflight is True)
|
||||||
|
m.maybe_first_login_service_sync("pending@x.org") # second member, same moment
|
||||||
|
m.maybe_first_login_service_sync("new@x.org") # same member again
|
||||||
|
sync_gate.set()
|
||||||
|
await drain()
|
||||||
|
check("inflight: exactly ONE sync ran for three gate hits",
|
||||||
|
sync_calls == ["loomio", "matrix"])
|
||||||
|
sync_gate = None
|
||||||
|
|
||||||
|
# --- 8. The gate NEVER raises, even if its own DB read fails. ---
|
||||||
|
real_invited = m.get_loomio_invited_at
|
||||||
|
|
||||||
|
def broken_invited(_email):
|
||||||
|
raise RuntimeError("simulated DB failure")
|
||||||
|
|
||||||
|
m.get_loomio_invited_at = broken_invited
|
||||||
|
err = None
|
||||||
|
try:
|
||||||
|
m.maybe_first_login_service_sync("new@x.org")
|
||||||
|
await drain()
|
||||||
|
except Exception as e:
|
||||||
|
err = e
|
||||||
|
check("gate swallows its own DB failure (broker response untouched)", err is None)
|
||||||
|
check("gate DB failure schedules nothing", sync_calls == ["loomio", "matrix"])
|
||||||
|
m.get_loomio_invited_at = real_invited
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import os, sys
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m
|
||||||
|
v=m._fx_verdict(1.16); assert v["alert"] is False, v
|
||||||
|
v=m._fx_verdict(1.20); assert v["alert"] is True and v["drift_pct"] > 0, v
|
||||||
|
v=m._fx_verdict(1.10); assert v["alert"] is True and v["drift_pct"] < 0, v
|
||||||
|
v=m._fx_verdict(1.157); assert v["alert"] is False, v # 0.26% drift
|
||||||
|
print("FX VERDICT OK: thresholds and signs behave")
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Guest-account SELF-CANCEL tests — structurally isolated from live services.
|
||||||
|
|
||||||
|
Same harness contract as test_guest_lifecycle.py: a FIXTURE database with the
|
||||||
|
network layer REPLACED BY A RAISING GUARD, so any code path that tries to
|
||||||
|
reach Cloudron, LiteLLM, OC, Listmonk or SMTP outside the stubs fails the
|
||||||
|
test loudly instead of acting on live systems.
|
||||||
|
|
||||||
|
GUARD
|
||||||
|
1. A paying member can NEVER cancel through the guest path (403).
|
||||||
|
2. An unknown identity is refused.
|
||||||
|
CANCEL (the full self-service flow)
|
||||||
|
3. The row deactivates (active=0) and the account is KEPT.
|
||||||
|
4. The Cloudron user leaves the guests group for the ended-guests group.
|
||||||
|
5. The gateway budget is zeroed (revoke path called).
|
||||||
|
6. The newsletter unsubscribe fires.
|
||||||
|
7. The credit RETURN is written: a NEGATIVE ledger delta whose reason
|
||||||
|
names the cancellation and the original guest reference, deduped on
|
||||||
|
its own reference; the member's credit_balance goes to 0.
|
||||||
|
8. The guests ledger records inviter → recipient → 'cancelled by
|
||||||
|
recipient' (rows appended, never rewritten).
|
||||||
|
IDEMPOTENCE
|
||||||
|
9. A second cancel is a NO-OP: no second ledger row, no re-deactivation
|
||||||
|
calls, and the reported status is the recorded one.
|
||||||
|
PARTIAL-FAILURE REPLAY
|
||||||
|
10. A cancel whose return row already exists (deactivation failed
|
||||||
|
mid-way last time) reports the recorded amount and writes no second
|
||||||
|
ledger row.
|
||||||
|
ENDED-STATE READBACK (GET /broker/guest-status payload pieces)
|
||||||
|
11. The cancelled guest reports ended + cancelled + the returned amount;
|
||||||
|
a live guest reports active with its remaining credits; a member
|
||||||
|
reports guest: false.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_guest_cancel.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
|
||||||
|
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
|
||||||
|
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
|
||||||
|
os.environ.setdefault("GUESTS_ENDED_GROUP_ID", "gid-fixture-guests-ended")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok, detail=""):
|
||||||
|
results.append((name, bool(ok), detail))
|
||||||
|
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
class _NoNetwork:
|
||||||
|
"""Guard: ANY httpx client construction inside the test is a failure."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
def __call__(self, *a, **k): # pragma: no cover
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = _NoNetwork
|
||||||
|
|
||||||
|
calls = {"group": [], "revoke": [], "listmonk": [], "email": []}
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_switch(user_id, add_gid=None, remove_gids=()):
|
||||||
|
calls["group"].append((user_id, add_gid))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_group(user_id, group_id=None):
|
||||||
|
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_revoke(email):
|
||||||
|
calls["revoke"].append(email)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_listmonk(email, subscribe):
|
||||||
|
calls["listmonk"].append((email, bool(subscribe)))
|
||||||
|
|
||||||
|
|
||||||
|
def rec_email(to, subject, text_body=None, html_body=None):
|
||||||
|
calls["email"].append((to, subject))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
TEAM_SPEND = {}
|
||||||
|
|
||||||
|
|
||||||
|
def fake_team_db(team_id):
|
||||||
|
return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0),
|
||||||
|
"budget_reset_at": None}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team_id(email):
|
||||||
|
return "team-" + email
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_switch_group = rec_switch
|
||||||
|
m.cloudron_set_group = rec_group
|
||||||
|
m.cloudron_set_active = rec_group # same signature (uid, bool)
|
||||||
|
m.litellm_team_id_for_email = fake_team_id
|
||||||
|
m.get_team_budget_from_db = fake_team_db
|
||||||
|
m.revoke_member_litellm_access = rec_revoke
|
||||||
|
m.listmonk_sync = rec_listmonk
|
||||||
|
m.send_email = rec_email
|
||||||
|
|
||||||
|
|
||||||
|
def seed_gift(conn, email, active=1, credits=2.0, balance=0.0):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type, guest_expires_at) "
|
||||||
|
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, ?, 'guest', "
|
||||||
|
"datetime('now', '+30 days'))",
|
||||||
|
(email, email, active, balance, credits),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
|
||||||
|
"VALUES ('member-one@x.org', ?, datetime('now'), 'active')", (email,)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ledger_rows(conn, email):
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT delta, reason, reference FROM credit_ledger WHERE email = ? "
|
||||||
|
"ORDER BY id", (email,)
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
# the inviter: an active member (guard requirement), and a PAYING member
|
||||||
|
# whose cancellation must be refused
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type) "
|
||||||
|
"VALUES ('member-one@x.org', 'enc', 'uid-m1', 'memberone', 1, 15.0, 0.0, 'member')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 1/2. the member guard ----------------------------------------------
|
||||||
|
try:
|
||||||
|
asyncio.run(m.cancel_guest_account("member-one@x.org"))
|
||||||
|
check("guard: paying member cannot cancel via the guest path", False, "no 403 raised")
|
||||||
|
except m.HTTPException as e:
|
||||||
|
check("guard: paying member cannot cancel via the guest path", e.status_code == 403,
|
||||||
|
str(e.status_code))
|
||||||
|
try:
|
||||||
|
asyncio.run(m.cancel_guest_account("nobody@x.org"))
|
||||||
|
check("guard: unknown identity refused", False, "no 403 raised")
|
||||||
|
except m.HTTPException as e:
|
||||||
|
check("guard: unknown identity refused", e.status_code == 403, str(e.status_code))
|
||||||
|
|
||||||
|
# --- 3-8. the full cancel flow ------------------------------------------
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_gift(conn, "invited@x.org", active=1, credits=2.0)
|
||||||
|
# the grant row production writes at provisioning (add_credits on the
|
||||||
|
# guest reference) — the return is audited against it
|
||||||
|
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) "
|
||||||
|
"VALUES ('invited@x.org', 2.0, 'guest account — $2 credit from a member', "
|
||||||
|
"'guest:invited@x.org')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
out = asyncio.run(m.cancel_guest_account("invited@x.org"))
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
row = conn.execute("SELECT active, account_type, credit_balance FROM members "
|
||||||
|
"WHERE email = 'invited@x.org'").fetchone()
|
||||||
|
check("cancel: row deactivated, account kept",
|
||||||
|
row[0] == 0 and row[1] == "guest", str(row))
|
||||||
|
check("cancel: credit balance drawn to 0", row[2] == 0.0, str(row))
|
||||||
|
check("cancel: group moved guests → ended-guests",
|
||||||
|
any(u == "uid-invited@x.org" and g == m.GUESTS_ENDED_GROUP_ID
|
||||||
|
for u, g in calls["group"]), str(calls["group"]))
|
||||||
|
check("cancel: gateway budget zeroed (revoke called)",
|
||||||
|
"invited@x.org" in calls["revoke"], str(calls["revoke"]))
|
||||||
|
check("cancel: newsletter unsubscribed",
|
||||||
|
("invited@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
|
||||||
|
led = ledger_rows(conn, "invited@x.org")
|
||||||
|
grants = [r for r in led if r[2] == "guest:invited@x.org"]
|
||||||
|
returns = [r for r in led if r[2] == "guest-return:invited@x.org"]
|
||||||
|
check("cancel: ledger holds the $2 grant and ONE negative return row",
|
||||||
|
len(grants) == 1 and grants[0][0] == 2.0 and len(returns) == 1
|
||||||
|
and returns[0][0] == -2.0, str(led))
|
||||||
|
check("cancel: return reason names the cancellation and the guest reference",
|
||||||
|
len(returns) == 1 and "cancelled by recipient" in returns[0][1]
|
||||||
|
and "guest:invited@x.org" in returns[0][1], str(returns))
|
||||||
|
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
|
||||||
|
"WHERE recipient_email = 'invited@x.org'").fetchone()
|
||||||
|
check("cancel: guests ledger shows inviter → recipient → cancelled by recipient",
|
||||||
|
g and g[0] == "member-one@x.org" and g[1] == "invited@x.org"
|
||||||
|
and g[2] == "cancelled by recipient", str(g))
|
||||||
|
check("cancel: result reports the returned amount",
|
||||||
|
out.get("status") == "cancelled" and out.get("credits_returned") == 2.0, str(out))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 9. idempotence: the second cancel is a no-op -----------------------
|
||||||
|
calls["group"].clear(); calls["revoke"].clear(); calls["listmonk"].clear()
|
||||||
|
out2 = asyncio.run(m.cancel_guest_account("invited@x.org"))
|
||||||
|
conn = m.get_db()
|
||||||
|
led2 = ledger_rows(conn, "invited@x.org")
|
||||||
|
check("idempotent: second cancel reports already_ended",
|
||||||
|
out2.get("status") == "already_ended"
|
||||||
|
and out2.get("guest_status") == "cancelled by recipient", str(out2))
|
||||||
|
check("idempotent: no second return row",
|
||||||
|
len([r for r in led2 if r[2] == "guest-return:invited@x.org"]) == 1, str(led2))
|
||||||
|
check("idempotent: no re-deactivation side effects",
|
||||||
|
not calls["group"] and not calls["revoke"] and not calls["listmonk"],
|
||||||
|
str(calls))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 10. partial-failure replay: return row exists, deactivation failed -
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_gift(conn, "halfway@x.org", active=1, credits=4.0)
|
||||||
|
# simulate the ledger row written before a crash: return recorded, row still active
|
||||||
|
conn.execute("UPDATE members SET credit_balance = 0.0 WHERE email = 'halfway@x.org'")
|
||||||
|
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) "
|
||||||
|
"VALUES ('halfway@x.org', -4.0, 'guest cancelled by recipient — "
|
||||||
|
"unspent credit returned to the co-op (original guest: "
|
||||||
|
"guest:halfway@x.org)', 'guest-return:halfway@x.org')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
out3 = asyncio.run(m.cancel_guest_account("halfway@x.org"))
|
||||||
|
conn = m.get_db()
|
||||||
|
led3 = ledger_rows(conn, "halfway@x.org")
|
||||||
|
check("replay: the recorded return is reported, not re-written",
|
||||||
|
len([r for r in led3 if r[2] == "guest-return:halfway@x.org"]) == 1
|
||||||
|
and out3.get("credits_returned") == 4.0, str(led3) + " / " + str(out3))
|
||||||
|
check("replay: deactivation still completed",
|
||||||
|
conn.execute("SELECT active FROM members WHERE email='halfway@x.org'"
|
||||||
|
).fetchone()[0] == 0)
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 11. the guest-status payload pieces ---------------------------------
|
||||||
|
# member: guest false
|
||||||
|
conn = m.get_db()
|
||||||
|
ok_member = conn.execute("SELECT 1 FROM members WHERE email='member-one@x.org'").fetchone()
|
||||||
|
conn.close()
|
||||||
|
if ok_member:
|
||||||
|
# call the payload logic directly (the route needs a Request object)
|
||||||
|
conn = m.get_db()
|
||||||
|
row = conn.execute("SELECT active, balance, credit_balance FROM members "
|
||||||
|
"WHERE email = 'member-one@x.org'").fetchone()
|
||||||
|
conn.close()
|
||||||
|
check("status: a member is not a guest (payload contract)",
|
||||||
|
not m.is_guest_account("member-one@x.org"))
|
||||||
|
|
||||||
|
# cancelled guest: ended + cancelled + returned amount
|
||||||
|
st_cancelled = {
|
||||||
|
"ended": True, "guest_status": m._guest_ledger_status("invited@x.org"),
|
||||||
|
"cancelled": m._guest_ledger_status("invited@x.org") == "cancelled by recipient",
|
||||||
|
"credits_returned": m._guest_returned_credits("invited@x.org"),
|
||||||
|
}
|
||||||
|
check("status: cancelled guest reads ended + cancelled + amount returned",
|
||||||
|
st_cancelled["ended"] and st_cancelled["cancelled"]
|
||||||
|
and st_cancelled["credits_returned"] == 2.0, str(st_cancelled))
|
||||||
|
|
||||||
|
# live guest: active with remaining credits
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_gift(conn, "live@x.org", active=1, credits=2.0)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
st_live = {
|
||||||
|
"active": bool(conn_active := 1),
|
||||||
|
"guest_status": m._guest_ledger_status("live@x.org"),
|
||||||
|
}
|
||||||
|
check("status: live guest reads active with an 'active' ledger row",
|
||||||
|
st_live["active"] and st_live["guest_status"] == "active", str(st_live))
|
||||||
|
|
||||||
|
failed = [r for r in results if not r[1]]
|
||||||
|
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Parallel guest invitations cannot slip two guests past the 30-day rule.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
The one-guest-per-member-per-30-days rule is a READ of the guests ledger,
|
||||||
|
provisioning takes seconds of external calls, and the ledger row that closes
|
||||||
|
the window is written LAST. Two PARALLEL direct calls (curl, not the
|
||||||
|
dashboard JS) could therefore both pass the guard before either row exists.
|
||||||
|
The member invite path now runs under _GUEST_INVITE_LOCK, which makes
|
||||||
|
check-and-send atomic for the single-process uvicorn app.
|
||||||
|
|
||||||
|
Proven here, against a FIXTURE database with the network layer replaced by
|
||||||
|
raising guards (any live call fails the test loudly):
|
||||||
|
1. With the lock DISABLED, two parallel invites from the same member BOTH
|
||||||
|
provision — the race is real, and the test has teeth.
|
||||||
|
2. With the real lock, the same parallel pair yields exactly ONE
|
||||||
|
provisioned guest; the second is refused 429 inside the 30-day window.
|
||||||
|
3. Exactly one ledger row and one members row exist per accepted invite;
|
||||||
|
the refused recipient is unborn (no row, no credit, no email).
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_guest_concurrency.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
|
||||||
|
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
|
||||||
|
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok, detail=""):
|
||||||
|
results.append((name, bool(ok), detail))
|
||||||
|
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
class _NoNetwork:
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
def __call__(self, *a, **k): # pragma: no cover
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient(_NoNetwork):
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
async def post(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = _FakeClient
|
||||||
|
|
||||||
|
# --- provisioning stubs: same contract as test_guest_requests, but
|
||||||
|
# cloudron_create_user SUSPENDS briefly, forcing real task interleaving so the
|
||||||
|
# parallel window is actually exercised (without a suspension point asyncio
|
||||||
|
# would run the two requests back-to-back and prove nothing). ----------------#
|
||||||
|
calls = {"group": [], "email": [], "listmonk": [], "budget": [], "uids": 0}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_user_create(email, name):
|
||||||
|
calls["uids"] += 1
|
||||||
|
await asyncio.sleep(0.05) # the suspension that opens the parallel window
|
||||||
|
return f"uid-fixture-{calls['uids']}"
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_group(user_id, group_id=None):
|
||||||
|
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
|
||||||
|
|
||||||
|
|
||||||
|
def rec_email(to, subject, text_body=None, html_body=None):
|
||||||
|
calls["email"].append((to, subject or ""))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_listmonk(email, subscribe):
|
||||||
|
calls["listmonk"].append((email, bool(subscribe)))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_budget(team_id, budget):
|
||||||
|
calls["budget"].append((team_id, round(float(budget), 2)))
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team(email, budget, budget_duration="30d"):
|
||||||
|
return "team-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_key(email, budget, team_id):
|
||||||
|
return "sk-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_invite_link(user_id):
|
||||||
|
return "https://my.example/setupaccount.html?inviteToken=x"
|
||||||
|
|
||||||
|
|
||||||
|
def fake_team_db(team_id):
|
||||||
|
return {"max_budget": None, "spend": 0.0, "budget_reset_at": None}
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_create_user = fake_user_create
|
||||||
|
m.cloudron_set_group = rec_group
|
||||||
|
m.cloudron_set_active = rec_group
|
||||||
|
m.cloudron_get_invite_link = fake_invite_link
|
||||||
|
m.litellm_get_or_create_team = fake_team
|
||||||
|
m.litellm_create_key = fake_key
|
||||||
|
m.litellm_update_team_budget = rec_budget
|
||||||
|
m.get_team_budget_from_db = fake_team_db
|
||||||
|
m.send_email = rec_email
|
||||||
|
m.listmonk_sync = rec_listmonk
|
||||||
|
|
||||||
|
# --- real Request objects (the slowapi limiter decorator requires them) ----- #
|
||||||
|
from starlette.requests import Request as StarletteRequest # noqa: E402
|
||||||
|
import json as _json # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def make_request(body=None):
|
||||||
|
raw = _json.dumps(body or {}).encode()
|
||||||
|
headers = {"content-type": "application/json", "content-length": str(len(raw))}
|
||||||
|
async def receive():
|
||||||
|
return {"type": "http.request", "body": raw, "more_body": False}
|
||||||
|
scope = {
|
||||||
|
"type": "http", "method": "POST", "path": "/", "query_string": b"",
|
||||||
|
"headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],
|
||||||
|
"server": ("testserver", 80), "client": ("testclient", 123),
|
||||||
|
}
|
||||||
|
return StarletteRequest(scope, receive)
|
||||||
|
|
||||||
|
|
||||||
|
def seed_member(conn, email):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type) "
|
||||||
|
"VALUES (?, 'enc', 'uid-' || ?, '', 1, ?, 0, 'member')",
|
||||||
|
(email, email, m.MEMBER_BUDGET),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class _NoLock:
|
||||||
|
"""Stands in for the real lock to demonstrate the unguarded race."""
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def parallel_pair(inviter, recipients):
|
||||||
|
"""Fire TWO member invites at once (the direct-call attack shape)."""
|
||||||
|
m._verify_broker_secret = lambda request: inviter
|
||||||
|
return await asyncio.gather(
|
||||||
|
*(m.broker_guest_invite(make_request({"email": r})) for r in recipients),
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ledger_count(inviter):
|
||||||
|
conn = m.get_db()
|
||||||
|
n = conn.execute("SELECT COUNT(*) FROM guests WHERE inviter_email=?",
|
||||||
|
(inviter,)).fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def row_count(email):
|
||||||
|
conn = m.get_db()
|
||||||
|
n = conn.execute("SELECT COUNT(*) FROM members WHERE email=?", (email,)).fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn)
|
||||||
|
|
||||||
|
# --- 1. the RACE, unguarded: prove two parallel invites both provision -- #
|
||||||
|
seed_member(conn, "racer-one@x.org")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
real_lock = m._GUEST_INVITE_LOCK
|
||||||
|
m._GUEST_INVITE_LOCK = _NoLock()
|
||||||
|
try:
|
||||||
|
out = asyncio.run(parallel_pair(
|
||||||
|
"racer-one@x.org", ["race-a@x.org", "race-b@x.org"]))
|
||||||
|
finally:
|
||||||
|
m._GUEST_INVITE_LOCK = real_lock
|
||||||
|
provisioned = [o for o in out if isinstance(o, dict)]
|
||||||
|
refused = [o for o in out if isinstance(o, Exception)]
|
||||||
|
check("race (unguarded): both parallel invites slipped through "
|
||||||
|
"(the test has teeth — this is the defect the lock closes)",
|
||||||
|
len(provisioned) == 2 and not refused,
|
||||||
|
f"provisioned={len(provisioned)} refused={len(refused)}")
|
||||||
|
check("race (unguarded): two ledger rows — the rule is broken without "
|
||||||
|
"serialization", ledger_count("racer-one@x.org") == 2,
|
||||||
|
str(ledger_count("racer-one@x.org")))
|
||||||
|
|
||||||
|
# --- 2. the LOCK: the same parallel pair now yields exactly one guest --- #
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, "racer-two@x.org")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
calls["email"].clear()
|
||||||
|
out = asyncio.run(parallel_pair(
|
||||||
|
"racer-two@x.org", ["race-c@x.org", "race-d@x.org"]))
|
||||||
|
provisioned = [o for o in out if isinstance(o, dict)]
|
||||||
|
refused = [o for o in out if isinstance(o, Exception)]
|
||||||
|
check("lock: exactly ONE of two parallel invites provisions",
|
||||||
|
len(provisioned) == 1 and len(refused) == 1,
|
||||||
|
f"provisioned={len(provisioned)} refused={len(refused)} "
|
||||||
|
f"{[type(o).__name__ for o in out]}")
|
||||||
|
check("lock: the refusal is the over-limit error (429, 30-day window)",
|
||||||
|
refused and getattr(refused[0], "status_code", None) == 429
|
||||||
|
and "30 days" in str(getattr(refused[0], "detail", "")),
|
||||||
|
f"{refused}")
|
||||||
|
check("lock: exactly ONE ledger row for the inviter",
|
||||||
|
ledger_count("racer-two@x.org") == 1,
|
||||||
|
str(ledger_count("racer-two@x.org")))
|
||||||
|
born = sum(1 for r in ("race-c@x.org", "race-d@x.org") if row_count(r))
|
||||||
|
check("lock: exactly ONE recipient account was created", born == 1, str(born))
|
||||||
|
check("lock: the refused recipient is unborn (no row, no guest, no credit)",
|
||||||
|
sum(1 for r in ("race-c@x.org", "race-d@x.org") if row_count(r) == 0) == 1)
|
||||||
|
check("lock: exactly ONE invitation email left the building",
|
||||||
|
len(calls["email"]) == 1, str(calls["email"]))
|
||||||
|
|
||||||
|
# --- 3. sequential semantics unchanged: the second invite still refuses - #
|
||||||
|
conn = m.get_db()
|
||||||
|
refusal = m.guest_request_guard(conn, "racer-two@x.org", "race-e@x.org")
|
||||||
|
conn.close()
|
||||||
|
check("aftermath: a later invite from the same member is still refused "
|
||||||
|
"(one per 30 days, unchanged)",
|
||||||
|
refusal is not None and "30 days" in refusal, str(refusal))
|
||||||
|
|
||||||
|
failed = [r for r in results if not r[1]]
|
||||||
|
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Guest invited state — a provisioned-but-NOT-set-up guest never reads 'active'.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
A guest invitation provisions IMMEDIATELY (Cloudron user + invitation email
|
||||||
|
with the setup link), but the Cloudron account is not ACCEPTED until the
|
||||||
|
guest clicks that link (inviteAccepted=false, no username) — they cannot
|
||||||
|
log in yet. Every surface that reads the guest's state must therefore show
|
||||||
|
'invited' (awaiting setup) at that point, never 'active', and flip to the
|
||||||
|
ordinary state only when the invite is accepted. Display/state semantics
|
||||||
|
only: access rules, the guest cap and the expiry box are unchanged.
|
||||||
|
|
||||||
|
Every path here runs against a FIXTURE database with the network layer
|
||||||
|
REPLACED: any code path that reaches Cloudron/LiteLLM/OC/Listmonk outside
|
||||||
|
the stubs fails the test loudly instead of acting on live systems.
|
||||||
|
|
||||||
|
1. guest_invite_pending — the derivation itself: accepted, username-set,
|
||||||
|
unseen-record (fetch failed) and no-user-id cases.
|
||||||
|
2. GET /admin/overview: a fresh guest (inviteAccepted=false, no
|
||||||
|
username) reports state='invited' with an 'awaiting setup' reason.
|
||||||
|
Once accepted, state FOLLOWS THE LEDGER STATUS (active / expired /
|
||||||
|
...) — the single derivation point for the guest display state,
|
||||||
|
consumed as-is by the panel and dashboard; a guest with no ledger
|
||||||
|
row falls back to the membership state.
|
||||||
|
3. Simulated acceptance (inviteAccepted flips true, or a username is
|
||||||
|
chosen) → the same endpoint reports state='active'.
|
||||||
|
4. A FAILED Cloudron users fetch never claims 'invited' — the row falls
|
||||||
|
back to the membership state rather than inventing a state the data
|
||||||
|
does not show.
|
||||||
|
5. An established MEMBER row is untouched by the guest branch: state
|
||||||
|
'active', empty reason, still in members[].
|
||||||
|
6. The member's trail (GET /broker/guests) carries state='invited' for
|
||||||
|
the un-accepted guest and state=<ledger status> once accepted.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_guest_invited_state.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
os.environ["ADMIN_TOKEN"] = "test-admin-token" # admin endpoints authenticate on this
|
||||||
|
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
|
||||||
|
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
|
||||||
|
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok, detail=""):
|
||||||
|
results.append((name, bool(ok), detail))
|
||||||
|
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
# --- Cloudron users fixture (the ONLY external signal this feature reads) --- #
|
||||||
|
CLOUDRON_USERS = {
|
||||||
|
"uid-guest@x.org": {"inviteAccepted": False, "username": None},
|
||||||
|
"uid-member@x.org": {"inviteAccepted": True, "username": "established"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeResponse:
|
||||||
|
status_code = 200
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return [] # LiteLLM /team/list: no teams in this fixture
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
"""Answers only what admin_overview asks: cloudron_fetch_all_users (stubbed
|
||||||
|
separately) and the LiteLLM team/list GET (empty)."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, url, **k):
|
||||||
|
return _FakeResponse()
|
||||||
|
|
||||||
|
|
||||||
|
class _NoNetwork:
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
def __call__(self, *a, **k): # pragma: no cover
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = _FakeClient # ONLY _FakeClient.__init__-safe paths run
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_users_ok(client):
|
||||||
|
return [{"id": uid, "username": v.get("username"),
|
||||||
|
"inviteAccepted": v.get("inviteAccepted", False)}
|
||||||
|
for uid, v in CLOUDRON_USERS.items()]
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_users_broken(client):
|
||||||
|
return None # page 1 unresolvable — the documented fetch-failure shape
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_fetch_all_users = fetch_users_ok
|
||||||
|
# The overview's all-time-spend query is a PG read — absent in the fixture and
|
||||||
|
# fail-soft by design; make that loud rather than implicit.
|
||||||
|
def _no_pg(*a, **k):
|
||||||
|
raise AssertionError("live PG attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m._pg_connect = _no_pg
|
||||||
|
|
||||||
|
|
||||||
|
# --- real Request objects (the slowapi limiter decorator requires them) ----- #
|
||||||
|
from starlette.requests import Request as StarletteRequest # noqa: E402
|
||||||
|
import json as _json # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def make_request(method="GET", body=None, headers=None):
|
||||||
|
raw = _json.dumps(body or {}).encode()
|
||||||
|
headers = dict(headers or {})
|
||||||
|
if raw and "content-length" not in headers:
|
||||||
|
headers["content-length"] = str(len(raw))
|
||||||
|
async def receive():
|
||||||
|
return {"type": "http.request", "body": raw, "more_body": False}
|
||||||
|
scope = {
|
||||||
|
"type": "http", "method": method, "path": "/", "query_string": b"",
|
||||||
|
"headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
|
||||||
|
"server": ("testserver", 80), "client": ("testclient", 123),
|
||||||
|
}
|
||||||
|
return StarletteRequest(scope, receive)
|
||||||
|
|
||||||
|
|
||||||
|
def seed_account(conn, email, account_type="member", active=1, uid=None):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type) "
|
||||||
|
"VALUES (?, 'enc', ?, '', ?, ?, 0, ?)",
|
||||||
|
(email, uid or ("uid-" + email), active, 0.0, account_type),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def seed_guest_ledger(conn, inviter, recipient, status="active"):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO guests (inviter_email, recipient_email, oc_reference, "
|
||||||
|
"guest_expires_at, status, created_at) "
|
||||||
|
"VALUES (?, ?, NULL, datetime('now', '+60 days'), ?, datetime('now'))",
|
||||||
|
(inviter, recipient, status),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn)
|
||||||
|
|
||||||
|
# --- 1. the derivation itself --------------------------------------------
|
||||||
|
check("derive: accepted invite is not pending",
|
||||||
|
m.guest_invite_pending("u", {}, {"u": True}) is False)
|
||||||
|
check("derive: a chosen username counts as accepted (first login)",
|
||||||
|
m.guest_invite_pending("u", {"u": "theirname"}, {"u": False}) is False)
|
||||||
|
check("derive: un-accepted + no username IS pending",
|
||||||
|
m.guest_invite_pending("u", {}, {"u": False}) is True)
|
||||||
|
check("derive: a record we never saw is NOT pending (fetch failed)",
|
||||||
|
m.guest_invite_pending("u", {}, {}) is False)
|
||||||
|
check("derive: no user id is never pending",
|
||||||
|
m.guest_invite_pending(None, {}, {"u": False}) is False)
|
||||||
|
|
||||||
|
# --- 2-5. /admin/overview --------------------------------------------------
|
||||||
|
inviter = "info@inference.coop" # the admin path's inviter
|
||||||
|
seed_account(conn, "member@x.org", account_type="member", active=1)
|
||||||
|
seed_account(conn, "guest@x.org", account_type="guest", active=1)
|
||||||
|
seed_account(conn, "ended@x.org", account_type="guest", active=0)
|
||||||
|
seed_guest_ledger(conn, inviter, "guest@x.org")
|
||||||
|
seed_guest_ledger(conn, inviter, "ended@x.org", status="expired")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
async def overview():
|
||||||
|
return await m.admin_overview(make_request(
|
||||||
|
"GET", headers={"X-Admin-Token": "test-admin-token"}))
|
||||||
|
|
||||||
|
data = asyncio.run(overview())
|
||||||
|
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
|
||||||
|
check("overview: fresh guest listed under guests[], never members[]",
|
||||||
|
len(data["guests"]) == 2 and not any(x["email"] == "guest@x.org" for x in data["members"]),
|
||||||
|
str([x["email"] for x in data["guests"]]))
|
||||||
|
check("overview: un-accepted guest reads state='invited'",
|
||||||
|
g["state"] == "invited", str(g.get("state")))
|
||||||
|
check("overview: invited reason is the awaiting-setup line",
|
||||||
|
str(g.get("state_reason", "")).startswith("awaiting setup"),
|
||||||
|
str(g.get("state_reason")))
|
||||||
|
check("overview: ledger status still the record of record",
|
||||||
|
g.get("guest_status") == "active", str(g.get("guest_status")))
|
||||||
|
check("overview: activated flag agrees (pending)",
|
||||||
|
g.get("activated") is False, str(g.get("activated")))
|
||||||
|
ended = [x for x in data["guests"] if x["email"] == "ended@x.org"][0]
|
||||||
|
check("overview: ended guest reads its LEDGER status ('expired'), not the bare flag",
|
||||||
|
ended["state"] == "expired" and ended["state_reason"] == "",
|
||||||
|
f"{ended.get('state')} / {ended.get('state_reason')!r}")
|
||||||
|
|
||||||
|
# The ledger is the record of record even when it disagrees with the
|
||||||
|
# members.active flag: an active-flagged guest whose access has ENDED
|
||||||
|
# (expired ledger row, active flag not yet flipped) reads 'expired'.
|
||||||
|
conn = m.get_db()
|
||||||
|
CLOUDRON_USERS["uid-lapsed@x.org"] = {"inviteAccepted": True, "username": "lapsedg"}
|
||||||
|
seed_account(conn, "lapsed@x.org", account_type="guest", active=1,
|
||||||
|
uid="uid-lapsed@x.org")
|
||||||
|
seed_guest_ledger(conn, inviter, "lapsed@x.org", status="expired")
|
||||||
|
# ...and a guest with NO ledger row falls back to the membership state.
|
||||||
|
CLOUDRON_USERS["uid-noledger@x.org"] = {"inviteAccepted": True, "username": "noledger"}
|
||||||
|
seed_account(conn, "noledger@x.org", account_type="guest", active=1,
|
||||||
|
uid="uid-noledger@x.org")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
data = asyncio.run(overview())
|
||||||
|
lapsed = [x for x in data["guests"] if x["email"] == "lapsed@x.org"][0]
|
||||||
|
check("overview: ledger status wins over the active flag (lapsed guest = 'expired')",
|
||||||
|
lapsed["state"] == "expired", str(lapsed.get("state")))
|
||||||
|
noledger = [x for x in data["guests"] if x["email"] == "noledger@x.org"][0]
|
||||||
|
check("overview: no ledger row → membership-state fallback ('active')",
|
||||||
|
noledger["state"] == "active", str(noledger.get("state")))
|
||||||
|
|
||||||
|
# --- 3. simulated acceptance: the flip to active ---------------------------
|
||||||
|
CLOUDRON_USERS["uid-guest@x.org"]["inviteAccepted"] = True
|
||||||
|
data = asyncio.run(overview())
|
||||||
|
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
|
||||||
|
check("overview: after acceptance the guest reads state='active'",
|
||||||
|
g["state"] == "active", str(g.get("state")))
|
||||||
|
check("overview: accepted guest carries no awaiting-setup reason",
|
||||||
|
g.get("state_reason", "") == "", str(g.get("state_reason")))
|
||||||
|
check("overview: activated flag agrees (yes)",
|
||||||
|
g.get("activated") is True, str(g.get("activated")))
|
||||||
|
|
||||||
|
# ...and the username-only variant (the guest finished setup by name):
|
||||||
|
CLOUDRON_USERS["uid-guest@x.org"]["inviteAccepted"] = False
|
||||||
|
CLOUDRON_USERS["uid-guest@x.org"]["username"] = "theirname"
|
||||||
|
data = asyncio.run(overview())
|
||||||
|
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
|
||||||
|
check("overview: a chosen username alone flips the guest to active",
|
||||||
|
g["state"] == "active", str(g.get("state")))
|
||||||
|
CLOUDRON_USERS["uid-guest@x.org"]["username"] = None
|
||||||
|
|
||||||
|
# --- 4. a failed Cloudron fetch never claims 'invited' ---------------------
|
||||||
|
m.cloudron_fetch_all_users = fetch_users_broken
|
||||||
|
data = asyncio.run(overview())
|
||||||
|
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
|
||||||
|
check("overview: users fetch failed → fallback state, never 'invited'",
|
||||||
|
g["state"] == "active" and g["state_reason"] == "",
|
||||||
|
f"{g.get('state')} / {g.get('state_reason')!r}")
|
||||||
|
m.cloudron_fetch_all_users = fetch_users_ok
|
||||||
|
|
||||||
|
# --- 5. an established member's row is untouched ----------------------------
|
||||||
|
data = asyncio.run(overview()) # fresh payload from the working fetch
|
||||||
|
mem = [x for x in data["members"] if x["email"] == "member@x.org"][0]
|
||||||
|
check("overview: established member state unchanged ('active', no reason)",
|
||||||
|
mem["state"] == "active" and mem["state_reason"] == "",
|
||||||
|
f"{mem.get('state')} / {mem.get('state_reason')!r}")
|
||||||
|
check("overview: established member activated (not caught by the guest branch)",
|
||||||
|
mem.get("activated") is True, str(mem.get("activated")))
|
||||||
|
|
||||||
|
# --- 6. the member's trail carries the same derivation ----------------------
|
||||||
|
m._verify_broker_secret = lambda request: "member@x.org"
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_guest_ledger(conn, "member@x.org", "friend@x.org")
|
||||||
|
seed_account(conn, "friend@x.org", account_type="guest", active=1)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
CLOUDRON_USERS["uid-friend@x.org"] = {"inviteAccepted": False, "username": None}
|
||||||
|
|
||||||
|
view = asyncio.run(m.broker_guest_list(make_request("GET")))
|
||||||
|
trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"]
|
||||||
|
check("trail: un-accepted guest carries state='invited'",
|
||||||
|
len(trail_guests) == 1 and trail_guests[0]["state"] == "invited",
|
||||||
|
str(view["trail"]))
|
||||||
|
check("trail: ledger status still 'active' underneath",
|
||||||
|
trail_guests and trail_guests[0]["status"] == "active", str(view["trail"]))
|
||||||
|
|
||||||
|
CLOUDRON_USERS["uid-friend@x.org"]["inviteAccepted"] = True
|
||||||
|
view = asyncio.run(m.broker_guest_list(make_request("GET")))
|
||||||
|
trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"]
|
||||||
|
check("trail: after acceptance state follows the ledger status",
|
||||||
|
trail_guests and trail_guests[0]["state"] == "active", str(view["trail"]))
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("UPDATE members SET active = 0 WHERE email = 'friend@x.org'")
|
||||||
|
conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'friend@x.org'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
view = asyncio.run(m.broker_guest_list(make_request("GET")))
|
||||||
|
trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"]
|
||||||
|
check("trail: an ended guest shows its ledger status, never 'invited'",
|
||||||
|
trail_guests and trail_guests[0]["state"] == "expired", str(view["trail"]))
|
||||||
|
|
||||||
|
failed = [name for name, ok, _ in results if not ok]
|
||||||
|
print()
|
||||||
|
print(f"{len(results) - len(failed)}/{len(results)} checks passed")
|
||||||
|
if failed:
|
||||||
|
print("FAILED: " + ", ".join(failed))
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Guest-account lifecycle tests — structurally isolated from live services.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
Guest accounts (operator feature, 2026-11-08) touch money ($2 of credits),
|
||||||
|
Cloudron groups and email. Every path proven here runs against a FIXTURE
|
||||||
|
database with the network layer REPLACED BY A RAISING GUARD: any code path
|
||||||
|
that tries to reach Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP
|
||||||
|
outside the stubs fails the test loudly instead of acting on live systems.
|
||||||
|
|
||||||
|
GUARDS (abuse protection — one guest per inviter per 30d, one per recipient)
|
||||||
|
1. An inviter who is not an active member is refused.
|
||||||
|
2. A SECOND guest by the same inviter within the window is refused.
|
||||||
|
3. A recipient who already received a guest (ledger) or already has a
|
||||||
|
portal row is refused.
|
||||||
|
PROVISION
|
||||||
|
4. The full guest pipeline marks the row (account_type='guest', balance 0,
|
||||||
|
credit_balance 5, guest_expires_at set, anchor day kept), records
|
||||||
|
inviter → recipient in the guests ledger, subscribes the newsletter,
|
||||||
|
and sends the guest welcome email — no Loomio/Matrix calls.
|
||||||
|
CONVERT (guest → member)
|
||||||
|
5. Group moves guests → members; allowance set to MEMBER_BUDGET; the
|
||||||
|
unspent guest credit carries; the cap lifts to allowance + credits
|
||||||
|
(15 + 5); the anchor day is KEPT; the congrats email goes out; the
|
||||||
|
guests-ledger row becomes 'converted'; Loomio + Matrix syncs fire.
|
||||||
|
LIFECYCLE (sweep pass)
|
||||||
|
6. An EXPIRED guest (past guest_expires_at, credits remaining) is
|
||||||
|
deactivated by the sweep: row active=0, group → inactive, budget
|
||||||
|
zeroed, newsletter unsubscribed, ledger status 'expired'.
|
||||||
|
7. A DEPLETED guest (spend reached the credits) is deactivated likewise,
|
||||||
|
status 'depleted'.
|
||||||
|
8. A healthy guest (not expired, credits left) is left untouched.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_guest_lifecycle.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
|
||||||
|
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
|
||||||
|
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok, detail=""):
|
||||||
|
results.append((name, bool(ok), detail))
|
||||||
|
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
class _NoNetwork:
|
||||||
|
"""Guard: ANY httpx client construction inside the test is a failure."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
def __call__(self, *a, **k): # pragma: no cover
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = _NoNetwork
|
||||||
|
|
||||||
|
# --- recorders -------------------------------------------------------------- #
|
||||||
|
calls = {"group": [], "budget": [], "pin": [], "email": [], "listmonk": [],
|
||||||
|
"loomio": 0, "matrix": 0, "revoke": [], "owui": [], "subscribe": []}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_fetch_users(client):
|
||||||
|
# No existing Cloudron account for the fixture addresses.
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_email_exists(email):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_switch(user_id, add_gid=None, remove_gids=()):
|
||||||
|
calls["group"].append((user_id, add_gid))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_group(user_id, group_id=None):
|
||||||
|
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_budget(team_id, budget):
|
||||||
|
calls["budget"].append((team_id, round(float(budget), 2)))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_pin(team_id, reset_at):
|
||||||
|
calls["pin"].append((team_id, str(reset_at)))
|
||||||
|
|
||||||
|
|
||||||
|
def rec_email(to, subject, text_body=None, html_body=None):
|
||||||
|
calls["email"].append((to, subject))
|
||||||
|
return True # send_email's contract: truthy = the send left the building
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_listmonk(email, subscribe):
|
||||||
|
calls["listmonk"].append((email, bool(subscribe)))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_loomio():
|
||||||
|
calls["loomio"] += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_matrix():
|
||||||
|
calls["matrix"] += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_revoke(email):
|
||||||
|
calls["revoke"].append(email)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_owui(uid):
|
||||||
|
calls["owui"].append(uid)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
CALL_KEYS = ("group", "budget", "pin", "email", "listmonk", "loomio", "matrix",
|
||||||
|
"revoke", "owui", "subscribe")
|
||||||
|
|
||||||
|
|
||||||
|
def reset_calls():
|
||||||
|
for k in CALL_KEYS:
|
||||||
|
calls[k] = 0 if k in ("loomio", "matrix") else []
|
||||||
|
|
||||||
|
|
||||||
|
TEAM_SPEND = {} # team_id -> cycle spend (default 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def fake_team_db(team_id):
|
||||||
|
return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0),
|
||||||
|
"budget_reset_at": None}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team_id(email):
|
||||||
|
return "team-" + email
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_get_or_create_team(email, budget, budget_duration="30d"):
|
||||||
|
return "team-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_create_key(email, budget, team_id):
|
||||||
|
return "sk-fixture-key"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_user_create(email, name):
|
||||||
|
return "uid-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_invite_link(user_id):
|
||||||
|
return "https://my.example/setupaccount.html?inviteToken=x"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_activated(user_id):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_fetch_all_users = fake_fetch_users
|
||||||
|
m.cloudron_email_exists = fake_email_exists
|
||||||
|
m.cloudron_switch_group = rec_switch
|
||||||
|
m.cloudron_set_group = rec_group
|
||||||
|
m.cloudron_set_active = rec_group # same signature (uid, bool); recorded nowhere critical
|
||||||
|
m.cloudron_create_user = fake_user_create
|
||||||
|
m.cloudron_get_invite_link = fake_invite_link
|
||||||
|
m.cloudron_is_activated = fake_activated
|
||||||
|
m.litellm_get_or_create_team = fake_get_or_create_team
|
||||||
|
m.litellm_create_key = fake_create_key
|
||||||
|
m.litellm_team_id_for_email = fake_team_id
|
||||||
|
m.litellm_update_team_budget = rec_budget
|
||||||
|
m.litellm_pin_reset_date = rec_pin
|
||||||
|
m.get_team_budget_from_db = fake_team_db
|
||||||
|
m.send_email = rec_email
|
||||||
|
m.listmonk_sync = rec_listmonk
|
||||||
|
m.sync_loomio_memberships = rec_loomio
|
||||||
|
m.sync_matrix_space = rec_matrix
|
||||||
|
m.revoke_member_litellm_access = rec_revoke
|
||||||
|
m.owui_add_to_members_group = rec_owui
|
||||||
|
|
||||||
|
|
||||||
|
def seed_member(conn, email, account_type="member", active=1, balance=None,
|
||||||
|
credits=None, anchor=None, expires=None, slug=""):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type, anchor_day, guest_expires_at) "
|
||||||
|
"VALUES (?, 'enc', 'uid-' || ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(email, email, slug, active,
|
||||||
|
balance if balance is not None else m.MEMBER_BUDGET,
|
||||||
|
credits if credits is not None else 0.0,
|
||||||
|
account_type, anchor, expires),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def row_of(conn, email, col):
|
||||||
|
return conn.execute(f"SELECT {col} FROM members WHERE email = ?", (email,)).fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # anchor_day column (as production does)
|
||||||
|
conn.close()
|
||||||
|
inviter = "member-one@x.org"
|
||||||
|
|
||||||
|
# --- 1. inviter must be an active member -------------------------------
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, inviter, active=1)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
conn = m.get_db()
|
||||||
|
check("guard: non-member inviter refused",
|
||||||
|
m.guest_provision_guard(conn, "stranger@x.org", "friend@x.org") is not None)
|
||||||
|
check("guard: active member inviter allowed",
|
||||||
|
m.guest_provision_guard(conn, inviter, "friend@x.org") is None)
|
||||||
|
# --- 2. one guest per inviter per 30 days -------------------------------
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
|
||||||
|
"VALUES (?, 'friend@x.org', datetime('now'), 'active')", (inviter,))
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
|
||||||
|
check("guard: second guest within 30 days refused", refusal is not None and "30 days" in refusal,
|
||||||
|
str(refusal))
|
||||||
|
# backdate the ledger row: outside the window the inviter may guest again
|
||||||
|
conn.execute("UPDATE guests SET created_at = datetime('now', '-31 days')")
|
||||||
|
check("guard: guest allowed again after the window",
|
||||||
|
m.guest_provision_guard(conn, inviter, "friend2@x.org") is None)
|
||||||
|
# --- 3. one guest per recipient ever ------------------------------------
|
||||||
|
conn.execute("UPDATE guests SET recipient_email = 'friend2@x.org'")
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
|
||||||
|
check("guard: recipient already in ledger refused", refusal is not None, str(refusal))
|
||||||
|
seed_member(conn, "existing@x.org", account_type="member", active=1)
|
||||||
|
conn.commit()
|
||||||
|
check("guard: existing member as recipient refused",
|
||||||
|
m.guest_provision_guard(conn, inviter, "existing@x.org") is not None)
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 4. the full guest pipeline (provision_guest_member) ------------------
|
||||||
|
reset_calls()
|
||||||
|
asyncio.run(m.provision_guest_member("invited@x.org", "Invited Friend", inviter))
|
||||||
|
conn = m.get_db()
|
||||||
|
check("provision: row marked guest", row_of(conn, "invited@x.org", "account_type") == "guest")
|
||||||
|
check("provision: allowance balance 0", row_of(conn, "invited@x.org", "balance") == 0.0)
|
||||||
|
check("provision: $2 credit", row_of(conn, "invited@x.org", "credit_balance") == 2.0)
|
||||||
|
check("provision: guest_expires_at set", bool(row_of(conn, "invited@x.org", "guest_expires_at")))
|
||||||
|
check("provision: group = guests group",
|
||||||
|
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
|
||||||
|
check("provision: cap set to 2.00 (one-time)",
|
||||||
|
(calls["budget"] and calls["budget"][0][1] == 2.0), str(calls["budget"]))
|
||||||
|
check("provision: invitation email sent (merged invite + welcome)",
|
||||||
|
any("invited to the Inference Cooperative" in s for _, s in calls["email"]), str(calls["email"]))
|
||||||
|
check("provision: newsletter subscribed",
|
||||||
|
("invited@x.org", True) in calls["listmonk"], str(calls["listmonk"]))
|
||||||
|
check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0)
|
||||||
|
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
|
||||||
|
"WHERE recipient_email = 'invited@x.org'").fetchone()
|
||||||
|
check("provision: guests ledger records inviter→recipient",
|
||||||
|
bool(g) and g[0] == inviter and g[1] == "invited@x.org" and g[2] == "active", str(g))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 5. conversion (guest → member) -------------------------------------
|
||||||
|
reset_calls()
|
||||||
|
anchor_before = row_of(m.get_db(), "invited@x.org", "anchor_day")
|
||||||
|
asyncio.run(m.convert_guest_to_member("invited@x.org", "Invited Friend", "invitedfriend"))
|
||||||
|
conn = m.get_db()
|
||||||
|
check("convert: account_type back to member",
|
||||||
|
row_of(conn, "invited@x.org", "account_type") == "member")
|
||||||
|
check("convert: allowance lifted to MEMBER_BUDGET",
|
||||||
|
row_of(conn, "invited@x.org", "balance") == m.MEMBER_BUDGET)
|
||||||
|
check("convert: unspent guest credit carried",
|
||||||
|
row_of(conn, "invited@x.org", "credit_balance") == 2.0)
|
||||||
|
check("convert: group moved to members",
|
||||||
|
calls["group"] and calls["group"][0][1] == m.MEMBERS_GROUP_ID, str(calls["group"]))
|
||||||
|
check("convert: cap lifted to 17.00 (15 + 2 credits)",
|
||||||
|
(calls["budget"] and calls["budget"][0][1] == m.MEMBER_BUDGET + 2.0), str(calls["budget"]))
|
||||||
|
check("convert: anchor day kept", row_of(conn, "invited@x.org", "anchor_day") == anchor_before)
|
||||||
|
check("convert: congrats email sent",
|
||||||
|
any("member now" in s for _, s in calls["email"]), str(calls["email"]))
|
||||||
|
check("convert: Loomio + Matrix syncs fired", calls["loomio"] == 1 and calls["matrix"] == 1)
|
||||||
|
check("convert: guests ledger status converted",
|
||||||
|
conn.execute("SELECT status FROM guests WHERE recipient_email='invited@x.org'"
|
||||||
|
).fetchone()[0] == "converted")
|
||||||
|
check("convert: expiry cleared", row_of(conn, "invited@x.org", "guest_expires_at") is None)
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 6/7/8. lifecycle sweep: expired / depleted / healthy ---------------
|
||||||
|
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
|
||||||
|
future = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat()
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, "expired@x.org", account_type="guest", active=1, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=past)
|
||||||
|
seed_member(conn, "healthy@x.org", account_type="guest", active=1, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=future)
|
||||||
|
seed_member(conn, "depleted@x.org", account_type="guest", active=1, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=future)
|
||||||
|
# A guest whose guest ended BEFORE the reaching-limits email shipped: the
|
||||||
|
# sweep's catch-up pass must tell them exactly once.
|
||||||
|
seed_member(conn, "already-gone@x.org", account_type="guest", active=0, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=past)
|
||||||
|
for e in ("expired@x.org", "healthy@x.org", "depleted@x.org", "already-gone@x.org"):
|
||||||
|
conn.execute("INSERT INTO guests (inviter_email, recipient_email, guest_expires_at, status) "
|
||||||
|
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
|
||||||
|
conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
TEAM_SPEND.clear() # healthy + expired have unspent credits
|
||||||
|
reset_calls()
|
||||||
|
out = asyncio.run(m.reconcile_guest_lifecycles())
|
||||||
|
conn = m.get_db()
|
||||||
|
check("lifecycle: expired guest deactivated by the sweep",
|
||||||
|
row_of(conn, "expired@x.org", "active") == 0)
|
||||||
|
check("lifecycle: expired guest group → inactive",
|
||||||
|
any(e == "uid-expired@x.org" and g == m.INACTIVE_GROUP_ID
|
||||||
|
for e, g in calls["group"]), str(calls["group"]))
|
||||||
|
check("lifecycle: expired guest budget zeroed (revoke path called)",
|
||||||
|
"expired@x.org" in calls["revoke"], str(calls["revoke"]))
|
||||||
|
check("lifecycle: expired guest unsubscribed",
|
||||||
|
("expired@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
|
||||||
|
check("lifecycle: ledger status 'expired'",
|
||||||
|
conn.execute("SELECT status FROM guests WHERE recipient_email='expired@x.org'"
|
||||||
|
).fetchone()[0] == "expired")
|
||||||
|
check("lifecycle: healthy guest untouched",
|
||||||
|
row_of(conn, "healthy@x.org", "active") == 1 and
|
||||||
|
not any(e == "uid-healthy@x.org" for e, _ in calls["group"]))
|
||||||
|
check("lifecycle: counts report expired=1 depleted=0",
|
||||||
|
out.get("expired") == 1 and out.get("depleted") == 0, str(out))
|
||||||
|
check("lifecycle: reaching-limits email sent once to the expired guest",
|
||||||
|
sum(1 for to, s in calls["email"]
|
||||||
|
if to == "expired@x.org" and "guest access has ended" in s) == 1,
|
||||||
|
str(calls["email"]))
|
||||||
|
check("lifecycle: catch-up told the pre-shutdown guest exactly once",
|
||||||
|
sum(1 for to, s in calls["email"]
|
||||||
|
if to == "already-gone@x.org" and "guest access has ended" in s) == 1,
|
||||||
|
str(calls["email"]))
|
||||||
|
check("lifecycle: notice counts in the sweep result",
|
||||||
|
out.get("lapse_notices") == 2, str(out))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
|
||||||
|
reset_calls()
|
||||||
|
out = asyncio.run(m.reconcile_guest_lifecycles())
|
||||||
|
conn = m.get_db()
|
||||||
|
check("lifecycle: depleted guest deactivated",
|
||||||
|
row_of(conn, "depleted@x.org", "active") == 0)
|
||||||
|
check("lifecycle: depleted ledger status",
|
||||||
|
conn.execute("SELECT status FROM guests WHERE recipient_email='depleted@x.org'"
|
||||||
|
).fetchone()[0] == "depleted")
|
||||||
|
check("lifecycle: healthy guest STILL untouched on second pass",
|
||||||
|
row_of(conn, "healthy@x.org", "active") == 1)
|
||||||
|
check("lifecycle: counts report depleted=1", out.get("depleted") == 1, str(out))
|
||||||
|
check("lifecycle: depleted guest also told once",
|
||||||
|
sum(1 for to, s in calls["email"]
|
||||||
|
if to == "depleted@x.org" and "guest access has ended" in s) == 1,
|
||||||
|
str(calls["email"]))
|
||||||
|
check("lifecycle: ONCE per guest — second sweep sent no repeat notices",
|
||||||
|
sum(1 for to, s in calls["email"] if "guest access has ended" in s) == 1
|
||||||
|
and m.guest_lapse_notice_sent("expired@x.org")
|
||||||
|
and m.guest_lapse_notice_sent("already-gone@x.org"),
|
||||||
|
str(calls["email"]))
|
||||||
|
check("lifecycle: healthy guest never emailed",
|
||||||
|
not any(to == "healthy@x.org" for to, _ in calls["email"]), str(calls["email"]))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
failed = [r for r in results if not r[1]]
|
||||||
|
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Member self-serve guest invitations — structurally isolated from live services.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
The member path creates REAL guest accounts ($2 of credits, Cloudron users,
|
||||||
|
invitation email) IMMEDIATELY on a valid request (operator decision,
|
||||||
|
2026-11-08: the trial-era approval gate is gone — nothing waits, nothing is
|
||||||
|
pending). Every path proven here runs against a FIXTURE database with the
|
||||||
|
network layer REPLACED BY A RAISING GUARD: any code path that tries to reach
|
||||||
|
Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP outside the stubs
|
||||||
|
fails the test loudly instead of acting on live systems.
|
||||||
|
|
||||||
|
IMMEDIATE PROVISIONING (POST /broker/guests, member broker identity)
|
||||||
|
1. A valid member invitation provisions at once through the FULL guest
|
||||||
|
pipeline: row marked account_type='guest', the $2 non-expiring credit,
|
||||||
|
the LiteLLM cap at $2, guest_expires_at set (the 60-day box), a guests
|
||||||
|
ledger row inviter → recipient, the invitation email (the INVITING
|
||||||
|
member named in it), and the newsletter subscription.
|
||||||
|
2. NO guest_requests row is written — no pending state exists anywhere.
|
||||||
|
3. The member's own trail shows the new guest (active) and the rolling
|
||||||
|
window flips them ineligible with next_eligible_at.
|
||||||
|
PROTECTIONS (member path — every rule still enforced)
|
||||||
|
4. A SECOND invitation by the same member inside the rolling 30-day
|
||||||
|
window is refused (one guest per member per month — the window is
|
||||||
|
counted from the guests ledger).
|
||||||
|
5. A recipient who is an EXISTING MEMBER is refused.
|
||||||
|
6. A recipient with a PRIOR guest (ledger row) is refused.
|
||||||
|
7. A recipient on MANUAL_MEMBERS is refused.
|
||||||
|
8. A non-member (no portal row) and a GUEST account are refused — only
|
||||||
|
members invite guests.
|
||||||
|
9. Re-inviting an address that was just provisioned is refused (one guest
|
||||||
|
per recipient ever — the moved-state guard behind the endpoint).
|
||||||
|
10. The GATE IS GONE: the app defines no guest-request approve/reject
|
||||||
|
routes and no GUEST_AUTO_APPROVE flag — nothing to approve anywhere.
|
||||||
|
LEGACY HISTORY
|
||||||
|
11. A rejected request from the trial period still shows in the member's
|
||||||
|
trail (history only); a rejected request blocks nothing.
|
||||||
|
PANEL LEDGER FEED
|
||||||
|
12. GET /admin/guest-ledger serves the guests ledger (the panel's
|
||||||
|
duplicate-send guard reads it).
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_guest_requests.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
os.environ["ADMIN_TOKEN"] = "test-admin-token" # admin endpoints authenticate on this
|
||||||
|
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
|
||||||
|
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
|
||||||
|
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok, detail=""):
|
||||||
|
results.append((name, bool(ok), detail))
|
||||||
|
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
class _NoNetwork:
|
||||||
|
"""Guard: ANY httpx client construction inside the test is a failure."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
def __call__(self, *a, **k): # pragma: no cover
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
# The trail now derives each guest's invited/active state from the Cloudron
|
||||||
|
# user record, so it opens an httpx client around a STUBBED users fetch: the
|
||||||
|
# client is constructible but every real HTTP attempt still raises — the
|
||||||
|
# guard, kept.
|
||||||
|
class _FakeClient(_NoNetwork):
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
async def post(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = _FakeClient
|
||||||
|
|
||||||
|
# Cloudron users fixture for the invited-state derivation: the fixture guest's
|
||||||
|
# Cloudron user id is 'uid-fixture' (fake_user_create below) with the invite
|
||||||
|
# NOT yet accepted. Tests flip `inviteAccepted` to simulate acceptance.
|
||||||
|
CLOUDRON_USERS = {"uid-fixture": {"inviteAccepted": False, "username": None}}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_fetch_users(client):
|
||||||
|
return [{"id": uid, "username": v.get("username"),
|
||||||
|
"inviteAccepted": v.get("inviteAccepted", False)}
|
||||||
|
for uid, v in CLOUDRON_USERS.items()]
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_fetch_all_users = fake_fetch_users
|
||||||
|
|
||||||
|
# --- recorders (same contract as test_guest_lifecycle) ---------------------- #
|
||||||
|
calls = {"group": [], "budget": [], "email": [], "listmonk": [], "loomio": 0,
|
||||||
|
"matrix": 0}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_email_exists(email):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_email_exists = fake_email_exists
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_switch(user_id, add_gid=None, remove_gids=()):
|
||||||
|
calls["group"].append((user_id, add_gid))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_group(user_id, group_id=None):
|
||||||
|
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
|
||||||
|
|
||||||
|
|
||||||
|
def rec_email(to, subject, text_body=None, html_body=None):
|
||||||
|
calls["email"].append((to, subject, text_body or ""))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_listmonk(email, subscribe):
|
||||||
|
calls["listmonk"].append((email, bool(subscribe)))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_loomio():
|
||||||
|
calls["loomio"] += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_matrix():
|
||||||
|
calls["matrix"] += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team_id(email):
|
||||||
|
return "team-" + email
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_get_or_create_team(email, budget, budget_duration="30d"):
|
||||||
|
return "team-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_create_key(email, budget, team_id):
|
||||||
|
return "***"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_user_create(email, name):
|
||||||
|
return "uid-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_invite_link(user_id):
|
||||||
|
return "https://my.example/setupaccount.html?inviteToken=x"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_activated(user_id):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def fake_team_db(team_id):
|
||||||
|
return {"max_budget": None, "spend": 0.0, "budget_reset_at": None}
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_switch_group = rec_switch
|
||||||
|
m.cloudron_set_group = rec_group
|
||||||
|
m.cloudron_set_active = rec_group
|
||||||
|
m.cloudron_create_user = fake_user_create
|
||||||
|
m.cloudron_get_invite_link = fake_invite_link
|
||||||
|
m.cloudron_is_activated = fake_activated
|
||||||
|
m.litellm_get_or_create_team = fake_get_or_create_team
|
||||||
|
m.litellm_create_key = fake_create_key
|
||||||
|
m.litellm_team_id_for_email = fake_team_id
|
||||||
|
m.litellm_update_team_budget = async_rec_budget = (lambda *a: None) # replaced below
|
||||||
|
m.get_team_budget_from_db = fake_team_db
|
||||||
|
m.send_email = rec_email
|
||||||
|
m.listmonk_sync = rec_listmonk
|
||||||
|
m.sync_loomio_memberships = rec_loomio
|
||||||
|
m.sync_matrix_space = rec_matrix
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_budget(team_id, budget):
|
||||||
|
calls["budget"].append((team_id, round(float(budget), 2)))
|
||||||
|
|
||||||
|
|
||||||
|
m.litellm_update_team_budget = rec_budget
|
||||||
|
|
||||||
|
# --- real Request objects (the slowapi limiter decorator requires them) ----- #
|
||||||
|
from starlette.requests import Request as StarletteRequest # noqa: E402
|
||||||
|
import json as _json # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def make_request(method="GET", body=None, headers=None):
|
||||||
|
raw = _json.dumps(body or {}).encode()
|
||||||
|
headers = dict(headers or {})
|
||||||
|
if raw and "content-length" not in headers:
|
||||||
|
headers["content-length"] = str(len(raw))
|
||||||
|
async def receive():
|
||||||
|
return {"type": "http.request", "body": raw, "more_body": False}
|
||||||
|
scope = {
|
||||||
|
"type": "http", "method": method, "path": "/", "query_string": b"",
|
||||||
|
"headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
|
||||||
|
"server": ("testserver", 80), "client": ("testclient", 123),
|
||||||
|
}
|
||||||
|
return StarletteRequest(scope, receive)
|
||||||
|
|
||||||
|
|
||||||
|
def seed_member(conn, email, account_type="member", active=1):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type) "
|
||||||
|
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, 0, ?)",
|
||||||
|
(email, email, active, m.MEMBER_BUDGET, account_type),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn)
|
||||||
|
inviter = "member-one@x.org"
|
||||||
|
seed_member(conn, inviter, active=1)
|
||||||
|
conn.execute("UPDATE members SET slug = 'member-one' WHERE email = ?", (inviter,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 1-3. a valid invitation PROVISIONS IMMEDIATELY ----------------------
|
||||||
|
reset = lambda: calls.update({"group": [], "budget": [], "email": [],
|
||||||
|
"listmonk": [], "loomio": 0, "matrix": 0})
|
||||||
|
reset()
|
||||||
|
conn = m.get_db()
|
||||||
|
refusal = m.guest_request_guard(conn, inviter, "friend@x.org")
|
||||||
|
check("guard: passes for an active member + fresh recipient",
|
||||||
|
refusal is None, str(refusal))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
async def post_guest(email_addr, recipient, name=""):
|
||||||
|
"""Drive the POST /broker/guests handler directly (auth is stubbed)."""
|
||||||
|
m._verify_broker_secret = lambda request: email_addr
|
||||||
|
return await m.broker_guest_invite(
|
||||||
|
make_request("POST", {"email": recipient, "name": name}))
|
||||||
|
outcome = asyncio.run(post_guest(inviter, "friend@x.org", "Friend"))
|
||||||
|
check("invite: status is provisioned (immediate, nothing pending)",
|
||||||
|
outcome.get("status") == "provisioned", str(outcome))
|
||||||
|
check("invite: no pending_approval status anywhere in the response",
|
||||||
|
"pending" not in str(outcome).lower(), str(outcome))
|
||||||
|
check("invite: response carries the cap and the box",
|
||||||
|
outcome.get("budget") == m.GUEST_BUDGET
|
||||||
|
and outcome.get("expires_in_days") == int(m.GUEST_DAYS), str(outcome))
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
acct = conn.execute(
|
||||||
|
"SELECT account_type, balance, credit_balance, guest_expires_at "
|
||||||
|
"FROM members WHERE email = ?", ("friend@x.org",)).fetchone()
|
||||||
|
check("invite: recipient row marked guest",
|
||||||
|
acct and acct[0] == "guest", str(acct))
|
||||||
|
check("invite: allowance balance 0 (the $2 is all credit)",
|
||||||
|
acct and acct[1] == 0.0, str(acct))
|
||||||
|
check("invite: $2 non-expiring credit granted",
|
||||||
|
acct and acct[2] == m.GUEST_BUDGET, str(acct))
|
||||||
|
check("invite: 60-day box set (guest_expires_at)",
|
||||||
|
acct and bool(acct[3]), str(acct))
|
||||||
|
if acct and acct[3]:
|
||||||
|
exp = datetime.strptime(str(acct[3])[:19], "%Y-%m-%d %H:%M:%S")
|
||||||
|
delta = exp - datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
check("invite: expiry sits ~GUEST_DAYS out",
|
||||||
|
timedelta(0) < delta <= timedelta(days=int(m.GUEST_DAYS)),
|
||||||
|
str(acct[3]))
|
||||||
|
ledger = conn.execute(
|
||||||
|
"SELECT inviter_email, recipient_email, status FROM guests "
|
||||||
|
"WHERE recipient_email = 'friend@x.org'").fetchall()
|
||||||
|
check("invite: ledger row inviter → recipient (active)",
|
||||||
|
ledger and ledger[0][0] == inviter and ledger[0][2] == "active", str(ledger))
|
||||||
|
reqs = conn.execute("SELECT COUNT(*) FROM guest_requests").fetchone()[0]
|
||||||
|
check("invite: NO guest_requests row written (no pending state exists)",
|
||||||
|
reqs == 0, str(reqs))
|
||||||
|
conn.close()
|
||||||
|
check("invite: LiteLLM cap set to the guest budget (one-time)",
|
||||||
|
calls["budget"] == [("team-fixture", round(m.GUEST_BUDGET, 2))],
|
||||||
|
str(calls["budget"]))
|
||||||
|
check("invite: Cloudron user created into the guests group",
|
||||||
|
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
|
||||||
|
check("invite: invitation email sent to the recipient AT ONCE",
|
||||||
|
len(calls["email"]) == 1 and calls["email"][0][0] == "friend@x.org",
|
||||||
|
str(calls["email"]))
|
||||||
|
check("invite: invitation email NAMES the inviting member",
|
||||||
|
"member-one" in calls["email"][0][2], str(calls["email"]))
|
||||||
|
check("invite: newsletter subscribe fired",
|
||||||
|
calls["listmonk"] == [("friend@x.org", True)], str(calls["listmonk"]))
|
||||||
|
check("invite: NO Loomio/Matrix invites", not calls["loomio"] and not calls["matrix"])
|
||||||
|
|
||||||
|
# --- 3. the member's own trail shows the guest + the closed window -------
|
||||||
|
m._verify_broker_secret = lambda request: inviter
|
||||||
|
view = asyncio.run(m.broker_guest_list(make_request("GET")))
|
||||||
|
guests = [t for t in view["trail"] if t.get("kind") == "guest"]
|
||||||
|
check("trail: the new guest visible to the member as active",
|
||||||
|
len(guests) == 1 and guests[0]["recipient"] == "friend@x.org"
|
||||||
|
and guests[0]["status"] == "active", str(view["trail"]))
|
||||||
|
check("trail: un-accepted invite shows state='invited' (never reads active)",
|
||||||
|
guests and guests[0]["state"] == "invited", str(guests))
|
||||||
|
CLOUDRON_USERS["uid-fixture"]["inviteAccepted"] = True # simulate acceptance
|
||||||
|
view = asyncio.run(m.broker_guest_list(make_request("GET")))
|
||||||
|
guests = [t for t in view["trail"] if t.get("kind") == "guest"]
|
||||||
|
check("trail: after acceptance the state follows the ledger (active)",
|
||||||
|
guests and guests[0]["state"] == "active", str(guests))
|
||||||
|
check("trail: no pending entries in the member's trail",
|
||||||
|
not any(t.get("status") == "pending" for t in view["trail"]),
|
||||||
|
str(view["trail"]))
|
||||||
|
check("trail: member is not eligible inside the 30-day window",
|
||||||
|
view["eligible"] is False, str(view["eligible"]))
|
||||||
|
check("trail: next_eligible_at given", bool(view["next_eligible_at"]),
|
||||||
|
str(view["next_eligible_at"]))
|
||||||
|
|
||||||
|
# --- 4. second invitation inside the window: refused (1/month) -----------
|
||||||
|
conn = m.get_db()
|
||||||
|
refusal = m.guest_request_guard(conn, inviter, "friend2@x.org")
|
||||||
|
check("limit: second guest within 30 days refused",
|
||||||
|
refusal is not None and "30 days" in refusal, str(refusal))
|
||||||
|
# another member may still invite a DIFFERENT recipient
|
||||||
|
seed_member(conn, "member-two@x.org", active=1)
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.guest_request_guard(conn, "member-two@x.org", "other@x.org")
|
||||||
|
check("limit: a DIFFERENT member is not blocked by someone else's guest",
|
||||||
|
refusal is None, str(refusal))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 5-8. recipient-side + inviter-side refusal paths ---------------------
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, "existing@x.org", account_type="member", active=1)
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.guest_request_guard(conn, "member-two@x.org", "existing@x.org")
|
||||||
|
check("refusal: existing member as recipient", refusal is not None, str(refusal))
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
|
||||||
|
"VALUES ('member-two@x.org', 'prior@x.org', datetime('now'), 'active')")
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.guest_request_guard(conn, "member-two@x.org", "prior@x.org")
|
||||||
|
check("refusal: prior guest (ledger) as recipient", refusal is not None, str(refusal))
|
||||||
|
conn.close()
|
||||||
|
old_manual = set(m.MANUAL_MEMBERS)
|
||||||
|
m.MANUAL_MEMBERS = {"manual@x.org"}
|
||||||
|
conn = m.get_db()
|
||||||
|
refusal = m.guest_request_guard(conn, "member-two@x.org", "manual@x.org")
|
||||||
|
check("refusal: recipient on MANUAL_MEMBERS", refusal is not None, str(refusal))
|
||||||
|
conn.close()
|
||||||
|
m.MANUAL_MEMBERS = old_manual
|
||||||
|
|
||||||
|
# --- 8. only members reach the member path -------------------------------
|
||||||
|
conn = m.get_db()
|
||||||
|
# a non-member: no portal row at all → guest_provision_guard refuses
|
||||||
|
refusal = m.guest_request_guard(conn, "stranger@x.org", "someone@x.org")
|
||||||
|
check("refusal: non-member inviter", refusal is not None, str(refusal))
|
||||||
|
seed_member(conn, "guest-acct@x.org", account_type="guest", active=1)
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.guest_request_guard(conn, "guest-acct@x.org", "someone@x.org")
|
||||||
|
check("refusal: a GUEST cannot invite guests", refusal is not None, str(refusal))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 9. re-inviting a just-provisioned address is refused (moved state) --
|
||||||
|
reset()
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, "member-three@x.org", active=1)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
try:
|
||||||
|
asyncio.run(post_guest("member-three@x.org", "friend@x.org"))
|
||||||
|
check("moved-state: duplicate invite refused", False, "no exception raised")
|
||||||
|
except Exception as e:
|
||||||
|
code = getattr(e, "status_code", None)
|
||||||
|
check("moved-state: duplicate invite refused (429)",
|
||||||
|
code == 429 and "already received a guest account" in str(getattr(e, "detail", e)),
|
||||||
|
str(e))
|
||||||
|
conn = m.get_db()
|
||||||
|
reqs = conn.execute("SELECT COUNT(*) FROM guest_requests").fetchone()[0]
|
||||||
|
check("moved-state: still NO pending state written", reqs == 0, str(reqs))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 10. the gate is GONE from the app -----------------------------------
|
||||||
|
paths = {getattr(r, "path", "") for r in m.app.routes}
|
||||||
|
gone = [p for p in paths if "guest-requests" in p]
|
||||||
|
check("gate gone: no guest-request routes remain on the app",
|
||||||
|
not gone, str(sorted(gone)))
|
||||||
|
check("gate gone: GUEST_AUTO_APPROVE no longer exists",
|
||||||
|
not hasattr(m, "GUEST_AUTO_APPROVE"), str(getattr(m, "GUEST_AUTO_APPROVE", None)))
|
||||||
|
|
||||||
|
# --- 11. legacy rejected history shows in the trail; blocks nothing ------
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO guest_requests (inviter_email, recipient_email, status, decided_at, note) "
|
||||||
|
"VALUES (?, 'rejected-back-then@x.org', 'rejected', datetime('now'), 'not right now')",
|
||||||
|
(inviter,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
m._verify_broker_secret = lambda request: inviter
|
||||||
|
view = asyncio.run(m.broker_guest_list(make_request("GET")))
|
||||||
|
rej = [t for t in view["trail"] if t.get("kind") == "request"
|
||||||
|
and t.get("recipient") == "rejected-back-then@x.org"]
|
||||||
|
check("legacy: a rejected request still shows in the trail (history)",
|
||||||
|
len(rej) == 1 and rej[0]["status"] == "rejected", str(view["trail"]))
|
||||||
|
check("legacy: no pending entries ever appear in the trail",
|
||||||
|
not any(t.get("status") == "pending" for t in view["trail"]),
|
||||||
|
str(view["trail"]))
|
||||||
|
conn = m.get_db()
|
||||||
|
# (member-three is already seeded and active with a fresh recipient; the
|
||||||
|
# point is a legacy rejection blocks nothing)
|
||||||
|
refusal = m.guest_request_guard(conn, "member-three@x.org", "fresh@x.org")
|
||||||
|
check("legacy: a legacy rejection does not count against anyone's window",
|
||||||
|
refusal is None, str(refusal))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 12. the panel's ledger feed -----------------------------------------
|
||||||
|
fed = asyncio.run(m.admin_guest_ledger(
|
||||||
|
make_request("GET", headers={"X-Admin-Token": "test-admin-token"})))
|
||||||
|
recips = [r["recipient"] for r in fed.get("ledger", [])]
|
||||||
|
check("ledger feed: serves the guests ledger for the panel's guard",
|
||||||
|
"friend@x.org" in recips and "prior@x.org" in recips, str(fed))
|
||||||
|
check("ledger feed: no pending key in the payload",
|
||||||
|
"pending" not in fed and "decided" not in fed, str(sorted(fed.keys())))
|
||||||
|
|
||||||
|
print()
|
||||||
|
passed = sum(1 for _, ok, _ in results if ok)
|
||||||
|
print(f"{passed}/{len(results)} checks passed")
|
||||||
|
return 0 if passed == len(results) else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the Loomio sync is idempotent and non-duplicating.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-04 a live run of sync_loomio_memberships() emailed a Loomio invite
|
||||||
|
notification to (effectively) the whole membership. The guards that must hold
|
||||||
|
are proven here on a FIXTURE db with the network STUBBED:
|
||||||
|
|
||||||
|
ADD / dedupe
|
||||||
|
1. A member already in the Loomio group is skipped SILENTLY — no invite
|
||||||
|
payload ever contains their address.
|
||||||
|
2. members.loomio_invited_at is a second guard: an address we have handed
|
||||||
|
over before is never sent again, even if it is not (yet) visible in the
|
||||||
|
live roster.
|
||||||
|
3. `remove_absent` is never sent (no evict-then-re-add re-invite path).
|
||||||
|
4. FAIL CLOSED — if the live roster cannot be read, nothing is sent.
|
||||||
|
5. Running the sync twice adds nobody a second time.
|
||||||
|
|
||||||
|
REMOVE / reconciliation (a deactivation MUST still propagate to Loomio)
|
||||||
|
6. A member in the group who is no longer active is removed exactly once.
|
||||||
|
7. The operator allowlist is never removed, even when not active.
|
||||||
|
8. Removal is targeted — it never re-sends a present member's address, so it
|
||||||
|
cannot re-invite or notify anyone who is staying.
|
||||||
|
9. A second run removes nobody again (the roster no longer lists them).
|
||||||
|
10. remove_loomio_membership treats 404 as success (idempotent, no error).
|
||||||
|
|
||||||
|
The sync is ON by default (kill switch LOOMIO_SYNC_ENABLED=0 pauses it).
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_loomio_guard.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["LOOMIO_API_KEY"] = "test-user-key"
|
||||||
|
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
|
||||||
|
os.environ["LOOMIO_GROUP_ID"] = "1"
|
||||||
|
# Leave LOOMIO_SYNC_ENABLED unset -> the sync must default to ENABLED.
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
# Keep the membership assertions isolated: no extra keep accounts, and no
|
||||||
|
# username-fix pass (it makes its own /api/b3/users calls).
|
||||||
|
m.LOOMIO_ALWAYS_KEEP = ["keep@x.org"]
|
||||||
|
|
||||||
|
posts = [] # every b2/memberships POST payload
|
||||||
|
deletes = [] # every b3 membership DELETE url
|
||||||
|
ROSTER = {} # email -> membership id currently in the group
|
||||||
|
GET_FAILS = False # exercise fail-closed
|
||||||
|
DELETE_STATUS = 200 # toggle to prove 404 tolerance
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResp:
|
||||||
|
def __init__(self, status=200, payload=None):
|
||||||
|
self.status_code = status
|
||||||
|
self._payload = payload or {}
|
||||||
|
self.text = str(payload or {})
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
if self.status_code >= 400:
|
||||||
|
raise RuntimeError(f"HTTP {self.status_code}")
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, url, headers=None, params=None):
|
||||||
|
if GET_FAILS:
|
||||||
|
raise RuntimeError("simulated Loomio roster read failure")
|
||||||
|
offset = (params or {}).get("offset", 0)
|
||||||
|
limit = (params or {}).get("limit", 50)
|
||||||
|
rows = [{"id": i, "user_email": e} for e, i in ROSTER.items()]
|
||||||
|
page = rows[offset:offset + limit]
|
||||||
|
return FakeResp(200, {"memberships": page, "meta": {"total": len(rows)}})
|
||||||
|
|
||||||
|
async def post(self, url, headers=None, json=None):
|
||||||
|
posts.append({"url": url, "json": json or {}})
|
||||||
|
return FakeResp(200, {"added_emails": (json or {}).get("emails", [])})
|
||||||
|
|
||||||
|
async def delete(self, url, headers=None):
|
||||||
|
deletes.append(url)
|
||||||
|
return FakeResp(DELETE_STATUS)
|
||||||
|
|
||||||
|
async def patch(self, *a, **k):
|
||||||
|
return FakeResp(200, {})
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_active():
|
||||||
|
# active members: new@ / old@ are NOT in the group; member@ IS.
|
||||||
|
return ["new@x.org", "old@x.org", "member@x.org"]
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_activated(emails):
|
||||||
|
return emails
|
||||||
|
|
||||||
|
|
||||||
|
async def noop_fix(_client):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, ok))
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
global GET_FAILS, ROSTER, DELETE_STATUS
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
for e in ("new@x.org", "old@x.org", "member@x.org"):
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (e,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
cols = [r[1] for r in m.get_db().execute("PRAGMA table_info(members)").fetchall()]
|
||||||
|
m.get_db().close()
|
||||||
|
check("migration: members.loomio_invited_at exists", "loomio_invited_at" in cols)
|
||||||
|
|
||||||
|
m.get_active_member_emails = fake_active
|
||||||
|
m.filter_loomio_activated = fake_activated
|
||||||
|
m.httpx.AsyncClient = FakeClient
|
||||||
|
m.loomio_fix_usernames = noop_fix
|
||||||
|
|
||||||
|
check("default: sync is ENABLED when the flag is unset", m.LOOMIO_SYNC_ENABLED is True)
|
||||||
|
|
||||||
|
# Loomio group currently holds: an active member (member@), and the operator
|
||||||
|
# allowlist account (keep@) which is NOT an active portal member.
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||||
|
|
||||||
|
# --- 1. ADD path: only the never-seen address is invited. ---
|
||||||
|
m.mark_loomio_invited("old@x.org") # recorded -> excluded by layer (b)
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
body = posts[0]["json"] if posts else {}
|
||||||
|
check("add: exactly one invite call", len(posts) == 1)
|
||||||
|
check("add: only the never-seen address is invited", body.get("emails") == ["new@x.org"])
|
||||||
|
check("add: a member ALREADY in Loomio is skipped silently",
|
||||||
|
"member@x.org" not in (body.get("emails") or []))
|
||||||
|
check("add: the record guard excludes a previously-invited address",
|
||||||
|
"old@x.org" not in (body.get("emails") or []))
|
||||||
|
check("add: remove_absent is NEVER sent (no re-add path)", "remove_absent" not in body)
|
||||||
|
check("add: the newly-invited address is recorded",
|
||||||
|
m.get_loomio_invited_at("new@x.org") is not None)
|
||||||
|
check("add: nothing removed when nobody has lapsed", deletes == [])
|
||||||
|
|
||||||
|
# --- 2. Second run adds nobody again. ---
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # Loomio now has new@
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("double-run: no second invite", posts == [])
|
||||||
|
check("double-run: no removals", deletes == [])
|
||||||
|
|
||||||
|
# --- 3. REMOVE path: a lapsed member is removed exactly once. ---
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "lapsed@x.org": 77}
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("remove: the lapsed member is removed exactly once",
|
||||||
|
deletes == [f"{m.LOOMIO_BASE}/api/b3/memberships/77"])
|
||||||
|
check("remove: the live active member is NOT removed",
|
||||||
|
f"{m.LOOMIO_BASE}/api/b3/memberships/10" not in deletes)
|
||||||
|
check("remove: the operator allowlist is NEVER removed (even though not active)",
|
||||||
|
f"{m.LOOMIO_BASE}/api/b3/memberships/2" not in deletes)
|
||||||
|
check("remove: no re-invite is sent while removing", posts == [])
|
||||||
|
check("remove: it does not send present members to any endpoint",
|
||||||
|
all("keep@x.org" not in (p["json"].get("emails") or []) for p in posts))
|
||||||
|
|
||||||
|
# --- 4. Second run after the removal changes nothing. ---
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # lapsed gone
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("remove double-run: nothing removed again", deletes == [])
|
||||||
|
check("remove double-run: nothing invited", posts == [])
|
||||||
|
|
||||||
|
# --- 5. A re-run against a STALE roster (member already gone) must not error:
|
||||||
|
# Loomio answers 404 for an absent membership, which is success. ---
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "lapsed@x.org": 77}
|
||||||
|
DELETE_STATUS = 404
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
err = None
|
||||||
|
try:
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
except Exception as e: # pragma: no cover
|
||||||
|
err = e
|
||||||
|
check("idempotent remove: a 404 (already absent) is treated as success", err is None)
|
||||||
|
check("idempotent remove: still no re-invite", posts == [])
|
||||||
|
DELETE_STATUS = 200
|
||||||
|
|
||||||
|
# --- 6. FAIL CLOSED: an unreadable roster stops BOTH phases. ---
|
||||||
|
ROSTER = {"lapsed@x.org": 77}
|
||||||
|
GET_FAILS = True
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("fail-closed: no invite when the roster is unreadable", posts == [])
|
||||||
|
check("fail-closed: no removal when the roster is unreadable", deletes == [])
|
||||||
|
GET_FAILS = False
|
||||||
|
|
||||||
|
# --- 7. The kill switch really pauses everything. ---
|
||||||
|
m.LOOMIO_SYNC_ENABLED = False
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("kill switch: no calls at all when LOOMIO_SYNC_ENABLED=0",
|
||||||
|
posts == [] and deletes == [])
|
||||||
|
m.LOOMIO_SYNC_ENABLED = True
|
||||||
|
|
||||||
|
# --- 8. Recording is idempotent — an existing timestamp is never overwritten. ---
|
||||||
|
first = m.get_loomio_invited_at("old@x.org")
|
||||||
|
m.mark_loomio_invited("old@x.org")
|
||||||
|
check("mark_loomio_invited never overwrites an existing timestamp",
|
||||||
|
m.get_loomio_invited_at("old@x.org") == first)
|
||||||
|
|
||||||
|
# --- 9. remove_loomio_membership status handling (200/204/404 ok, 500 not). ---
|
||||||
|
async with FakeClient() as c:
|
||||||
|
DELETE_STATUS = 204
|
||||||
|
check("remove_loomio_membership: 204 is success", await m.remove_loomio_membership(c, 1))
|
||||||
|
DELETE_STATUS = 500
|
||||||
|
check("remove_loomio_membership: 500 is a failure", not await m.remove_loomio_membership(c, 1))
|
||||||
|
DELETE_STATUS = 200
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import asyncio, os, sys, tempfile
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "aliases.db")
|
||||||
|
os.environ.setdefault("ADMIN_TOKEN", "admin-test")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]; m.ADMIN_TOKEN = "admin-test"
|
||||||
|
|
||||||
|
conn = m.get_db(); m._ensure_allowance_tables(conn)
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance, source) VALUES (?,?,?,?,?)",
|
||||||
|
("a@example.org", "main-slug", 1, 0.0, "oc"))
|
||||||
|
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
|
||||||
|
("hidden-abc", "", "A", 10.0, "oc:hidden-abc:ref1"))
|
||||||
|
conn.commit(); conn.close()
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
async def add():
|
||||||
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://p", timeout=60) as c:
|
||||||
|
r = await c.post("/admin/aliases", headers={"x-admin-token": "admin-test"},
|
||||||
|
json={"slug": "hidden-abc", "email": "a@example.org"})
|
||||||
|
return r.status_code, r.json()
|
||||||
|
st, d = asyncio.run(add())
|
||||||
|
assert st == 200, (st, d)
|
||||||
|
r1 = asyncio.run(m.settle_held_credits(send=False))
|
||||||
|
conn = m.get_db(); bal = conn.execute("SELECT credit_balance FROM members WHERE email='a@example.org'").fetchone()[0]; conn.close()
|
||||||
|
print(" alias add:", st, "| granted:", r1["granted"], "| balance:", bal)
|
||||||
|
assert bal == 10.0, "a purchase from the aliased hidden profile must credit the member"
|
||||||
|
assert len(r1["granted"]) == 1
|
||||||
|
r2 = asyncio.run(m.settle_held_credits(send=False))
|
||||||
|
assert len(r2["granted"]) == 0 and bal == 10.0
|
||||||
|
print("ALIAS TABLE OK: hidden-profile hold credits the member; no double-apply")
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the panel's membership state must not call a paying member "grace".
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-13 mark@ofosos.org showed as in grace. He was current: the reminder
|
||||||
|
went out 2026-11-04 for the cycle that looked unpaid, his grace window elapsed
|
||||||
|
2026-11-11, and the reconciliation logged `renewed` for him at 19:02 that
|
||||||
|
afternoon — his next charge is 2026-11-26, which had not arrived and was not
|
||||||
|
supposed to.
|
||||||
|
|
||||||
|
The state function asked "is there a row in payment_reminders?" and stopped
|
||||||
|
there. That table is a HISTORY, kept so the sweep does not re-remind inside a
|
||||||
|
cycle; it is not a state. Two bugs followed: a reminder never expired (grace is
|
||||||
|
PAYMENT_GRACE_DAYS long), and a renewal never cleared it.
|
||||||
|
|
||||||
|
Ordering matters too: the same member had allowance_log id 2296 dated 2026-11-11
|
||||||
|
next to id 2286 dated 2026-11-13, so "latest by id" reads the WRONG decision.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import pathlib
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "state-fixture.db")
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
def check(cond, msg):
|
||||||
|
print((" ok " if cond else " FAIL ") + msg)
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(msg)
|
||||||
|
|
||||||
|
NOW = datetime.now(timezone.utc)
|
||||||
|
def stamp(dt):
|
||||||
|
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn)
|
||||||
|
conn.execute("DELETE FROM payment_reminders")
|
||||||
|
conn.execute("DELETE FROM allowance_log")
|
||||||
|
|
||||||
|
EMAIL = "mark@ofosos.org"
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (EMAIL,))
|
||||||
|
|
||||||
|
print("1. a RENEWAL after a reminder means active — the actual bug")
|
||||||
|
conn.execute("INSERT INTO payment_reminders (email, cycle, sent_at) VALUES (?,?,?)",
|
||||||
|
(EMAIL, "2026-10-26", stamp(NOW - timedelta(days=9)))) # reminded 9d ago
|
||||||
|
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
|
||||||
|
(EMAIL, "2026-10-26", "in_grace", stamp(NOW - timedelta(days=9))))
|
||||||
|
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
|
||||||
|
(EMAIL, "2026-10-26", "renewed", stamp(NOW - timedelta(hours=2))))
|
||||||
|
conn.commit()
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "active", f"paid member reads active, not grace (got {state!r}: {why})")
|
||||||
|
|
||||||
|
print("2. the LATEST decision wins, even when an older row has a higher id")
|
||||||
|
conn.execute("DELETE FROM allowance_log")
|
||||||
|
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
|
||||||
|
(EMAIL, "2026-10-26", "renewed", stamp(NOW - timedelta(hours=2)))) # id 1
|
||||||
|
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
|
||||||
|
(EMAIL, "2026-10-26", "in_grace", stamp(NOW - timedelta(days=9)))) # id 2, OLDER date
|
||||||
|
conn.commit()
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "active",
|
||||||
|
f"an older-dated row inserted later does not override the renewal (got {state!r}: {why})")
|
||||||
|
|
||||||
|
print("3. a reminder INSIDE the grace window still reads in_grace")
|
||||||
|
conn.execute("DELETE FROM allowance_log")
|
||||||
|
conn.execute("UPDATE payment_reminders SET sent_at = ? WHERE email = ?",
|
||||||
|
(stamp(NOW - timedelta(days=2)), EMAIL))
|
||||||
|
conn.commit()
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "in_grace", f"two days into a {int(m.PAYMENT_GRACE_DAYS)}-day grace reads in_grace (got {state!r})")
|
||||||
|
|
||||||
|
print("4. grace EXPIRES — no reminder row may mean grace forever")
|
||||||
|
conn.execute("UPDATE payment_reminders SET sent_at = ? WHERE email = ?",
|
||||||
|
(stamp(NOW - timedelta(days=int(m.PAYMENT_GRACE_DAYS) + 3)), EMAIL))
|
||||||
|
conn.commit()
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "awaiting_contribution", f"past the window reads awaiting, not grace (got {state!r})")
|
||||||
|
check("elapsed" in why, f"and says the grace elapsed (got {why!r})")
|
||||||
|
|
||||||
|
print("5. a previewed deactivation is not grace either")
|
||||||
|
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
|
||||||
|
(EMAIL, "2026-10-26", "would_deactivate", stamp(NOW - timedelta(hours=1))))
|
||||||
|
conn.commit()
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "awaiting_contribution", f"would_deactivate reads awaiting (got {state!r})")
|
||||||
|
|
||||||
|
print("6. nobody flagged is simply active")
|
||||||
|
conn.execute("DELETE FROM payment_reminders")
|
||||||
|
conn.execute("DELETE FROM allowance_log")
|
||||||
|
conn.commit()
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "active" and why == "", f"clean member reads active with no reason (got {state!r}, {why!r})")
|
||||||
|
|
||||||
|
print("7. inactive is still inactive")
|
||||||
|
check(m.member_membership_state(EMAIL, False)[0] == "inactive", "active=0 reads inactive")
|
||||||
|
|
||||||
|
print("8. an unreadable database fails SAFE, not into a grace badge")
|
||||||
|
real = m.get_db
|
||||||
|
try:
|
||||||
|
def boom():
|
||||||
|
raise RuntimeError("db locked")
|
||||||
|
m.get_db = boom
|
||||||
|
state, why = m.member_membership_state(EMAIL, True)
|
||||||
|
check(state == "active", f"a failed read does not invent a payment problem (got {state!r})")
|
||||||
|
finally:
|
||||||
|
m.get_db = real
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
print()
|
||||||
|
if FAILS:
|
||||||
|
print(f"membership state: {len(FAILS)} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("membership state: OK — renewals clear grace, grace expires, reads fail safe")
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import asyncio, os, sys, tempfile
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "status.db")
|
||||||
|
os.environ.setdefault("BROKER_SECRET", "test-secret")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.BROKER_SECRET = "test-secret"
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn)
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance, balance, source) VALUES (?,?,?,?,?,?)",
|
||||||
|
("lapsed@example.org", "lapsed", 0, 3.0, 0.0, "oc"))
|
||||||
|
conn.execute("INSERT INTO allowance_log (email, cycle, decision, evidence, anchor_day) VALUES (?,?,?,?,?)",
|
||||||
|
("lapsed@example.org", "2026-11-05", "awaiting_contribution", "no live recurring contribution in this cycle", 5))
|
||||||
|
conn.commit(); conn.close()
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
async def run():
|
||||||
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://p", timeout=60) as c:
|
||||||
|
r = await c.get("/broker/membership-status", headers={"x-broker-secret": "test-secret", "x-member-email": "lapsed@example.org"})
|
||||||
|
return r.status_code, r.json()
|
||||||
|
st, d = asyncio.run(run())
|
||||||
|
print(" route:", st, "| active:", d.get("active"), "| state:", d.get("state"), "| min:", d.get("minimum_contribution"), "| decision:", (d.get("last_decision") or {}).get("decision"))
|
||||||
|
assert st == 200 and d["active"] is False and d["minimum_contribution"] == 5.0
|
||||||
|
assert (d.get("last_decision") or {}).get("decision") == "awaiting_contribution"
|
||||||
|
assert d.get("contribute_url")
|
||||||
|
print("MEMBERSHIP STATUS ROUTE OK: answers for a lapsed member, states minimum and last decision")
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for the metrics day-completion fix (Nov 2026 under-count).
|
||||||
|
|
||||||
|
Bug: snapshot() wrote only TODAY's row at 03:15 UTC — the first ~3 hours of
|
||||||
|
that day's traffic — and never revisited it, so every metrics_daily row was
|
||||||
|
frozen at its first hours (Nov 6 read $1.20/93 requests vs a true $34.26/4508).
|
||||||
|
|
||||||
|
Fix: each run completes YESTERDAY's row with its full-day usage/impact
|
||||||
|
aggregates (usage columns ONLY — membership columns are point-in-time
|
||||||
|
measurements that must survive), then records today live as before.
|
||||||
|
backfill() gains --since: a targeted usage-only repair that leaves the
|
||||||
|
published membership curve untouched.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* from the repo root: python3 tests/test_metrics_completion.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 tests/test_metrics_completion.py
|
||||||
|
"""
|
||||||
|
import datetime as dt
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="metrics-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE metrics_snapshot is imported
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"),
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "metrics_snapshot.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
import metrics_snapshot as ms # noqa: E402
|
||||||
|
|
||||||
|
TODAY = ms.today()
|
||||||
|
YESTERDAY = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=1)).isoformat()
|
||||||
|
DAY_BEFORE = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=2)).isoformat()
|
||||||
|
|
||||||
|
FAILED = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, cond, detail=""):
|
||||||
|
if cond:
|
||||||
|
print(f" ok {name}")
|
||||||
|
else:
|
||||||
|
print(f" FAIL {name} {detail}")
|
||||||
|
FAILED.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def stub_sources(spend, op_spend, tokens, joins=(), active=40, total=71,
|
||||||
|
subs=71, matrix=65, balance=123.45):
|
||||||
|
"""Replace every network source with fixed in-memory data."""
|
||||||
|
ms.from_sqlite = lambda: {"active": active, "total": total, "joins": list(joins)}
|
||||||
|
ms.from_listmonk = lambda: subs
|
||||||
|
ms.listmonk_joins = lambda: list(joins)
|
||||||
|
ms.from_matrix = lambda: matrix
|
||||||
|
ms.oc_collective_balance = lambda: balance
|
||||||
|
ms.spend_by_day = lambda since=None: dict(spend)
|
||||||
|
ms.operator_spend_by_day = lambda since=None: None if op_spend is None else dict(op_spend)
|
||||||
|
ms.tokens_by_day_model = lambda since=None: {k: dict(v) for k, v in tokens.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def read_row(day):
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
try:
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn.execute("SELECT * FROM metrics_daily WHERE day = ?", (day,)).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def seed(day, **cols):
|
||||||
|
"""Insert a row with arbitrary columns (the nightly snapshot's shape)."""
|
||||||
|
ms.upsert(day, {"spend_usd": None, "requests": None, "out_tokens": None,
|
||||||
|
"energy_wh": None, "co2e_g": None, "tokens_measured": None,
|
||||||
|
"tokens_estimated": None, "factor_revision": None, **cols})
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
print("1. snapshot() completes YESTERDAY with full-day usage, records today live")
|
||||||
|
stub_sources(
|
||||||
|
spend={YESTERDAY: (29.0604, 3384), TODAY: (2.19, 691)},
|
||||||
|
op_spend={YESTERDAY: 1.1613, TODAY: 0.5},
|
||||||
|
tokens={YESTERDAY: {"greenpt/glm-5.3-flash": 500000},
|
||||||
|
TODAY: {"greenpt/glm-5.3-flash": 100000}},
|
||||||
|
joins=["2026-11-01"],
|
||||||
|
)
|
||||||
|
row = ms.snapshot()
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
t = read_row(TODAY)
|
||||||
|
check("yesterday spend_usd = full-day total", y["spend_usd"] == 29.0604, y["spend_usd"])
|
||||||
|
check("yesterday requests = full-day count", y["requests"] == 3384, y["requests"])
|
||||||
|
check("yesterday operator_spend carried", y["operator_spend_usd"] == 1.1613, y["operator_spend_usd"])
|
||||||
|
check("yesterday out_tokens from full day", y["out_tokens"] == 500000, y["out_tokens"])
|
||||||
|
check("yesterday energy computed from tokens", y["energy_wh"] is not None and y["energy_wh"] > 0)
|
||||||
|
check("yesterday co2e_g computed (>0, unit tripwire band)", y["co2e_g"] is not None and y["co2e_g"] > 0)
|
||||||
|
check("today's row keeps the live partial", t["spend_usd"] == 2.19 and t["requests"] == 691)
|
||||||
|
check("today's row carries live membership", t["members_total"] == 71 and t["members_active"] == 40)
|
||||||
|
check("today's row carries oc_balance", t["oc_balance_usd"] == 123.45)
|
||||||
|
check("yesterday's membership columns are NULL (not measured, never 0)",
|
||||||
|
y["members_active"] is None and y["members_total"] is None and y["newsletter_subs"] is None)
|
||||||
|
|
||||||
|
print("2. completion overwrites a stale partial WITHOUT touching membership columns")
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
conn.execute("DELETE FROM metrics_daily")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
# What the OLD nightly code left behind: partial usage + that morning's counts.
|
||||||
|
seed(YESTERDAY, spend_usd=2.192, requests=691, members_active=39, members_total=70,
|
||||||
|
newsletter_subs=70, matrix_space_members=64)
|
||||||
|
stub_sources(
|
||||||
|
spend={YESTERDAY: (29.0604, 3384), TODAY: (0.5, 100)},
|
||||||
|
op_spend={YESTERDAY: 1.1613, TODAY: None},
|
||||||
|
tokens={YESTERDAY: {"greenpt/glm-5.3-flash": 500000}},
|
||||||
|
)
|
||||||
|
ms.snapshot()
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
check("stale partial spend replaced with full-day value", y["spend_usd"] == 29.0604, y["spend_usd"])
|
||||||
|
check("stale partial requests replaced", y["requests"] == 3384, y["requests"])
|
||||||
|
check("members_active preserved from that morning", y["members_active"] == 39, y["members_active"])
|
||||||
|
check("members_total preserved", y["members_total"] == 70, y["members_total"])
|
||||||
|
check("newsletter_subs preserved", y["newsletter_subs"] == 70)
|
||||||
|
check("matrix_space_members preserved", y["matrix_space_members"] == 64)
|
||||||
|
|
||||||
|
print("3. upsert_usage on a missing row INSERTs usage + NULL membership (fail-closed)")
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
conn.execute("DELETE FROM metrics_daily")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
ms.upsert_usage(DAY_BEFORE, {"spend_usd": 5.0, "requests": 42, "out_tokens": None,
|
||||||
|
"energy_wh": None, "co2e_g": None, "tokens_measured": None,
|
||||||
|
"tokens_estimated": None, "factor_revision": None,
|
||||||
|
"operator_spend_usd": None})
|
||||||
|
y = read_row(DAY_BEFORE)
|
||||||
|
check("usage columns written", y["spend_usd"] == 5.0 and y["requests"] == 42)
|
||||||
|
check("membership columns NULL, never zero",
|
||||||
|
y["members_active"] is None and y["members_total"] is None and y["members_new"] is None)
|
||||||
|
|
||||||
|
print("4. backfill(since=...) repairs usage only — membership curve untouched")
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
conn.execute("DELETE FROM metrics_daily")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
# Three days as the nightly snapshots wrote them: membership present, usage partial.
|
||||||
|
for d, sp, rq in ((DAY_BEFORE, 1.0, 50), (YESTERDAY, 2.0, 60)):
|
||||||
|
seed(d, spend_usd=sp, requests=rq, members_active=39, members_total=70,
|
||||||
|
members_new=3, newsletter_subs=70, matrix_space_members=64)
|
||||||
|
seed(TODAY, spend_usd=0.5, requests=10, members_active=40, members_total=71)
|
||||||
|
stub_sources(
|
||||||
|
spend={DAY_BEFORE: (17.8791, 4493), YESTERDAY: (29.0604, 3384), TODAY: (0.5, 10)},
|
||||||
|
op_spend={DAY_BEFORE: 0.2, YESTERDAY: 1.1613, TODAY: None},
|
||||||
|
tokens={DAY_BEFORE: {"greenpt/deepseek-v4.1-flash": 200000},
|
||||||
|
YESTERDAY: {"greenpt/glm-5.3-flash": 500000}},
|
||||||
|
joins=["2026-11-01"],
|
||||||
|
)
|
||||||
|
ms.backfill(since=YESTERDAY)
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
db = read_row(DAY_BEFORE)
|
||||||
|
t = read_row(TODAY)
|
||||||
|
check("repaired day matches ground truth spend", y["spend_usd"] == 29.0604, y["spend_usd"])
|
||||||
|
check("repaired day matches ground truth requests", y["requests"] == 3384, y["requests"])
|
||||||
|
check("repaired day keeps its membership columns",
|
||||||
|
y["members_active"] == 39 and y["members_total"] == 70 and y["members_new"] == 3)
|
||||||
|
check("day BEFORE --since untouched", db["spend_usd"] == 1.0 and db["requests"] == 50)
|
||||||
|
check("today still gets the full live update", t["members_total"] == 71)
|
||||||
|
|
||||||
|
print("5. full backfill (no --since) rebuilds membership columns as before")
|
||||||
|
conn = sqlite3.connect(_TEST_DB)
|
||||||
|
conn.execute("DELETE FROM metrics_daily")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
ms.backfill()
|
||||||
|
y = read_row(YESTERDAY)
|
||||||
|
check("full backfill writes joins-derived members_total",
|
||||||
|
y["members_total"] == 1, y["members_total"]) # one join on 2026-11-01
|
||||||
|
check("full backfill still writes full-day usage", y["spend_usd"] == 29.0604)
|
||||||
|
|
||||||
|
print("6. provenance: a day with tokens but no measured factor reports estimated, not measured")
|
||||||
|
ms.upsert_usage(DAY_BEFORE, {"spend_usd": 1.0, "requests": 5, "out_tokens": 1000,
|
||||||
|
"energy_wh": 0.5, "co2e_g": 0.125,
|
||||||
|
"tokens_measured": 0, "tokens_estimated": 1000,
|
||||||
|
"factor_revision": "x"})
|
||||||
|
y = read_row(DAY_BEFORE)
|
||||||
|
check("split persisted", y["tokens_measured"] == 0 and y["tokens_estimated"] == 1000)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILED:
|
||||||
|
print(f"FAILED: {len(FAILED)} check(s): {FAILED}")
|
||||||
|
sys.exit(1)
|
||||||
|
print("ALL CHECKS PASSED")
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: 'oc-incognito' — an OC payer whose OC profile hides its email.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
mmoya@mmoya.org sat in MANUAL_MEMBERS because OC hides the address on their
|
||||||
|
profile (incognito-5ad60182, email null since 2023), so email matching can never
|
||||||
|
find them. But "manual" means hand-provisioned, and the sweep SKIPS manual
|
||||||
|
members entirely — so a paying subscriber had no lapse logic, no dues tracking
|
||||||
|
and no order attribution. Two different facts were sharing one word.
|
||||||
|
|
||||||
|
An oc-incognito member needs no exemption from reconciliation: the partition
|
||||||
|
already matches OC orders by the PAYER'S SLUG, and members.slug holds exactly
|
||||||
|
that slug for these people. What they need is to stop being skipped.
|
||||||
|
|
||||||
|
The invariants pinned here:
|
||||||
|
* an explicit source beats MANUAL_MEMBERS membership — that is the whole
|
||||||
|
point; mmoya must not read as manual just because their address is listed;
|
||||||
|
* only 'manual' is exempt (lapse guard, reconciliation skip, shortfall
|
||||||
|
credits). 'oc-incognito' is a payer and gets payer treatment;
|
||||||
|
* an unreadable or unexpected source falls back to 'oc' — the direction that
|
||||||
|
keeps reconciling someone rather than quietly exempting them;
|
||||||
|
* the source column is optional (every existing row is NULL, meaning
|
||||||
|
"not stated"), so this ships without a data migration.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "source-fixture.db")
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
def check(cond, msg):
|
||||||
|
print((" ok " if cond else " FAIL ") + msg)
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(msg)
|
||||||
|
|
||||||
|
MMOYA = "mmoya@mmoya.org"
|
||||||
|
OTHER = "someone@example.org"
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
# The column arrives with get_db()'s own migration — asserted, not created here,
|
||||||
|
# because "the migration ran" is part of what this test is for.
|
||||||
|
check_cols = {r[1] for r in conn.execute("PRAGMA table_info(members)")}
|
||||||
|
assert "source" in check_cols, "get_db() must migrate in members.source"
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active) VALUES (?,?,1)",
|
||||||
|
(MMOYA, "incognito-5ad60182"))
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active) VALUES (?,?,1)",
|
||||||
|
(OTHER, "guest-abc123"))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
m.MANUAL_MEMBERS = {MMOYA, "founder@example.org"}
|
||||||
|
|
||||||
|
print("1. the fallback: a listed address with no source of its own is manual")
|
||||||
|
check(m.member_source(MMOYA) == "manual",
|
||||||
|
"an address in MANUAL_MEMBERS and nothing else reads manual (before the flip)")
|
||||||
|
check(m.is_manual_member(MMOYA) is True, "…and is exempt as such")
|
||||||
|
|
||||||
|
print("2. an explicit source BEATS the manual list — this is the mmoya case")
|
||||||
|
check(m.set_member_source(MMOYA, "oc-incognito") is True, "the source is written")
|
||||||
|
check(m.member_source(MMOYA) == "oc-incognito",
|
||||||
|
f"mmoya reads oc-incognito even while listed in MANUAL_MEMBERS (got {m.member_source(MMOYA)!r})")
|
||||||
|
check(m.is_manual_member(MMOYA) is False,
|
||||||
|
"and is therefore NOT exempt: a paying member gets payer treatment")
|
||||||
|
|
||||||
|
print("3. everyone else is unchanged")
|
||||||
|
check(m.member_source(OTHER) == "oc", "an unlisted member is oc (the default)")
|
||||||
|
check(m.member_source("founder@example.org") == "manual", "an unlisted-in-DB manual address stays manual")
|
||||||
|
check(m.member_source("nobody@nowhere.test") == "oc", "an address with no row at all is oc, not manual")
|
||||||
|
|
||||||
|
print("4. a bad source value never silently exempts anyone")
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("UPDATE members SET source = 'banana' WHERE lower(email) = ?", (OTHER,))
|
||||||
|
conn.commit(); conn.close()
|
||||||
|
check(m.member_source(OTHER) == "oc",
|
||||||
|
f"an unrecognised source falls back to oc — the direction that keeps reconciling (got {m.member_source(OTHER)!r})")
|
||||||
|
try:
|
||||||
|
m.set_member_source(OTHER, "banana")
|
||||||
|
check(False, "set_member_source must reject an unknown source")
|
||||||
|
except ValueError:
|
||||||
|
check(True, "set_member_source rejects an unknown source")
|
||||||
|
|
||||||
|
print("5. the three decisions that used to key on MANUAL_MEMBERS now key on the source")
|
||||||
|
src = (ROOT / "app" / "main.py").read_text()
|
||||||
|
recon = src[src.index("async def reconcile_allowances"):]
|
||||||
|
recon = recon[:recon.index("def ", recon.index("for row in rows"))]
|
||||||
|
check('member_source(email, conn) == "manual"' in recon,
|
||||||
|
"the reconciliation skips only source == manual")
|
||||||
|
check('member_source(email, conn) == "oc-incognito"' in recon and "oc_slug = slug" in recon,
|
||||||
|
"an oc-incognito member takes the OC slug from their own row — the index cannot give it "
|
||||||
|
"(it drops anyone without an email), and without a slug the reconciler skips them as "
|
||||||
|
"'cannot verify payment'")
|
||||||
|
check("in MANUAL_MEMBERS" not in recon,
|
||||||
|
"and no longer keys on the raw list (an oc-incognito member must not be skipped)")
|
||||||
|
check("not is_manual_member(email)" in src,
|
||||||
|
"the sweep's deactivation guard uses the source too")
|
||||||
|
check("is_manual_member(email) or m.get(\"org_slug\")" in src,
|
||||||
|
"shortfall credits exempt manual + org-backed, nothing else")
|
||||||
|
check('"source": member_source(email)' in src,
|
||||||
|
"the panel payload carries the source (so it can stop saying 'manual')")
|
||||||
|
|
||||||
|
print("6. the column is optional — existing rows carry NULL and still work")
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("UPDATE members SET source = NULL WHERE lower(email) = ?", (MMOYA,))
|
||||||
|
conn.commit(); conn.close()
|
||||||
|
m.MANUAL_MEMBERS = {"founder@example.org"} # the address leaves the list
|
||||||
|
check(m.member_source(MMOYA) == "oc",
|
||||||
|
"once mmoya leaves MANUAL_MEMBERS with no source set, they read oc — which is why the "
|
||||||
|
"source is set BEFORE the address is removed from the env")
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILS:
|
||||||
|
print(f"oc-incognito: {len(FAILS)} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("oc-incognito: OK — an explicit source wins, only manual is exempt, bad values fail safe")
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for app.main._payment_verdict (allowance payment assessment).
|
||||||
|
|
||||||
|
Self-contained and runnable:
|
||||||
|
|
||||||
|
* from the repo root: python3 tests/test_payment_verdict.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_payment_verdict.py
|
||||||
|
(the container has the app's own dependencies; the host usually does not)
|
||||||
|
|
||||||
|
Covers the FREQUENCY-AWARE decision:
|
||||||
|
- ACTIVE YEARLY whose coverage window includes the cycle -> paid (renew)
|
||||||
|
[the regression this file exists for]
|
||||||
|
- ACTIVE YEARLY whose year has lapsed -> not paid
|
||||||
|
- ACTIVE MONTHLY -> paid
|
||||||
|
- PROCESSING -> paid (paid-pending; never a reminder)
|
||||||
|
- ONETIME-only -> not paid (credit, not an allowance cycle)
|
||||||
|
- an ONETIME payment does NOT mask an unpaid monthly member
|
||||||
|
- ERROR MONTHLY with the last charge before the cycle -> not paid (mark-meyer's
|
||||||
|
exact order, asserted to keep his current, correct outcome)
|
||||||
|
- CANCELLED MONTHLY with an old charge -> not paid
|
||||||
|
|
||||||
|
Does NOT cover (deliberate): the OC network fetch, the members table / anchor-day
|
||||||
|
storage, email sending, the report/send modes, or deactivation. It tests the pure
|
||||||
|
decision function only. The yearly case is SYNTHETIC: the collective has no yearly
|
||||||
|
orders today, so this guards the branch without implying any member has one.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
# Locate the app package: explicit env, the deployed path, or the repo root.
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.main import _payment_verdict # noqa: E402
|
||||||
|
|
||||||
|
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=timezone.utc)
|
||||||
|
CYCLE = datetime(2026, 10, 26, 0, 0, tzinfo=timezone.utc) # mark-meyer join-day 26
|
||||||
|
|
||||||
|
|
||||||
|
def order(freq, status, last=None, next_=None):
|
||||||
|
return {"frequency": freq, "status": status,
|
||||||
|
"lastChargedAt": last, "nextChargeDate": next_}
|
||||||
|
|
||||||
|
|
||||||
|
# (name, orders, expected_paid, evidence_must_contain)
|
||||||
|
CASES = [
|
||||||
|
("active yearly covers this cycle (last charge 2026-09-26, next 2027-09-01)",
|
||||||
|
[order("YEARLY", "ACTIVE", "2026-09-26T18:00:00.000Z", "2027-09-01T00:00:00.000Z")],
|
||||||
|
True, "yearly"),
|
||||||
|
("active yearly whose year has lapsed",
|
||||||
|
[order("YEARLY", "ACTIVE", "2024-01-01T00:00:00.000Z", "2025-01-01T00:00:00.000Z")],
|
||||||
|
False, "before this cycle"),
|
||||||
|
("active monthly",
|
||||||
|
[order("MONTHLY", "ACTIVE", "2026-11-02T18:00:00.000Z", "2026-12-01T00:00:00.000Z")],
|
||||||
|
True, "live recurring contribution"),
|
||||||
|
("processing monthly is paid-pending",
|
||||||
|
[order("MONTHLY", "PROCESSING", "2026-09-16T19:03:08.000Z", "2026-11-01T00:00:00.000Z")],
|
||||||
|
True, "live recurring contribution"),
|
||||||
|
("onetime-only is not an allowance cycle",
|
||||||
|
[order("ONETIME", "PAID", "2026-11-01T00:00:00.000Z", None)],
|
||||||
|
False, "no recurring"),
|
||||||
|
("onetime does not mask an unpaid monthly",
|
||||||
|
[order("ONETIME", "PAID", "2026-11-02T00:00:00.000Z", None),
|
||||||
|
order("MONTHLY", "ERROR", "2026-09-26T18:05:00.000Z", "2026-11-06T00:00:00.000Z")],
|
||||||
|
False, "before this cycle"),
|
||||||
|
("mark-meyer's exact order: monthly ERROR, last charge 2026-09-26",
|
||||||
|
[order("MONTHLY", "ERROR", "2026-09-26T18:05:00.000Z", "2026-11-06T00:00:00.000Z")],
|
||||||
|
False, "last charge 2026-09-26 is before this cycle"),
|
||||||
|
("cancelled monthly with old charge",
|
||||||
|
[order("MONTHLY", "CANCELLED", "2026-08-01T11:05:08.000Z", None)],
|
||||||
|
False, "before this cycle"),
|
||||||
|
("monthly charged within the cycle (7-day slack)",
|
||||||
|
[order("MONTHLY", "ERROR", "2026-10-28T00:00:00.000Z", None)],
|
||||||
|
True, "within the current cycle"),
|
||||||
|
("no orders at all",
|
||||||
|
[],
|
||||||
|
False, "no recurring"),
|
||||||
|
]
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
for name, orders, expect_paid, expect_text in CASES:
|
||||||
|
paid, evidence = _payment_verdict(orders, CYCLE, now=NOW)
|
||||||
|
ok = (paid == expect_paid) and (expect_text in evidence)
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}\n"
|
||||||
|
f" paid={paid} (expected {expect_paid}) evidence={evidence!r}")
|
||||||
|
|
||||||
|
print(f"\n{len(CASES) - failures}/{len(CASES)} passed")
|
||||||
|
sys.exit(1 if failures else 0)
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for M5 (atomic held-credit grant) + M6 (Cloudron user
|
||||||
|
pagination) — audit 2026-11-05.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* from the repo root: python3 tests/test_portal_hardening.py
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_portal_hardening.py
|
||||||
|
|
||||||
|
Covered:
|
||||||
|
M5 — grant_held_credits
|
||||||
|
- matched holds (by email AND by slug) flip + credit in one transaction
|
||||||
|
- a re-run moves no money (held:<id> reference exists-check)
|
||||||
|
- a hold whose ledger row already exists is reconciled, never re-credited
|
||||||
|
M6 — cloudron_fetch_all_users (async) / _sync
|
||||||
|
- pages past the first: >100 users returned in full (the old code silently
|
||||||
|
truncated at 100)
|
||||||
|
- page-1 failure -> None / raise (callers keep failing loudly)
|
||||||
|
- later-page failure -> keep what was read
|
||||||
|
- the hard page cap holds even if the API never runs short
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="hardening-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
||||||
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
||||||
|
sys.path.insert(0, _cand)
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.main import ( # noqa: E402
|
||||||
|
cloudron_fetch_all_users, cloudron_fetch_all_users_sync, get_credit_balance,
|
||||||
|
get_db, grant_held_credits,
|
||||||
|
)
|
||||||
|
|
||||||
|
failures = 0
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = got == want
|
||||||
|
if not ok:
|
||||||
|
failures += 1
|
||||||
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
if not ok:
|
||||||
|
print(f" got {got!r}\n want {want!r}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- M5 ---------
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute("INSERT INTO members (email, key_token, slug, active) "
|
||||||
|
"VALUES ('newmember@example.com', '', 'newmember', 1)")
|
||||||
|
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('newmember', 'someone-else@example.com', 'W', 10.0, 'oc:newmember:or_1', 'held')")
|
||||||
|
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
|
||||||
|
"VALUES ('newmember', NULL, 'X', 5.0, 'oc:other:or_2', 'held')")
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
# Mixed-case email on purpose: the grant must normalize it (the balance
|
||||||
|
# UPDATE/SELECT join on the member row and silently miss otherwise).
|
||||||
|
granted = grant_held_credits(conn, "NewMember@Example.com", "newmember")
|
||||||
|
check("matched holds sum (including the non-member slug hold)", granted, 15.0)
|
||||||
|
check("balance credited", get_credit_balance("newmember@example.com"), 15.0)
|
||||||
|
statuses = dict(conn.execute("SELECT id, status FROM held_credits").fetchall())
|
||||||
|
check("both holds flipped in the same pass", set(statuses.values()), {"granted"})
|
||||||
|
refs = [r[0] for r in conn.execute("SELECT reference FROM credit_ledger ORDER BY id").fetchall()]
|
||||||
|
check("one ledger row per hold, held:<id> shape", refs, ["held:1", "held:2"])
|
||||||
|
|
||||||
|
granted2 = grant_held_credits(conn, "newmember@example.com", "newmember")
|
||||||
|
check("re-run grants nothing (reference exists-check)", granted2, 0.0)
|
||||||
|
refs = [r[0] for r in conn.execute("SELECT reference FROM credit_ledger ORDER BY id").fetchall()]
|
||||||
|
check("re-run wrote no extra ledger rows", refs, ["held:1", "held:2"])
|
||||||
|
check("re-run left the balance alone", get_credit_balance("newmember@example.com"), 15.0)
|
||||||
|
|
||||||
|
# Crash-recovery shape: a hold flipped but its ledger row lost… inverse — a
|
||||||
|
# ledger row that exists while the hold reads 'held' (a crash between the two
|
||||||
|
# commits of the OLD code) must reconcile the status and move no money.
|
||||||
|
conn.execute("UPDATE held_credits SET status='held', resolved_at=NULL WHERE id = 2")
|
||||||
|
conn.commit()
|
||||||
|
granted3 = grant_held_credits(conn, "newmember@example.com", "newmember")
|
||||||
|
check("already-credited hold reconciles without re-crediting", granted3, 0.0)
|
||||||
|
check("its status is reconciled to granted",
|
||||||
|
dict(conn.execute("SELECT id, status FROM held_credits").fetchall()), {1: "granted", 2: "granted"})
|
||||||
|
check("balance still 15 after the reconciliation pass",
|
||||||
|
get_credit_balance("newmember@example.com"), 15.0)
|
||||||
|
|
||||||
|
_conn2 = get_db() # separate handle to prove committed state, not in-transaction state
|
||||||
|
n = _conn2.execute("SELECT COUNT(*) FROM credit_ledger").fetchone()[0]
|
||||||
|
check("committed state equals in-call state", n, 2)
|
||||||
|
_conn2.close()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- M6 ---------
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, status_code, payload):
|
||||||
|
self.status_code = status_code
|
||||||
|
self._payload = payload
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAsyncClient:
|
||||||
|
def __init__(self, pages):
|
||||||
|
self.pages = list(pages) # one entry per expected page
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
async def get(self, url, params=None, headers=None):
|
||||||
|
self.calls.append(dict(params or {}))
|
||||||
|
if not self.pages:
|
||||||
|
return FakeResponse(200, {"users": []})
|
||||||
|
item = self.pages.pop(0)
|
||||||
|
if isinstance(item, int):
|
||||||
|
return FakeResponse(item, {})
|
||||||
|
return FakeResponse(200, {"users": item})
|
||||||
|
|
||||||
|
|
||||||
|
users_120 = [{"id": f"u{i}", "email": f"m{i}@example.com"} for i in range(120)]
|
||||||
|
page1, page2 = users_120[:100], users_120[100:]
|
||||||
|
|
||||||
|
fc = FakeAsyncClient([page1, page2])
|
||||||
|
got = asyncio.run(cloudron_fetch_all_users(fc))
|
||||||
|
check("110+ users: walked past the first page", len(got), 120)
|
||||||
|
check("per_page=100 on every page", {c.get("per_page") for c in fc.calls}, {100})
|
||||||
|
check("pages requested in order", [c.get("page") for c in fc.calls], [1, 2])
|
||||||
|
|
||||||
|
fc = FakeAsyncClient([500])
|
||||||
|
check("page-1 failure -> None (caller fails loudly)",
|
||||||
|
asyncio.run(cloudron_fetch_all_users(fc)), None)
|
||||||
|
|
||||||
|
fc = FakeAsyncClient([page1, 500, page2])
|
||||||
|
got = asyncio.run(cloudron_fetch_all_users(fc))
|
||||||
|
check("later-page failure keeps what was read", len(got), 100)
|
||||||
|
|
||||||
|
|
||||||
|
class EndlessFullPagesClient:
|
||||||
|
"""A fake API that never runs short — the hard cap must stop the walk."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.calls = 0
|
||||||
|
|
||||||
|
async def get(self, url, params=None, headers=None):
|
||||||
|
self.calls += 1
|
||||||
|
return FakeResponse(200, {"users": users_120[:100]})
|
||||||
|
|
||||||
|
|
||||||
|
fc = EndlessFullPagesClient()
|
||||||
|
got = asyncio.run(cloudron_fetch_all_users(fc))
|
||||||
|
check("hard cap: stops at 50 pages (5000 users)", (len(got), fc.calls), (5000, 50))
|
||||||
|
|
||||||
|
# --- sync walker (monkeypatch urllib at the call site's own module) ---------
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
_real_urlopen = urllib.request.urlopen
|
||||||
|
_seen = {"n": 0}
|
||||||
|
|
||||||
|
|
||||||
|
def fake_urlopen(req, timeout=None):
|
||||||
|
_seen["n"] += 1
|
||||||
|
if _seen["n"] == 1:
|
||||||
|
raise RuntimeError("page 1 simulated failure")
|
||||||
|
class R:
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
def read(self):
|
||||||
|
return b'{"users": []}'
|
||||||
|
return R()
|
||||||
|
|
||||||
|
|
||||||
|
urllib.request.urlopen = fake_urlopen
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
cloudron_fetch_all_users_sync()
|
||||||
|
check("sync walker: page-1 failure raises", False, True)
|
||||||
|
except RuntimeError:
|
||||||
|
check("sync walker: page-1 failure raises", True, True)
|
||||||
|
finally:
|
||||||
|
urllib.request.urlopen = _real_urlopen
|
||||||
|
|
||||||
|
_real_urlopen = urllib.request.urlopen
|
||||||
|
_state = {"pages": [users_120[:100], users_120[100:]], "urls": []}
|
||||||
|
|
||||||
|
|
||||||
|
def fake_urlopen2(req, timeout=None):
|
||||||
|
_state["urls"].append(req.full_url)
|
||||||
|
page = _state["pages"].pop(0) if _state["pages"] else []
|
||||||
|
import io
|
||||||
|
body = ('{"users": %s}' % __import__("json").dumps(page)).encode()
|
||||||
|
return io.BytesIO(body)
|
||||||
|
|
||||||
|
|
||||||
|
urllib.request.urlopen = fake_urlopen2
|
||||||
|
try:
|
||||||
|
got = cloudron_fetch_all_users_sync()
|
||||||
|
check("sync walker pages past the first page too", len(got), 120)
|
||||||
|
check("sync walker issued a page=2 request",
|
||||||
|
any("page=2" in u for u in _state["urls"]), True)
|
||||||
|
finally:
|
||||||
|
urllib.request.urlopen = _real_urlopen
|
||||||
|
|
||||||
|
# ------------------------------------------------------- M1: log redaction ---
|
||||||
|
# The webhook token and member emails must not survive into portal logs. The
|
||||||
|
# guard must FIRE: feed a record with both a token and an email and read back
|
||||||
|
# the formatted line.
|
||||||
|
import logging # noqa: E402
|
||||||
|
|
||||||
|
from app.main import _EMAIL_RE, _RedactWebhookPath # noqa: E402
|
||||||
|
|
||||||
|
flt = _RedactWebhookPath()
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1,
|
||||||
|
"Credit pack: +%s for %s (balance %s)", (20.0, "member@example.org", 30.0), None)
|
||||||
|
flt.filter(rec)
|
||||||
|
check("email in %-args redacted", rec.getMessage(), "Credit pack: +20.0 for <email> (balance 30.0)")
|
||||||
|
check("argument tuple preserved", isinstance(rec.args, tuple), True)
|
||||||
|
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1,
|
||||||
|
"Provisioned member hidden@example.org ok", (), None)
|
||||||
|
flt.filter(rec)
|
||||||
|
check("email embedded via f-string (msg) redacted", rec.getMessage(), "Provisioned member <email> ok")
|
||||||
|
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1, "Loomio invites: %s",
|
||||||
|
(["a@example.org", "b@example.org"],), None)
|
||||||
|
flt.filter(rec)
|
||||||
|
check("list args redacted, list type kept",
|
||||||
|
(rec.getMessage(), type(rec.args[0]).__name__), ("Loomio invites: ['<email>', '<email>']", "list"))
|
||||||
|
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1,
|
||||||
|
'POST /webhook/opencollective/sekret123?x=1 HTTP/1.1', (), None)
|
||||||
|
filt_result = flt.filter(rec)
|
||||||
|
check("webhook token redacted, filter returns True",
|
||||||
|
(rec.getMessage(), filt_result), ("POST /webhook/opencollective/<redacted>?x=1 HTTP/1.1", True))
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1,
|
||||||
|
"Credit pack for member@example.org via /webhook/opencollective/tok9", (), None)
|
||||||
|
flt.filter(rec)
|
||||||
|
check("token and email redacted in one line",
|
||||||
|
"<email>" in rec.getMessage() and "<redacted>" in rec.getMessage()
|
||||||
|
and "member@example.org" not in rec.getMessage() and "tok9" not in rec.getMessage(), True)
|
||||||
|
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1, "Matrix invite for @someuser:inference.coop", (), None)
|
||||||
|
flt.filter(rec)
|
||||||
|
check("MXIDs are not emails and stay readable",
|
||||||
|
rec.getMessage(), "Matrix invite for @someuser:inference.coop")
|
||||||
|
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1, "counter=%d", (7,), None)
|
||||||
|
flt.filter(rec)
|
||||||
|
check("non-string args untouched", rec.getMessage(), "counter=7")
|
||||||
|
|
||||||
|
rec = logging.LogRecord("t", logging.INFO, "p", 1, "boom", (), None)
|
||||||
|
rec.exc_text = "ValueError: No member account for lost@example.org"
|
||||||
|
flt.filter(rec)
|
||||||
|
check("already-formatted exception text redacted",
|
||||||
|
rec.exc_text, "ValueError: No member account for <email>")
|
||||||
|
|
||||||
|
check("regex matches a real-shaped address",
|
||||||
|
bool(_EMAIL_RE.search("contact info@a.b-stuff.coop today")), True)
|
||||||
|
|
||||||
|
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
|
||||||
|
sys.exit(1 if failures else 0)
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: a first-time contributor's order must not be dropped in silence.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-13 21:59:43 OC delivered `order.processed` for a live $5/month
|
||||||
|
membership (Conor W, conor.canaday@gmail.com, order or_eU8gRkrPCvFsaYHrgiCfz).
|
||||||
|
The portal answered 200 and did nothing: the membership branch resolves the
|
||||||
|
payer with
|
||||||
|
|
||||||
|
members = await fetch_members()
|
||||||
|
member = next((m for m in members if m["slug"] == slug), None)
|
||||||
|
|
||||||
|
and for a FIRST-TIME contributor the payer's OC account is not in the
|
||||||
|
collective's members list yet — OC reports them as guest-…/incognito-…. So
|
||||||
|
`member` was None, the whole branch fell through, and because the payload had
|
||||||
|
arrived successfully there was no error to record either. No account, no
|
||||||
|
welcome email, no credit, no log line. The sweep's unmapped-backers check
|
||||||
|
found it hours later, which is the wrong place to find it.
|
||||||
|
|
||||||
|
The fix resolves the payer from the order's account slug (`Individual.email`,
|
||||||
|
which OC exposes for an ordinary guest checkout), and when even that yields no
|
||||||
|
email it says so at ERROR level. A payment we cannot attribute is news, never
|
||||||
|
a shrug.
|
||||||
|
|
||||||
|
The "silent no-op" shape is the actual defect here: an `if` with no `else` on a
|
||||||
|
money path, where the absence of an action leaves no trace.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "payer-fixture.db")
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.OC_PERSONAL_TOKEN = "test-token"
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
def check(cond, msg):
|
||||||
|
print((" ok " if cond else " FAIL ") + msg)
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(msg)
|
||||||
|
|
||||||
|
REAL_POST = m._oc_graphql_post
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
"""Mirror httpx.Response: the REAL _oc_graphql_post returns a response, not
|
||||||
|
parsed JSON. An earlier stub returned a dict, the test passed, and the first
|
||||||
|
live call died with 'Response object has no attribute get' — a stub that does
|
||||||
|
not match the real return shape certifies nothing."""
|
||||||
|
def __init__(self, payload):
|
||||||
|
self._payload = payload
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
LAST_HEADERS = {}
|
||||||
|
|
||||||
|
|
||||||
|
def fake_post(payload):
|
||||||
|
"""Stand in for OC's GraphQL endpoint (the response wrapper, not the JSON)."""
|
||||||
|
async def _post(client, json_body, headers=None, attempts=2):
|
||||||
|
LAST_HEADERS.clear()
|
||||||
|
LAST_HEADERS.update(headers or {})
|
||||||
|
return FakeResponse(payload)
|
||||||
|
return _post
|
||||||
|
|
||||||
|
|
||||||
|
print("1. an ordinary guest checkout resolves to the payer's email")
|
||||||
|
m._oc_graphql_post = fake_post({"data": {"account": {
|
||||||
|
"__typename": "Individual", "id": "acc_x", "name": "Conor W",
|
||||||
|
"slug": "guest-71e9d110", "email": "Conor.Canaday@Gmail.com", "isIncognito": False}}})
|
||||||
|
acct = asyncio.run(m.fetch_account_by_slug("guest-71e9d110"))
|
||||||
|
check(acct and acct["email"] == "conor.canaday@gmail.com",
|
||||||
|
f"the email is returned and normalised (got {acct and acct.get('email')!r})")
|
||||||
|
check(acct and acct["name"] == "Conor W", "the name comes back too, for the welcome email")
|
||||||
|
check(LAST_HEADERS.get("Personal-Token") == "test-token",
|
||||||
|
"the lookup AUTHENTICATES: without the personal token OC answers the unauthenticated view and hides every email "
|
||||||
|
f"(headers sent: {sorted(LAST_HEADERS)})")
|
||||||
|
|
||||||
|
print("2. an incognito profile yields NO email — and says so rather than guessing")
|
||||||
|
m._oc_graphql_post = fake_post({"data": {"account": {
|
||||||
|
"__typename": "Individual", "id": "acc_y", "name": "Incognito",
|
||||||
|
"slug": "incognito-5ad60182", "email": None, "isIncognito": True}}})
|
||||||
|
acct = asyncio.run(m.fetch_account_by_slug("incognito-5ad60182"))
|
||||||
|
check(acct is not None and acct.get("email") is None,
|
||||||
|
"incognito: the account is returned, the email is None (a slug is not an address)")
|
||||||
|
|
||||||
|
print("3. failures and edge cases never raise — the caller must be able to report")
|
||||||
|
m._oc_graphql_post = fake_post({"data": {"account": None}})
|
||||||
|
check(asyncio.run(m.fetch_account_by_slug("guest-nope")) is None,
|
||||||
|
"an account OC does not know returns None")
|
||||||
|
m._oc_graphql_post = fake_post({})
|
||||||
|
check(asyncio.run(m.fetch_account_by_slug("guest-nope")) is None,
|
||||||
|
"an empty payload returns None")
|
||||||
|
|
||||||
|
def boom(client, json_body, headers=None, attempts=2):
|
||||||
|
raise RuntimeError("OC read timed out")
|
||||||
|
m._oc_graphql_post = boom
|
||||||
|
check(asyncio.run(m.fetch_account_by_slug("guest-x")) is None,
|
||||||
|
"a failing lookup returns None instead of dying mid-webhook")
|
||||||
|
check(asyncio.run(m.fetch_account_by_slug("")) is None, "an empty slug is not looked up")
|
||||||
|
m.OC_PERSONAL_TOKEN = ""
|
||||||
|
check(asyncio.run(m.fetch_account_by_slug("guest-x")) is None,
|
||||||
|
"with no OC token configured there is no lookup to make")
|
||||||
|
m.OC_PERSONAL_TOKEN = "test-token"
|
||||||
|
|
||||||
|
print("4. the webhook branch: the fix is present, and its silent-fallthrough shape is gone")
|
||||||
|
src = (ROOT / "app" / "main.py").read_text()
|
||||||
|
branch = src[src.index('if "membership" in verified_tier.lower()'):]
|
||||||
|
branch = branch[:branch.index("elif slug and first_payment")]
|
||||||
|
check("fetch_account_by_slug(slug)" in branch,
|
||||||
|
"the branch resolves an unknown payer by account email")
|
||||||
|
check("logger.error(" in branch and "NOBODY was provisioned or credited" in branch,
|
||||||
|
"an unresolvable payer is logged at ERROR — not swallowed")
|
||||||
|
check(branch.count("if member:") == 1 and "logger.warning(" in branch,
|
||||||
|
"a resolved-by-email payer is announced in the log")
|
||||||
|
|
||||||
|
m._oc_graphql_post = REAL_POST
|
||||||
|
print()
|
||||||
|
if FAILS:
|
||||||
|
print(f"resolve payer: {len(FAILS)} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("resolve payer: OK — first-time payers resolve, unresolvable ones are loud")
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the service-invite sync (per-room invites + frequent tick).
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
A new member got a Loomio account and a Matrix account but could see NOTHING:
|
||||||
|
no forum group, no Space. Two separate defects produced that, and a third
|
||||||
|
made it take hours.
|
||||||
|
|
||||||
|
1. PER-ROOM GATE (the visibility bug). sync_matrix_space() gated each member
|
||||||
|
on the SPACE's membership: anyone already joined/invited to the Space was
|
||||||
|
skipped for EVERY room. So a member whose invite pass was interrupted, or
|
||||||
|
who predates a room added to MATRIX_INVITE_ROOMS later, never received
|
||||||
|
that room's invite — and a restricted child room is invisible until you
|
||||||
|
are invited to it.
|
||||||
|
2. RATE LIMITS ENDED NOTHING. A 429 slept for retry_after_ms (minutes) inside
|
||||||
|
the pass, so a scheduled run could outlive its own tick. A rate limit must
|
||||||
|
END the pass; the next run resumes (every invite is idempotent).
|
||||||
|
3. THE DEDUPE RECORD DRIFTED. A member sitting in the Loomio group with no
|
||||||
|
members.loomio_invited_at stamp (added by an earlier sync generation, or
|
||||||
|
by hand) reads as "never invited" — the guard is only as good as the rows
|
||||||
|
it happens to have. The sync now heals the record from the live roster.
|
||||||
|
4. NOTHING WATCHED ACTIVATION. Provisioning skips an unactivated account by
|
||||||
|
design, and activation happens later with nobody watching, so the 3x/day
|
||||||
|
sweep was the pickup. /admin/service-sync is the frequent tick that closes
|
||||||
|
that window; it must be a no-op (one SELECT) in the steady state.
|
||||||
|
|
||||||
|
Network is STUBBED throughout; assertions are on what we SENT and on our own
|
||||||
|
recorded state.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_service_invites.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["MATRIX_BOT_TOKEN"] = "test-bot-token"
|
||||||
|
os.environ["MATRIX_SPACE_ID"] = "!space:inference.coop"
|
||||||
|
os.environ["MATRIX_HOMESERVER"] = "https://matrix.inference.coop"
|
||||||
|
os.environ["MATRIX_INVITE_ROOMS"] = "!space:inference.coop,!general:inference.coop,!design:inference.coop"
|
||||||
|
os.environ["LOOMIO_API_KEY"] = "test-user-key"
|
||||||
|
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
|
||||||
|
os.environ["LOOMIO_GROUP_ID"] = "1"
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
# The app module and this test share the SAME httpx module object, so stubbing
|
||||||
|
# the client below replaces it process-wide. Keep a handle on the real class for
|
||||||
|
# the ASGI call at the end.
|
||||||
|
REAL_ASYNC_CLIENT = httpx.AsyncClient
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.MATRIX_BOT_TOKEN = "test-bot-token"
|
||||||
|
m.MATRIX_SPACE_ID = "!space:inference.coop"
|
||||||
|
m.MATRIX_HOMESERVER = "https://matrix.inference.coop"
|
||||||
|
m.MATRIX_INVITE_ROOMS = [
|
||||||
|
"!space:inference.coop", "!general:inference.coop", "!design:inference.coop"
|
||||||
|
]
|
||||||
|
m.MATRIX_EXTRA_ROOMS = []
|
||||||
|
m.LOOMIO_ALWAYS_KEEP = []
|
||||||
|
m.ADMIN_TOKEN = "test-admin-token"
|
||||||
|
m.ADMIN_TOKEN_LEGACY = ""
|
||||||
|
m.WEBHOOK_TOKEN = ""
|
||||||
|
|
||||||
|
ROOMS = ["!space:inference.coop", "!general:inference.coop", "!design:inference.coop"]
|
||||||
|
USERS = {"a@x.org": "amember", "b@x.org": "bmember", "c@x.org": "cmember"}
|
||||||
|
|
||||||
|
ROOM_JOINED = {} # room -> set(mxid)
|
||||||
|
ROOM_INVITED = {} # room -> set(mxid)
|
||||||
|
UNREADABLE = set() # rooms whose joined_members 500s
|
||||||
|
invites_sent = [] # (room, mxid)
|
||||||
|
INVITE_429_FOR = set() # mxids whose invite comes back 429
|
||||||
|
INVITE_TIMEOUT_FOR = set() # mxids whose invite POST raises httpx.ReadTimeout
|
||||||
|
POSTS = [] # Loomio POST payloads
|
||||||
|
|
||||||
|
ROSTER = {} # Loomio roster: email -> membership id
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResp:
|
||||||
|
def __init__(self, status=200, payload=None, text=None):
|
||||||
|
self.status_code = status
|
||||||
|
self._payload = payload or {}
|
||||||
|
self.text = text if text is not None else str(payload or {})
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
if self.status_code >= 400:
|
||||||
|
raise RuntimeError(f"HTTP {self.status_code}")
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, url, headers=None, params=None):
|
||||||
|
if "/api/v1/users" in url:
|
||||||
|
return FakeResp(200, {"users": [
|
||||||
|
{"email": e, "username": u, "inviteAccepted": True}
|
||||||
|
for e, u in USERS.items()
|
||||||
|
]})
|
||||||
|
for room in ROOMS:
|
||||||
|
if f"/rooms/{room}/joined_members" in url:
|
||||||
|
if room in UNREADABLE:
|
||||||
|
return FakeResp(500, {"error": "boom"})
|
||||||
|
return FakeResp(200, {"joined": {m: {} for m in ROOM_JOINED.get(room, set())}})
|
||||||
|
if f"/rooms/{room}/members" in url:
|
||||||
|
return FakeResp(200, {"chunk": [
|
||||||
|
{"state_key": mx} for mx in ROOM_INVITED.get(room, set())
|
||||||
|
]})
|
||||||
|
if "/api/b3/memberships" in url:
|
||||||
|
rows = [{"id": i, "user_email": e} for e, i in ROSTER.items()]
|
||||||
|
offset = (params or {}).get("offset", 0)
|
||||||
|
limit = (params or {}).get("limit", 50)
|
||||||
|
return FakeResp(200, {"memberships": rows[offset:offset + limit]})
|
||||||
|
return FakeResp(404, {})
|
||||||
|
|
||||||
|
async def post(self, url, headers=None, json=None):
|
||||||
|
if "/invite" in url:
|
||||||
|
mxid = (json or {}).get("user_id")
|
||||||
|
if mxid in INVITE_TIMEOUT_FOR:
|
||||||
|
raise httpx.ReadTimeout("timed out")
|
||||||
|
if mxid in INVITE_429_FOR:
|
||||||
|
return FakeResp(429, {"retry_after_ms": 300000},
|
||||||
|
text='{"errcode":"M_LIMIT_EXCEEDED"}')
|
||||||
|
for room in ROOMS:
|
||||||
|
if f"/rooms/{room}/invite" in url:
|
||||||
|
invites_sent.append((room, mxid))
|
||||||
|
ROOM_INVITED.setdefault(room, set()).add(mxid)
|
||||||
|
return FakeResp(200, {})
|
||||||
|
return FakeResp(200, {})
|
||||||
|
if "/api/b2/memberships" in url:
|
||||||
|
POSTS.append(json or {})
|
||||||
|
return FakeResp(200, {"added_emails": (json or {}).get("emails", [])})
|
||||||
|
return FakeResp(200, {})
|
||||||
|
|
||||||
|
async def put(self, *a, **k):
|
||||||
|
return FakeResp(200, {})
|
||||||
|
|
||||||
|
async def delete(self, *a, **k):
|
||||||
|
return FakeResp(200, {})
|
||||||
|
|
||||||
|
async def patch(self, *a, **k):
|
||||||
|
return FakeResp(200, {})
|
||||||
|
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, ok))
|
||||||
|
|
||||||
|
|
||||||
|
def reset():
|
||||||
|
global invites_sent
|
||||||
|
invites_sent = []
|
||||||
|
POSTS.clear()
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
global ROOM_JOINED, ROOM_INVITED, UNREADABLE, INVITE_429_FOR, ROSTER
|
||||||
|
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
for email in USERS:
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (email,))
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active, account_type) VALUES (?, 1, 'guest')",
|
||||||
|
("guest@x.org",))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = FakeClient
|
||||||
|
|
||||||
|
async def _active():
|
||||||
|
return list(USERS.keys())
|
||||||
|
m.get_active_member_emails = _active
|
||||||
|
|
||||||
|
# --- 1. PER-ROOM GATE -------------------------------------------------
|
||||||
|
# a@ is already in every room. b@ has the Space + General but is MISSING
|
||||||
|
# Design — the exact state an interrupted pass leaves behind.
|
||||||
|
ROOM_JOINED = {"!space:inference.coop": {"@amember:inference.coop"},
|
||||||
|
"!general:inference.coop": {"@amember:inference.coop"},
|
||||||
|
"!design:inference.coop": {"@amember:inference.coop"}}
|
||||||
|
ROOM_INVITED = {"!space:inference.coop": {"@bmember:inference.coop"},
|
||||||
|
"!general:inference.coop": {"@bmember:inference.coop"},
|
||||||
|
"!design:inference.coop": set()}
|
||||||
|
USERS["c@x.org"] = "cmember"
|
||||||
|
ROOM_JOINED["!space:inference.coop"].add("@cmember:inference.coop")
|
||||||
|
ROOM_INVITED["!space:inference.coop"].add("@cmember:inference.coop")
|
||||||
|
ROOM_JOINED["!general:inference.coop"].add("@cmember:inference.coop")
|
||||||
|
ROOM_INVITED["!general:inference.coop"].add("@cmember:inference.coop")
|
||||||
|
ROOM_JOINED["!design:inference.coop"].add("@cmember:inference.coop")
|
||||||
|
ROOM_INVITED["!design:inference.coop"].add("@cmember:inference.coop")
|
||||||
|
reset()
|
||||||
|
r = await m.sync_matrix_space()
|
||||||
|
check("per-room: only the MISSING room is invited, by room id",
|
||||||
|
invites_sent == [("!design:inference.coop", "@bmember:inference.coop")])
|
||||||
|
check("per-room: an account already in every room is not re-invited",
|
||||||
|
not any(mx == "@amember:inference.coop" for _, mx in invites_sent))
|
||||||
|
check("per-room: two members can be pending on different rooms",
|
||||||
|
not any(mx == "@cmember:inference.coop" for _, mx in invites_sent))
|
||||||
|
check("return shape: the result carries invited + rate_limited",
|
||||||
|
set(r) == {"invited", "rate_limited"} and r["rate_limited"] is False)
|
||||||
|
|
||||||
|
# --- 2. IDEMPOTENCE: a second pass sends nothing ----------------------
|
||||||
|
reset()
|
||||||
|
await m.sync_matrix_space()
|
||||||
|
check("idempotent: a second pass sends no invites", invites_sent == [])
|
||||||
|
|
||||||
|
# --- 3. RATE LIMIT ENDS THE PASS (no sleeping inside a scheduled tick) -
|
||||||
|
# d@ is missing all three rooms; the FIRST invite 429s.
|
||||||
|
USERS["d@x.org"] = "dmember"
|
||||||
|
m.get_db().close()
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES ('d@x.org', 1)")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
async def active_with_d():
|
||||||
|
return ["d@x.org", "a@x.org"]
|
||||||
|
m.get_active_member_emails = active_with_d
|
||||||
|
INVITE_429_FOR = {"@dmember:inference.coop"}
|
||||||
|
reset()
|
||||||
|
r = await m.sync_matrix_space()
|
||||||
|
check("rate limit: the pass reports it was rate limited", r["rate_limited"] is True)
|
||||||
|
check("rate limit: it does NOT retry in a loop inside the pass",
|
||||||
|
invites_sent == [])
|
||||||
|
INVITE_429_FOR = set()
|
||||||
|
m.get_active_member_emails = _active
|
||||||
|
|
||||||
|
# A resumed pass DOES send the invites the limited one could not.
|
||||||
|
reset()
|
||||||
|
r = await m.sync_matrix_space()
|
||||||
|
check("rate limit: the next pass resumes and invites the missed rooms",
|
||||||
|
len(invites_sent) == 3 and {room for room, _ in invites_sent} == set(ROOMS))
|
||||||
|
|
||||||
|
# --- 4. A ROOM WE CANNOT READ IS LEFT ALONE ---------------------------
|
||||||
|
# e@ is only missing Design, and Design's membership cannot be read.
|
||||||
|
USERS["e@x.org"] = "emember"
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES ('e@x.org', 1)")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
async def active_with_e():
|
||||||
|
return ["e@x.org"]
|
||||||
|
m.get_active_member_emails = active_with_e
|
||||||
|
ROOM_JOINED = {r_: set() for r_ in ROOMS}
|
||||||
|
ROOM_INVITED = {"!space:inference.coop": {"@emember:inference.coop"},
|
||||||
|
"!general:inference.coop": {"@emember:inference.coop"},
|
||||||
|
"!design:inference.coop": set()}
|
||||||
|
UNREADABLE = {"!design:inference.coop"}
|
||||||
|
reset()
|
||||||
|
await m.sync_matrix_space()
|
||||||
|
check("unreadable room: never invited into a room whose members we could not read",
|
||||||
|
invites_sent == [])
|
||||||
|
UNREADABLE = set()
|
||||||
|
m.get_active_member_emails = _active
|
||||||
|
|
||||||
|
# --- 5. LOOMIO RECORD SELF-HEAL --------------------------------------
|
||||||
|
# b@ is sitting in the group with NO stamp: the guard would call them
|
||||||
|
# "never invited". The sync must heal the record from the roster, and must
|
||||||
|
# not send their address anywhere while doing it.
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("UPDATE members SET loomio_invited_at = NULL")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
ROSTER = {"b@x.org": 55}
|
||||||
|
reset()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
sent = sorted((POSTS[0].get("emails") if POSTS else []) or [])
|
||||||
|
check("heal: a present member with no stamp is stamped as invited",
|
||||||
|
m.get_loomio_invited_at("b@x.org") is not None)
|
||||||
|
check("heal: healing never re-sends a member already in the group",
|
||||||
|
"b@x.org" not in sent)
|
||||||
|
check("heal: an unstamped member who is NOT present is still invited",
|
||||||
|
sent == ["a@x.org", "c@x.org", "d@x.org", "e@x.org"])
|
||||||
|
|
||||||
|
# --- 6. THE FREQUENT TICK'S WAKE-UP CONDITION -------------------------
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("UPDATE members SET loomio_invited_at = NULL WHERE email = 'e@x.org'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
pending = m._service_sync_pending()
|
||||||
|
check("pending: a member still awaiting their invite is counted", pending == ["e@x.org"])
|
||||||
|
check("pending: an invited member is NOT counted", "a@x.org" not in pending)
|
||||||
|
check("pending: guests are never counted", "guest@x.org" not in pending)
|
||||||
|
m.mark_loomio_invited("e@x.org")
|
||||||
|
check("pending: empty once every member is stamped", m._service_sync_pending() == [])
|
||||||
|
|
||||||
|
# --- 7. ONE MEMBER'S TRANSPORT TIMEOUT MUST NOT KILL THE PASS ---------
|
||||||
|
# A ReadTimeout on ONE invite used to abort the whole sync: every member
|
||||||
|
# after the timed-out one silently got nothing, and the log line carried an
|
||||||
|
# empty message. Two members need invites; the FIRST times out.
|
||||||
|
global INVITE_TIMEOUT_FOR
|
||||||
|
conn = m.get_db()
|
||||||
|
for email, stamp in (("t@x.org", "2026-01-01 00:00:00"), ("u@x.org", "2026-01-01 00:00:00")):
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_invited_at) VALUES (?, 1, ?)",
|
||||||
|
(email, stamp))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
USERS["t@x.org"] = "tmember"
|
||||||
|
USERS["u@x.org"] = "umember"
|
||||||
|
|
||||||
|
async def active_with_tu():
|
||||||
|
return ["t@x.org", "u@x.org"]
|
||||||
|
m.get_active_member_emails = active_with_tu
|
||||||
|
ROOM_JOINED = {r_: set() for r_ in ROOMS}
|
||||||
|
ROOM_INVITED = {r_: set() for r_ in ROOMS}
|
||||||
|
INVITE_TIMEOUT_FOR = {"@tmember:inference.coop"}
|
||||||
|
reset()
|
||||||
|
r = await m.sync_matrix_space()
|
||||||
|
check("timeout: a transport timeout does not raise out of the pass", isinstance(r, dict))
|
||||||
|
check("timeout: the member AFTER the timed-out one is still invited",
|
||||||
|
{room for room, _ in invites_sent} == set(ROOMS)
|
||||||
|
and all(mx == "@umember:inference.coop" for _, mx in invites_sent))
|
||||||
|
check("timeout: the timed-out member is not counted as invited", r["invited"] == 1)
|
||||||
|
|
||||||
|
# The next pass retries the timed-out member (invites are idempotent).
|
||||||
|
INVITE_TIMEOUT_FOR = set()
|
||||||
|
reset()
|
||||||
|
await m.sync_matrix_space()
|
||||||
|
check("timeout: the next pass sends the timed-out member's invites",
|
||||||
|
len(invites_sent) == 3 and all(mx == "@tmember:inference.coop" for _, mx in invites_sent))
|
||||||
|
|
||||||
|
# Clean up so the endpoint checks see a steady state.
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("DELETE FROM members WHERE email IN ('t@x.org', 'u@x.org')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
INVITE_TIMEOUT_FOR = set()
|
||||||
|
m.get_active_member_emails = _active
|
||||||
|
ROOM_JOINED = {r_: set() for r_ in ROOMS}
|
||||||
|
ROOM_INVITED = {r_: set() for r_ in ROOMS}
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
# --- 7. THE ENDPOINT (real ASGI call, so the wiring is exercised) ----------
|
||||||
|
|
||||||
|
|
||||||
|
async def endpoint_checks():
|
||||||
|
transport = httpx.ASGITransport(app=m.app)
|
||||||
|
|
||||||
|
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
|
||||||
|
r = await c.post("/admin/service-sync")
|
||||||
|
check(f"endpoint: rejects a caller with no admin token (got {r.status_code})",
|
||||||
|
r.status_code == 403)
|
||||||
|
r = await c.post("/admin/service-sync", headers={"X-Admin-Token": "wrong"})
|
||||||
|
check(f"endpoint: rejects a wrong admin token (got {r.status_code})",
|
||||||
|
r.status_code == 403)
|
||||||
|
r = await c.post("/admin/service-sync", headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
check(f"endpoint: accepts the admin token (got {r.status_code})", r.status_code == 200)
|
||||||
|
body = r.json()
|
||||||
|
check(f"endpoint: is IDLE (one SELECT) when nobody is awaiting an invite (got {body})",
|
||||||
|
body.get("status") == "idle")
|
||||||
|
# Make one member await an invite again and prove the tick RUNS.
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("UPDATE members SET loomio_invited_at = NULL WHERE email = 'a@x.org'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
r = await c.post("/admin/service-sync", headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
body = r.json()
|
||||||
|
check(f"endpoint: RUNS while a member is awaiting invites (got {body})",
|
||||||
|
body.get("status") == "ran" and body.get("pending") == 1)
|
||||||
|
check(f"endpoint: runs BOTH syncs (got {body})",
|
||||||
|
body.get("loomio") == "ok" and "matrix" in body)
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(endpoint_checks())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import asyncio, os, sys, tempfile
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "settle.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
def seed():
|
||||||
|
conn = m.get_db()
|
||||||
|
for email, slug, active, credits in (
|
||||||
|
("active@example.org", "active-slug", 1, 0.0),
|
||||||
|
("inactive@example.org", "inactive-slug", 0, 0.0),
|
||||||
|
):
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance) VALUES (?,?,?,?)",
|
||||||
|
(email, slug, active, credits))
|
||||||
|
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
|
||||||
|
("active-slug", "active@example.org", "A", 10.0, "oc:active-slug:xyz"))
|
||||||
|
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
|
||||||
|
("inactive-slug", "inactive@example.org", "I", 5.0, "oc:inactive-slug:xyz"))
|
||||||
|
conn.commit(); conn.close()
|
||||||
|
|
||||||
|
def credits(email):
|
||||||
|
conn = m.get_db(); v = conn.execute("SELECT credit_balance FROM members WHERE email=?", (email,)).fetchone()[0]; conn.close(); return v
|
||||||
|
|
||||||
|
seed()
|
||||||
|
r1 = asyncio.run(m.settle_held_credits(send=False))
|
||||||
|
print(" run1:", r1["held"], "held |", len(r1["granted"]), "granted |", len(r1["unresolved"]), "unresolved")
|
||||||
|
assert credits("active@example.org") == 10.0, "active member's hold must be credited"
|
||||||
|
assert credits("inactive@example.org") == 0.0, "inactive member must NOT be credited"
|
||||||
|
assert len(r1["granted"]) == 1 and len(r1["unresolved"]) == 1
|
||||||
|
r2 = asyncio.run(m.settle_held_credits(send=False))
|
||||||
|
assert credits("active@example.org") == 10.0, "re-run must not double-apply"
|
||||||
|
assert len(r2["granted"]) == 0, "second run grants nothing"
|
||||||
|
print("SETTLE HELD CREDITS OK: grants to active, holds for inactive, idempotent")
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the spend-consistency check (portal aggregate vs LiteLLM's API).
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-05 the portal's aggregation of all-time spend failed SOFT: its copy of
|
||||||
|
the gateway's LiteLLM DB credential had gone stale, so the query returned nothing,
|
||||||
|
every surface showed $0, and nothing looked wrong — the portal WAS the thing that
|
||||||
|
was wrong. The guard ran as a daily script on the bot's host. It now runs in the
|
||||||
|
portal's sweep.
|
||||||
|
|
||||||
|
The first TWO live runs also taught the shape of the comparison, and both lessons
|
||||||
|
are pinned here:
|
||||||
|
|
||||||
|
* window. LiteLLM's per-day view reaches back a fixed number of days (31 on
|
||||||
|
2026-11-13) while our table holds everything, so comparing our ALL-TIME figure
|
||||||
|
against it reported $107.63 of "drift" that was only the missing window. Compare
|
||||||
|
the days BOTH sides cover.
|
||||||
|
* like-for-like source. `/global/spend/keys` reports each key's spend over the
|
||||||
|
key's own budget cycle (`total_spend` — and reading `spend` returned $0 for all
|
||||||
|
306 keys), so it is NOT an all-time figure. The per-day teams view is comparable,
|
||||||
|
and comparing day by day localises drift instead of hiding it in a sum.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_spend_check.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.ADMIN_TOKEN = "test-admin-token"
|
||||||
|
m.ADMIN_TOKEN_LEGACY = ""
|
||||||
|
m.LITELLM_MASTER_KEY = "test-master-key" # the parser test calls the real function
|
||||||
|
|
||||||
|
SENT = []
|
||||||
|
|
||||||
|
# main() replaces the module attribute with a stub; keep the REAL implementation so
|
||||||
|
# the parser itself can be exercised.
|
||||||
|
REAL_API_DAILY_SPEND = m.litellm_api_daily_spend
|
||||||
|
|
||||||
|
|
||||||
|
def fake_send(to, subject, body, *a, **k):
|
||||||
|
SENT.append({"to": to, "subject": subject, "body": body})
|
||||||
|
|
||||||
|
|
||||||
|
# --- stubs ----------------------------------------------------------------- #
|
||||||
|
DAYS = {"2026-11-10": 10.0, "2026-11-11": 20.0, "2026-11-12": 30.0}
|
||||||
|
API_DAYS = dict(DAYS)
|
||||||
|
PORTAL_DAYS = dict(DAYS)
|
||||||
|
PORTAL_ROWS = 1000
|
||||||
|
FAIL_PORTAL = False
|
||||||
|
FAIL_API = False
|
||||||
|
|
||||||
|
|
||||||
|
def fake_portal_days():
|
||||||
|
if FAIL_PORTAL:
|
||||||
|
raise RuntimeError("psycopg2: connection refused")
|
||||||
|
return dict(PORTAL_DAYS), round(sum(PORTAL_DAYS.values()), 6), PORTAL_ROWS
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_api_days():
|
||||||
|
if FAIL_API:
|
||||||
|
raise RuntimeError("LiteLLM spend API: HTTP 401")
|
||||||
|
return dict(API_DAYS)
|
||||||
|
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, bool(ok)))
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
global FAIL_PORTAL, FAIL_API, PORTAL_DAYS, PORTAL_ROWS, API_DAYS
|
||||||
|
m.litellm_spend_by_day = fake_portal_days
|
||||||
|
m.litellm_api_daily_spend = fake_api_days
|
||||||
|
m.send_email = fake_send
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
|
||||||
|
def marker():
|
||||||
|
conn = m.get_db()
|
||||||
|
row = conn.execute("SELECT value FROM portal_state WHERE key = ?",
|
||||||
|
(m.SPEND_CHECK_MARKER,)).fetchone()
|
||||||
|
conn.close()
|
||||||
|
return row[0] if row else None
|
||||||
|
|
||||||
|
def reset():
|
||||||
|
global PORTAL_DAYS, PORTAL_ROWS, API_DAYS
|
||||||
|
PORTAL_DAYS, PORTAL_ROWS, API_DAYS = dict(DAYS), 1000, dict(DAYS)
|
||||||
|
|
||||||
|
# --- agreement over the shared window: silent ---
|
||||||
|
reset()
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"agreement is ok (got {r.get('status')})", r.get("status") == "ok")
|
||||||
|
check(f"agreement reports the shared window (got {r})",
|
||||||
|
r.get("window") == "2026-11-10..2026-11-12" and r.get("days_compared") == 3
|
||||||
|
and r.get("portal_window") == 60.0 and r.get("api_window") == 60.0)
|
||||||
|
check(f"agreement sends NO email (got {len(SENT)})", len(SENT) == 0)
|
||||||
|
check(f"agreement clears the marker (got {marker()!r})", not marker())
|
||||||
|
|
||||||
|
# --- days only ONE side has are NOT drift ---
|
||||||
|
PORTAL_DAYS = {"2026-09-04": 99.0, **DAYS} # 69-day history vs a 31-day view
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"a longer portal history is not reported as drift (got {r.get('status')}, "
|
||||||
|
f"all-time {r.get('portal_all_time')}, delta {r.get('delta')})",
|
||||||
|
r.get("status") == "ok" and r.get("portal_all_time") == 159.0
|
||||||
|
and r.get("delta") == 0.0 and len(SENT) == 0)
|
||||||
|
reset()
|
||||||
|
|
||||||
|
# --- the 2026-11-05 signature: portal empty while LiteLLM is real ---
|
||||||
|
PORTAL_DAYS, PORTAL_ROWS = {}, 0
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"an EMPTY portal aggregate against real spend FAILS (got {r.get('status')})",
|
||||||
|
r.get("status") == "failed" and "silent-clean signature" in (r.get("reason") or ""))
|
||||||
|
check(f"info@ is told once (got {len(SENT)})",
|
||||||
|
len(SENT) == 1 and SENT[0]["to"] == "info@inference.coop"
|
||||||
|
and "credential" in SENT[0]["body"])
|
||||||
|
r2 = await m.check_spend_consistency()
|
||||||
|
check(f"the SAME failure is not re-mailed (got {len(SENT)} emails)",
|
||||||
|
r2.get("reported") is False and len(SENT) == 1)
|
||||||
|
|
||||||
|
# --- recovery is clean again, and a recurrence speaks ---
|
||||||
|
PORTAL_DAYS, PORTAL_ROWS = dict(DAYS), 1000
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"recovery is clean (got {r.get('status')})", r.get("status") == "ok")
|
||||||
|
check(f"recovery clears the marker (got {marker()!r})", not marker())
|
||||||
|
PORTAL_DAYS, PORTAL_ROWS = {}, 0
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"a recurrence mails again (got {r.get('status')}, {len(SENT)} emails)",
|
||||||
|
r.get("status") == "failed" and len(SENT) == 1)
|
||||||
|
reset()
|
||||||
|
await m.check_spend_consistency() # back to clean
|
||||||
|
|
||||||
|
# --- a DAY that drifts beyond the per-day tolerance is named ---
|
||||||
|
API_DAYS = {"2026-11-10": 10.0, "2026-11-11": 20.0, "2026-11-12": 44.0}
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"a drifting day FAILS and is named (got {r.get('status')}, {r.get('drifting_days')})",
|
||||||
|
r.get("status") == "failed" and bool(r.get("drifting_days"))
|
||||||
|
and r["drifting_days"][0]["date"] == "2026-11-12"
|
||||||
|
and "2026-11-12" in (r.get("reason") or ""))
|
||||||
|
check(f"the notice lists the worst day (got {len(SENT)})",
|
||||||
|
len(SENT) == 1 and "2026-11-12" in SENT[0]["body"])
|
||||||
|
reset()
|
||||||
|
await m.check_spend_consistency()
|
||||||
|
|
||||||
|
# --- cents-level rounding is NOT drift ---
|
||||||
|
API_DAYS = {"2026-11-10": 10.02, "2026-11-11": 19.98, "2026-11-12": 30.01}
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"cent-level rounding passes (got {r.get('status')}, delta {r.get('delta')})",
|
||||||
|
r.get("status") == "ok" and len(SENT) == 0)
|
||||||
|
reset()
|
||||||
|
|
||||||
|
# --- no shared window: cannot compare, must NOT read as clean ---
|
||||||
|
API_DAYS = {"2026-10-01": 5.0}
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"no shared window is skipped, not clean (got {r})",
|
||||||
|
r.get("status") == "skipped" and r.get("reason") == "no_overlapping_window")
|
||||||
|
reset()
|
||||||
|
|
||||||
|
# --- a read that cannot be made is UNKNOWN ---
|
||||||
|
FAIL_PORTAL = True
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"an unreadable portal side is skipped (got {r})",
|
||||||
|
r.get("status") == "skipped" and r.get("reason") == "portal_read_failed"
|
||||||
|
and len(SENT) == 0)
|
||||||
|
FAIL_PORTAL = False
|
||||||
|
FAIL_API = True
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"an unreadable LiteLLM side is skipped (got {r})",
|
||||||
|
r.get("status") == "skipped" and r.get("reason") == "litellm_api_failed")
|
||||||
|
FAIL_API = False
|
||||||
|
|
||||||
|
# --- notify=False never mails and never consumes ---
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("DELETE FROM portal_state")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
PORTAL_DAYS, PORTAL_ROWS = {}, 0
|
||||||
|
SENT.clear()
|
||||||
|
r = await m.check_spend_consistency(notify=False)
|
||||||
|
check(f"notify=False reports nothing (got {r.get('reported')}, {len(SENT)} emails)",
|
||||||
|
r.get("status") == "failed" and r.get("reported") is False and len(SENT) == 0)
|
||||||
|
r = await m.check_spend_consistency()
|
||||||
|
check(f"...and a later notifying run still speaks (got {len(SENT)} emails)",
|
||||||
|
r.get("reported") is True and len(SENT) == 1)
|
||||||
|
reset()
|
||||||
|
|
||||||
|
# --- the parser: the API's shape is per-day, per-team ---
|
||||||
|
class _Resp:
|
||||||
|
status_code = 200
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return {"daily_spend": [
|
||||||
|
{"date": "2026-11-12", "member:a@x.org": 1.5, "member:b@x.org": 2.25},
|
||||||
|
{"date": "2026-11-13", "member:a@x.org": 0.5},
|
||||||
|
{"date": "", "member:a@x.org": 9.0}, # no date -> ignored
|
||||||
|
{"member:a@x.org": 7.0}, # no date -> ignored
|
||||||
|
]}
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, *a, **k):
|
||||||
|
return _Resp()
|
||||||
|
|
||||||
|
real_httpx = m.httpx
|
||||||
|
m.httpx = types.SimpleNamespace(AsyncClient=_FakeClient)
|
||||||
|
try:
|
||||||
|
days = await REAL_API_DAILY_SPEND()
|
||||||
|
finally:
|
||||||
|
m.httpx = real_httpx
|
||||||
|
check(f"the parser sums each day's teams (got {days})",
|
||||||
|
days == {"2026-11-12": 3.75, "2026-11-13": 0.5})
|
||||||
|
|
||||||
|
# --- the endpoint ---
|
||||||
|
SENT.clear()
|
||||||
|
transport = httpx.ASGITransport(app=m.app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
|
||||||
|
r = await c.post("/admin/spend-check")
|
||||||
|
check(f"endpoint needs the admin token (got {r.status_code})",
|
||||||
|
r.status_code in (401, 403))
|
||||||
|
r = await c.post("/admin/spend-check", headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
body = r.json()
|
||||||
|
check(f"endpoint reports the comparison (got {body.get('status')})",
|
||||||
|
r.status_code == 200 and body.get("status") == "ok"
|
||||||
|
and body.get("api_window") == 60.0)
|
||||||
|
check(f"endpoint: a clean result mails nothing (got {len(SENT)})", len(SENT) == 0)
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: paid OC contributors with no portal row (the unmapped-backer net).
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
A contributor pays the collective and never gets an account, because our sweep
|
||||||
|
cannot SEE them: fetch_members() drops every member node with no email, and an
|
||||||
|
OC Organization never exposes one at all. The mmoya case (2026-10/11) was found
|
||||||
|
weeks late, by the member asking. The net ran as a script on the bot's host,
|
||||||
|
driving `cloudron exec` from outside; it now lives in the portal, where both
|
||||||
|
sides of the comparison already are.
|
||||||
|
|
||||||
|
WHAT IS PINNED DOWN HERE
|
||||||
|
* the member definition matches fetch_members()'s (ADMIN, or Membership/legacy
|
||||||
|
tier — a Credit-pack-only BACKER is the held-credits flow, not a member),
|
||||||
|
* the three classes of finding are told apart (org / visible email / hidden
|
||||||
|
email) because each needs a DIFFERENT action from a human,
|
||||||
|
* a member node with no account object is attributed through same-day current
|
||||||
|
orders, and stays silent when every same-day payer is already mapped,
|
||||||
|
* info@ is told ONLY when there are findings, and only when the SET changes —
|
||||||
|
it runs three times a day, and a stuck finding must not mail every time,
|
||||||
|
* a fetch failure reports `skipped`, never a clean bill of health.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_unmapped_backers.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.ADMIN_TOKEN = "test-admin-token"
|
||||||
|
m.ADMIN_TOKEN_LEGACY = ""
|
||||||
|
|
||||||
|
SENT = []
|
||||||
|
|
||||||
|
|
||||||
|
def fake_send(to, subject, body, *a, **k):
|
||||||
|
SENT.append({"to": to, "subject": subject, "body": body})
|
||||||
|
|
||||||
|
|
||||||
|
FAIL_NODES = False
|
||||||
|
NODES: list = []
|
||||||
|
ORDERS: list = []
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_nodes():
|
||||||
|
if FAIL_NODES:
|
||||||
|
raise RuntimeError("OC member fetch blew up")
|
||||||
|
return list(NODES)
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_orders(per_page=100, max_pages=3):
|
||||||
|
return list(ORDERS)
|
||||||
|
|
||||||
|
|
||||||
|
def node(role, tier, slug=None, email=None, atype="INDIVIDUAL", name=None,
|
||||||
|
created="2026-11-01T00:00:00Z", account=True):
|
||||||
|
return {"role": role, "tier": ({"name": tier} if tier else None),
|
||||||
|
"createdAt": created,
|
||||||
|
"account": ({"name": name or (slug or "?"), "slug": slug, "type": atype,
|
||||||
|
"email": email} if account else None)}
|
||||||
|
|
||||||
|
|
||||||
|
def order(slug, status="ACTIVE", day="2026-11-01", amount=15):
|
||||||
|
return {"id": f"or_{slug}_{day}", "status": status, "createdAt": f"{day}T10:00:00Z",
|
||||||
|
"frequency": "MONTHLY", "amount": {"value": amount},
|
||||||
|
"totalAmount": {"value": amount}, "fromAccount": {"slug": slug, "name": slug}}
|
||||||
|
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, bool(ok)))
|
||||||
|
|
||||||
|
|
||||||
|
def seed():
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("DELETE FROM members")
|
||||||
|
conn.execute("DELETE FROM portal_state")
|
||||||
|
for email, slug, org in (("alice@x.org", "alice", None),
|
||||||
|
("admin@x.org", "adminco", None),
|
||||||
|
("contact@beta.example", "beta-contact", "betaorg")):
|
||||||
|
conn.execute("INSERT INTO members (email, slug, org_slug, active, account_type, "
|
||||||
|
"credit_balance) VALUES (?, ?, ?, 1, 'member', 0)", (email, slug, org))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
global FAIL_NODES
|
||||||
|
m.fetch_all_member_nodes = fake_nodes
|
||||||
|
m.fetch_collective_orders = fake_orders
|
||||||
|
m.send_email = fake_send
|
||||||
|
|
||||||
|
seed()
|
||||||
|
NODES[:] = [
|
||||||
|
# mapped by email -> not a finding
|
||||||
|
node("BACKER", "Membership", "alice", "alice@x.org", name="Alice"),
|
||||||
|
# mapped ADMIN -> not a finding
|
||||||
|
node("ADMIN", "Membership", "adminco", "admin@x.org", name="Co-op"),
|
||||||
|
# NOT a member: a credit-pack-only BACKER takes the held-credits path
|
||||||
|
node("BACKER", "Credit pack", "packbuyer", "pack@x.org", name="Pack Buyer"),
|
||||||
|
# NOT a member: a plain DONATION (no tier, joined after the legacy cutoff).
|
||||||
|
# OC grants BACKER role for any one-time contribution; a donation must stay
|
||||||
|
# silent instead of mailing info@ about a "missing account".
|
||||||
|
node("BACKER", None, "donor", "donor@x.org", name="Donor",
|
||||||
|
created="2026-11-21T15:10:00Z"),
|
||||||
|
# FINDING: a LEGACY no-tier BACKER (before the tier system) IS a member
|
||||||
|
node("BACKER", None, "legacy", "legacy@x.org", name="Legacy",
|
||||||
|
created="2026-01-01T00:00:00Z"),
|
||||||
|
# not a member role
|
||||||
|
node("MEMBER", "Membership", "roleonly", "role@x.org", name="Role Only"),
|
||||||
|
# FINDING: visible email -> the sweep should have provisioned this
|
||||||
|
node("BACKER", "Membership", "vic", "vic@x.org", name="Visible Vic"),
|
||||||
|
# FINDING: email hidden even from the admin view
|
||||||
|
node("BACKER", "Membership", "han", None, name="Hidden Han"),
|
||||||
|
# a MAPPED Organization (its org_slug is on a portal row) -> not a finding
|
||||||
|
node("BACKER", "Membership", "betaorg", None, atype="ORGANIZATION", name="Beta Org"),
|
||||||
|
# FINDING: an Organization OC never exposes an email for
|
||||||
|
node("BACKER", "Membership", "gammaorg", None, atype="ORGANIZATION", name="Gamma Org"),
|
||||||
|
# null-account node on a day whose only payer is MAPPED -> silent
|
||||||
|
node("BACKER", "Membership", account=False, created="2026-11-01T00:00:00Z"),
|
||||||
|
# null-account node on a day with an UNMAPPED payer -> finding
|
||||||
|
node("BACKER", "Membership", account=False, created="2026-11-02T00:00:00Z"),
|
||||||
|
# null-account node with NO date -> NOT a finding: there is nothing to
|
||||||
|
# attribute it against, and reporting it is how a phantom appears (the
|
||||||
|
# members query did not select createdAt, so every such node looked like an
|
||||||
|
# uncredited payer on the day "").
|
||||||
|
{"role": "BACKER", "tier": {"name": "Membership"}, "createdAt": None, "account": None},
|
||||||
|
]
|
||||||
|
ORDERS[:] = [
|
||||||
|
order("alice", day="2026-11-01"),
|
||||||
|
order("ghost", day="2026-11-02"),
|
||||||
|
order("vic", day="2026-11-03", amount=25),
|
||||||
|
]
|
||||||
|
|
||||||
|
SENT.clear()
|
||||||
|
res = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"the check runs (got {res.get('status')})", res.get("status") == "ok")
|
||||||
|
classes = sorted(res.get("classes") or [])
|
||||||
|
check(f"five findings in four classes (got {res.get('findings')} {classes})",
|
||||||
|
res.get("findings") == 5 and classes == ["hidden", "null-account", "org", "visible"])
|
||||||
|
check("a node with no createdAt is NOT reported (nothing to attribute it against)",
|
||||||
|
sum(1 for f in res["detail"] if f["class"] == "null-account") == 1)
|
||||||
|
slugs = sorted(f["slug"] or "(null-account)" for f in res["detail"])
|
||||||
|
check(f"exactly the unmapped member-ish nodes are findings (got {slugs})",
|
||||||
|
slugs == ["(null-account)", "gammaorg", "han", "legacy", "vic"])
|
||||||
|
check("a Credit-pack-only BACKER is not a member finding",
|
||||||
|
not any(f["slug"] == "packbuyer" for f in res["detail"]))
|
||||||
|
check("a post-cutoff no-tier BACKER (a plain donation) is not a finding",
|
||||||
|
not any(f["slug"] == "donor" for f in res["detail"]))
|
||||||
|
check("a LEGACY no-tier BACKER is still a member finding",
|
||||||
|
any(f["slug"] == "legacy" for f in res["detail"]))
|
||||||
|
check("a MEMBER-role node is not a member finding",
|
||||||
|
not any(f["slug"] == "roleonly" for f in res["detail"]))
|
||||||
|
vis = {f["slug"]: f["email_visibility"] for f in res["detail"]}
|
||||||
|
check("the VISIBLE case tells the operator the sweep should have caught it",
|
||||||
|
"VISIBLE" in vis.get("vic", "") and "sweep" in
|
||||||
|
next(f["action"] for f in res["detail"] if f["slug"] == "vic"))
|
||||||
|
check("the ORG case points at /admin/org-link",
|
||||||
|
"/admin/org-link" in next(f["action"] for f in res["detail"] if f["slug"] == "gammaorg"))
|
||||||
|
check("the HIDDEN case says the email must be fetched out-of-band",
|
||||||
|
"out-of-band" in next(f["action"] for f in res["detail"] if f["slug"] == "han"))
|
||||||
|
check(f"findings carry the payer's dues (got {next(f['dues'] for f in res['detail'] if f['slug'] == 'vic')})",
|
||||||
|
"$25 MONTHLY ACTIVE" in next(f["dues"] for f in res["detail"] if f["slug"] == "vic"))
|
||||||
|
check(f"the null-account finding names the unmapped same-day payer (got "
|
||||||
|
f"{next(f['dues'] for f in res['detail'] if f['class'] == 'null-account')})",
|
||||||
|
"ghost" in next(f["dues"] for f in res["detail"] if f["class"] == "null-account"))
|
||||||
|
check(f"info@ is told once, with every class in the body (got {len(SENT)})",
|
||||||
|
len(SENT) == 1 and SENT[0]["to"] == "info@inference.coop"
|
||||||
|
and "org-link" in SENT[0]["body"] and "out-of-band" in SENT[0]["body"])
|
||||||
|
check("it says the notice covers what is new, not every sweep",
|
||||||
|
"not every sweep" in SENT[0]["body"])
|
||||||
|
|
||||||
|
# Same set again: a report, but NO second email.
|
||||||
|
res2 = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"the same finding set is not re-emailed (got {len(SENT)} emails)",
|
||||||
|
res2.get("findings") == 5 and res2.get("reported") is False and len(SENT) == 1)
|
||||||
|
|
||||||
|
# The set CHANGES (one finding resolved): mail again.
|
||||||
|
NODES[:] = [n for n in NODES
|
||||||
|
if ((n.get("account") or {}) or {}).get("slug") != "han"]
|
||||||
|
res3 = await m.reconcile_unmapped_backers()
|
||||||
|
# A set that SHRINKS (one finding resolved) must NOT re-mail the survivors: a
|
||||||
|
# person already told about a finding is not told again just because the list
|
||||||
|
# got shorter. Only genuinely NEW keys speak.
|
||||||
|
check(f"a smaller set re-mails nobody (got {res3.get('findings')} findings, "
|
||||||
|
f"{res3.get('new')} new, {len(SENT)} emails)",
|
||||||
|
res3.get("findings") == 4 and res3.get("new") == 0 and len(SENT) == 1)
|
||||||
|
|
||||||
|
# Fully clear: silent, and the marker is cleared so a recurrence speaks up.
|
||||||
|
NODES[:] = [node("BACKER", "Membership", "alice", "alice@x.org", name="Alice")]
|
||||||
|
res4 = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"a clean run says nothing (got {res4.get('findings')}, {len(SENT)} emails)",
|
||||||
|
res4.get("findings") == 0 and res4.get("reported") is False and len(SENT) == 1)
|
||||||
|
conn = m.get_db()
|
||||||
|
marker = conn.execute("SELECT value FROM portal_state WHERE key = ?",
|
||||||
|
(m.UNMAPPED_BACKERS_MARKER,)).fetchone()
|
||||||
|
conn.close()
|
||||||
|
check(f"the marker is cleared on a clean run (got {marker})", not (marker and marker[0]))
|
||||||
|
|
||||||
|
NODES[:] = [node("BACKER", "Membership", "vic", "vic@x.org", name="Visible Vic")]
|
||||||
|
res5 = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"a finding after a clean run speaks up again (got {len(SENT)} emails)",
|
||||||
|
res5.get("findings") == 1 and res5.get("new") == 1 and len(SENT) == 2)
|
||||||
|
|
||||||
|
# Notify can be suppressed (on-demand checks must not mail).
|
||||||
|
NODES[:] = [node("BACKER", "Membership", "newguy", "new@x.org", name="New Guy")]
|
||||||
|
res6 = await m.reconcile_unmapped_backers(notify=False)
|
||||||
|
check(f"notify=False suppresses the mail (got {res6.get('findings')} findings, {len(SENT)} emails)",
|
||||||
|
res6.get("findings") == 1 and res6.get("reported") is False and len(SENT) == 2)
|
||||||
|
# ...and a look must not CONSUME the alert: the next notifying run still speaks.
|
||||||
|
res6b = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"a silent look does not swallow the alert (got {res6b.get('new')} new, {len(SENT)} emails)",
|
||||||
|
res6b.get("reported") is True and len(SENT) == 3)
|
||||||
|
|
||||||
|
# A failed read is UNKNOWN, not silence.
|
||||||
|
FAIL_NODES = True
|
||||||
|
res7 = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"a failed member fetch is skipped, not clean (got {res7})",
|
||||||
|
res7.get("status") == "skipped" and res7.get("reason") == "member_fetch_failed")
|
||||||
|
FAIL_NODES = False
|
||||||
|
|
||||||
|
# An order-fetch failure must not lose the finding.
|
||||||
|
async def boom_orders(per_page=100, max_pages=3):
|
||||||
|
raise RuntimeError("orders unavailable")
|
||||||
|
|
||||||
|
m.fetch_collective_orders = boom_orders
|
||||||
|
res8 = await m.reconcile_unmapped_backers()
|
||||||
|
check(f"a failed ORDER fetch still reports the finding (got {res8.get('findings')})",
|
||||||
|
res8.get("findings") == 1)
|
||||||
|
check("...and says so in the dues line",
|
||||||
|
"no order found" in res8["detail"][0]["dues"])
|
||||||
|
m.fetch_collective_orders = fake_orders
|
||||||
|
|
||||||
|
# --- the endpoint ---
|
||||||
|
# A fresh finding set, so the endpoint run has something NEW to report
|
||||||
|
# (the marker is per-set: the same set would rightly stay quiet).
|
||||||
|
NODES[:] = [node("BACKER", "Membership", "endpointcase", "ep@x.org", name="EP")]
|
||||||
|
SENT.clear()
|
||||||
|
transport = httpx.ASGITransport(app=m.app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
|
||||||
|
r = await c.post("/admin/unmapped-check")
|
||||||
|
check(f"endpoint: needs the admin token (got {r.status_code})", r.status_code in (401, 403))
|
||||||
|
r = await c.post("/admin/unmapped-check", headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
body = r.json()
|
||||||
|
check(f"endpoint: runs the check (got {body.get('findings')} findings)",
|
||||||
|
r.status_code == 200 and body.get("findings") == 1)
|
||||||
|
check(f"endpoint: the run mails once for the new set (got {len(SENT)})", len(SENT) == 1)
|
||||||
|
r = await c.post("/admin/unmapped-check?notify=0",
|
||||||
|
headers={"X-Admin-Token": "test-admin-token"})
|
||||||
|
check(f"endpoint: ?notify=0 suppresses the mail (got {len(SENT)} emails)",
|
||||||
|
r.status_code == 200 and len(SENT) == 1)
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: an Open Collective webhook must never fail as a bare 500.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
On 2026-11-13 a member's $50 credit-pack purchase arrived as an
|
||||||
|
`order.processed` delivery. The handler called fetch_members() to turn the OC
|
||||||
|
slug into an email, `fetch_all_member_nodes` used a bare httpx.AsyncClient()
|
||||||
|
(httpx's DEFAULT 5-second timeout), OC's GraphQL answered slower than that,
|
||||||
|
and `httpx.ReadTimeout` escaped the handler as an unhandled ASGI exception:
|
||||||
|
|
||||||
|
* the delivery returned 500, so nothing retried it usefully,
|
||||||
|
* no credits were granted — the member paid and got nothing for 40 minutes,
|
||||||
|
* the log carried a stack trace instead of anything naming the member or
|
||||||
|
the order, so the purchase could not be reconciled from the log alone.
|
||||||
|
|
||||||
|
The guards proven here, on a FIXTURE db with the network stubbed:
|
||||||
|
|
||||||
|
AUTH
|
||||||
|
1. A wrong URL token is still a 401 — the new error net must not swallow
|
||||||
|
the one status that means "the webhook URL and WEBHOOK_TOKEN disagree".
|
||||||
|
|
||||||
|
NO BARE 500
|
||||||
|
2. A transport failure while resolving the purchase answers 503 (retryable)
|
||||||
|
and the handler does not raise out of the ASGI app.
|
||||||
|
3. The same is true for a failure raised anywhere else in the handler.
|
||||||
|
|
||||||
|
MONEY
|
||||||
|
4. A resolvable purchase grants credits ONCE, with the per-order reference
|
||||||
|
`oc:<slug>:<idV2>`.
|
||||||
|
5. Re-delivering the identical payload returns `already_credited` and moves
|
||||||
|
no money — this is what makes OC's retries safe.
|
||||||
|
|
||||||
|
TRANSPORT
|
||||||
|
6. `_oc_graphql_post` retries once on a transport error and returns the
|
||||||
|
response; if both attempts fail it RAISES (callers keep their
|
||||||
|
fail-safes — a partial member list must never look complete).
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_webhook_resilience.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["WEBHOOK_TOKEN"] = "test-webhook-token"
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
# The app module shares this httpx object, so stubbing it later would replace
|
||||||
|
# httpx.AsyncClient process-wide — keep a handle on the real class.
|
||||||
|
REAL_ASYNC_CLIENT = httpx.AsyncClient
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
TOKEN = "test-webhook-token"
|
||||||
|
MEMBER_SLUG = "nightrose"
|
||||||
|
MEMBER_EMAIL = "nightrose@example.org"
|
||||||
|
ORDER_ID = "or_testOrderId123"
|
||||||
|
|
||||||
|
PAYLOAD = {
|
||||||
|
"type": "order.processed",
|
||||||
|
"data": {
|
||||||
|
"fromCollective": {"slug": MEMBER_SLUG, "name": "NightRose"},
|
||||||
|
"order": {
|
||||||
|
"idV2": ORDER_ID,
|
||||||
|
"description": "Financial contribution to Inference Cooperative (Credit pack)",
|
||||||
|
"totalAmount": 5000,
|
||||||
|
},
|
||||||
|
"amount": 5000,
|
||||||
|
"firstPayment": False,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, ok))
|
||||||
|
|
||||||
|
|
||||||
|
SENT = []
|
||||||
|
|
||||||
|
|
||||||
|
def fake_send(to, subject, body, *a, **k):
|
||||||
|
SENT.append({"to": to, "subject": subject, "body": body})
|
||||||
|
|
||||||
|
|
||||||
|
# --- stubs ----------------------------------------------------------------- #
|
||||||
|
async def fetch_members_ok():
|
||||||
|
return [{"email": MEMBER_EMAIL, "name": "NightRose", "slug": MEMBER_SLUG,
|
||||||
|
"role": "BACKER"}]
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_members_timeout():
|
||||||
|
raise httpx.ReadTimeout("simulated OC read timeout")
|
||||||
|
|
||||||
|
|
||||||
|
async def order_amount_ok(_order_id_v2=None):
|
||||||
|
return 5000
|
||||||
|
|
||||||
|
|
||||||
|
async def order_details_ok(_order_id_v2=None):
|
||||||
|
"""Verified OC order for the credit-pack fixture (2026-11-19 hardening)."""
|
||||||
|
return {
|
||||||
|
"id": "or_testOrderId123",
|
||||||
|
"status": "PAID",
|
||||||
|
"frequency": "ONETIME",
|
||||||
|
"amount": {"valueInCents": 5000},
|
||||||
|
"platformTipAmount": {"valueInCents": 0},
|
||||||
|
"fromAccount": {"slug": MEMBER_SLUG},
|
||||||
|
"toAccount": {"slug": m.OC_COLLECTIVE_SLUG},
|
||||||
|
"tier": {"name": "Credit pack"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def budget_noop(_email):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance) "
|
||||||
|
"VALUES (?, ?, 1, 0)", (MEMBER_EMAIL, MEMBER_SLUG))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
transport = httpx.ASGITransport(app=m.app)
|
||||||
|
url = f"/webhook/opencollective/{TOKEN}"
|
||||||
|
|
||||||
|
m.sync_team_budget_from_balance = budget_noop # no LiteLLM calls in a test
|
||||||
|
m.get_order_amount = order_amount_ok
|
||||||
|
m.get_order_details = order_details_ok
|
||||||
|
|
||||||
|
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
|
||||||
|
# --- 1. AUTH: a wrong token is still a 401. ---
|
||||||
|
r = await c.post("/webhook/opencollective/wrong-token", json=PAYLOAD)
|
||||||
|
check(f"auth: a wrong webhook token is 401 (got {r.status_code})", r.status_code == 401)
|
||||||
|
|
||||||
|
# --- 2. NO BARE 500 when the OC lookup times out. ---
|
||||||
|
m.fetch_members = fetch_members_timeout
|
||||||
|
r = await c.post(url, json=PAYLOAD)
|
||||||
|
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
||||||
|
check(f"timeout: the delivery answers 503, not 500 (got {r.status_code})",
|
||||||
|
r.status_code == 503)
|
||||||
|
check(f"timeout: the response asks for a retry (got {body})",
|
||||||
|
body.get("retry") is True)
|
||||||
|
check("timeout: an unexpected failure never raises out of the app "
|
||||||
|
"(httpx.ReadTimeout was caught by the handler net)",
|
||||||
|
r.status_code != 500)
|
||||||
|
|
||||||
|
# --- 2b. The SYSTEM records the failures it refuses. ---
|
||||||
|
# The money-critical alert used to be a log scraper on the operator's own
|
||||||
|
# machine, reading a buffer with hours of memory — whole hours were missing
|
||||||
|
# from it during the 2026-11-13 investigation. The portal handles every
|
||||||
|
# delivery, so the portal is what must notice and say.
|
||||||
|
conn = m.get_db()
|
||||||
|
rows = [dict(zip(("id", "at", "status", "event_type", "detail"), r)) for r in
|
||||||
|
conn.execute("SELECT id, at, status, event_type, detail FROM webhook_failures "
|
||||||
|
"ORDER BY id")]
|
||||||
|
conn.close()
|
||||||
|
check(f"record: the refused 401 delivery is recorded by the portal (got {rows})",
|
||||||
|
any(r["status"] == 401 for r in rows))
|
||||||
|
check(f"record: the 503 is recorded with its event type (got {rows})",
|
||||||
|
any(r["status"] == 503 and r["event_type"] == "order.processed" for r in rows))
|
||||||
|
check("record: the 503 row names the exception that caused it",
|
||||||
|
any(r["status"] == 503 and "ReadTimeout" in (r["detail"] or "") for r in rows))
|
||||||
|
|
||||||
|
SENT.clear()
|
||||||
|
m.send_email = fake_send
|
||||||
|
rep = m.webhook_failure_report()
|
||||||
|
check(f"report: new failures are summarised (got {rep.get('new_failures')} rows)",
|
||||||
|
rep.get("status") == "reported" and rep.get("new_failures") == len(rows))
|
||||||
|
check(f"report: info@ is told, naming both kinds of failure (got {SENT})",
|
||||||
|
len(SENT) == 1 and SENT[0]["to"] == "info@inference.coop"
|
||||||
|
and "401" in SENT[0]["body"] and "503" in SENT[0]["body"]
|
||||||
|
and "WEBHOOK_TOKEN" in SENT[0]["body"])
|
||||||
|
rep2 = m.webhook_failure_report()
|
||||||
|
check(f"report: the SAME batch is not re-reported (got {rep2})",
|
||||||
|
rep2.get("new_failures") == 0 and len(SENT) == 1)
|
||||||
|
await c.post("/webhook/opencollective/wrong-token", json=PAYLOAD)
|
||||||
|
rep3 = m.webhook_failure_report()
|
||||||
|
check(f"report: a LATER failure is reported again (got {rep3.get('new_failures')})",
|
||||||
|
rep3.get("new_failures") == 1 and len(SENT) == 2)
|
||||||
|
|
||||||
|
# --- 3. MONEY: a resolvable purchase credits exactly once. ---
|
||||||
|
m.fetch_members = fetch_members_ok
|
||||||
|
r = await c.post(url, json=PAYLOAD)
|
||||||
|
body = r.json()
|
||||||
|
check(f"grant: a resolvable credit pack grants credits (got {body})",
|
||||||
|
r.status_code == 200 and body.get("status") == "credits_added"
|
||||||
|
and body.get("credits_added") == 50.0)
|
||||||
|
check("grant: the balance reflects the purchase",
|
||||||
|
m.get_credit_balance(MEMBER_EMAIL) == 50.0)
|
||||||
|
ref = m.credit_pack_reference(MEMBER_SLUG, {"idV2": ORDER_ID})
|
||||||
|
check("grant: the ledger row is keyed on the OC order (idempotence key)",
|
||||||
|
ref == f"oc:{ORDER_ID}" and m.credit_reference_exists(ref))
|
||||||
|
|
||||||
|
# --- 4. Re-delivery moves no money. ---
|
||||||
|
r = await c.post(url, json=PAYLOAD)
|
||||||
|
body = r.json()
|
||||||
|
check(f"redelivery: the identical payload answers already_credited (got {body})",
|
||||||
|
r.status_code == 200 and body.get("status") == "already_credited"
|
||||||
|
and body.get("credits_added") == 0.0)
|
||||||
|
check("redelivery: the balance is unchanged",
|
||||||
|
m.get_credit_balance(MEMBER_EMAIL) == 50.0)
|
||||||
|
|
||||||
|
# --- 5. TRANSPORT: retry-once, then raise. ---
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class FlakyClient:
|
||||||
|
def __init__(self, fail_times):
|
||||||
|
self.fail_times = fail_times
|
||||||
|
|
||||||
|
async def post(self, *a, **k):
|
||||||
|
calls.append(1)
|
||||||
|
if len(calls) <= self.fail_times:
|
||||||
|
raise httpx.ReadTimeout("simulated timeout")
|
||||||
|
return "RESPONSE"
|
||||||
|
|
||||||
|
sentinel = await m._oc_graphql_post(FlakyClient(1), {"query": "x"})
|
||||||
|
check(f"transport: one transient failure is retried and succeeds (got {sentinel!r})",
|
||||||
|
sentinel == "RESPONSE" and len(calls) == 2)
|
||||||
|
|
||||||
|
calls.clear()
|
||||||
|
err = None
|
||||||
|
try:
|
||||||
|
await m._oc_graphql_post(FlakyClient(2), {"query": "x"})
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
err = e
|
||||||
|
check("transport: a persistent failure still RAISES to the caller",
|
||||||
|
isinstance(err, httpx.ReadTimeout))
|
||||||
|
|
||||||
|
# --- 6. The client used for the member walk has a real timeout. ---
|
||||||
|
src = open(os.path.join(os.path.dirname(os.path.dirname(
|
||||||
|
os.path.abspath(__file__))), "app", "main.py"), encoding="utf-8").read()
|
||||||
|
check("timeout: fetch_all_member_nodes does NOT use httpx's 5s default",
|
||||||
|
"async with httpx.AsyncClient(timeout=30.0) as client:" in src)
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
Reference in new issue
Block a user