diff --git a/README.md b/README.md index 15cbaaa91c..85fb5b46f4 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [OpenClaw](roles/web-app-openclaw/) | beta | Self-hosted personal AI agent gateway with a browser control UI, sandboxed in a Kata microVM or gVisor runtime | [🌐](https://openclaw.ai/) [🛠️](roles/web-app-openclaw/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-design/), [Dashboard](roles/web-app-dashboard/), [Documentation](roles/web-app-docs/), [Kata & gVisor](roles/svc-virt-kata/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [OpenCloud](roles/web-app-opencloud/) | beta | Self-hosted platform for file sync, sharing, and collaboration with Keycloak SSO and central LDAP directory | [🌐](https://opencloud.eu/) [🎬](https://www.youtube.com/watch?v=Cg48rFNY0R4) [🛠️](roles/web-app-opencloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-design/), [Dashboard](roles/web-app-dashboard/), [Documentation](roles/web-app-docs/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Stalwart](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [OpenLDAP](roles/svc-db-openldap/) | beta | Self-hosted LDAP directory service for centralized user, group, and schema management with TLS-secured access | [🌐](https://www.openldap.org/) [🛠️](roles/svc-db-openldap/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Documentation](roles/web-app-docs/), [Tor Onion Service](roles/svc-net-tor/) | +| [OpenPost](roles/web-app-openpost/) | beta | Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks | [🌐](https://openpo.st/) [🎬](https://www.youtube.com/watch?v=_mZf3HzQaN8) [🛠️](roles/web-app-openpost/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [PeerTube](roles/web-app-peertube/), [Pixelfed](roles/web-app-pixelfed/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-svc-seaweedfs/), [Stalwart](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [OpenProject](roles/web-app-openproject/) | beta | Self-hosted platform for project management, work-package tracking, Gantt planning, and team collaboration | [🌐](https://www.openproject.org/) [🎬](https://www.youtube.com/watch?v=rvCd0xH7rCs) [🛠️](roles/web-app-openproject/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-design/), [Dashboard](roles/web-app-dashboard/), [Documentation](roles/web-app-docs/), [GitLab](roles/web-app-gitlab/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Nextcloud](roles/web-app-nextcloud/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-svc-seaweedfs/), [Stalwart](roles/web-app-stalwart/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [OpenResty](roles/svc-prx-openresty/) | beta | NGINX-based web platform and reverse proxy with validated config reloads and Let's Encrypt integration | [🌐](https://openresty.org/) [🎬](https://www.youtube.com/watch?v=NR8U1qYHGqk) [🛠️](roles/svc-prx-openresty/README.md#quick-setup) | [Documentation](roles/web-app-docs/), [Tor Onion Service](roles/svc-net-tor/) | | [OpenTalk](roles/web-app-opentalk/) | beta | Sovereign open-source video conferencing platform for audio/video calls, screen sharing, breakout rooms, and SSO | [🌐](https://opentalk.eu/) [🛠️](roles/web-app-opentalk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-design/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Documentation](roles/web-app-docs/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-svc-seaweedfs/), [Stalwart](roles/web-app-stalwart/), [Universal Logout](roles/web-svc-logout/) | diff --git a/cli/administration/inventory/provision/passwords.py b/cli/administration/inventory/provision/passwords.py index 251c466b03..e7cc965de4 100644 --- a/cli/administration/inventory/provision/passwords.py +++ b/cli/administration/inventory/provision/passwords.py @@ -4,6 +4,7 @@ import re import secrets import string +from utils.annotations.message import mask from utils.manager.value_generator import ValueGenerator USER_PASSWORD_LENGTH = 64 @@ -37,6 +38,7 @@ def generate_user_password(length: int = USER_PASSWORD_LENGTH) -> str: body[secrets.randbelow(length - 1) + 1] = secrets.choice(SHELL_SAFE_MARKS) password = "".join(body) if _USER_PASSWORD_RE.match(password): + mask(password) return password raise RuntimeError("Failed to generate a user password after many attempts") diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index 8674265aac..0cce4e47f2 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -187,11 +187,13 @@ networks: local: subnet: 192.168.101.112/28 # required; CIDR of the role's docker network dns_resolver: 192.168.102.29 # optional, only when a fixed DNS resolver IP is needed (today: mailu) + outside_pool: true # optional, only when something outside the repository pins the subnet outside NETWORK_ROLE_SUBNET_POOL (today: bigbluebutton, openpost) ``` The role's name is implied by the path. There is NO `web-app-` key inside the file. -The materialised path is `applications..networks.local.{subnet,dns_resolver}`. +The materialised path is `applications..networks.local.{subnet,dns_resolver,outside_pool}`. +`NETWORK_ROLE_SUBNET_EXCEPTION_ROLES` collects every role that sets `outside_pool` through `lookup('role_subnet_exceptions')`. ## Per-Entity Ports: `meta/services.yml..ports` 🚪 diff --git a/docs/requirements/035-mcp-proxy-expansion.md b/docs/requirements/035-mcp-proxy-expansion.md index 2e02a9c46e..1986553fa2 100644 --- a/docs/requirements/035-mcp-proxy-expansion.md +++ b/docs/requirements/035-mcp-proxy-expansion.md @@ -34,11 +34,11 @@ It does not authorize enabling a new MCP endpoint, upgrading an application, ins `svc-db-qdrant`, `web-app-baserow`, `web-app-checkmk`, `web-app-fider`, `web-app-gitea`, `web-app-gitlab`, `web-app-jellyfin`, `web-app-jenkins`, `web-app-listmonk`, `web-app-mattermost`, `web-app-nextcloud`, `web-app-pretix`, `web-app-prometheus`, `web-app-snipe-it`, `web-app-zammad`, `web-svc-libretranslate`. -### blocked (11) +### blocked (12) An upstream path exists or is claimed, and something concrete stops it here. Each row names what, using the reason vocabulary above, so "blocked" never reads as "nobody looked". -`svc-ai-litellm`, `svc-ai-lmstudio`, `svc-db-elasticsearch`, `svc-db-mariadb`, `svc-db-redis`, `web-app-discourse`, `web-app-erpnext`, `web-app-matomo`, `web-app-odoo`, `web-app-penpot`, `web-app-shopware`. +`svc-ai-litellm`, `svc-ai-lmstudio`, `svc-db-elasticsearch`, `svc-db-mariadb`, `svc-db-redis`, `web-app-discourse`, `web-app-erpnext`, `web-app-matomo`, `web-app-odoo`, `web-app-openpost`, `web-app-penpot`, `web-app-shopware`. | role | reason | blocker | | --- | --- | --- | @@ -51,6 +51,7 @@ An upstream path exists or is claimed, and something concrete stops it here. Eac | `web-app-erpnext` | `version_unverified` | The Frappe MCP component is experimental and unverified against the pinned Frappe v16. | | `web-app-matomo` | `unreviewed_third_party` | The project-owned plugin is unaudited: endpoint, transport, auth and tool scope are unverified in source. | | `web-app-odoo` | `unreviewed_third_party` | Neither Odoo SA nor the OCA publishes a server; the leading third party carries 197 of 231 commits from one author, keeps its access control in a separate Odoo Apps store module outside any pinnable tag, and defaults to a mutating tool scope. | +| `web-app-openpost` | `version_unverified` | The pinned v7.42.2 serves a native `/mcp` endpoint, but its tool list, client registration and publishing side effects on external networks are not audited against that release. | | `web-app-penpot` | `interactive_browser_session` | The server needs an active browser tab and plugin connection, and can execute powerful design-context operations. | | `web-app-shopware` | `version_unverified` | The pinned 6.7.8.2 predates the experimental native `/api/_mcp` server. | diff --git a/docs/requirements/062-web-app-openpost.md b/docs/requirements/062-web-app-openpost.md new file mode 100644 index 0000000000..f2211bc3c4 --- /dev/null +++ b/docs/requirements/062-web-app-openpost.md @@ -0,0 +1,309 @@ +# 062 - OpenPost Publishing Desk Role + +## User Story + +As an Infinito.Nexus PR manager, I want a self-hosted [OpenPost](https://github.com/getopenpost/openpost) publishing desk deployed as the `web-app-openpost` role behind Keycloak single sign-on so that I can compose, schedule and publish content to Fediverse and commercial social networks from one sovereign interface. + +## Background + +This requirement implements the publishing half of the OpenProject user story "sovereign social media publishing and crossposting" (story criteria AC1, AC2, AC3, AC4, AC6, AC7 and the desk part of AC8). +Automated crossposting from Fediverse accounts (story criterion AC5 and its tests) is specified in [063-openpost-crossposter.md](063-openpost-crossposter.md), which builds on this role. +OpenPost is self-hosted and integrated like every other application of the stack: the official upstream image, configured through environment variables, wired into the shared proxy, Keycloak, Postgres, object storage and backups. + +### Evaluation and selection + +| Candidate | Verdict | Decisive evidence | +|---|---|---| +| [OpenPost](https://github.com/getopenpost/openpost) | Selected | Only candidate that publishes to Mastodon (any instance), Pixelfed and PeerTube as well as Facebook, Instagram, X, YouTube, LinkedIn, Threads, TikTok and Bluesky. One image, Postgres, S3 media, OIDC with issuer discovery, AES-256-GCM encryption of provider tokens. | +| [Postiz](https://github.com/gitroomhq/postiz-app) | Rejected | No Pixelfed or PeerTube code, one Mastodon instance per deployment, provider tokens stored in plaintext, Temporal plus Elasticsearch required, OIDC without discovery that self-registers users even with registrations disabled, 19 published advisories. | +| [Ferryman](https://ferryman.io/) | Reference only | Closed SaaS without self-hosting, no Pixelfed or PeerTube, no named legal entity in its privacy policy. | +| [Mixpost](https://mixpost.app/) Pro | Rejected | Commercial source-available licence, no PeerTube, image and database support unverified. | +| [TryPost](https://github.com/trypostit/trypost) | Rejected | No published image, no documented SSO, major version churn within weeks. | +| [n8n](https://n8n.io/) | Not a desk | Automation engine only, Sustainable Use License, native OIDC is a paid feature. | + +OpenPost carries known risks that this requirement mitigates rather than ignores: it was created on 2026-03-21, one maintainer wrote about 95% of its commits, it shipped 265 releases by 2026-10-20, only the latest release receives security fixes, and its maintainer states that no posting option has passed the project's own live certification yet ([provider reference](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/providers/index.md)). + +### Upstream facts established by research + +All OpenPost source references point at commit `0deadaf7`, the branch head on 2026-10-20; the latest published release is `v7.22.9`. + +| Topic | Finding | Source | +|---|---|---| +| Image | `ghcr.io/getopenpost/openpost` publishes release tags for amd64 and arm64; the image runs as UID 1000 on Alpine and ships a HEALTHCHECK on `/api/v1/health`. | [Dockerfile](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/deploy/docker/Dockerfile) | +| Processes | One binary with the roles `all`, `web`, `worker` and `migrate`; Postgres job claiming uses `FOR UPDATE SKIP LOCKED`, migrations take an advisory lock. | [worker.go](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/queue/worker.go) | +| Database | SQLite or Postgres; no MariaDB, no Redis. | [database.go](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/database/database.go) | +| Media | Local disk or S3 (`OPENPOST_S3_*`); Facebook, Instagram and TikTok fetch media from public HTTPS URLs. | [.env.example](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/.env.example) | +| App URL | `OPENPOST_APP_URL` MUST carry a real domain, because OpenPost derives the WebAuthn relying-party ID from it and refuses to start otherwise; cookie sessions additionally require a same-origin `Origin` header. | Proof run on 2026-10-21 (see [Egress proof](#egress-proof)) | +| SSO | One instance-wide OIDC provider (`OPENPOST_OIDC_ISSUER`, `_CLIENT_ID`, `_CLIENT_SECRET_FILE`, `_SCOPES`, `_JIT_ENABLED`, `_BOOTSTRAP_ALLOWLIST`, `OPENPOST_SSO_BREAK_GLASS_EMAILS`); identities match on issuer and subject; `groups` and `preferred_username` are not consumed. | [.env.example](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/.env.example), [identity/service.go](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/services/identity/service.go) | +| Proxy auth | Trusted-proxy mode accepts `X-OpenPost-Proxy-User` together with `OPENPOST_PROXY_AUTH_SECRET`. | [proxyauth middleware](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/services/proxyauth/middleware.go) | +| Secrets at rest | Provider tokens and secrets use AES-256-GCM with key IDs and rotation; JWT, encryption and media signing keys accept `_FILE` variants. | [encrypt.go](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/services/crypto/encrypt.go) | +| Telemetry | Diagnostics to `app.openpo.st` are on by default (`OPENPOST_DIAGNOSTICS_ENABLED`), the update check is on (`OPENPOST_UPDATE_CHECK_ENABLED`), public profiles are on (`OPENPOST_PUBLIC_PROFILES_ENABLED`), PostHog telemetry is off (`OPENPOST_TELEMETRY_ENABLED`). | [diagnostics.md](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/configuration/diagnostics.md) | +| Egress guard | `netguard` is OpenPost's SSRF protection: it rejects a destination when any resolved address lies in a private, loopback, CGNAT, link-local, documentation, benchmarking, multicast or reserved range, checks again at connect time and on every redirect, ignores proxy variables, and has no switch for built-in providers. | [netguard.go](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/netguard/netguard.go) | +| Guard exceptions | Only operator configuration may reach private addresses: the instance OIDC issuer and custom connectors with `mode: private_allowlist`; built-in provider URLs entered by users never may. Custom CAs are honoured through `SSL_CERT_FILE` and the Go `SSL_CERT_DIR` lookup. | [environment-variables.md](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/configuration/environment-variables.md), [custom-connectors.md](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/configuration/custom-connectors.md) | +| Providers | Mastodon (any instance, out-of-band code, `https` on port 443 only), Pixelfed, PeerTube (password exchanged once for tokens), Bluesky (app password), Facebook Pages, Instagram, Threads, X, YouTube, LinkedIn and TikTok; X, LinkedIn and Threads use env triples, Facebook, Instagram, YouTube and TikTok use `OPENPOST_PROVIDER_APPS`. | [.env.example](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/.env.example) | +| API | REST API with `Idempotency-Key`, publications with per-account renditions, `schedule`, `publish-now`, `retry-failed`, job polling and API tokens. | [openapi.json](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/web/openapi.json) | +| Cost control | `OPENPOST_X_MONTHLY_BUDGET_MICROUSD` and per-post cost settings cap X spending. | [.env.example](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/.env.example) | + +### Egress proof + +Inside the development stack, sibling domains such as `*.infinito.test` resolve to the private stack address, and in split-horizon or WireGuard deployments they resolve to private or mesh addresses (`NETWORK_MESH_POOL` is `10.100.0.0/16`), so the unmodified image refuses them. +A role-local egress relay solves this without touching OpenPost: OpenPost reaches the deployment's sibling vhosts through network aliases on a Docker network whose subnet lies outside the guard's ranges, and the relay forwards the untouched TLS stream by SNI to the shared proxy. +The design was proven on 2026-10-21 against the unmodified `ghcr.io/getopenpost/openpost:v7.22.9` with an `nginx:1.30.6-alpine` stream relay on `192.88.99.0/24` (the deprecated 6to4 relay anycast block, RFC 7526) in the compose development stack: + +| Check | Observed result | +|---|---| +| Aliased name forwarded to a Mastodon stub | Mastodon app registration succeeded; the stub received `POST /api/v1/apps` for `microblog.infinito.test`. | +| Aliased name forwarded to the real shared proxy by address | TLS verified against the platform CA through OpenResty; the vhost answered HTTP 404 because it is not a Mastodon instance. | +| Sibling name resolved through normal DNS to the stack address | Rejected: "resolves to a private or local address". | +| Private alias and private IP literal | Rejected by the guard. | +| Aliased name missing from the relay's SNI map | Refused by the relay. | + +### Platform constraints + +| Network | Access path for one organisation | Publish quota | Cost (October 2026) | Token upkeep | Constraint | +|---|---|---|---|---|---| +| Facebook Pages | Own Meta Business app; Standard Access for app-role users without App Review | Reels: 30 per Page per 24 h | No fee found | Long-lived Page tokens do not expire | Development-mode posts are visible only to app-role users | +| Instagram | Professional account via Facebook Login or Instagram Login | 100 per 24 h | No fee found | Instagram Login tokens last 60 days and refresh | JPEG only, fetched from a public URL | +| X | Developer app with prepaid credits | 100 per 15 min per user | $0.015 per post, $0.20 per post with a URL | OAuth 2.0 access tokens refresh via `offline.access` | Identical content across own accounts is forbidden | +| YouTube | Google OAuth client in production status | 100 `videos.insert` calls per day | No fee found | Testing-status refresh tokens expire after 7 days | Private-upload rule for unverified projects is contradictory | +| LinkedIn | Community Management API with legal-entity vetting | Development tier: 500 calls per app per day | No fee found | 60-day tokens without refresh | Human re-authorisation every 60 days | +| Threads | Meta app with `threads_content_publish` | 250 per 24 h | No fee found | 60 days, refreshable | 500 characters per post | +| TikTok | Content Posting API plus audit | About 15 per creator per day | No fee found | Not researched | In-house upload tools are an unacceptable use case | +| Bluesky | App password or atproto OAuth | About 1,666 creates per hour | No fee found | Up to 180 days | Already reachable through `web-app-bridgy-fed` | + +Sources: + +- [X pricing](https://docs.x.com/x-api/getting-started/pricing) +- [Meta access levels](https://developers.facebook.com/docs/graph-api/overview/access-levels) +- [Instagram publishing](https://developers.facebook.com/docs/instagram-platform/content-publishing) +- [YouTube quota costs](https://developers.google.com/youtube/v3/determine_quota_cost) +- [LinkedIn app review](https://learn.microsoft.com/en-us/linkedin/marketing/community-management-app-review) +- [TikTok content sharing guidelines](https://developers.tiktok.com/doc/content-sharing-guidelines) +- [Bluesky rate limits](https://docs.bsky.app/docs/advanced-guides/rate-limits) + +### In-repo analogues + +- [`web-app-nextcloud`](../../roles/web-app-nextcloud/), [`web-app-mastodon`](../../roles/web-app-mastodon/), [`web-app-fider`](../../roles/web-app-fider/), [`web-app-penpot`](../../roles/web-app-penpot/) and [`web-app-discourse`](../../roles/web-app-discourse/) relax their own SSRF guards through native switches; OpenPost has none for built-in providers, which is why the relay exists. +- [container_extra_hosts.py](../../plugins/lookup/container_extra_hosts.py) already resolves the address that reaches the shared proxy per deploy mode for the SSO back-channel pin; the relay forwards to the same address. +- [`svc-net-wireguard`](../../roles/svc-net-wireguard/) carries swarm overlay traffic inside its `swarm` mesh, so the role's overlay network is tunnelled without extra configuration. +- [`web-app-semaphore`](../../roles/web-app-semaphore/) consumes Keycloak through `sso.flavor: oidc`. +- [`web-app-mastodon`](../../roles/web-app-mastodon/), [`web-app-pixelfed`](../../roles/web-app-pixelfed/) and [`web-app-peertube`](../../roles/web-app-peertube/) provide the local Fediverse accounts used as publishing targets in tests. +- [`web-svc-seaweedfs`](../../roles/web-svc-seaweedfs/) provides S3 object storage through the `seaweedfs` service with `public: true`, as in `web-app-mastodon`. +- [18_api.yml](../../group_vars/all/18_api.yml) is the central SPOT for proprietary API credentials, read through `lookup('api', ...)` and gated by `lookup('api_enabled', ...)`. + +## Confirmed Decisions + +These decisions were confirmed by the operator before implementation starts and are NOT subject to re-litigation during implementation. + +| # | Decision | Reason | +|---|---|---| +| 1 | OpenPost is the publishing desk. | Only candidate covering every required source and target network. | +| 2 | Role id `web-app-openpost`, canonical domain `publish.{{ DOMAIN_PRIMARY }}`. | `social.{{ DOMAIN_PRIMARY }}` belongs to `web-app-friendica`. | +| 3 | The role runs the official `ghcr.io/getopenpost/openpost` image unmodified, pinned to a release tag and configured through environment variables only. | The application is integrated like every other role; the project does not maintain OpenPost. | +| 4 | OpenPost reaches the deployment's own sibling vhosts only through an always-on, role-local egress relay on the role network `192.88.99.0/24` (declared in `meta/networks.yml` with `outside_pool: true`, which `NETWORK_ROLE_SUBNET_EXCEPTION_ROLES` collects), with exact aliases and an SNI allowlist, forwarding to the shared proxy. | One proven path for development, CI and production, including split-horizon DNS and WireGuard meshes, with the guard intact for every other destination; the existing role-subnet exception mechanism already carries out-of-pool blocks, so no new SPOT is needed. | +| 5 | Keycloak SSO through native OIDC (`sso.flavor: oidc`); publishing permissions are enforced through OpenPost workspace roles. | OpenPost ships an OIDC adapter and does not consume group claims. | +| 6 | Shared `svc-db-postgres`; media on `web-svc-seaweedfs` S3 when deployed, a role volume otherwise. | Postgres is the only multi-process database; S3 gives public media URLs for Meta. | +| 7 | One `all` process with one replica in compose and swarm. | State lives in Postgres and S3, so rescheduling is safe; split `web`/`worker` scaling is out of scope. | +| 8 | Provider app credentials live in the central `API` SPOT. | One place for proprietary credentials. | +| 9 | Diagnostics, update check, PostHog telemetry, feedback and public profiles are disabled. | No unnecessary transmission of internal data. | +| 10 | CI tests Fediverse publishing end to end against local instances through the relay, and the commercial adapters against a role-local provider simulator on the same role network; real platforms are checked manually in staging. | Real OAuth logins, public redirect hosts and per-post billing make real platforms unusable in CI. | +| 11 | Automated crossposting is a separate sidecar specified in [063](063-openpost-crossposter.md). | Separable deliverable and pull request. | + +## Target Schema + +### Role layout + +``` +roles/web-app-openpost/ +├── Administration.md +├── README.md +├── files/ +│ ├── playwright/ +│ │ ├── _shared.js +│ │ ├── playwright.spec.js +│ │ └── test-*.js +│ ├── simulator/ +│ └── test/ +│ ├── probe.py +│ └── test.sh +├── meta/ +│ ├── csp.yml +│ ├── domains.yml +│ ├── info.yml +│ ├── main.yml +│ ├── networks.yml +│ ├── rbac.yml +│ ├── secrets.yml +│ ├── services.yml +│ ├── tests.yml +│ ├── users.yml +│ ├── variants.yml +│ └── volumes.yml +├── tasks/ +│ ├── 00_core.yml +│ ├── 01_fediverse_apps.yml +│ ├── 02_simulator.yml +│ ├── 03_breakglass.yml +│ └── main.yml +├── templates/ +│ ├── compose.yml.j2 +│ ├── env.j2 +│ ├── playwright.env.j2 +│ ├── relay.conf.j2 +│ └── test.env.j2 +└── vars/ + └── main.yml +``` + +`templates/relay.conf.j2` renders the relay's SNI map from the deployed sibling vhosts; `files/simulator/` holds the provider simulator mappings. + +### `meta/services.yml` excerpt (proposed shape) + +```yaml +openpost: + image: ghcr.io/getopenpost/openpost + version: "v7.22.9" + update: + type: registry_tags + ports: + internal: + http: 8080 + local: + http: 8100 + lifecycle: alpha +relay: + image: nginx + version: 1.31.7-alpine +simulator: + enabled: false + image: wiremock/wiremock + version: "3.13.2" +``` + +## Acceptance Criteria + +### Evaluation and documentation (story AC1) + +- [x] `roles/web-app-openpost/Administration.md` documents, per network (Mastodon, Pixelfed, PeerTube, Facebook Pages, Instagram, X, YouTube, LinkedIn, Threads, TikTok, Bluesky), the supported post types, the developer app and account type, the required scopes, review or verification steps, quotas, costs and token upkeep. +- [x] `Administration.md` lists every unsupported feature with its workaround, including TikTok's ban on in-house upload tools, the X link surcharge, Instagram's JPEG and public-URL rule, LinkedIn vetting and Bluesky reach through `web-app-bridgy-fed`. +- [x] `Administration.md` documents data processing (which data each platform receives), third-party dependencies, and licence compatibility of the unmodified AGPL-3.0-only application with the role's own licence. +- [x] `Administration.md` contains a staging checklist and a verified-combinations matrix (network, content type, OpenPost version, date) for manual checks of the real platforms. + +### Image and configuration (story AC2) + +- [x] The role runs `ghcr.io/getopenpost/openpost` pinned to a release tag in `meta/services.yml` and ships no role-local Dockerfile or source modification. +- [x] The external update tooling proposes new upstream release tags through `update.type: registry_tags`. +- [x] Every OpenPost setting is rendered through `templates/env.j2`, and `OPENPOST_APP_URL` and `OPENPOST_PUBLIC_URL` carry `https://publish.{{ DOMAIN_PRIMARY }}`. + +### Egress relay (story AC2, AC4, AC7) + +- [ ] `roles/web-app-openpost/meta/networks.yml` declares the role subnet `192.88.99.0/24`, a block outside every range OpenPost's guard rejects and outside every Docker, mesh, Tor and role subnet pool, and sets `outside_pool: true` next to it, which `NETWORK_ROLE_SUBNET_EXCEPTION_ROLES` in `group_vars/all/08_networks.yml` collects through `lookup('role_subnet_exceptions')`; the network is a bridge in compose and an overlay in swarm. +- [x] A `relay` entity running a pinned `nginx` image carries network aliases, declared as `services.relay.network_aliases` in `meta/services.yml` and read by the shared `container_networks` lookup, only for the canonical domains of the deployed sibling roles OpenPost publishes to (`web-app-mastodon`, `web-app-pixelfed`, `web-app-peertube`), each gated by that role's dynamic service flag. +- [ ] The relay forwards TLS unmodified by SNI to `host.docker.internal`, which `container_extra_hosts` resolves to the address that reaches the shared proxy in the effective deploy mode, and never resolves its own aliases. +- [x] The relay refuses every SNI that is not in its map. +- [x] When `TLS_MODE` is self-signed, OpenPost trusts the platform CA so that relayed vhosts verify; with public certificates no extra trust is configured. +- [x] The CLI test proves that OpenPost reaches an aliased sibling vhost, that it still rejects a private container name and a private IP literal, and that the relay refuses a TLS connection whose SNI is not in its map. +- [ ] Publishing to a local Mastodon account succeeds in swarm through the role's overlay network, verified by `make roundtrip apps="web-app-openpost"`. +- [x] `Administration.md` explains the guard, the relay, and how a deployment with sibling vhosts on another host or behind split-horizon DNS is covered. + +### Deployment and operations (story AC2) + +- [x] `publish.{{ DOMAIN_PRIMARY }}` serves the OpenPost UI through the shared OpenResty proxy with TLS and a `Content-Security-Policy` header, and `/api/v1/ready` returns HTTP 200. +- [ ] The role deploys green in compose (`make compose-deploy mode=reinstall apps=web-app-openpost full_cycle=true`) and in swarm, with one `all` replica and no reliance on `container_name`. +- [x] OpenPost stores its data in `svc-db-postgres`, and no SQLite database exists in the container. +- [x] With `web-svc-seaweedfs` deployed, media lands in S3 and an uploaded file is fetchable anonymously over HTTPS from its public URL; without it, media lands in a role volume served under `/media/`. +- [x] Media URLs and `/api/v1/accounts//callback` are reachable without a session, while every other UI and API route requires authentication. +- [x] The container healthcheck probes `/api/v1/health`, and the deploy waits for `/api/v1/ready`. +- [x] Database and media are part of the platform backup, and a restore drill (purge, restore, redeploy) brings back users, connected accounts and publications. +- [x] Changing the pinned version and redeploying migrates the schema without manual steps. +- [x] OpenPost sends mail through the platform mail service resolved by `lookup('email', application_id)`. + +### Secrets and provider credentials (story AC2, AC7) + +- [x] The JWT secret, encryption key and media signing key are generated through `meta/secrets.yml`, the OIDC client secret comes from `OIDC.CLIENT.SECRET`, and all of them reach OpenPost through the role's env file like every other role's secrets. +- [x] The break-glass instance admin `web-app-openpost-breakglass` is declared in `meta/users.yml` with a generated password, is bootstrapped as the first account on a fresh instance, and its e-mail differs from every Keycloak user so just-in-time provisioning never collides with it. +- [x] `group_vars/all/18_api.yml` gains the entries `x`, `meta`, `threads`, `linkedin`, `youtube` and `tiktok`, and the role renders them into `X_CLIENT_*`, `THREADS_CLIENT_*`, `LINKEDIN_CLIENT_*` and `OPENPOST_PROVIDER_APPS`. +- [x] A provider whose `lookup('api_enabled', ...)` is false cannot be connected in the UI. +- [x] Connected provider tokens are stored encrypted, verified by reading the token column from Postgres and finding no plaintext token. +- [x] `Administration.md` documents that OpenPost's X budget guardrail (`OPENPOST_X_MONTHLY_BUDGET_MICROUSD`) applies only in its cloud edition, so a self-hosted deployment caps X spending through the prepaid credits of the X developer account. + +### Single sign-on (story AC3) + +- [x] `meta/services.yml` declares `sso.flavor: oidc`, and OpenPost reads its issuer from `OIDC.CLIENT.ISSUER_URL`, its client from `OIDC.CLIENT.ID` and `OIDC.CLIENT.SECRET`, and uses the scopes `openid profile email`. +- [x] Password self-registration is closed and SSO users are provisioned just in time on their first login; because OpenPost gates both with `OPENPOST_DISABLE_REGISTRATIONS`, the role keeps the switch open when Keycloak is deployed and the shared proxy answers `POST /api/v1/auth/register` with HTTP 403. +- [x] The platform administrator becomes instance administrator through `OPENPOST_OIDC_BOOTSTRAP_ALLOWLIST` on first SSO login. +- [x] A just-in-time provisioned user without a workspace invitation cannot see or use the organisation workspace or its connected accounts. +- [x] `Administration.md` documents the break-glass procedure (`OPENPOST_SSO_BREAK_GLASS_EMAILS`), linking an existing account to its SSO identity, and the trusted-proxy fallback through oauth2-proxy. +- [x] `README.md` documents that OpenPost ships no LDAP adapter, so the role declares no `ldap` service and directory accounts sign in through Keycloak's OpenLDAP federation over OIDC. + +### Telemetry and data minimisation (story AC7) + +- [x] `OPENPOST_DIAGNOSTICS_ENABLED`, `OPENPOST_UPDATE_CHECK_ENABLED`, `OPENPOST_TELEMETRY_ENABLED`, `OPENPOST_FEEDBACK_ENABLED` and `OPENPOST_PUBLIC_PROFILES_ENABLED` are rendered as `false`, and the CLI test asserts it through the running instance. + +### Fediverse publishing (story AC4) + +- [x] The deploy registers an `OpenPost` app once on each deployed sibling Mastodon and Pixelfed instance, persists it, and pins it through `MASTODON_SERVERS` and `PIXELFED_SERVERS` named by the canonical URL, because the dynamic registration path of v7.22.9 fails its own readiness check on code exchange. +- [x] An administrator connects a local Mastodon account through the out-of-band code flow and publishes a text post that appears on the Mastodon instance. +- [x] An administrator connects a local Pixelfed account and publishes an image post that appears on the Pixelfed instance. +- [x] An administrator connects a local PeerTube account and publishes a video that appears on the PeerTube instance. + +### Provider simulator (story AC4, AC8) + +- [x] A `simulator` entity running the pinned `wiremock/wiremock` image is enabled by one `meta/variants.yml` variant only and is absent from the base configuration. +- [x] Inside that variant, the simulator joins the role network with aliases for the API hostnames OpenPost uses for X, Facebook, Instagram, YouTube, LinkedIn and TikTok, presents a certificate for those names signed by a per-deploy test CA, and OpenPost trusts that CA. +- [x] An X, Facebook Page, Instagram, YouTube, LinkedIn and TikTok account each connect through OpenPost's real callback against the simulator without a real provider login. +- [x] Publishing to those accounts produces the documented request sequence, asserted from the simulator's request journal: one X post within 280 weighted characters, one Facebook Page post, an Instagram media container followed by a publish call with a public JPEG URL, a resumable YouTube upload, one LinkedIn post, and one TikTok photo post followed by a status poll. +- [x] A simulated 429 response with a reset header is retried automatically and ends in exactly one successful delivery. +- [x] A simulated 503 response to a write leaves the destination in OpenPost's manual review instead of resending it, because OpenPost treats it as an ambiguous delivery; publishing the post again to that destination alone ends in exactly one successful delivery. +- [x] A permanent 4xx response leaves the rendition in a failed state that the UI shows together with the provider error, which OpenPost v7.22.9 reports as the provider's HTTP status and the reason `provider_rejected`. + +### Publishing management (story AC6) + +- [x] A post published immediately reaches the local Mastodon target, and a post scheduled two minutes ahead reaches its simulated destination exactly once and not before its time. +- [x] Every destination shows its state (scheduled, published, failed) and a failed destination can be retried alone. +- [x] Two accounts of the same network can be connected in one workspace and selected together for one publication. +- [x] A workspace member with a role that cannot publish is refused when publishing, while an editor succeeds. + +### Variants, tests and quality (story AC8) + +- [x] `meta/variants.yml` stays within the three-variant limit: variant 0 enables every integration but the onion, the simulator and the local Mastodon target, variant 1 adds the local Pixelfed and PeerTube targets with the integrations off, and variant 2 switches everything off, so no single round deploys all three instances; every variant deploys cleanly on a fresh host. +- [x] `files/playwright/` covers the `guest`, `biber` and `administrator` personas per the [Playwright contract](../contributing/artefact/files/role/playwright.specs.js.md), with the administrator connecting a Fediverse account and publishing, and `biber` being denied the organisation workspace. +- [x] `files/test/test.sh` with `templates/test.env.j2` covers readiness, the telemetry flags, the egress relay and its negative controls, token encryption at rest, Fediverse delivery and the simulator journal assertions. +- [ ] `make compose-playwright role=web-app-openpost` exits 0 without stub tests and ends logged out. +- [ ] `make roundtrip apps="web-app-openpost"` is green in compose and swarm. +- [ ] `make test` is green tree-wide. + +### Role documentation + +- [x] `README.md` follows the [role README rules](../contributing/artefact/files/role/readme_md.md) and states the image and bump policy, the egress relay, the SSO model and the telemetry defaults; `meta/services.yml` declares the `relay` entity that the documentation build draws into the role's Cosmos diagram. +- [ ] This requirement is cross-linked from the implementing pull request and from the OpenProject work item. + +## Validation Apps + +```bash +INFINITO_PLAYWRIGHT_KEEP=true make compose-deploy mode=reinstall apps=web-app-openpost full_cycle=true +make roundtrip apps="web-app-openpost" +``` + +Smoke: open `https://publish.{{ DOMAIN_PRIMARY }}/`, sign in through Keycloak, connect the local Mastodon account, publish a post and find it on the Mastodon instance. + +## Prerequisites + +Before implementation, the agent MUST read [AGENTS.md](../../AGENTS.md), then [Compose Loop](../agents/action/iteration/compose.md), [Swarm Loop](../agents/action/iteration/swarm.md) and the [Playwright contract](../contributing/artefact/files/role/playwright.specs.js.md). + +## Implementation Strategy + +Execute autonomously and start from the proven egress topology: the role network on `192.88.99.0/24`, an nginx `stream` relay with `ssl_preread` and an SNI map, and OpenPost attached to that network. +Verify against the pinned upstream image before claiming a criterion: the provider hostnames and OAuth endpoints the simulator must answer, how OpenPost validates the OAuth `state` on its callback, and the account-linking flow. +Prove every relay and simulator change in the live stack via `make compose-exec` and `make compose-inner-run` before redeploying. + +## Commit Policy + +- No git commit until every Acceptance Criterion is checked off. +- When met and `make test` is green, instruct the operator to run `git-sign-push` outside the sandbox. The agent MUST NOT push. + +## See Also + +- Automated crossposting: [063-openpost-crossposter.md](063-openpost-crossposter.md) +- Requirement format: [requirements.md](../contributing/requirements.md) +- How agents process requirements: [requirements.md](../agents/action/requirements.md) diff --git a/docs/requirements/063-openpost-crossposter.md b/docs/requirements/063-openpost-crossposter.md new file mode 100644 index 0000000000..16bbdf5212 --- /dev/null +++ b/docs/requirements/063-openpost-crossposter.md @@ -0,0 +1,253 @@ +# 063 - OpenPost Crossposter for Automated Fediverse Crossposting + +## User Story + +As an Infinito.Nexus PR manager, I want new posts on our organisation's Mastodon, Pixelfed and PeerTube accounts to be detected and distributed automatically through the OpenPost desk to the selected Fediverse and commercial networks, with optional review, duplicate prevention, retries and attribution, so that one post reaches every audience without duplicated work. + +## Background + +This requirement implements the crossposting half of the OpenProject user story "sovereign social media publishing and crossposting" (story criterion AC5 and the crossposting part of AC8). +It builds on [062-web-app-openpost.md](062-web-app-openpost.md), which delivers the OpenPost desk, the egress relay to the deployment's Fediverse instances, the connected Fediverse targets and the provider simulator for X, Facebook, Instagram and YouTube. +OpenPost's session cookies only accept same-origin requests, so programmatic access uses Bearer API tokens (observed in the 062 egress proof on 2026-10-21). + +No evaluated product forwards Fediverse posts unattended. +OpenPost's built-in workflows refuse to schedule unless a human approves the exact revision in the same run, and its native imports never dispatch automation ([runtime.go](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/server/internal/services/workflows/runtime.go)). +Postiz turns feeds into drafts without media, and Ferryman is a closed SaaS. +The crossposter therefore lives in the role as a sidecar that detects posts, applies routing, prevents duplicates and drives OpenPost through its API. + +### Upstream facts established by research + +| Topic | Finding | Source | +|---|---|---| +| Mastodon detection | `GET /api/v1/accounts/:id/statuses` accepts a `min_id` cursor plus `exclude_replies`, `exclude_reblogs`, `only_media` and `tagged`; cursor paging is limited to 300 requests per 15 minutes. | [Mastodon accounts API](https://docs.joinmastodon.org/methods/accounts/), [rack_attack.rb](https://github.com/mastodon/mastodon/blob/v4.7.3/config/initializers/rack_attack.rb) | +| Mastodon loop signal | A status fetched with the owner's token exposes the `application` that posted it. | [status_serializer.rb](https://github.com/mastodon/mastodon/blob/v4.7.3/app/serializers/rest/status_serializer.rb) | +| Mastodon push | Admin webhooks fire only for local posts, have no delete event and are dropped after 16 retries. | [webhook.rb](https://github.com/mastodon/mastodon/blob/main/app/models/webhook.rb) | +| Pixelfed detection | The Mastodon-compatible API requires a token even for public posts and ignores `exclude_reblogs`; the Atom feed is opt-in, photo-only, limited to 10 posts and cached for 4 hours. | [ApiV1Controller.php](https://github.com/pixelfed/pixelfed/blob/v0.15.1/app/Http/Controllers/Api/ApiV1Controller.php), [ProfileController.php](https://github.com/pixelfed/pixelfed/blob/v0.15.1/app/Http/Controllers/ProfileController.php) | +| PeerTube detection | Video lists paginate by offset only; sorting by `-publishedAt` and deduplicating on `uuid` works; no webhook or plugin hook fires when a video becomes published. | [PeerTube OpenAPI](https://github.com/Chocobozzz/PeerTube/blob/v8.3.1/support/doc/api/openapi.yaml) | +| PeerTube media | Default installs keep only HLS files; one MP4 comes from a combined HLS file or the `generate` endpoint; downloads are throttled to 2 MB/s per IP by default. | [default.yaml](https://github.com/Chocobozzz/PeerTube/blob/v8.3.1/config/default.yaml) | +| Idempotency | Mastodon and Pixelfed honour `Idempotency-Key` for one hour, PeerTube has none, and OpenPost answers a reused key with different input with HTTP 409. | [post_status_service.rb](https://github.com/mastodon/mastodon/blob/v4.7.3/app/services/post_status_service.rb), [OpenPost API reliability](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/docs/content/docs/automate/api/reliability.mdx) | +| OpenPost publish API | `POST /api/v1/publications` takes the workspace, title, source text, target accounts or a social set, renditions, media, metadata and an optional `scheduled_at`; `publish-now`, `events` and media upload sessions complete the flow. | [openapi.json](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/apps/web/openapi.json) | +| Length rules | Mastodon counts graphemes of content warning plus text with 23 per URL; X weights emoji and CJK characters double; Threads allows 500 characters; Instagram allows 2,200 characters and 30 hashtags. | [status_length_validator.rb](https://github.com/mastodon/mastodon/blob/v4.7.3/app/validators/status_length_validator.rb), [X counting](https://docs.x.com/fundamentals/counting-characters) | +| Media rules | Pixelfed rejects text-only posts; Mastodon caps video at 99 MB; Instagram accepts JPEG only. | [ApiV1Controller.php](https://github.com/pixelfed/pixelfed/blob/v0.15.1/app/Http/Controllers/Api/ApiV1Controller.php), [media_attachment.rb](https://github.com/mastodon/mastodon/blob/v4.7.3/app/models/media_attachment.rb), [062 platform constraints](062-web-app-openpost.md#platform-constraints) | +| Test tokens | Mastodon disables the password grant and `tootctl` mints no tokens; PeerTube offers a password grant; Pixelfed issues personal access tokens. | [doorkeeper.rb](https://github.com/mastodon/mastodon/blob/v4.7.3/config/initializers/doorkeeper.rb), [tootctl](https://docs.joinmastodon.org/admin/tootctl/) | +| X cost | A post costs $0.015, a post containing a URL costs $0.20. | [X pricing](https://docs.x.com/x-api/getting-started/pricing) | + +### In-repo analogues + +- `web-app-openpost` from [062](062-web-app-openpost.md) provides the desk, the API, the provider simulator and the local Fediverse targets. +- [`web-app-bluesky`](../../roles/web-app-bluesky/) builds its sidecar from `files/login-broker/Dockerfile`. +- `roles/web-app-n8n/files/python/provision/` is tested from `tests/unit/python/roles/web-app-n8n/files/provision/`, the pattern for role-local Python tests. + +## Confirmed Decisions + +These decisions were confirmed by the operator before implementation starts and are NOT subject to re-litigation during implementation. + +| # | Decision | Reason | +|---|---|---| +| 1 | The crossposter is a Python sidecar entity `crossposter` in `web-app-openpost`, built from `files/crossposter/Dockerfile`. | Operator decision over n8n workflows and OpenPost's approval-gated workflows. | +| 2 | Every publication goes through the OpenPost API; the crossposter never calls a target platform directly. | One place for tokens, delivery state and provider adapters. | +| 3 | Detection uses authenticated REST polling with persisted cursors. | The only method that is complete on Mastodon, Pixelfed and PeerTube. | +| 4 | Crossposting state lives in a `crossposter` schema of the role's Postgres database, unique per source post and target account. | Durable duplicate prevention independent of platform idempotency windows. | +| 5 | Routes are declared in the inventory with a `review` mode (OpenPost draft) and an `auto` mode (immediate publishing). | Configurable routing with optional manual approval. | +| 6 | CI covers Mastodon, Pixelfed and PeerTube as sources against local instances, Fediverse targets end to end, and commercial targets through the 062 provider simulator. | Operator decision on automated testing. | +| 7 | New routes start in `review` mode. | Routes are cleared for unattended publishing one by one. | +| 8 | Activating a route forwards no existing posts; its cursor starts at the newest item. | Prevents flooding targets with the account history. | +| 9 | The opt-out hashtag is `nocrosspost`. | Authors can keep a single post local. | +| 10 | The X attribution template omits the source link. | A post with a URL costs about 13 times more on X. | +| 11 | One active instance, enforced by a Postgres advisory lock. | Two pollers would race for the same cursors. | +| 12 | Dead-lettered items are reported by email through the platform mail service. | Failures reach the PR team without another dashboard. | +| 13 | The end-to-end journey reaches commercial networks through a stateful fake provider owned by the role, piloted on LinkedIn; real provider sandboxes are not used in CI. | Meta has paused programmatic test users, LinkedIn test profiles are created by hand only, X and YouTube offer no sandbox, and CI runs must stay offline, deterministic and free of real accounts. | +| 14 | The fake is a role-local Python sidecar entity `provider`, enabled with the simulator; the simulator keeps answering for every network the fake does not serve yet. | Networks move to the fake one at a time without losing coverage. | + +## Target Schema + +### Files + +``` +roles/web-app-openpost/files/crossposter/ +├── Dockerfile +└── requirements.txt +roles/web-app-openpost/files/provider/ +└── Dockerfile +roles/web-app-openpost/files/python/ +├── crossposter/ +│ ├── __init__.py +│ ├── __main__.py +│ ├── adapt.py +│ ├── config.py +│ ├── notify.py +│ ├── openpost.py +│ ├── retry.py +│ ├── service.py +│ ├── store.py +│ ├── web.py +│ └── sources/ +│ ├── __init__.py +│ ├── mastodon.py +│ ├── peertube.py +│ └── pixelfed.py +└── provider/ + ├── __init__.py + ├── __main__.py + ├── linkedin.py + └── store.py +roles/web-app-openpost/files/sql/crossposter/ +├── create/.sql schema statements crossposter/store.py runs on start +├── select/.sql the reads it runs +└── .sql the writes, one file each; the tree is staged into the image as crossposter/sql/ +tests/unit/python/roles/web-app-openpost/files/crossposter/ +tests/unit/python/roles/web-app-openpost/files/provider/ +``` + +### Route shape (proposed) + +```yaml +crossposter: + enabled: false + poll_interval_seconds: 60 + opt_out_tag: nocrosspost + retry: + max_attempts: 8 + base_seconds: 30 + cap_seconds: 3600 + notify: + recipients: [] + routes: + - name: press-mastodon + source: + platform: mastodon + base_url: "https://microblog.{{ DOMAIN_PRIMARY }}" + account: press + token: "{{ vault_crosspost_press_mastodon_token }}" + filters: + visibility: [public] + exclude_replies: true + exclude_reblogs: true + tags: [] + media: any + targets: + social_set: Commercial + mode: review + attribution: + default: "{text}\n\n{source_url}" + x: "{text}" +``` + +## Acceptance Criteria + +### Packaging and lifecycle + +- [x] The `crossposter` entity is built from `files/crossposter/Dockerfile` on a Python base image pinned in `meta/services.yml` and passed as an `ARG` without default, and it runs as a non-root user. +- [ ] Its container healthcheck works on the slim base image without extra binaries. +- [ ] The entity is enabled only when at least one route is configured, and the role deploys green with and without it in compose and swarm. +- [ ] A second crossposter instance neither polls nor publishes while the first holds the Postgres advisory lock. +- [ ] The crossposter authenticates to OpenPost with a Bearer API token that the deploy provisions non-interactively for the organisation workspace, and it reaches OpenPost directly on the role network, not through the egress relay. +- [ ] The crossposter's own requests to Mastodon, Pixelfed and PeerTube resolve the sibling vhosts the same way as the relay does, so detection works in compose, swarm and mesh deployments. + +### Configuration + +- [ ] Routes are read from `services.crossposter.routes`, and an invalid route (unknown platform, missing token, unknown target) fails the deploy with a message naming the route and the field. +- [x] Source tokens come from the vault-encrypted inventory and reach the container as files, never as environment variables. + +### Detection + +- [ ] New public statuses of a configured Mastodon account are detected through `GET /api/v1/accounts/:id/statuses` with a persisted `min_id` cursor, excluding replies and boosts. +- [ ] New posts of a configured Pixelfed account are detected through its API with a token. +- [ ] New videos of a configured PeerTube channel are detected by sorting on `-publishedAt`, and only videos in the published state with public privacy are forwarded. +- [ ] At the configured interval, polling stays within each platform's documented rate limits. +- [ ] Activating a route on an account with existing posts forwards none of them. +- [ ] Posts created while the crossposter was stopped are forwarded exactly once after it restarts. + +### Routing and approval + +- [ ] Each route maps one source account to OpenPost target accounts or a social set and filters by visibility, hashtag and media. +- [ ] A post carrying the opt-out hashtag is never forwarded. +- [ ] In `review` mode the crossposter creates an unscheduled OpenPost draft that an editor can adjust and schedule in the desk, and in `auto` mode it publishes immediately. +- [ ] A post with a content warning, or with mentions that cannot be mapped to a target network, becomes a draft even on an `auto` route. + +### Duplicate and loop prevention + +- [ ] The `crossposter` schema holds one row per source post URI and target account under a unique constraint, and every OpenPost request carries an `Idempotency-Key` derived from that pair. +- [ ] Replaying source items through a restart, a cursor reset or overlapping polls creates no second publication, verified against OpenPost and the target instances. +- [ ] A status that OpenPost itself published to Mastodon is never forwarded again, so one Mastodon account can be source and target without loops. + +### Adaptation and attribution + +- [ ] Text is shortened to each target's limit with that network's counting rules without breaking words, links or hashtags. +- [ ] Fediverse mentions are rewritten to plain names or profile links for commercial targets. +- [ ] Alt text travels with images to every target that supports it. +- [ ] Images for Instagram are converted to JPEG, Pixelfed targets receive only posts with media, PeerTube videos reach YouTube as one MP4 fetched over the internal network, and PeerTube videos above 99 MB reach Mastodon targets as links. +- [ ] Each route renders an attribution template per target network with the source post URL, and the default X template omits the link. + +### Retries and error reporting + +- [ ] Transient failures (network errors, HTTP 429 and 5xx) from sources and from OpenPost are retried with capped exponential backoff and jitter that honours `Retry-After` and rate-limit reset headers. +- [ ] After the configured maximum attempts, an item enters a dead-letter state and an email naming the source post, the target and the last error reaches the configured recipients through `lookup('email', application_id)`. +- [ ] Delivery failures that OpenPost reports for a crossposted publication are stored in the mapping row and included in the notification. +- [ ] A documented command inside the container lists every crossposted item with its state (pending, drafted, published, failed, dead-lettered). + +### Tests + +- [x] Unit tests under `tests/unit/python/roles/web-app-openpost/files/crossposter/` cover length counting, adaptation, routing filters, the idempotency key, backoff timing and the state machine with fixtures recorded from Mastodon, Pixelfed and PeerTube responses. +- [ ] The CLI test posts as a test user on the local Mastodon, Pixelfed and PeerTube instances and asserts within a bounded time exactly one OpenPost publication per route, one delivered post on the local Fediverse target, and the expected simulator requests for X, Facebook, Instagram and YouTube. +- [ ] The CLI test asserts review mode (draft without delivery), the opt-out hashtag, loop prevention, restart without duplicates, and no forwarding of existing posts on route activation. +- [ ] The CLI test lets the simulator answer 503 before succeeding and asserts one delivery, then forces a permanent failure and asserts the dead-letter state and that the platform mail server accepted the notification for the configured recipients. +- [ ] The Playwright spec shows the administrator persona finding a crossposted draft in the desk, editing it and scheduling it. +- [ ] `make test` and `make roundtrip apps="web-app-openpost"` are green. + +### Fake provider and end-to-end journey + +- [ ] The `provider` entity is built from `files/provider/Dockerfile` on the Python base image pinned in `meta/services.yml`, runs as a non-root user, has a healthcheck that works on the slim image, and is enabled exactly when the simulator is. +- [ ] It answers for `www.linkedin.com` and `api.linkedin.com` on the role network with a certificate OpenPost trusts, and the simulator no longer serves LinkedIn. +- [ ] A person can create an account on the fake's sign-up page, and the account exists only in the fake's state. +- [ ] `GET /oauth/v2/authorization` shows sign-in and consent for OpenPost's client and redirects to the registered callback with a single-use code bound to the client id and redirect URI; `POST /oauth/v2/accessToken` exchanges codes and refresh tokens; `GET /v2/userinfo` describes the signed-in account. +- [ ] `POST /rest/images?action=initializeUpload` and its upload URL store images, `POST /rest/posts` stores a post authored by the token's member and answers its id in `x-restli-id`, and `GET /rest/posts/{id}` returns that post; requests with an unknown token are refused. +- [ ] The Playwright browser reaches the fake's pages under the real LinkedIn host names by routing them to the fake's published plain-HTTP port; tor rounds skip the journey. +- [ ] The Playwright spec walks the journey as the administrator: it signs up a new account on the fake, connects it to OpenPost through the fake's consent page, adds it to the review social set, posts on the local Mastodon, finds the crossposter's draft in the desk, edits it and publishes it, then opens the post through the URL OpenPost recorded, finds the edited text, and finds that post exactly once in the fake's delivery list. +- [ ] The CLI test connects LinkedIn through the fake's code flow instead of calling OpenPost's callback with a fixed code. +- [x] Unit tests under `tests/unit/python/roles/web-app-openpost/files/provider/` cover sign-up, the code and refresh flows, token checks, and storing and reading posts and images. + +### Documentation + +- [x] `Administration.md` documents the route schema with examples, the review and auto modes, the opt-out hashtag, the attribution templates and their X cost impact, token creation per source platform, and the handling of dead-lettered items. +- [x] `README.md` lists automated crossposting under Features, and `meta/services.yml` declares the `crossposter` entity that the documentation build draws into the role's Cosmos diagram. +- [ ] This requirement is cross-linked from the implementing pull request and from the OpenProject work item. + +## Out of Scope + +- Propagating edits and deletions from source posts to targets. +- Push-based detection through Mastodon webhooks, streaming or an ActivityPub follower actor. +- Bluesky as a crossposting target, because federation through `web-app-bridgy-fed` already reaches it. +- TikTok publishing, because TikTok's terms exclude in-house upload tools. +- Serving X, Facebook, Instagram and YouTube from the fake provider; they follow the LinkedIn pilot in later work. + +## Validation Apps + +```bash +INFINITO_PLAYWRIGHT_KEEP=true make compose-deploy mode=reinstall apps=web-app-openpost full_cycle=true +make roundtrip apps="web-app-openpost" +``` + +Smoke: post as a test user on the local Mastodon instance, find the draft in the OpenPost desk, schedule it, and see it on the local Fediverse target and in the simulator journal. + +## Prerequisites + +Every Acceptance Criterion of [062](062-web-app-openpost.md) MUST be checked off before this requirement starts. +The agent MUST read [AGENTS.md](../../AGENTS.md), then [Compose Loop](../agents/action/iteration/compose.md), [Unit Tests](../contributing/actions/testing/unit.md) and the [Playwright contract](../contributing/artefact/files/role/playwright.specs.js.md). + +## Implementation Strategy + +Execute autonomously and write the failing unit tests for the state machine, the idempotency key and the backoff before the code. +Verify against the running OpenPost before claiming a criterion: how an unscheduled publication appears as a draft, how media upload sessions attach files, how long OpenPost keeps idempotency keys, and how a workspace API token is created without a browser. +Verify on the deployed Mastodon, Pixelfed and PeerTube versions that the behaviour cited above from newer upstream releases still holds. + +## Commit Policy + +- No git commit until every Acceptance Criterion is checked off. +- When met and `make test` is green, instruct the operator to run `git-sign-push` outside the sandbox. The agent MUST NOT push. + +## See Also + +- Publishing desk: [062-web-app-openpost.md](062-web-app-openpost.md) +- Requirement format: [requirements.md](../contributing/requirements.md) +- How agents process requirements: [requirements.md](../agents/action/requirements.md) diff --git a/group_vars/all/08_networks.yml b/group_vars/all/08_networks.yml index b4716eb4de..89a7f876db 100644 --- a/group_vars/all/08_networks.yml +++ b/group_vars/all/08_networks.yml @@ -20,8 +20,7 @@ NETWORK_PRIVATE_CIDRS: class_c: "192.168.0.0/16" NETWORK_INTERNAL_CIDRS: "{{ [NETWORK_LOOPBACK_CIDR] + (NETWORK_PRIVATE_CIDRS.values() | list) }}" NETWORK_ROLE_SUBNET_POOL: "{{ NETWORK_PRIVATE_CIDRS.class_c }}" -NETWORK_ROLE_SUBNET_EXCEPTION_ROLES: - - web-app-bigbluebutton +NETWORK_ROLE_SUBNET_EXCEPTION_ROLES: "{{ lookup('role_subnet_exceptions') }}" NETWORK_SWARM_GWBRIDGE_POOL: "{{ NETWORK_PRIVATE_CIDRS.class_b }}" NETWORK_TRUSTED_PROXY_CIDRS: "{{ [NETWORK_LOOPBACK_IPV4, NETWORK_LOOPBACK_IPV6] + (NETWORK_PRIVATE_CIDRS.values() | list) }}" NETWORK_DOCKER_ADDRESS_POOLS: diff --git a/group_vars/all/18_api.yml b/group_vars/all/18_api.yml index 7b4b893809..effd4a3148 100644 --- a/group_vars/all/18_api.yml +++ b/group_vars/all/18_api.yml @@ -26,3 +26,21 @@ API: jira: client_id: "" client_secret: "" + x: + client_id: "" + client_secret: "" + meta: + client_id: "" + client_secret: "" + threads: + client_id: "" + client_secret: "" + linkedin: + client_id: "" + client_secret: "" + youtube: + client_id: "" + client_secret: "" + tiktok: + client_id: "" + client_secret: "" diff --git a/locale/aa/LC_MESSAGES/core.po b/locale/aa/LC_MESSAGES/core.po index 34336cefb5..4e96dd5071 100644 --- a/locale/aa/LC_MESSAGES/core.po +++ b/locale/aa/LC_MESSAGES/core.po @@ -1728,6 +1728,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Selbsokta portallu for samordnet tilgogo til alle eplastret applikasjoner gjennom en tilpassbar tiler og menybrukerintasjen" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ab/LC_MESSAGES/core.po b/locale/ab/LC_MESSAGES/core.po index c156f76c22..a8e2145f8c 100644 --- a/locale/ab/LC_MESSAGES/core.po +++ b/locale/ab/LC_MESSAGES/core.po @@ -1744,6 +1744,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # güvenli ödeme yönetimi için platform msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/af/LC_MESSAGES/core.po b/locale/af/LC_MESSAGES/core.po index 044c74b9a4..860bba7b0d 100644 --- a/locale/af/LC_MESSAGES/core.po +++ b/locale/af/LC_MESSAGES/core.po @@ -1723,6 +1723,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-hostede portal vir enheidlike toegang tot alle uitgebreide toepassings via 'n aanpasbare teggevat en meniuinskript" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ak/LC_MESSAGES/core.po b/locale/ak/LC_MESSAGES/core.po index d09aa4e60e..a3f27ab259 100644 --- a/locale/ak/LC_MESSAGES/core.po +++ b/locale/ak/LC_MESSAGES/core.po @@ -1730,6 +1730,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portalti yadebi na yire ɗọ̀nọ̀ nitori nitori na aṣi aṣi ọ̀pọ̀tọ́nọ̀ tàbẹ̀ nọ̀nà ẹmọ̀njẹtọ̀ fun ọ̀pọ̀tọ́nọ̀ ọ̀pọ̀tọ́nọ̀ na ọ̀pọ̀tọ́nọ̀ tí ó ṣẹlẹ̀ fun ọ̀pọ̀tọ́nọ̀ tàbẹ̀ fun ọ̀pọ̀tọ́nọ̀" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/am/LC_MESSAGES/core.po b/locale/am/LC_MESSAGES/core.po index e57f83c6c6..452f4d7a64 100644 --- a/locale/am/LC_MESSAGES/core.po +++ b/locale/am/LC_MESSAGES/core.po @@ -1750,6 +1750,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/an/LC_MESSAGES/core.po b/locale/an/LC_MESSAGES/core.po index 1f75229c76..13865be083 100644 --- a/locale/an/LC_MESSAGES/core.po +++ b/locale/an/LC_MESSAGES/core.po @@ -1672,6 +1672,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ar/LC_MESSAGES/core.po b/locale/ar/LC_MESSAGES/core.po index 31122c05cf..9944c3de52 100644 --- a/locale/ar/LC_MESSAGES/core.po +++ b/locale/ar/LC_MESSAGES/core.po @@ -1799,6 +1799,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "بوابة مأهولة ذاتيا من أجل الوصول الموحد إلى جميع التطبيقات المنشورة عن طريق وصلة بينية مصممة حسب الطلب والقائمة" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/as/LC_MESSAGES/core.po b/locale/as/LC_MESSAGES/core.po index c4763777f0..0981b7bb4b 100644 --- a/locale/as/LC_MESSAGES/core.po +++ b/locale/as/LC_MESSAGES/core.po @@ -2003,6 +2003,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate # fagin á módin próðugu, og táfvagum safnar msgctxt "role:web-app-pretix:description" diff --git a/locale/av/LC_MESSAGES/core.po b/locale/av/LC_MESSAGES/core.po index 64a5655198..72aae8254e 100644 --- a/locale/av/LC_MESSAGES/core.po +++ b/locale/av/LC_MESSAGES/core.po @@ -2036,6 +2036,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate # gögnar, aðalstöður til netjárar, og skoðastu tónulegar gögnum msgctxt "role:web-app-pretix:description" diff --git a/locale/ay/LC_MESSAGES/core.po b/locale/ay/LC_MESSAGES/core.po index d78262faaf..e736f4863e 100644 --- a/locale/ay/LC_MESSAGES/core.po +++ b/locale/ay/LC_MESSAGES/core.po @@ -1682,6 +1682,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Sul-bun daluwa daluwa a siis a baarsu a kaƙarin aɓarƙarin iya aɓarƙarin kai aɗaba ko aɗaba taimaka da iya koƙoƙa ko yawa" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/az/LC_MESSAGES/core.po b/locale/az/LC_MESSAGES/core.po index 54514f3644..b3190a532a 100644 --- a/locale/az/LC_MESSAGES/core.po +++ b/locale/az/LC_MESSAGES/core.po @@ -1741,6 +1741,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Xüsusi dəstək və menyu interfeyssi ilə bütün istifadə edilmiş proqramlar üçün Self- hosting portalı" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: ollama msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ba/LC_MESSAGES/core.po b/locale/ba/LC_MESSAGES/core.po index 5dd19ae582..e8ee7e97b4 100644 --- a/locale/ba/LC_MESSAGES/core.po +++ b/locale/ba/LC_MESSAGES/core.po @@ -2039,6 +2039,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate # penjualan online, pemeliharaan pendaftaran, dan pembayaran yang aman msgctxt "role:web-app-pretix:description" diff --git a/locale/be/LC_MESSAGES/core.po b/locale/be/LC_MESSAGES/core.po index d621385eb8..f32e20905d 100644 --- a/locale/be/LC_MESSAGES/core.po +++ b/locale/be/LC_MESSAGES/core.po @@ -1811,6 +1811,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # z dostępem online, zarządzaniem rejestrowaniem oraz płatności # zabezpieczonymi msgctxt "role:web-app-pretix:description" diff --git a/locale/bg/LC_MESSAGES/core.po b/locale/bg/LC_MESSAGES/core.po index 66e077f5ad..5f700109e4 100644 --- a/locale/bg/LC_MESSAGES/core.po +++ b/locale/bg/LC_MESSAGES/core.po @@ -1747,6 +1747,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-hosted портал за единен достъп до всички разположени приложения чрез персонализируема плочка и интерфейс меню" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/bh/LC_MESSAGES/core.po b/locale/bh/LC_MESSAGES/core.po index 789fd59f02..62db85bdd0 100644 --- a/locale/bh/LC_MESSAGES/core.po +++ b/locale/bh/LC_MESSAGES/core.po @@ -1728,6 +1728,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/bi/LC_MESSAGES/core.po b/locale/bi/LC_MESSAGES/core.po index 54a2b87071..eb50ab9945 100644 --- a/locale/bi/LC_MESSAGES/core.po +++ b/locale/bi/LC_MESSAGES/core.po @@ -1709,6 +1709,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-hôte portail pour l'accès unifié à tous les applications déployées via une interface de menu et de palette personnalisable" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/bm/LC_MESSAGES/core.po b/locale/bm/LC_MESSAGES/core.po index fd9c82fdd7..006fac333a 100644 --- a/locale/bm/LC_MESSAGES/core.po +++ b/locale/bm/LC_MESSAGES/core.po @@ -1709,6 +1709,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal self-hosted untuk akses yang sejuk ke semua aplikasi yang diluncurkan melalui antologi yang dikustomisasi dan antologi menu" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/bn/LC_MESSAGES/core.po b/locale/bn/LC_MESSAGES/core.po index 8a7b5335cb..3bea8fe97a 100644 --- a/locale/bn/LC_MESSAGES/core.po +++ b/locale/bn/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "স্বনির্বাচিত টালি এবং মেনু ইন্টারফেসের মাধ্যমে সব অ্যাপ্লিকেশনের জন্য একত্রিত করার উদ্দেশ্যে স্ব-পরীক্ষণ বক্স" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/bo/LC_MESSAGES/core.po b/locale/bo/LC_MESSAGES/core.po index 6935a91a80..5313d7eaab 100644 --- a/locale/bo/LC_MESSAGES/core.po +++ b/locale/bo/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/br/LC_MESSAGES/core.po b/locale/br/LC_MESSAGES/core.po index 976d8bd678..d3aeb92e86 100644 --- a/locale/br/LC_MESSAGES/core.po +++ b/locale/br/LC_MESSAGES/core.po @@ -1723,6 +1723,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal self-hostado para acesso unificado a todas as aplicações desembolsadas via interface de tijolo e menu personalizável" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/bs/LC_MESSAGES/core.po b/locale/bs/LC_MESSAGES/core.po index 61881e5f46..2b56c0c6da 100644 --- a/locale/bs/LC_MESSAGES/core.po +++ b/locale/bs/LC_MESSAGES/core.po @@ -1726,6 +1726,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Sloborni portal za zajedničko pristup svega napravljenim aplikačnim dijelovima kroz dostupno tvrtkovu ikonu i rubrični interfejs" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: ollama msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ca/LC_MESSAGES/core.po b/locale/ca/LC_MESSAGES/core.po index ba0152692d..10a874ed1c 100644 --- a/locale/ca/LC_MESSAGES/core.po +++ b/locale/ca/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Un portal auto-ordinador per a accedir unificat a totes les aplicacions que s' usen mitjançant una fitxa i interfície de menú personalitzable" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ce/LC_MESSAGES/core.po b/locale/ce/LC_MESSAGES/core.po index 6215e10db6..4c5267ea39 100644 --- a/locale/ce/LC_MESSAGES/core.po +++ b/locale/ce/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ch/LC_MESSAGES/core.po b/locale/ch/LC_MESSAGES/core.po index a3fa9e6718..b4b6602aef 100644 --- a/locale/ch/LC_MESSAGES/core.po +++ b/locale/ch/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/co/LC_MESSAGES/core.po b/locale/co/LC_MESSAGES/core.po index 851af277c4..9a92e2ca61 100644 --- a/locale/co/LC_MESSAGES/core.po +++ b/locale/co/LC_MESSAGES/core.po @@ -1720,6 +1720,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal autoseñaal voor eenheidse toegang tot alle geplande toepassingen via een aanpasbare blok en menuinterface" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: ollama msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/cr/LC_MESSAGES/core.po b/locale/cr/LC_MESSAGES/core.po index 17d7e7d8cb..ee7c59ee8f 100644 --- a/locale/cr/LC_MESSAGES/core.po +++ b/locale/cr/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/cs/LC_MESSAGES/core.po b/locale/cs/LC_MESSAGES/core.po index e6939e3293..c38d905cb9 100644 --- a/locale/cs/LC_MESSAGES/core.po +++ b/locale/cs/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self- hostovaný portál pro jednotný přístup ke všem nasazeným aplikacím přes přizpůsobitelné dlaždice a menu rozhraní" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/cu/LC_MESSAGES/core.po b/locale/cu/LC_MESSAGES/core.po index 07f3785749..3337b5a46f 100644 --- a/locale/cu/LC_MESSAGES/core.po +++ b/locale/cu/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/cv/LC_MESSAGES/core.po b/locale/cv/LC_MESSAGES/core.po index eae1e6ac53..cd79a303c5 100644 --- a/locale/cv/LC_MESSAGES/core.po +++ b/locale/cv/LC_MESSAGES/core.po @@ -1742,6 +1742,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Індивідуальна порталка для однієї доступу до всієї підключеної програми через налаштувану плитку та інтерфейс мenu" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: ollama msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/cy/LC_MESSAGES/core.po b/locale/cy/LC_MESSAGES/core.po index 49f268f270..afb9fd892b 100644 --- a/locale/cy/LC_MESSAGES/core.po +++ b/locale/cy/LC_MESSAGES/core.po @@ -1691,6 +1691,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal self-hospidol ar ystod y gallwn o drafod ynglŷn ag y bobwiwn wedi bod yn ymhlith, gyda wahân a menydd ariannol cymhleth" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: ollama msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/da/LC_MESSAGES/core.po b/locale/da/LC_MESSAGES/core.po index 78fb7270df..1df146f120 100644 --- a/locale/da/LC_MESSAGES/core.po +++ b/locale/da/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-hosted portal for samlet adgang til alle installerede programmer via en brugervenlig flise og menu interface" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/de/LC_MESSAGES/core.po b/locale/de/LC_MESSAGES/core.po index 5574461fe4..5d5ff907f6 100644 --- a/locale/de/LC_MESSAGES/core.po +++ b/locale/de/LC_MESSAGES/core.po @@ -1723,6 +1723,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Selbst gehostetes Portal für einheitlichen Zugriff auf alle bereitgestellten Anwendungen über eine anpassbare Kachel- und Menüoberfläche" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/dv/LC_MESSAGES/core.po b/locale/dv/LC_MESSAGES/core.po index 72ae2d0e1d..4f366acbc6 100644 --- a/locale/dv/LC_MESSAGES/core.po +++ b/locale/dv/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/dz/LC_MESSAGES/core.po b/locale/dz/LC_MESSAGES/core.po index bd37bcda57..9eb83fd2d4 100644 --- a/locale/dz/LC_MESSAGES/core.po +++ b/locale/dz/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ee/LC_MESSAGES/core.po b/locale/ee/LC_MESSAGES/core.po index 340eb25aff..8ef180b0a6 100644 --- a/locale/ee/LC_MESSAGES/core.po +++ b/locale/ee/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/el/LC_MESSAGES/core.po b/locale/el/LC_MESSAGES/core.po index 7471fe11f8..e9ec795d59 100644 --- a/locale/el/LC_MESSAGES/core.po +++ b/locale/el/LC_MESSAGES/core.po @@ -1738,6 +1738,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Αυτο-φιλοξενούμενη πύλη για ενιαία πρόσβαση σε όλες τις χρησιμοποιούμενες εφαρμογές μέσω μιας προσαρμόσιμης διεπαφής πλακιδίων και μενού" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/eo/LC_MESSAGES/core.po b/locale/eo/LC_MESSAGES/core.po index b666dc5998..bc91924c1f 100644 --- a/locale/eo/LC_MESSAGES/core.po +++ b/locale/eo/LC_MESSAGES/core.po @@ -1732,6 +1732,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Mem-gastigita portalo por unuigita aliro al ĉiuj deplojitaj aplikoj per specialadaptita kahelo kaj menuo interfaco" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/es/LC_MESSAGES/core.po b/locale/es/LC_MESSAGES/core.po index 8101d4f64f..f4b8a391b7 100644 --- a/locale/es/LC_MESSAGES/core.po +++ b/locale/es/LC_MESSAGES/core.po @@ -1727,6 +1727,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal auto hospedado para un acceso unificado a todas las aplicaciones implementadas a través de una interfaz de mosaico y menú personalizable" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/et/LC_MESSAGES/core.po b/locale/et/LC_MESSAGES/core.po index 0023c7d0e9..4757cf8695 100644 --- a/locale/et/LC_MESSAGES/core.po +++ b/locale/et/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Isehostitud portaal, mis võimaldab ühtset juurdepääsu kõigile kasutatud rakendustele kohandatava plaadi- ja menüüliidese kaudu" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/eu/LC_MESSAGES/core.po b/locale/eu/LC_MESSAGES/core.po index 2e5b3ba63e..6d74c66dbb 100644 --- a/locale/eu/LC_MESSAGES/core.po +++ b/locale/eu/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Auto-ostatutako ataria, hedatutako aplikazio guztietarako sarbide bateratua, pertsonalizatutako fitxa eta menu-interfazearen bidez." +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/fa/LC_MESSAGES/core.po b/locale/fa/LC_MESSAGES/core.po index ebe764c2b2..d7891e4408 100644 --- a/locale/fa/LC_MESSAGES/core.po +++ b/locale/fa/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "پورتال خود میزبان برای دسترسی یکپارچه به تمام برنامه های کاربردی از طریق یک کاشی قابل تنظیم و رابط منو" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ff/LC_MESSAGES/core.po b/locale/ff/LC_MESSAGES/core.po index bfdf9209b4..10468aecca 100644 --- a/locale/ff/LC_MESSAGES/core.po +++ b/locale/ff/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/fi/LC_MESSAGES/core.po b/locale/fi/LC_MESSAGES/core.po index 1538ab0b67..da3e15c996 100644 --- a/locale/fi/LC_MESSAGES/core.po +++ b/locale/fi/LC_MESSAGES/core.po @@ -1738,6 +1738,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Itse isännöimä portaali, joka mahdollistaa yhtenäisen pääsyn kaikkiin käytössä oleviin sovelluksiin muokattavissa olevien laattojen ja valikon käyttöliittymän kautta" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/fj/LC_MESSAGES/core.po b/locale/fj/LC_MESSAGES/core.po index fb727d6dd1..ef566927bb 100644 --- a/locale/fj/LC_MESSAGES/core.po +++ b/locale/fj/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/fo/LC_MESSAGES/core.po b/locale/fo/LC_MESSAGES/core.po index 28621bc1e4..e0e31463f9 100644 --- a/locale/fo/LC_MESSAGES/core.po +++ b/locale/fo/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/fr/LC_MESSAGES/core.po b/locale/fr/LC_MESSAGES/core.po index cd2083daa9..89d52ae6b3 100644 --- a/locale/fr/LC_MESSAGES/core.po +++ b/locale/fr/LC_MESSAGES/core.po @@ -1723,6 +1723,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portail autonome pour un accès unifié à toutes les applications déployées via une interface de carrelage et de menu personnalisable" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/fy/LC_MESSAGES/core.po b/locale/fy/LC_MESSAGES/core.po index 6379314941..d9599957b6 100644 --- a/locale/fy/LC_MESSAGES/core.po +++ b/locale/fy/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ga/LC_MESSAGES/core.po b/locale/ga/LC_MESSAGES/core.po index 1720211877..c9d9292808 100644 --- a/locale/ga/LC_MESSAGES/core.po +++ b/locale/ga/LC_MESSAGES/core.po @@ -1744,6 +1744,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Tairseach féin-óstáil le haghaidh rochtain aontaithe ar gach iarratas imscaradh trí tíl customizable agus roghchlár comhéadan" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/gd/LC_MESSAGES/core.po b/locale/gd/LC_MESSAGES/core.po index 4fc8cda3c0..aa9acf320a 100644 --- a/locale/gd/LC_MESSAGES/core.po +++ b/locale/gd/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/gl/LC_MESSAGES/core.po b/locale/gl/LC_MESSAGES/core.po index 4784d5cd5b..74b5c83073 100644 --- a/locale/gl/LC_MESSAGES/core.po +++ b/locale/gl/LC_MESSAGES/core.po @@ -1733,6 +1733,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal auto-hosted para un acceso único a todas as aplicacións despregadas a través dunha interface de menú e tella personalizables." +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/gn/LC_MESSAGES/core.po b/locale/gn/LC_MESSAGES/core.po index 69e4009e83..2c0381ec07 100644 --- a/locale/gn/LC_MESSAGES/core.po +++ b/locale/gn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/gu/LC_MESSAGES/core.po b/locale/gu/LC_MESSAGES/core.po index c1a4243299..0dc4999487 100644 --- a/locale/gu/LC_MESSAGES/core.po +++ b/locale/gu/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/gv/LC_MESSAGES/core.po b/locale/gv/LC_MESSAGES/core.po index 49617bcc70..399688375b 100644 --- a/locale/gv/LC_MESSAGES/core.po +++ b/locale/gv/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ha/LC_MESSAGES/core.po b/locale/ha/LC_MESSAGES/core.po index 0bd6cfabb5..d3bff4aedf 100644 --- a/locale/ha/LC_MESSAGES/core.po +++ b/locale/ha/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/he/LC_MESSAGES/core.po b/locale/he/LC_MESSAGES/core.po index fd5353a0e9..314fc2f7e7 100644 --- a/locale/he/LC_MESSAGES/core.po +++ b/locale/he/LC_MESSAGES/core.po @@ -1741,6 +1741,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "פורטל עוין עצמי לגישה מאוחדת לכל היישומים שנקבעו באמצעות אריח מותאם אישית וממשק התפריט" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/hi/LC_MESSAGES/core.po b/locale/hi/LC_MESSAGES/core.po index b94fd73611..baf6d886cc 100644 --- a/locale/hi/LC_MESSAGES/core.po +++ b/locale/hi/LC_MESSAGES/core.po @@ -1724,6 +1724,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "एक अनुकूलन योग्य टाइल और मेनू इंटरफ़ेस के माध्यम से सभी तैनात अनुप्रयोगों के लिए एकीकृत पहुँच के लिए स्व-होस्टेड पोर्टल" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ho/LC_MESSAGES/core.po b/locale/ho/LC_MESSAGES/core.po index f44d4169c2..7f2ab7ad8e 100644 --- a/locale/ho/LC_MESSAGES/core.po +++ b/locale/ho/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/hr/LC_MESSAGES/core.po b/locale/hr/LC_MESSAGES/core.po index 7cf0f0b1e6..8684113183 100644 --- a/locale/hr/LC_MESSAGES/core.po +++ b/locale/hr/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ht/LC_MESSAGES/core.po b/locale/ht/LC_MESSAGES/core.po index 409c3be112..ea6d76dd5f 100644 --- a/locale/ht/LC_MESSAGES/core.po +++ b/locale/ht/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/hu/LC_MESSAGES/core.po b/locale/hu/LC_MESSAGES/core.po index 9a438b40e1..03075ceaa2 100644 --- a/locale/hu/LC_MESSAGES/core.po +++ b/locale/hu/LC_MESSAGES/core.po @@ -1734,6 +1734,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self- hosted portál az összes telepített alkalmazáshoz való egységes hozzáférés érdekében testreszabható csempe és menüfelület segítségével" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/hy/LC_MESSAGES/core.po b/locale/hy/LC_MESSAGES/core.po index 8bf5ffdc85..632854c7c0 100644 --- a/locale/hy/LC_MESSAGES/core.po +++ b/locale/hy/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/hz/LC_MESSAGES/core.po b/locale/hz/LC_MESSAGES/core.po index 3846aca15b..de70ea6fa0 100644 --- a/locale/hz/LC_MESSAGES/core.po +++ b/locale/hz/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ia/LC_MESSAGES/core.po b/locale/ia/LC_MESSAGES/core.po index 2c1b158495..cf55c7f006 100644 --- a/locale/ia/LC_MESSAGES/core.po +++ b/locale/ia/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/id/LC_MESSAGES/core.po b/locale/id/LC_MESSAGES/core.po index 308d95693c..410fd72b97 100644 --- a/locale/id/LC_MESSAGES/core.po +++ b/locale/id/LC_MESSAGES/core.po @@ -1724,6 +1724,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal bertuan sendiri untuk akses unified ke semua aplikasi yang dipakai melalui tile dan menu antarmuka yang dapat diubah" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ie/LC_MESSAGES/core.po b/locale/ie/LC_MESSAGES/core.po index 568c971bed..bda0fb516f 100644 --- a/locale/ie/LC_MESSAGES/core.po +++ b/locale/ie/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ig/LC_MESSAGES/core.po b/locale/ig/LC_MESSAGES/core.po index 26e1899170..aab5f56222 100644 --- a/locale/ig/LC_MESSAGES/core.po +++ b/locale/ig/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ii/LC_MESSAGES/core.po b/locale/ii/LC_MESSAGES/core.po index 97001220ed..8b073643bc 100644 --- a/locale/ii/LC_MESSAGES/core.po +++ b/locale/ii/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ik/LC_MESSAGES/core.po b/locale/ik/LC_MESSAGES/core.po index 9b86d7738e..226b8f25ce 100644 --- a/locale/ik/LC_MESSAGES/core.po +++ b/locale/ik/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/io/LC_MESSAGES/core.po b/locale/io/LC_MESSAGES/core.po index 1b4d682c28..cfc7d3e7b5 100644 --- a/locale/io/LC_MESSAGES/core.po +++ b/locale/io/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/is/LC_MESSAGES/core.po b/locale/is/LC_MESSAGES/core.po index 56495b9d79..9cde006acf 100644 --- a/locale/is/LC_MESSAGES/core.po +++ b/locale/is/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/it/LC_MESSAGES/core.po b/locale/it/LC_MESSAGES/core.po index 5d4e92aa83..bc5ceda3d5 100644 --- a/locale/it/LC_MESSAGES/core.po +++ b/locale/it/LC_MESSAGES/core.po @@ -1724,6 +1724,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portale self-hosted per l'accesso unificato a tutte le applicazioni implementate tramite un'interfaccia per piastrelle e menu personalizzabile" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/iu/LC_MESSAGES/core.po b/locale/iu/LC_MESSAGES/core.po index fbc7695451..0250b85171 100644 --- a/locale/iu/LC_MESSAGES/core.po +++ b/locale/iu/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ja/LC_MESSAGES/core.po b/locale/ja/LC_MESSAGES/core.po index 98bbb27e5a..320c81540c 100644 --- a/locale/ja/LC_MESSAGES/core.po +++ b/locale/ja/LC_MESSAGES/core.po @@ -1736,6 +1736,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "カスタマイズ可能なタイルとメニューインターフェイスを介してすべての展開されたアプリケーションへの統一されたアクセスのためのセルフホストポータル" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/jv/LC_MESSAGES/core.po b/locale/jv/LC_MESSAGES/core.po index fefd64c301..fdf0b393cc 100644 --- a/locale/jv/LC_MESSAGES/core.po +++ b/locale/jv/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ka/LC_MESSAGES/core.po b/locale/ka/LC_MESSAGES/core.po index 2cdf0627af..ff43b8f26c 100644 --- a/locale/ka/LC_MESSAGES/core.po +++ b/locale/ka/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kg/LC_MESSAGES/core.po b/locale/kg/LC_MESSAGES/core.po index 89d8767823..855aa6f159 100644 --- a/locale/kg/LC_MESSAGES/core.po +++ b/locale/kg/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ki/LC_MESSAGES/core.po b/locale/ki/LC_MESSAGES/core.po index 5b8d590e70..308c254ba6 100644 --- a/locale/ki/LC_MESSAGES/core.po +++ b/locale/ki/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kj/LC_MESSAGES/core.po b/locale/kj/LC_MESSAGES/core.po index e71b139700..9c32f10008 100644 --- a/locale/kj/LC_MESSAGES/core.po +++ b/locale/kj/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kk/LC_MESSAGES/core.po b/locale/kk/LC_MESSAGES/core.po index bc21ef1ef2..a31ea8c9be 100644 --- a/locale/kk/LC_MESSAGES/core.po +++ b/locale/kk/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kl/LC_MESSAGES/core.po b/locale/kl/LC_MESSAGES/core.po index 2116c86be9..27285a601d 100644 --- a/locale/kl/LC_MESSAGES/core.po +++ b/locale/kl/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/km/LC_MESSAGES/core.po b/locale/km/LC_MESSAGES/core.po index a2752ec878..2e3bc281e5 100644 --- a/locale/km/LC_MESSAGES/core.po +++ b/locale/km/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kn/LC_MESSAGES/core.po b/locale/kn/LC_MESSAGES/core.po index 9241d3d623..71590d9730 100644 --- a/locale/kn/LC_MESSAGES/core.po +++ b/locale/kn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ko/LC_MESSAGES/core.po b/locale/ko/LC_MESSAGES/core.po index 6715ca83e1..86c336a922 100644 --- a/locale/ko/LC_MESSAGES/core.po +++ b/locale/ko/LC_MESSAGES/core.po @@ -1739,6 +1739,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "사용자 정의 타일 및 메뉴 인터페이스를 통해 모든 배포 응용 프로그램에 통합 된 액세스를위한 셀프 호스팅 포털" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/kr/LC_MESSAGES/core.po b/locale/kr/LC_MESSAGES/core.po index 50104a2e2f..82fbd9d811 100644 --- a/locale/kr/LC_MESSAGES/core.po +++ b/locale/kr/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ks/LC_MESSAGES/core.po b/locale/ks/LC_MESSAGES/core.po index c99fb095eb..aa6a0d14ca 100644 --- a/locale/ks/LC_MESSAGES/core.po +++ b/locale/ks/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ku/LC_MESSAGES/core.po b/locale/ku/LC_MESSAGES/core.po index 9884b3c645..55baabe3bf 100644 --- a/locale/ku/LC_MESSAGES/core.po +++ b/locale/ku/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kv/LC_MESSAGES/core.po b/locale/kv/LC_MESSAGES/core.po index 1360146dcd..3f501304b3 100644 --- a/locale/kv/LC_MESSAGES/core.po +++ b/locale/kv/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/kw/LC_MESSAGES/core.po b/locale/kw/LC_MESSAGES/core.po index da857b8067..a72a0416c7 100644 --- a/locale/kw/LC_MESSAGES/core.po +++ b/locale/kw/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ky/LC_MESSAGES/core.po b/locale/ky/LC_MESSAGES/core.po index 0c789103da..703bb398c2 100644 --- a/locale/ky/LC_MESSAGES/core.po +++ b/locale/ky/LC_MESSAGES/core.po @@ -1750,6 +1750,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Бардык жайгаштырылган тиркемелерге ылайыкташтырылган плитка жана меню интерфейси аркылуу бирдиктүү кирүү үчүн өз алдынча жайгаштырылган портал" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/la/LC_MESSAGES/core.po b/locale/la/LC_MESSAGES/core.po index 9d7945d1a1..9d792d1b35 100644 --- a/locale/la/LC_MESSAGES/core.po +++ b/locale/la/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/lb/LC_MESSAGES/core.po b/locale/lb/LC_MESSAGES/core.po index e04a6c849a..3ce582e894 100644 --- a/locale/lb/LC_MESSAGES/core.po +++ b/locale/lb/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/lg/LC_MESSAGES/core.po b/locale/lg/LC_MESSAGES/core.po index 485a8daa08..52aec46a39 100644 --- a/locale/lg/LC_MESSAGES/core.po +++ b/locale/lg/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/li/LC_MESSAGES/core.po b/locale/li/LC_MESSAGES/core.po index fa4fb6b388..61d78ee700 100644 --- a/locale/li/LC_MESSAGES/core.po +++ b/locale/li/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ln/LC_MESSAGES/core.po b/locale/ln/LC_MESSAGES/core.po index 8e9a88d7ad..e27fb32022 100644 --- a/locale/ln/LC_MESSAGES/core.po +++ b/locale/ln/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/lo/LC_MESSAGES/core.po b/locale/lo/LC_MESSAGES/core.po index 035f8e47fc..22c50ee9a7 100644 --- a/locale/lo/LC_MESSAGES/core.po +++ b/locale/lo/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/lt/LC_MESSAGES/core.po b/locale/lt/LC_MESSAGES/core.po index f8afc3a8ff..d3d262f999 100644 --- a/locale/lt/LC_MESSAGES/core.po +++ b/locale/lt/LC_MESSAGES/core.po @@ -1742,6 +1742,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Šūčių tinklė, kuriame galima pasiekti visus iššūkių įrengtus, individualiai pasizividinantį" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/lu/LC_MESSAGES/core.po b/locale/lu/LC_MESSAGES/core.po index 3b9c226b96..8415f417a5 100644 --- a/locale/lu/LC_MESSAGES/core.po +++ b/locale/lu/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/lv/LC_MESSAGES/core.po b/locale/lv/LC_MESSAGES/core.po index 5dfbc23a88..33b2c353be 100644 --- a/locale/lv/LC_MESSAGES/core.po +++ b/locale/lv/LC_MESSAGES/core.po @@ -1743,6 +1743,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Pašsaņemams portāls vienotai piekļuvei visām izvērstajām programmām, izmantojot pielāgojamu flīžu un izvēlnes saskarni" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/mg/LC_MESSAGES/core.po b/locale/mg/LC_MESSAGES/core.po index cffce8a414..ebb58933b6 100644 --- a/locale/mg/LC_MESSAGES/core.po +++ b/locale/mg/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/mh/LC_MESSAGES/core.po b/locale/mh/LC_MESSAGES/core.po index 0f14e0095b..995e2af48d 100644 --- a/locale/mh/LC_MESSAGES/core.po +++ b/locale/mh/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/mi/LC_MESSAGES/core.po b/locale/mi/LC_MESSAGES/core.po index df15f22602..5a4dfcf638 100644 --- a/locale/mi/LC_MESSAGES/core.po +++ b/locale/mi/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/mk/LC_MESSAGES/core.po b/locale/mk/LC_MESSAGES/core.po index 3d2ed43b51..0aa9d6f6c4 100644 --- a/locale/mk/LC_MESSAGES/core.po +++ b/locale/mk/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ml/LC_MESSAGES/core.po b/locale/ml/LC_MESSAGES/core.po index 3f1c5eff1f..87d69b216f 100644 --- a/locale/ml/LC_MESSAGES/core.po +++ b/locale/ml/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/mn/LC_MESSAGES/core.po b/locale/mn/LC_MESSAGES/core.po index 10c5f78952..c959646a15 100644 --- a/locale/mn/LC_MESSAGES/core.po +++ b/locale/mn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/mr/LC_MESSAGES/core.po b/locale/mr/LC_MESSAGES/core.po index 5a760df4c6..ae098c09a2 100644 --- a/locale/mr/LC_MESSAGES/core.po +++ b/locale/mr/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ms/LC_MESSAGES/core.po b/locale/ms/LC_MESSAGES/core.po index 68db583427..fe2017a186 100644 --- a/locale/ms/LC_MESSAGES/core.po +++ b/locale/ms/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal self-hosted untuk akses terpadu ke semua aplikasi yang dikerahkan melalui ubin dan antarmuka menu yang dapat disesuaikan" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/mt/LC_MESSAGES/core.po b/locale/mt/LC_MESSAGES/core.po index d7733e234d..15d419a269 100644 --- a/locale/mt/LC_MESSAGES/core.po +++ b/locale/mt/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/my/LC_MESSAGES/core.po b/locale/my/LC_MESSAGES/core.po index 9f4250d6b5..dd4c8ed98e 100644 --- a/locale/my/LC_MESSAGES/core.po +++ b/locale/my/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/na/LC_MESSAGES/core.po b/locale/na/LC_MESSAGES/core.po index 9857595317..b780deabed 100644 --- a/locale/na/LC_MESSAGES/core.po +++ b/locale/na/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/nb/LC_MESSAGES/core.po b/locale/nb/LC_MESSAGES/core.po index c5360a2c63..b312ab1171 100644 --- a/locale/nb/LC_MESSAGES/core.po +++ b/locale/nb/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Selvvært portal for enhetlig tilgang til alle utplasserte programmer via en tilpasset flis og menygrensesnitt" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/nd/LC_MESSAGES/core.po b/locale/nd/LC_MESSAGES/core.po index 8339efcd5a..2cf954255c 100644 --- a/locale/nd/LC_MESSAGES/core.po +++ b/locale/nd/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ne/LC_MESSAGES/core.po b/locale/ne/LC_MESSAGES/core.po index 82636c5a24..aac2f04321 100644 --- a/locale/ne/LC_MESSAGES/core.po +++ b/locale/ne/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ng/LC_MESSAGES/core.po b/locale/ng/LC_MESSAGES/core.po index df428fd479..04f195baf4 100644 --- a/locale/ng/LC_MESSAGES/core.po +++ b/locale/ng/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/nl/LC_MESSAGES/core.po b/locale/nl/LC_MESSAGES/core.po index 4a7b559b81..9cb729d8c9 100644 --- a/locale/nl/LC_MESSAGES/core.po +++ b/locale/nl/LC_MESSAGES/core.po @@ -1726,6 +1726,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-hosted portal voor uniforme toegang tot alle geïmplementeerde toepassingen via een aanpasbare tegel- en menuinterface" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/nn/LC_MESSAGES/core.po b/locale/nn/LC_MESSAGES/core.po index 681eeed1c8..b59281a5e1 100644 --- a/locale/nn/LC_MESSAGES/core.po +++ b/locale/nn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/no/LC_MESSAGES/core.po b/locale/no/LC_MESSAGES/core.po index c17af53063..8a0ccf1bf7 100644 --- a/locale/no/LC_MESSAGES/core.po +++ b/locale/no/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/nr/LC_MESSAGES/core.po b/locale/nr/LC_MESSAGES/core.po index ec8e1a8d46..b604c6187e 100644 --- a/locale/nr/LC_MESSAGES/core.po +++ b/locale/nr/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/nv/LC_MESSAGES/core.po b/locale/nv/LC_MESSAGES/core.po index a1ddd3ff78..1affc6c355 100644 --- a/locale/nv/LC_MESSAGES/core.po +++ b/locale/nv/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ny/LC_MESSAGES/core.po b/locale/ny/LC_MESSAGES/core.po index dbd41abd5d..ca898b7613 100644 --- a/locale/ny/LC_MESSAGES/core.po +++ b/locale/ny/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/oc/LC_MESSAGES/core.po b/locale/oc/LC_MESSAGES/core.po index 1a98d52d4b..42b65076ab 100644 --- a/locale/oc/LC_MESSAGES/core.po +++ b/locale/oc/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/oj/LC_MESSAGES/core.po b/locale/oj/LC_MESSAGES/core.po index aeca8c7e62..18e6b5bd10 100644 --- a/locale/oj/LC_MESSAGES/core.po +++ b/locale/oj/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/om/LC_MESSAGES/core.po b/locale/om/LC_MESSAGES/core.po index 7eb3fc1ae6..4424b9236f 100644 --- a/locale/om/LC_MESSAGES/core.po +++ b/locale/om/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/or/LC_MESSAGES/core.po b/locale/or/LC_MESSAGES/core.po index 9960fb5052..f130f0ce74 100644 --- a/locale/or/LC_MESSAGES/core.po +++ b/locale/or/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/os/LC_MESSAGES/core.po b/locale/os/LC_MESSAGES/core.po index a4af073632..28b87dcf80 100644 --- a/locale/os/LC_MESSAGES/core.po +++ b/locale/os/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/pa/LC_MESSAGES/core.po b/locale/pa/LC_MESSAGES/core.po index ac727d1b3d..2992954ef1 100644 --- a/locale/pa/LC_MESSAGES/core.po +++ b/locale/pa/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/pi/LC_MESSAGES/core.po b/locale/pi/LC_MESSAGES/core.po index 14c1c14329..c2848367c5 100644 --- a/locale/pi/LC_MESSAGES/core.po +++ b/locale/pi/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/pl/LC_MESSAGES/core.po b/locale/pl/LC_MESSAGES/core.po index f19b34f4ee..0cdd78870b 100644 --- a/locale/pl/LC_MESSAGES/core.po +++ b/locale/pl/LC_MESSAGES/core.po @@ -1723,6 +1723,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-host portal dla jednolitego dostępu do wszystkich zastosowanych aplikacji za pomocą dostosowanego interfejsu dachowego i menu" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ps/LC_MESSAGES/core.po b/locale/ps/LC_MESSAGES/core.po index 7825b9ca52..ab360801c6 100644 --- a/locale/ps/LC_MESSAGES/core.po +++ b/locale/ps/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/pt/LC_MESSAGES/core.po b/locale/pt/LC_MESSAGES/core.po index 4345746873..080b7d27b7 100644 --- a/locale/pt/LC_MESSAGES/core.po +++ b/locale/pt/LC_MESSAGES/core.po @@ -1723,6 +1723,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal auto- hospedado para acesso unificado a todos os aplicativos implantados através de uma interface de azulejo e menu personalizável" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/qu/LC_MESSAGES/core.po b/locale/qu/LC_MESSAGES/core.po index 2f8c763d7d..5978589656 100644 --- a/locale/qu/LC_MESSAGES/core.po +++ b/locale/qu/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/rm/LC_MESSAGES/core.po b/locale/rm/LC_MESSAGES/core.po index 3cf376d511..3e18b98b88 100644 --- a/locale/rm/LC_MESSAGES/core.po +++ b/locale/rm/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/rn/LC_MESSAGES/core.po b/locale/rn/LC_MESSAGES/core.po index 7b52860e75..07e9cbe7e7 100644 --- a/locale/rn/LC_MESSAGES/core.po +++ b/locale/rn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ro/LC_MESSAGES/core.po b/locale/ro/LC_MESSAGES/core.po index f75c54e508..6b0298ef16 100644 --- a/locale/ro/LC_MESSAGES/core.po +++ b/locale/ro/LC_MESSAGES/core.po @@ -1736,6 +1736,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Portal auto-hostat pentru acces unificat la toate aplicațiile implementate prin intermediul unei interfețe personalizabile pentru plăci și meniu" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ru/LC_MESSAGES/core.po b/locale/ru/LC_MESSAGES/core.po index ace8d03b33..0e9e874a80 100644 --- a/locale/ru/LC_MESSAGES/core.po +++ b/locale/ru/LC_MESSAGES/core.po @@ -1725,6 +1725,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Автономный портал для унифицированного доступа ко всем развернутым приложениям через настраиваемую плитку и интерфейс меню" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/rw/LC_MESSAGES/core.po b/locale/rw/LC_MESSAGES/core.po index 912554202f..d4d4392fb3 100644 --- a/locale/rw/LC_MESSAGES/core.po +++ b/locale/rw/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sa/LC_MESSAGES/core.po b/locale/sa/LC_MESSAGES/core.po index 1d626eaa89..c083484225 100644 --- a/locale/sa/LC_MESSAGES/core.po +++ b/locale/sa/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sc/LC_MESSAGES/core.po b/locale/sc/LC_MESSAGES/core.po index da208be57b..72cf1d9f8d 100644 --- a/locale/sc/LC_MESSAGES/core.po +++ b/locale/sc/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sd/LC_MESSAGES/core.po b/locale/sd/LC_MESSAGES/core.po index 39f220c13f..f2cb986da4 100644 --- a/locale/sd/LC_MESSAGES/core.po +++ b/locale/sd/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/se/LC_MESSAGES/core.po b/locale/se/LC_MESSAGES/core.po index 9e344acf9a..ec0bad19a8 100644 --- a/locale/se/LC_MESSAGES/core.po +++ b/locale/se/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sg/LC_MESSAGES/core.po b/locale/sg/LC_MESSAGES/core.po index 76d6eaf26e..ded81c9b1a 100644 --- a/locale/sg/LC_MESSAGES/core.po +++ b/locale/sg/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/si/LC_MESSAGES/core.po b/locale/si/LC_MESSAGES/core.po index 74853efb4f..aa9dc504c8 100644 --- a/locale/si/LC_MESSAGES/core.po +++ b/locale/si/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sk/LC_MESSAGES/core.po b/locale/sk/LC_MESSAGES/core.po index b91f93187a..c29555214d 100644 --- a/locale/sk/LC_MESSAGES/core.po +++ b/locale/sk/LC_MESSAGES/core.po @@ -1732,6 +1732,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Self-hosted portál pre jednotný prístup ku všetkým nasadeným aplikáciám prostredníctvom prispôsobiteľného rozhrania dlažby a menu" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/sl/LC_MESSAGES/core.po b/locale/sl/LC_MESSAGES/core.po index 7288f6c2cf..c95619aab8 100644 --- a/locale/sl/LC_MESSAGES/core.po +++ b/locale/sl/LC_MESSAGES/core.po @@ -1732,6 +1732,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Samogostujoči portal za enoten dostop do vseh razporejenih programov prek prilagodljivega vmesnika za ploščice in menije" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/sm/LC_MESSAGES/core.po b/locale/sm/LC_MESSAGES/core.po index 05d41623e6..1128f501bf 100644 --- a/locale/sm/LC_MESSAGES/core.po +++ b/locale/sm/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sn/LC_MESSAGES/core.po b/locale/sn/LC_MESSAGES/core.po index b1d71b5fb3..71718088d0 100644 --- a/locale/sn/LC_MESSAGES/core.po +++ b/locale/sn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/so/LC_MESSAGES/core.po b/locale/so/LC_MESSAGES/core.po index 5e21507f09..f194aa54c7 100644 --- a/locale/so/LC_MESSAGES/core.po +++ b/locale/so/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sq/LC_MESSAGES/core.po b/locale/sq/LC_MESSAGES/core.po index d861b0e2c0..46ccd91155 100644 --- a/locale/sq/LC_MESSAGES/core.po +++ b/locale/sq/LC_MESSAGES/core.po @@ -1731,6 +1731,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Porta e vetë-pritur për hyrje të unifikuar në të gjitha programet e vendosura nëpërmjet një tjegulle të personalizuar dhe ndërfaqe menush" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/sr/LC_MESSAGES/core.po b/locale/sr/LC_MESSAGES/core.po index da254170ec..55cee02f91 100644 --- a/locale/sr/LC_MESSAGES/core.po +++ b/locale/sr/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ss/LC_MESSAGES/core.po b/locale/ss/LC_MESSAGES/core.po index 22ef3a450a..bd28ac6451 100644 --- a/locale/ss/LC_MESSAGES/core.po +++ b/locale/ss/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/st/LC_MESSAGES/core.po b/locale/st/LC_MESSAGES/core.po index 119b3ce7fe..0f9bf86bf3 100644 --- a/locale/st/LC_MESSAGES/core.po +++ b/locale/st/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/su/LC_MESSAGES/core.po b/locale/su/LC_MESSAGES/core.po index 7d1800f971..b2d502c8c3 100644 --- a/locale/su/LC_MESSAGES/core.po +++ b/locale/su/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/sv/LC_MESSAGES/core.po b/locale/sv/LC_MESSAGES/core.po index 7ea211ef19..f26e2a5eb0 100644 --- a/locale/sv/LC_MESSAGES/core.po +++ b/locale/sv/LC_MESSAGES/core.po @@ -1732,6 +1732,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Självhäftad portal för enhetlig tillgång till alla utplacerade applikationer via ett anpassningsbart kakel- och menygränssnitt" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/sw/LC_MESSAGES/core.po b/locale/sw/LC_MESSAGES/core.po index d76549fc1c..f7b9ef85f3 100644 --- a/locale/sw/LC_MESSAGES/core.po +++ b/locale/sw/LC_MESSAGES/core.po @@ -1743,6 +1743,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Hifadhi ya kujitegemea ya upatikanaji wa umoja kwa maombi yote yaliyopelekwa kupitia interface ya tile na menu customizable" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ta/LC_MESSAGES/core.po b/locale/ta/LC_MESSAGES/core.po index d5e0ec15af..b2463f479a 100644 --- a/locale/ta/LC_MESSAGES/core.po +++ b/locale/ta/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/te/LC_MESSAGES/core.po b/locale/te/LC_MESSAGES/core.po index 7051ab1670..17d25b980d 100644 --- a/locale/te/LC_MESSAGES/core.po +++ b/locale/te/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/tg/LC_MESSAGES/core.po b/locale/tg/LC_MESSAGES/core.po index fc140d7308..4827fa60f0 100644 --- a/locale/tg/LC_MESSAGES/core.po +++ b/locale/tg/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/th/LC_MESSAGES/core.po b/locale/th/LC_MESSAGES/core.po index b2dc500b45..bffe9d1327 100644 --- a/locale/th/LC_MESSAGES/core.po +++ b/locale/th/LC_MESSAGES/core.po @@ -1738,6 +1738,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "ประตูมิติด้วยตนเอง สําหรับเข้าถึงโปรแกรมทั้งหมดที่ใช้งานอยู่ โดยผ่านส่วนติดต่อของกระเบื้องและเมนูที่กําหนดเอง" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ti/LC_MESSAGES/core.po b/locale/ti/LC_MESSAGES/core.po index c2d48ec612..f2d857d577 100644 --- a/locale/ti/LC_MESSAGES/core.po +++ b/locale/ti/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/tk/LC_MESSAGES/core.po b/locale/tk/LC_MESSAGES/core.po index fe5af941ea..98c276abfa 100644 --- a/locale/tk/LC_MESSAGES/core.po +++ b/locale/tk/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/tl/LC_MESSAGES/core.po b/locale/tl/LC_MESSAGES/core.po index e3ba79487c..94c8fcb74e 100644 --- a/locale/tl/LC_MESSAGES/core.po +++ b/locale/tl/LC_MESSAGES/core.po @@ -1733,6 +1733,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Sarili-hosted portal para sa nagkakaisang pag-access sa lahat ng mga naka-set na application sa pamamagitan ng isang custizable tile at menu interface" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/tn/LC_MESSAGES/core.po b/locale/tn/LC_MESSAGES/core.po index e50ccb9ceb..1cc3474546 100644 --- a/locale/tn/LC_MESSAGES/core.po +++ b/locale/tn/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/to/LC_MESSAGES/core.po b/locale/to/LC_MESSAGES/core.po index 6088d28141..be305dbc1d 100644 --- a/locale/to/LC_MESSAGES/core.po +++ b/locale/to/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/tr/LC_MESSAGES/core.po b/locale/tr/LC_MESSAGES/core.po index d6e4a8a1d7..35d40b1266 100644 --- a/locale/tr/LC_MESSAGES/core.po +++ b/locale/tr/LC_MESSAGES/core.po @@ -1737,6 +1737,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Kendi kendine evlenmiş portal, tüm dağıtılmış uygulamalara bir karot ve menü arayüzü aracılığıyla birleşik erişim için" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ts/LC_MESSAGES/core.po b/locale/ts/LC_MESSAGES/core.po index 7160969c68..1bc152b6b3 100644 --- a/locale/ts/LC_MESSAGES/core.po +++ b/locale/ts/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/tt/LC_MESSAGES/core.po b/locale/tt/LC_MESSAGES/core.po index 1444f6fef3..47995cef2f 100644 --- a/locale/tt/LC_MESSAGES/core.po +++ b/locale/tt/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/tw/LC_MESSAGES/core.po b/locale/tw/LC_MESSAGES/core.po index d89ae038d1..0080152269 100644 --- a/locale/tw/LC_MESSAGES/core.po +++ b/locale/tw/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ty/LC_MESSAGES/core.po b/locale/ty/LC_MESSAGES/core.po index d67797aba4..15d4348779 100644 --- a/locale/ty/LC_MESSAGES/core.po +++ b/locale/ty/LC_MESSAGES/core.po @@ -1390,6 +1390,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ug/LC_MESSAGES/core.po b/locale/ug/LC_MESSAGES/core.po index c1d1c65777..0f0261b31b 100644 --- a/locale/ug/LC_MESSAGES/core.po +++ b/locale/ug/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/uk/LC_MESSAGES/core.po b/locale/uk/LC_MESSAGES/core.po index abdab89f93..188e084623 100644 --- a/locale/uk/LC_MESSAGES/core.po +++ b/locale/uk/LC_MESSAGES/core.po @@ -1730,6 +1730,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Самостійний портал для єдиного доступу до всіх розгорнутих додатків за допомогою настроюваного інтерфейсу плитки та меню" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/ur/LC_MESSAGES/core.po b/locale/ur/LC_MESSAGES/core.po index 79358512f3..a7ebedc435 100644 --- a/locale/ur/LC_MESSAGES/core.po +++ b/locale/ur/LC_MESSAGES/core.po @@ -1751,6 +1751,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "خود کار طور پر متحدہ سمتوں تک رسائی کے لیے" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/uz/LC_MESSAGES/core.po b/locale/uz/LC_MESSAGES/core.po index a36c259578..f8b5754a9e 100644 --- a/locale/uz/LC_MESSAGES/core.po +++ b/locale/uz/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/ve/LC_MESSAGES/core.po b/locale/ve/LC_MESSAGES/core.po index 59a39d3b76..850bd756a8 100644 --- a/locale/ve/LC_MESSAGES/core.po +++ b/locale/ve/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/vi/LC_MESSAGES/core.po b/locale/vi/LC_MESSAGES/core.po index cf22dd9577..093942f75e 100644 --- a/locale/vi/LC_MESSAGES/core.po +++ b/locale/vi/LC_MESSAGES/core.po @@ -1728,6 +1728,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "Cổng tự tạo cho phép truy cập hợp nhất tới tất cả các ứng dụng được triển khai thông qua giao diện bảng điều khiển và trình đơn tùy chỉnh" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/vo/LC_MESSAGES/core.po b/locale/vo/LC_MESSAGES/core.po index bce45f8948..e1c90bda4b 100644 --- a/locale/vo/LC_MESSAGES/core.po +++ b/locale/vo/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/wa/LC_MESSAGES/core.po b/locale/wa/LC_MESSAGES/core.po index b6d5a4a2e3..c14ea996f9 100644 --- a/locale/wa/LC_MESSAGES/core.po +++ b/locale/wa/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/wo/LC_MESSAGES/core.po b/locale/wo/LC_MESSAGES/core.po index dcbf40d40a..bcfb5788f2 100644 --- a/locale/wo/LC_MESSAGES/core.po +++ b/locale/wo/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/xh/LC_MESSAGES/core.po b/locale/xh/LC_MESSAGES/core.po index 72131e9c58..15e4cb499a 100644 --- a/locale/xh/LC_MESSAGES/core.po +++ b/locale/xh/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/yi/LC_MESSAGES/core.po b/locale/yi/LC_MESSAGES/core.po index efb6c1af46..c073efb7fc 100644 --- a/locale/yi/LC_MESSAGES/core.po +++ b/locale/yi/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/yo/LC_MESSAGES/core.po b/locale/yo/LC_MESSAGES/core.po index 22a53d85f7..d315a6a5fd 100644 --- a/locale/yo/LC_MESSAGES/core.po +++ b/locale/yo/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/za/LC_MESSAGES/core.po b/locale/za/LC_MESSAGES/core.po index fd45a3698f..0394f46dcf 100644 --- a/locale/za/LC_MESSAGES/core.po +++ b/locale/za/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/locale/zh/LC_MESSAGES/core.po b/locale/zh/LC_MESSAGES/core.po index a03d510e88..a229584118 100644 --- a/locale/zh/LC_MESSAGES/core.po +++ b/locale/zh/LC_MESSAGES/core.po @@ -1739,6 +1739,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "自动托管的门户,通过自定义的瓷砖和菜单接口统一访问所有已部署的应用程序" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + # translated-by: libretranslate msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" diff --git a/locale/zu/LC_MESSAGES/core.po b/locale/zu/LC_MESSAGES/core.po index cf763d075c..a4ef521675 100644 --- a/locale/zu/LC_MESSAGES/core.po +++ b/locale/zu/LC_MESSAGES/core.po @@ -1391,6 +1391,10 @@ msgctxt "role:web-app-dashboard:description" msgid "Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface" msgstr "" +msgctxt "role:web-app-openpost:description" +msgid "Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks" +msgstr "" + msgctxt "role:web-app-pretix:description" msgid "Self-hosted ticketing platform for events with online sales, registration management, and secure payments" msgstr "" diff --git a/plugins/lookup/container_networks.py b/plugins/lookup/container_networks.py index 1bc105c1a1..e086f2d859 100644 --- a/plugins/lookup/container_networks.py +++ b/plugins/lookup/container_networks.py @@ -5,10 +5,13 @@ block. Reads the service_registry, the rendering role's ``application_id`` and Usage in any service template: {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', service_name) | indent(4) }} -Pass ``provider_self_alias=False`` for a sidecar service that must not carry the -provider's own alias, and ``own_network_only=True`` for one that must not -inherit the networks its provider joins as a consumer. +Pass the service key for a service that answers to extra names on the role's +default network; they are read from ``services..network_aliases`` of +the rendering role. Pass ``provider_self_alias=False`` for a sidecar service +that must not carry the provider's own alias, and ``own_network_only=True`` for +one that must not inherit the networks its provider joins as a consumer. """ from __future__ import annotations @@ -30,8 +33,10 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[str]: - if terms: - raise AnsibleError("container_networks lookup takes no positional terms") + if terms and len(terms) > 1: + raise AnsibleError( + "container_networks lookup takes at most one term, the service key" + ) ctx = build_context(self, variables) @@ -41,6 +46,18 @@ class LookupModule(LookupBase): "container_networks lookup: application_id is required in variables" ) + aliases = None + if terms: + path = f"services.{terms[0]}.network_aliases" + aliases = ctx.lookup_config(str(application_id), path, None) + if not isinstance(aliases, list) or not all( + isinstance(alias, str) and alias for alias in aliases + ): + raise AnsibleError( + f"container_networks lookup: {application_id} {path} " + "must be a list of non-empty strings" + ) + return [ render_container_networks( application_id=str(application_id), @@ -52,5 +69,6 @@ class LookupModule(LookupBase): provider_self_alias=bool(kwargs.get("provider_self_alias", True)), node_local=bool(kwargs.get("node_local", False)), own_network_only=bool(kwargs.get("own_network_only", False)), + aliases=aliases, ) ] diff --git a/plugins/lookup/container_volumes.py b/plugins/lookup/container_volumes.py index 33628e9e6b..6e8c2ba282 100644 --- a/plugins/lookup/container_volumes.py +++ b/plugins/lookup/container_volumes.py @@ -82,6 +82,29 @@ def _short_form_volume(source_name: str, target: str, read_only: bool) -> str: return f"{source_name}:{target}{suffix}" +def _with_owner( + reference: dict[str, Any], mount: dict[str, Any], render_jinja: Any +) -> dict[str, Any]: + """Add the mount's ``uid``/``gid`` to a config or secret reference. + + Args: + reference: long-syntax ``configs:``/``secrets:`` entry of the service. + mount: the meta/volumes.yml mount that may name the owning user and group. + render_jinja: renderer for templated values, or ``None`` outside Ansible. + + Returns: + The reference with ``uid``/``gid`` as strings when the mount sets them. + """ + for key in ("uid", "gid"): + if mount.get(key) is None: + continue + text = str(mount[key]) + if render_jinja is not None and ("{{" in text or "{%" in text): + text = str(render_jinja(text)) + reference[key] = text + return reference + + def container_volumes( applications: dict[str, Any], application_id: str, @@ -183,14 +206,14 @@ def container_volumes( mode_value = entry.get("mode") if mode_value: cfg_ref["mode"] = _coerce_mode_int(mode_value) - configs_block.append(cfg_ref) + configs_block.append(_with_owner(cfg_ref, mount, render_jinja)) elif vtype == "secret": sec_ref: dict[str, Any] = {"source": semantic_name, "target": target} mode_value = entry.get("mode") if mode_value: sec_ref["mode"] = _coerce_mode_int(mode_value) - secrets_block.append(sec_ref) + secrets_block.append(_with_owner(sec_ref, mount, render_jinja)) if extra_volumes: volumes_block.extend(to_plain(extra_volumes)) diff --git a/plugins/lookup/openpost_relay_domains.py b/plugins/lookup/openpost_relay_domains.py new file mode 100644 index 0000000000..989598b716 --- /dev/null +++ b/plugins/lookup/openpost_relay_domains.py @@ -0,0 +1,87 @@ +"""Lookup ``openpost_relay_domains``: the names OpenPost's egress relay answers to. + +Usage: + + {{ lookup('openpost_relay_domains') }} + +Returns OpenPost's canonical domain, then the canonical domain of every sibling +under ``services.relay.siblings`` whose service flag is on, then the object +store's public domain when OpenPost uses one. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ansible.errors import AnsibleError +from ansible.module_utils.parsing.convert_bool import boolean +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + +APPLICATION_ID = "web-app-openpost" +SIBLINGS_PATH = "services.relay.siblings" + + +def relay_domains( + own_domain: str, + siblings: Mapping[str, str], + sibling_enabled: Callable[[str], Any], + domain_of: Callable[[str], str], + objstore_domain: str, +) -> list[str]: + """Return the relay's names in alias order. + + Args: + own_domain: OpenPost's canonical domain. + siblings: service key to role id of every sibling the relay may carry. + sibling_enabled: the service flag of a sibling's key. + domain_of: the canonical domain of a role id. + objstore_domain: the object store's public domain, "" without one. + + Returns: + The own domain, the enabled siblings' domains, then the object store's. + """ + domains = [own_domain] + domains.extend( + domain_of(role) + for key, role in siblings.items() + if boolean(sibling_enabled(key)) + ) + if objstore_domain: + domains.append(objstore_domain) + return domains + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + if terms: + raise AnsibleError("lookup('openpost_relay_domains') expects no terms.") + + def _lookup(name: str, *args: str) -> Any: + plugin = lookup_loader.get(name, loader=self._loader, templar=self._templar) + return plugin.run(list(args), variables=variables)[0] + + objstore_domain = ( + str(_lookup("objstore", APPLICATION_ID, "public_domain")) + if boolean(_lookup("objstore", APPLICATION_ID, "enabled")) + else "" + ) + return [ + relay_domains( + own_domain=str(_lookup("domain", APPLICATION_ID)), + siblings=_lookup("config", APPLICATION_ID, SIBLINGS_PATH), + sibling_enabled=lambda key: _lookup( + "config", APPLICATION_ID, f"services.{key}.enabled" + ), + domain_of=lambda role: str(_lookup("domain", role)), + objstore_domain=objstore_domain, + ) + ] diff --git a/plugins/lookup/role_subnet_exceptions.py b/plugins/lookup/role_subnet_exceptions.py new file mode 100644 index 0000000000..4613cec366 --- /dev/null +++ b/plugins/lookup/role_subnet_exceptions.py @@ -0,0 +1,72 @@ +"""Lookup ``role_subnet_exceptions``: the roles whose local subnet sits outside +``NETWORK_ROLE_SUBNET_POOL``. + +Usage: + + {{ lookup('role_subnet_exceptions') }} # ['web-app-bigbluebutton', ...] + +A role declares the exception itself, next to the subnet it concerns, with +``local.outside_pool: true`` in its ``meta/networks.yml``. Consumers resolve +the returned ids to subnets through ``lookup('role_subnets', ...)``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.roles.applications.config import get as get_app_conf + +if TYPE_CHECKING: + from collections.abc import Mapping + +FLAG_PATH = "networks.local.outside_pool" + + +def outside_pool_roles(applications: Mapping[str, Any]) -> list[str]: + """Return the sorted ids of the applications that declare the flag. + + Args: + applications: the merged ``lookup('applications')`` mapping. + + Returns: + Every application id whose ``networks.local.outside_pool`` is true. + """ + roles: list[str] = [] + for app_id in sorted(applications): + flag = get_app_conf( + applications=applications, + application_id=app_id, + config_path=FLAG_PATH, + strict=False, + default=False, + skip_missing_app=True, + ) + if not isinstance(flag, bool): + raise AnsibleError( + f"role_subnet_exceptions: {app_id} {FLAG_PATH} must be a boolean, " + f"got {flag!r}" + ) + if flag: + roles.append(app_id) + return roles + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + if terms: + raise AnsibleError("lookup('role_subnet_exceptions') expects no terms.") + applications = lookup_loader.get( + "applications", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables)[0] + return [outside_pool_roles(applications)] diff --git a/plugins/lookup/role_subnets.py b/plugins/lookup/role_subnets.py index b3a06976a1..17d8e158bf 100644 --- a/plugins/lookup/role_subnets.py +++ b/plugins/lookup/role_subnets.py @@ -13,6 +13,10 @@ Usage: Terms may be role ids or lists of them, mixed. A role that declares no local subnet raises, because a silently dropped entry would narrow whatever firewall or trust list consumes the result. + +A term may also be the unrendered template text of a group var such as +``NETWORK_ROLE_SUBNET_EXCEPTION_ROLES``, which reaches a lookup as the file +holds it; it is rendered before its role ids are read. """ from __future__ import annotations @@ -22,10 +26,17 @@ from typing import Any from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from ansible.template import trust_as_template _SUBNET_PATH = "networks.local.subnet" +def _rendered(templar: Any, term: Any) -> Any: + if isinstance(term, str) and "{{" in term and templar is not None: + return templar.template(trust_as_template(term)) + return term + + def _flattened(terms: list[Any]) -> list[str]: roles: list[str] = [] for term in terms: @@ -43,7 +54,8 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[Any]: - roles = _flattened(terms or []) + templar = getattr(self, "_templar", None) + roles = _flattened([_rendered(templar, term) for term in terms or []]) if not roles: raise AnsibleError( "lookup('role_subnets', ) expects " @@ -52,7 +64,7 @@ class LookupModule(LookupBase): config = lookup_loader.get( "config", loader=getattr(self, "_loader", None), - templar=getattr(self, "_templar", None), + templar=templar, ) subnets: list[str] = [] for role in roles: diff --git a/roles/dsk-gnt-pi/meta/services.yml b/roles/dsk-gnt-pi/meta/services.yml index 77f36b0fb1..562ffa1535 100644 --- a/roles/dsk-gnt-pi/meta/services.yml +++ b/roles/dsk-gnt-pi/meta/services.yml @@ -9,7 +9,7 @@ pi: host: enabled: true lifecycle: alpha - npm_version: 1.6.0 + npm_version: 1.6.1 update: key: npm_version type: npm diff --git a/roles/test-e2e-playwright/README.md b/roles/test-e2e-playwright/README.md index a7bb9b2e57..d6f1e42ce6 100644 --- a/roles/test-e2e-playwright/README.md +++ b/roles/test-e2e-playwright/README.md @@ -30,7 +30,7 @@ This role: - Renders `.env` from `templates/playwright.env.j2` using Ansible variables (`application_id`, `domains`, `users`, `applications`) - Optionally waits until the application responds with HTTP `200` or `302` - Injects CA trust automatically for `TLS_MODE=self_signed` (via `CA_TRUST.*`), so Playwright accepts self-signed cert chains -- Runs Playwright in Docker with stable browser settings (`--ipc=host`, `--shm-size=1g`) +- Runs Playwright in Docker with stable browser settings (`--ipc=host`, `--shm-size=1g`) and without core dumps (`--ulimit=core=0`), so a crashing browser cannot fill the container's disk - Runs the suite once per role on one network it is served on (`lookup('network_siblings', ...)`), picked at random when there are several and kept for the flake retry, with the `.env` rendered for that network's vhost - Stores per-role reports/artifacts under `TEST_E2E_PLAYWRIGHT_REPORTS_BASE_DIR/`, or under `+` when the pick is not the canonical network diff --git a/roles/test-e2e-playwright/files/spec_secrets_container.py b/roles/test-e2e-playwright/files/spec_secrets_container.py index 337992a325..9bef582bcd 100644 --- a/roles/test-e2e-playwright/files/spec_secrets_container.py +++ b/roles/test-e2e-playwright/files/spec_secrets_container.py @@ -59,6 +59,7 @@ OPTIONS = { "--oom-score-adj": re.compile(r"-?[0-9]+"), "--network": re.compile(r"host|none"), "--user": re.compile(r"[0-9]+:[0-9]+"), + "--ulimit": re.compile(r"core=0"), "-w": re.compile(r"/e2e"), "-e": re.compile(r"[A-Z][A-Z0-9_]*=.*"), "-v": re.compile(r"/[^:]+:/[^:]+(?::ro)?"), @@ -494,7 +495,6 @@ def check_container(container: list[str], run: Path) -> None: f"{shared / 'personas'}:/e2e/tests/personas:ro", } mounts = check_ca(container, found, stage) - if len(set(mounts)) != len(mounts) or not required <= set(mounts) <= ( - required | optional - ): + unique = set(mounts) + if len(unique) != len(mounts) or not required <= unique <= required | optional: raise SpecSecretsError("a run with spec secrets takes no other mounts") diff --git a/roles/test-e2e-playwright/tasks/03_run_pass.yml b/roles/test-e2e-playwright/tasks/03_run_pass.yml index ff9bffe224..3def07ab20 100644 --- a/roles/test-e2e-playwright/tasks/03_run_pass.yml +++ b/roles/test-e2e-playwright/tasks/03_run_pass.yml @@ -110,7 +110,7 @@ {{ (['python3', '-I', '-B', TEST_E2E_PLAYWRIGHT_TOOLS_DIR ~ '/spec_secrets.py', 'guard'] if (_playwright_secrets_template_stat.stat.exists | bool) else []) + TEST_E2E_PLAYWRIGHT_MASK_ARGV - + [('docker' if (_playwright_secrets_template_stat.stat.exists | bool) else 'container'), 'run', '--rm', '--ipc=host', '--shm-size=1g'] + + [('docker' if (_playwright_secrets_template_stat.stat.exists | bool) else 'container'), 'run', '--rm', '--ipc=host', '--shm-size=1g', '--ulimit=core=0'] + ( ['--network', 'host'] if IS_SWARM_MODE diff --git a/roles/update/README.md b/roles/update/README.md index c9dc3e91c4..0beefaf2a9 100644 --- a/roles/update/README.md +++ b/roles/update/README.md @@ -26,6 +26,8 @@ message when a host runs a distribution that this role does not yet cover. | `CentOS` | `centos.yml` | `ansible.builtin.dnf` | | anything else | `unsupported.yml` | `ansible.builtin.fail` | +On Arch Linux ARM, `arch.yml` runs [alarm_mirror.sh](files/shell/alarm_mirror.sh) before the database refresh. The geo host `mirror.archlinuxarm.org` redirects every request on its own, so pacman can take the database from a mirror that already holds a new release and look the packages up on mirrors that do not yet serve it. The script moves every `Server` line of that host behind the last concrete `Server` of `/etc/pacman.d/mirrorlist`, so the database and the packages come from the first concrete mirror. When the upgrade still fails to retrieve packages, the role moves the first concrete `Server` behind the last concrete one, re-syncs the databases (`pacman -Syyu`) and upgrades again, at most once for every further concrete mirror; the geo host never leads. The role decides by the script's exit code, never by its output, and fails with the original error when no retry succeeded. A mirrorlist without that geo host, such as the one of x86_64 Arch Linux, stays untouched. + `centos.yml` first runs [centos_mirror.sh](files/shell/centos_mirror.sh), which replaces every `metalink=` of the CentOS Stream repo files with a `baseurl=` on `mirror.stream.centos.org` and every `metalink=` of the EPEL repo files with the file's own `baseurl` template on `dl.fedoraproject.org`, and then includes `fedora.yml`. The [Dockerfile](../../Dockerfile) runs the same script before its first `dnf` call, so the CentOS dev and swarm-node images resolve against the same source. ## Cosmos diff --git a/roles/update/files/shell/alarm_mirror.sh b/roles/update/files/shell/alarm_mirror.sh new file mode 100755 index 0000000000..c78c7acdbc --- /dev/null +++ b/roles/update/files/shell/alarm_mirror.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Param: $1 demote or retry, $2 the pacman mirrorlist. Only a mirrorlist with an active Server on the Arch Linux ARM geo host mirror.archlinuxarm.org is touched. A missing mirrorlist counts as one without that host. demote moves every geo Server behind the last concrete Server, prints the new first Server and exits 3; it exits 0 and prints nothing when nothing moved. retry moves the first concrete Server behind the last concrete one, then re-syncs the databases and upgrades, at most once for every concrete mirror after the first; it exits 0 after the upgrade that succeeded, with pacman's code when none did, and 1 when it retried nothing. +set -euo pipefail + +verb="$1" +mirrorlist="$2" +server='^[[:space:]]*Server[[:space:]]*=' +geo='^[[:space:]]*Server[[:space:]]*=[[:space:]]*https?://mirror\.archlinuxarm\.org/' + +case "${verb}" in +demote | retry) ;; +*) + echo "ERROR: unknown verb ${verb}, expected demote or retry" >&2 + exit 2 + ;; +esac + +scan() { + local index + geos=() + concrete=() + for index in "${!lines[@]}"; do + [[ "${lines[index]}" =~ ${server} ]] || continue + if [[ "${lines[index]}" =~ ${geo} ]]; then + geos+=("${index}") + else + concrete+=("${index}") + fi + done +} + +move_behind() { + local from="$1" after="$2" index + local moved=() + for index in "${!lines[@]}"; do + if ((index != from)); then + moved+=("${lines[index]}") + fi + if ((index == after)); then + moved+=("${lines[from]}") + fi + done + lines=("${moved[@]}") + printf '%s\n' "${lines[@]}" >"${mirrorlist}.new" + chmod --reference="${mirrorlist}" "${mirrorlist}.new" + chown --reference="${mirrorlist}" "${mirrorlist}.new" + mv -f "${mirrorlist}.new" "${mirrorlist}" + scan +} + +demote_geo() { + ((${#geos[@]} > 0 && ${#concrete[@]} > 0)) || return 0 + while ((geos[0] < concrete[-1])); do + move_behind "${geos[0]}" "${concrete[-1]}" + demoted=1 + done +} + +lead() { + printf '%s\n' "${lines[concrete[0]]}" +} + +lines=() +if [[ -f "${mirrorlist}" ]]; then + mapfile -t lines <"${mirrorlist}" +fi +scan +demoted=0 + +case "${verb}" in +demote) + demote_geo + if ((demoted)); then + lead + exit 3 + fi + ;; +retry) + ((${#geos[@]} > 0)) || exit 1 + demote_geo + status=1 + for ((rotation = 1; rotation < ${#concrete[@]}; rotation++)); do + move_behind "${concrete[0]}" "${concrete[-1]}" + status=0 + pacman --sync --refresh --refresh --sysupgrade --noconfirm >&2 || status=$? + if ((status == 0)); then + lead + exit 0 + fi + done + exit "${status}" + ;; +esac diff --git a/roles/update/tasks/arch.yml b/roles/update/tasks/arch.yml index bafbebed67..c44c7fe4a9 100644 --- a/roles/update/tasks/arch.yml +++ b/roles/update/tasks/arch.yml @@ -29,6 +29,14 @@ replace: "#DownloadUser =" when: "'DisableSandbox' in (update_pacman_conf.content | b64decode).splitlines()" +- name: "🪞 update (pacman) | take ALARM databases and packages from one concrete mirror" + become: true + ansible.builtin.script: + cmd: shell/alarm_mirror.sh demote {{ UPDATE_PACMAN_MIRRORLIST | quote }} + register: update_alarm_demoted + changed_when: update_alarm_demoted.rc == 3 + failed_when: update_alarm_demoted.rc not in [0, 3] + - name: "🔄 update (pacman) | refresh the pacman package databases" community.general.pacman: # nocheck: dynamic-package - database refresh, not a package install update_cache: true @@ -50,9 +58,29 @@ enabled: true when: not ansible_check_mode -- name: "🔄 update (pacman) | upgrade all installed packages" - community.general.pacman: # nocheck: dynamic-package - full-system upgrade, not a package install - upgrade: true +- name: "🔄 update (pacman) | upgrade all installed packages, retrying ALARM mirrors" + block: + - name: "🔄 update (pacman) | upgrade all installed packages" + community.general.pacman: # nocheck: dynamic-package - full-system upgrade, not a package install + upgrade: true + rescue: + - name: "🛑 update (pacman) | re-raise anything but packages no mirror served" # nocheck: rescue-recovery an Arch Linux ARM mirror can list packages in its database before it serves them, so the retry moves to the next concrete mirror, re-syncs and upgrades again, once per mirror; the last failure fails loud + ansible.builtin.fail: + msg: "{{ ansible_failed_result.msg }}" + when: "'failed to retrieve some files' not in (ansible_failed_result.stderr | default(''))" + + - name: "🔁 update (pacman) | upgrade from the next concrete ALARM mirror" + become: true + ansible.builtin.script: + cmd: shell/alarm_mirror.sh retry {{ UPDATE_PACMAN_MIRRORLIST | quote }} + register: update_alarm_retried + changed_when: update_alarm_retried.rc == 0 + failed_when: false + + - name: "🛑 update (pacman) | re-raise the failure no further ALARM mirror retried" + ansible.builtin.fail: + msg: "{{ ansible_failed_result.msg }}" + when: update_alarm_retried is skipped or update_alarm_retried.rc != 0 - name: "🛑 update (pacman) | reboot or guard when the running kernel was upgraded" ansible.builtin.include_tasks: arch/reboot.yml diff --git a/roles/update/vars/main.yml b/roles/update/vars/main.yml index a27068b088..d3269d9c56 100644 --- a/roles/update/vars/main.yml +++ b/roles/update/vars/main.yml @@ -3,3 +3,4 @@ application_id: update UPDATE_REBOOT_ENABLED: "{{ lookup('config', application_id, 'services.update.reboot.enabled') | bool }}" UPDATE_KERNEL_MODULES_HOOK_ENABLED: "{{ lookup('config', application_id, 'services.update.kernel_modules_hook.enabled') | bool }}" UPDATE_PACMAN_XFER: "{{ [ DIR_BIN, 'pacman-xfer' ] | path_join }}" +UPDATE_PACMAN_MIRRORLIST: /etc/pacman.d/mirrorlist diff --git a/roles/web-app-bigbluebutton/meta/networks.yml b/roles/web-app-bigbluebutton/meta/networks.yml index ec12c90e6e..329ea476f8 100644 --- a/roles/web-app-bigbluebutton/meta/networks.yml +++ b/roles/web-app-bigbluebutton/meta/networks.yml @@ -2,3 +2,4 @@ meshes: [] local: subnet: 10.7.7.0/24 + outside_pool: true diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index 6e3ccf8399..87d935c752 100644 --- a/roles/web-app-bridgy-fed/meta/services.yml +++ b/roles/web-app-bridgy-fed/meta/services.yml @@ -53,7 +53,7 @@ bridgy-fed: version: 3.14-slim name: web-app-bridgy-fed repository: https://github.com/snarfed/bridgy-fed.git - ref: cbb76808cd8f21b571939a2a7b42655d845ea40a + ref: 891f78efd4601d1590640fb02982d3c3ed64459b ports: local: http: 8053 diff --git a/roles/web-app-openpost/Administration.md b/roles/web-app-openpost/Administration.md new file mode 100644 index 0000000000..83aa879743 --- /dev/null +++ b/roles/web-app-openpost/Administration.md @@ -0,0 +1,284 @@ +# Administration + +## Accounts and workspaces + +OpenPost separates people (accounts) from the places they publish from (workspaces). +Connected social accounts, drafts, schedules and media belong to a workspace, and only its members see them. +Every member holds a workspace role, and only roles with publishing rights may publish or schedule. + +The first account of a fresh instance becomes the instance admin. +The deploy registers the break-glass account first for that reason (see [Break-glass instance admin](#break-glass-instance-admin)). +Instance admins manage users, provider apps and instance settings under **Settings → Instance**; workspace owners invite members and assign their roles under **Settings → Workspace → Team**. + +## Single sign-on + +The role configures OpenPost's instance-wide OIDC provider against the shared Keycloak client (`OIDC.CLIENT.*`) whenever `web-app-keycloak` is deployed. + +- Users sign in with the Keycloak button on the login page. + OpenPost provisions them just in time on their first verified login (`OPENPOST_OIDC_JIT_ENABLED=true`) and matches later logins by issuer and subject. +- The `platform_administrator` is listed in `OPENPOST_OIDC_BOOTSTRAP_ALLOWLIST` and becomes instance admin on its first SSO login. +- A just-in-time user starts without access to existing workspaces. + Grant access by inviting the user from the workspace's team settings; OpenPost does not consume Keycloak groups. +- Password self-registration is closed. + OpenPost gates password sign-up and just-in-time provisioning with the same switch, so with Keycloak deployed the role keeps `OPENPOST_DISABLE_REGISTRATIONS=false` and the shared proxy answers `POST /api/v1/auth/register` with HTTP 403; without Keycloak the switch itself is set. +- OpenPost ships no LDAP adapter, so the role declares no `ldap` service. + Directory accounts sign in through Keycloak, which federates OpenLDAP, over OIDC. +- OpenPost never links an SSO identity to an existing account with the same e-mail address automatically. + The break-glass account therefore uses its own address, and a person who already holds a local account keeps signing in with its password until an instance admin removes the local account and the person signs in through Keycloak again. +- For workspaces that require SSO, `OPENPOST_SSO_BREAK_GLASS_EMAILS` names instance admins that may still enter with their password plus TOTP or a passkey during an identity-provider outage. + Add the break-glass address to that list through the inventory once the account has a second factor. +- OpenPost also offers a trusted-proxy sign-in (`OPENPOST_PROXY_AUTH_SECRET`, header `X-OpenPost-Proxy-User`). + The role does not enable it; it is the fallback for a deployment that has to front OpenPost with `oauth2-proxy` instead of native OIDC, and it then requires the proxy to strip client-supplied `X-OpenPost-Proxy-*` headers. + +## Break-glass instance admin + +The deploy bootstraps the local account `web-app-openpost-breakglass` (username `openpost-breakglass`, password generated into the inventory) as the first OpenPost account, which makes it the instance admin. +Use it when Keycloak is unavailable: open `https://publish./` and sign in with the e-mail address and password from the inventory. +When the inventory password changes, for example through credential rotation, the deploy writes its bcrypt hash into the existing account, so a password changed in the UI is reset on the next deploy as well. +If the deploy reports that the break-glass account can neither sign in nor be registered, another account became the first instance admin; sign in with that account and repair the break-glass account, or restore the database from backup. + +## Egress guard and relay + +OpenPost protects itself against server-side request forgery with its `netguard` package. +Before it connects to a provider URL that a user entered, such as a Mastodon instance, it resolves the name and refuses the connection when any address lies in a private, loopback, CGNAT, link-local, documentation, benchmarking, multicast or reserved range. +It repeats the check when it dials and on every redirect, ignores proxy variables and offers no switch for built-in providers. + +Inside an Infinito.Nexus deployment the sibling vhosts usually resolve to private addresses: the development stack, split-horizon DNS and WireGuard meshes all answer with RFC 1918 or mesh addresses. +The role therefore runs an `nginx` stream relay next to OpenPost: + +- The role network uses `192.88.99.0/24`, the deprecated 6to4 relay anycast block (RFC 7526), which `netguard` accepts as a global unicast range and which never leaves the Docker host. + `meta/networks.yml` declares that block with `outside_pool: true` for that reason, which puts the role in `NETWORK_ROLE_SUBNET_EXCEPTION_ROLES`. +- The relay carries OpenPost's own canonical domain, the canonical domains of the deployed Mastodon, Pixelfed and PeerTube roles, and the public domain of the object store, as network aliases, so OpenPost resolves those names to the relay. + OpenPost writes media to the object store's public endpoint because browsers upload through the same presigned URLs; the alias keeps those writes on the shared proxy even where that public name only resolves through Tor. + OpenPost requests its own public media URLs before it lets a provider fetch them. With `svc-net-tor` deployed, the host drops DNS queries from every range outside the internal ones, `192.88.99.0/24` included, so without the alias that check would time out resolving the name. +- The relay reads the SNI of each TLS connection, forwards a mapped name unchanged to the shared OpenResty proxy and closes every other connection. +- Onion services carry no TLS, so the relay also forwards plain HTTP on port 80 to the proxy, which routes it by `Host`; only the aliased names resolve to the relay. + It forwards to `host.docker.internal`, which points at the Docker host in compose and at the stack host in swarm. +- TLS stays end to end between OpenPost and OpenResty; in self-signed mode OpenPost trusts the platform CA through the compose CA injection. + +Every destination that is not one of these aliases still passes through the guard unchanged. +A sibling instance that runs on another host is covered as long as the shared proxy of this host serves its vhost; a Fediverse instance outside the deployment needs no relay because it resolves to public addresses. +OpenPost's Mastodon registration accepts `https` on port 443 only, so the relay requires TLS on the sibling vhosts. + +## Provider credentials + +Developer app credentials live in the central `API` mapping of `group_vars/all/18_api.yml` and are overridden in the vault-encrypted inventory. +A network whose entry is incomplete (`lookup('api_enabled', '')` is false) is not configured in OpenPost and cannot be connected. + +| `API` entry | OpenPost setting | Networks | +|---|---|---| +| `x` | `X_CLIENT_ID`, `X_CLIENT_SECRET` | X | +| `meta` | `OPENPOST_PROVIDER_APPS` entries `facebook` and `instagram` | Facebook Pages, Instagram | +| `threads` | `THREADS_CLIENT_ID`, `THREADS_CLIENT_SECRET` | Threads | +| `linkedin` | `LINKEDIN_CLIENT_ID`, `LINKEDIN_CLIENT_SECRET` | LinkedIn | +| `youtube` | `OPENPOST_PROVIDER_APPS` entry `youtube` | YouTube | +| `tiktok` | `OPENPOST_PROVIDER_APPS` entry `tiktok` | TikTok | + +Mastodon, Pixelfed, PeerTube and Bluesky need no operator credentials: PeerTube exchanges the user's password once for tokens, and Bluesky uses an app password. +For Mastodon and Pixelfed the deploy registers an `OpenPost` app on every deployed sibling instance once, stores its credentials in `fediverse-apps.json` in the role's config directory and renders them into `MASTODON_SERVERS` and `PIXELFED_SERVERS`, named by the instance's canonical URL with a trailing slash. +OpenPost v7.22.9 can register apps on any other instance by itself, but its code exchange then checks provider readiness against the bare host name the dialog sends and refuses with `provider operation is not ready: needs_configuration`; an external instance therefore needs the same pinning through those two variables. +The name has to differ from the URL, because OpenPost hides a server named exactly like its URL from the connect dialog, which then falls back to its own registration and accepts only `https://` instances. +Its code exchange strips the trailing slash, so readiness still matches the canonical URL, and onion instances served over plain HTTP connect through the pinned app. +Pixelfed registers API apps without an owner, and Laravel Passport 13 then treats them as `client_credentials` clients and rejects every token whose user ID equals the app's client ID, which on a fresh instance is the administrator and app number 1. +The deploy therefore makes the Pixelfed administrator the owner of OpenPost's Pixelfed app on every run. +Every callback URL has the form `https://publish./api/v1/accounts//callback`. + +## Provider simulator + +Variant 0 of `meta/variants.yml` starts a WireMock `simulator` on the role network that answers for X, Facebook, Instagram, YouTube and TikTok under their real API host names. +Next to it runs the fake `provider`, a small stateful Python service built from `files/provider/Dockerfile` and the `files/python/provider/` package that plays LinkedIn on `www.linkedin.com` and `api.linkedin.com`: members sign up on `/signup`, grant OpenPost access on the consent page, and the fake keeps the tokens, images and posts it receives. +The deploy signs a certificate for all those names with a per-deploy test CA in the role's config directory, OpenPost trusts that CA through `SSL_CERT_DIR`, and the role renders `simulator-` credentials instead of the `API` entries for the simulated providers. +The keystore that carries the certificate uses WireMock's built-in keystore password, so WireMock starts without any password on its command line. +The fake also publishes plain HTTP on the local port of `services.provider.ports.local.http`; Playwright routes `https://www.linkedin.com/` there, and `/__fake/linkedin/posts` lists what OpenPost delivered. +The mappings live in `files/simulator/openpost.json`; a post whose text contains `[simulate-429]`, `[simulate-503]` or `[simulate-400]` gets that answer from the X endpoint once. +OpenPost v7.22.9 retries a 429 by itself after the reset header, but treats a 503 to a write as an ambiguous delivery: the destination stays in "Manual review required", its retry is refused, and after confirming on the network that nothing was posted the post has to be published again to that destination. +A destination that failed with a definite rejection can be retried on its own. +TikTok renditions need `content_posting_method`, `privacy_level` and `music_usage_confirmed`, YouTube renditions need `privacy` and `category_id` and wait for the media analysis to finish, and LinkedIn Organization Pages stay off, so a LinkedIn account connects as the member's personal profile. +The simulator and the fake provider never run in production; leave the variant to CI and local tests. + +## Networks + +| Network | Post types | Developer app and account | Scopes | Review or verification | Quota | Cost (October 2026) | Token upkeep | +|---|---|---|---|---|---|---|---| +| Mastodon | Text, up to 4 images or one video, threads, scheduling | None; any instance, account of the user | `read write` | None | Set by the instance | None | Tokens do not expire | +| Pixelfed | Up to 4 photos, albums | None; any instance | `read write` | None | Set by the instance | None | Tokens do not expire | +| PeerTube | One video per post to one channel | None; instance username and password | Password exchanged once | None | Instance upload quota | None | OAuth tokens stored encrypted; the password is never stored | +| Bluesky | Text, up to 4 images or one MP4, threads | None; app password | App password | None | About 1,666 creates per hour | None | Sessions last up to 180 days and renew from the app password | +| Facebook Pages | Text, 1–10 images, public video URL, Stories, Reels | Meta Business app; Facebook Page | `pages_manage_posts`, `pages_read_engagement`, `pages_show_list`, `business_management` and the further scopes in the upstream `.env.example` | Standard Access for app-role users without App Review; App Review for everyone else | Reels: 30 per Page per 24 h | No fee found | Long-lived Page tokens do not expire | +| Instagram | Images, carousels, Reels, Stories; no text-only posts | Meta app; Business or Creator account | `instagram_basic`, `instagram_content_publish`, `pages_show_list` and further scopes | App Review for non-role users | 100 per 24 h | No fee found | Instagram Login tokens last 60 days and refresh | +| X | Text (280 weighted characters), up to 4 images or one video, threads | X developer app with prepaid credits | `tweet.read`, `tweet.write`, `users.read`, `offline.access` | None beyond the developer agreement | 100 per 15 min per user | $0.015 per post, $0.20 per post with a URL | Access tokens refresh via `offline.access` | +| YouTube | One video or Short per post, no text or image posts | Google OAuth client; YouTube channel | `youtube.upload`, `youtube.readonly`, `userinfo.profile`, `userinfo.email` | Production status and Google verification for sensitive scopes | 100 `videos.insert` calls per day | No fee found | Testing-status refresh tokens expire after 7 days | +| LinkedIn | Text, images, documents, one MP4 | LinkedIn app; member or Organization Page | `openid`, `profile`, `w_member_social`; organization scopes need approval | Community Management API vetting of the legal entity | Development tier: 500 calls per app per day | No fee found | 60-day tokens without refresh | +| Threads | Text (500 characters), image or carousel, video | Meta app with the Threads product | `threads_basic`, `threads_content_publish` | App Review for non-role users | 250 per 24 h | No fee found | 60 days, refreshable | +| TikTok | One video or 1–35 photos; no text-only posts | TikTok developer app | `user.info.basic`, `video.publish`, `video.upload` | Content Posting API audit | About 15 per creator per day | No fee found | Not researched | + +Sources: the [OpenPost provider reference](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/providers/index.md), its [environment variables](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/configuration/environment-variables.md) and the platform sources listed in the role's requirement. + +## Crossposter + +The `crossposter` sidecar polls Mastodon, Pixelfed and PeerTube accounts and hands every new post to OpenPost through a workspace API token that the deploy issues for the organisation workspace. +It runs only while at least one route is configured, keeps its cursors and delivery records in the `crossposter` schema of the OpenPost database and lets exactly one instance work at a time through a Postgres advisory lock. + +### Routes + +Routes live under `services.crossposter.routes` of `web-app-openpost` in the inventory: + +```yaml +applications: + web-app-openpost: + services: + crossposter: + poll_interval_seconds: 60 + opt_out_tag: nocrosspost + retry: + max_attempts: 8 + base_seconds: 30 + cap_seconds: 3600 + notify: + recipients: + - press@example.org + routes: + - name: press-mastodon + source: + platform: mastodon + base_url: "https://microblog.example.org" + account: press + token: "{{ vault_crosspost_press_mastodon_token }}" + filters: + visibility: [public] + exclude_replies: true + exclude_reblogs: true + tags: [] + media: any + targets: + social_set: Commercial + mode: review + attribution: + default: "{text}\n\n{source_url}" + x: "{text}" +``` + +| Key | Meaning | +|---|---| +| `source.platform` | `mastodon`, `pixelfed` or `peertube`. | +| `source.account` | Mastodon or Pixelfed username, or PeerTube channel name. | +| `source.token` | Read token of the source account, vault-encrypted. It reaches the container as a secret file, never as an environment variable. | +| `filters.visibility` | Visibilities that are forwarded, usually `[public]`. | +| `filters.tags` | Forward only posts carrying one of these hashtags; empty forwards every post. | +| `filters.media` | `any`, `required` or `none`. | +| `targets` | Either `social_set` (name of an OpenPost Social Set) or `accounts` (list of account slugs). | +| `mode` | `review` creates an unscheduled draft; `auto` publishes immediately. New routes start in `review`. | +| `attribution` | Template per network with `{text}` and `{source_url}`; `default` covers networks without their own entry. | + +A route is left out of the deployed configuration while the OpenPost service of its `source.platform` (`services.mastodon`, `services.pixelfed` or `services.peertube`) is disabled, for example PeerTube on an onion-only deployment, since PeerTube refuses the onion. +The deploy validates every remaining route against OpenPost and fails with the route name and the field when a platform is unknown, a token is missing or a target is not connected. +Connect the target accounts and create the Social Set in OpenPost before adding the route. +On the CI rounds with the provider simulator the routes carry no token: the deploy mints read tokens on the local instances, connects the local Mastodon account and creates the empty Social Sets that the CLI probe fills. + +### Review and auto + +In `review` mode an editor finds the crossposted post among the drafts of the desk, adjusts it and schedules or publishes it. +In `auto` mode the crossposter publishes immediately. +A post with a content warning, or with mentions that a commercial network cannot resolve, always becomes a draft. + +Activating a route forwards none of the account's existing posts: its cursor starts at the newest post. +Each poll costs a route one request plus one per further page of new posts (at most five), and on PeerTube one more per new video, so the default 60-second interval stays far below Mastodon's and Pixelfed's 300 requests per five minutes and PeerTube's API limit. +An author keeps a single post local by adding the `#nocrosspost` hashtag. +Posts that OpenPost itself published to Mastodon are never forwarded again, so one account can be source and target. + +### Attribution and X cost + +Each network gets its own template. +The default X template omits the source link, because a post with a URL costs about 13 times more on the X API. +Text is shortened to each network's limit without breaking words, links or hashtags, and Fediverse mentions become plain names on X and profile links elsewhere. + +### Source tokens + +| Platform | How to create the read token | +|---|---| +| Mastodon | Preferences → Development → New application with the `read` scope, then copy the access token. | +| Pixelfed | Settings → Applications → Personal access tokens, create one with the `read` scope. | +| PeerTube | `POST /api/v1/users/token` with the local OAuth client and the account's password; PeerTube channel listings are public, the token only identifies the crossposter. | + +### Failed deliveries + +Transient errors (network errors, HTTP 429 and 5xx) are retried with capped exponential backoff and jitter that honours `Retry-After` and rate-limit reset headers. +When OpenPost reports a provider outage for an automatic publication, the crossposter publishes it again under a new idempotency key. +After `retry.max_attempts` the item is dead-lettered; a permanent rejection by the provider marks it failed. +Both reach `notify.recipients` in one mail per poll, with the source post, the target and the last error. + +List every crossposted item with its state: + +```bash +container exec python -m crossposter list --config /config/crossposter.json +``` + +A dead-lettered item stays in that state; publish the post again from the OpenPost desk when the cause is fixed. + +## Unsupported features and workarounds + +| Limitation | Workaround | +|---|---| +| TikTok's content sharing guidelines reject in-house upload tools as a use case for the Content Posting API. | Publish to TikTok manually, or apply with a use case TikTok accepts; keep TikTok credentials empty until then. | +| X charges $0.20 instead of $0.015 for a post that contains a URL. | Write the X rendition without links, or accept the surcharge per post. | +| X forbids identical content across accounts of the same owner. | Give each X account its own rendition. | +| On an onion-only deployment OpenPost marks uploaded media as unreachable for providers, because X, Meta, LinkedIn, YouTube and TikTok cannot fetch from a `.onion` origin. | Serve media from object storage with a clearnet public URL, or publish text-only posts to commercial networks. | +| OpenPost cannot connect a Mastodon or Pixelfed instance served only on a `.onion` name: its Go resolver refuses to look up `.onion` names (RFC 7686), and its own app registration accepts only `https://` instances. The deploy therefore pins no app for an onion sibling, and the CI connect checks skip it. | Connect the instance through a clearnet name. The crossposter still reads onion sources, because Python resolves them through the relay. | +| On a compose deployment served on `.onion`, single sign-on fails: OpenPost reaches the onion Keycloak only through Tor's SOCKS port, which `svc-net-tor` opens to the internal ranges, and OpenPost's role subnet `192.88.99.0/24` is not one of them. The CI round with SSO therefore runs clearnet only. | Sign in with a native OpenPost account on onion deployments. | +| OpenPost's X budget guardrail (`OPENPOST_X_MONTHLY_BUDGET_MICROUSD`) applies only in its cloud edition. | Cap X spending through the prepaid credits of the X developer account. | +| Instagram accepts JPEG only and fetches media from a public URL. | Deploy `web-svc-seaweedfs` so media gets public HTTPS URLs; convert other image formats before upload. | +| Facebook, Instagram, Threads and TikTok fetch media from public HTTPS URLs. | Same as above; without `web-svc-seaweedfs` media is served under `/media/` of the public OpenPost domain, which also works when that domain is reachable from the internet. | +| LinkedIn requires vetting of the legal entity and re-authorisation every 60 days. | Plan the vetting before launch and schedule a re-authorisation reminder. | +| YouTube projects in testing status lose refresh tokens after 7 days. | Move the Google OAuth client to production status and complete verification. | +| Bluesky is also reachable without OpenPost through `web-app-bridgy-fed`. | Use the bridge for automatic federation and OpenPost for deliberate Bluesky-native posts. | +| OpenPost connects PeerTube only through the OAuth password grant, and PeerTube accounts that sign in through Keycloak have no local password. | Connect a local PeerTube account: the `root` account, which a fresh `web-app-peertube` instance creates with the first 50 characters of the platform administrator's password, or one the PeerTube administrator creates for publishing. PeerTube then asks for the channel each video goes to. | +| Sibling Fediverse instances are reachable only over TLS on port 443. | Keep TLS enabled for `web-app-mastodon`, `web-app-pixelfed` and `web-app-peertube`. | +| OpenPost's media upload, avatar upload and instance backup routes believe `X-Forwarded-Proto` only from loopback, link-local or private peers, unlike the rest of its API, which follows `OPENPOST_TRUSTED_PROXY_CIDRS`. Behind the shared proxy on the role subnet `192.88.99.0/24` they take an HTTPS session for plain HTTP and refuse it as cross-site (HTTP 403 `cross-site session request rejected`) whenever media stays in the role volume. | The role adds one location for exactly those routes to its vhost (`templates/nginx/echo_routes.conf.j2`). It forwards them as plain HTTP and rewrites the browser's own `https://` origin to `http://`, so both sides agree in compose and swarm; OpenPost still compares the origin's host. | + +## Data processing and dependencies + +- Every network receives exactly what a user publishes to it: the rendition text, attached media, alt text and post settings, plus the OAuth tokens of the connected account. +- Facebook, Instagram, Threads and TikTok additionally download the attached media from its public URL. +- Provider tokens and provider-app secrets are stored in Postgres encrypted with AES-256-GCM under `OPENPOST_ENCRYPTION_KEY`; the key lives in the inventory and is needed to restore a backup. +- Diagnostics, the update check, PostHog telemetry, the feedback form, public profiles, stock media search and workflow AI are disabled, so the instance sends nothing to OpenPost's maintainers or to AI providers. +- Third-party dependencies at runtime are the APIs of the connected networks only. +- OpenPost is licensed AGPL-3.0-only. + The role deploys the unmodified upstream image and links its source, which satisfies the AGPL's source-offer obligation for network users; the role's own files remain under the Infinito.Nexus Community License. + +## Backup, restore and upgrades + +- With `web-svc-seaweedfs` deployed, browsers upload media directly to its public S3 vhost through presigned URLs, which is why `OPENPOST_S3_ENDPOINT` is the public endpoint and the CSP allows it in `connect-src`; OpenPost deduplicates identical files by content hash. + With `TLS_MODE=self_signed` the role always mounts the root CA into OpenPost and adds it to `SSL_CERT_DIR`, because an onion-primary OpenPost receives no CA injection while that vhost and the local Fediverse siblings behind the relay stay on clearnet HTTPS. +- The platform backup covers the OpenPost database in the shared Postgres and the `openpost_media` volume; media in `web-svc-seaweedfs` is covered by that role's backup. +- A restore needs the database, the media and the inventory secrets, especially `encryption_key`; without it the stored provider tokens cannot be decrypted and every network has to be reconnected. The key is pinned `rotatable: false` because OpenPost refuses to start once a stored row no longer decrypts; the other secrets rotate freely. +- Changing the pinned version in `meta/services.yml` and redeploying runs OpenPost's own migrations, which take a Postgres advisory lock. + Only the latest upstream release receives security fixes, so follow new release tags promptly. + +## Staging checklist + +Run these checks against real platforms after onboarding a network and after every OpenPost upgrade: + +1. Connect the account in a staging workspace and confirm OpenPost shows it as connected. +2. Publish a text post (where supported), an image post and a video post immediately. +3. Schedule a post five minutes ahead and confirm it appears on time. +4. Open each published post through the link in OpenPost. +5. Disconnect the account and reconnect it to confirm token renewal. +6. Record the result in the matrix below. + +## Verified combinations + +| Network | Content type | OpenPost version | Date | Result | +|---|---|---|---|---| +| Mastodon (local instance) | Text | v7.22.9 | 2026-10-22 | Published, CI end-to-end test | +| Pixelfed (local instance) | Image | v7.22.9 | 2026-10-22 | Published, CI end-to-end test | +| PeerTube (local instance) | Video | v7.22.9 | 2026-10-22 | Published to the `root` channel, CI end-to-end test | +| X (simulator) | Text, scheduled text | v7.22.9 | 2026-10-22 | Published; 429 retried, 503 held for manual review, 400 failed | +| Facebook Pages (simulator) | Text to two Pages | v7.22.9 | 2026-10-22 | Published | +| Instagram (simulator) | JPEG image | v7.22.9 | 2026-10-22 | Published from a public media URL | +| YouTube (simulator) | Video | v7.22.9 | 2026-10-22 | Published through a resumable upload | +| LinkedIn (fake provider) | Text, crossposted from Mastodon and edited in the desk | v7.22.9 | not yet verified | CI end-to-end test | +| TikTok (simulator) | Photo | v7.22.9 | 2026-10-22 | Published | +| Facebook Pages | Text, image | v7.22.9 | not yet verified | Manual staging check | +| Instagram | Image | v7.22.9 | not yet verified | Manual staging check | +| X | Text | v7.22.9 | not yet verified | Manual staging check | +| YouTube | Video | v7.22.9 | not yet verified | Manual staging check | diff --git a/roles/web-app-openpost/README.md b/roles/web-app-openpost/README.md new file mode 100644 index 0000000000..87e56211a5 --- /dev/null +++ b/roles/web-app-openpost/README.md @@ -0,0 +1,33 @@ +# OpenPost + +## Description + +[OpenPost](https://github.com/getopenpost/openpost) is a self-hosted publishing desk for social media. +Teams compose posts once, adapt them per network, schedule them and publish them to Mastodon, Pixelfed, PeerTube, Bluesky, Facebook Pages, Instagram, Threads, X, YouTube, LinkedIn and TikTok from one interface. + +## Overview + +This role deploys the unmodified official `ghcr.io/getopenpost/openpost` image as one `all` process behind the shared OpenResty proxy at `publish.`. +It stores data in the central PostgreSQL, keeps media in the `web-svc-seaweedfs` object store when one is deployed, signs users in through Keycloak over OIDC and sends mail through the platform mail service. +An always-on egress relay lets OpenPost publish to the Mastodon, Pixelfed and PeerTube instances of the same deployment without weakening its SSRF guard. +For operation, platform onboarding and the egress design see [Administration.md](./Administration.md). + +## Features + +- **Official image only:** The role pins an upstream release tag, configures OpenPost purely through environment variables and lets the update tooling propose new release tags. +- **Keycloak single sign-on:** OpenPost's native OIDC adapter provisions users just in time on their first login, and the platform administrator becomes instance admin through the bootstrap allowlist. +- **No LDAP adapter:** OpenPost ships no LDAP login, so the role declares no `ldap` service; directory accounts sign in through Keycloak's OpenLDAP federation over OIDC. +- **Egress relay:** An nginx stream relay carries the canonical domains of the deployed Mastodon, Pixelfed and PeerTube instances as network aliases on a subnet outside OpenPost's blocked ranges and forwards the untouched TLS stream by SNI to the shared proxy. +- **Break-glass admin:** A local instance admin is bootstrapped on the first deploy so the instance stays manageable when Keycloak is unavailable. +- **Data minimisation:** Diagnostics, the update check, product telemetry, feedback, public profiles, stock media search and workflow AI are switched off. +- **Central credentials:** Developer app credentials for X, Meta, Threads, LinkedIn, YouTube and TikTok come from the central `API` mapping, and a network without credentials stays unavailable. +- **Automated crossposting:** A crossposter sidecar polls configured Mastodon, Pixelfed and PeerTube accounts and hands every new post to OpenPost, as a draft for review or for immediate publishing, with per-network shortening, attribution, opt-out by hashtag, loop prevention and mailed reports of failed deliveries. + +## Developer Notes + +See [Administration.md](./Administration.md) for the egress relay, the break-glass procedure, per-network onboarding and the staging checklist. + +## Further Resources + +- [OpenPost on GitHub](https://github.com/getopenpost/openpost) +- [OpenPost provider reference](https://github.com/getopenpost/openpost/blob/0deadaf7bbf3b3be045e783c3eeef323c9e3c440/docs/reference/providers/index.md) diff --git a/roles/web-app-openpost/files/crossposter/Dockerfile b/roles/web-app-openpost/files/crossposter/Dockerfile new file mode 100644 index 0000000000..ab96a6bf56 --- /dev/null +++ b/roles/web-app-openpost/files/crossposter/Dockerfile @@ -0,0 +1,24 @@ +ARG CROSSPOSTER_BASE_IMAGE +ARG CROSSPOSTER_BASE_VERSION +FROM ${CROSSPOSTER_BASE_IMAGE}:${CROSSPOSTER_BASE_VERSION} + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +ARG CROSSPOSTER_UID +RUN groupadd --system --gid "${CROSSPOSTER_UID}" crossposter \ + && useradd --system --uid "${CROSSPOSTER_UID}" --gid crossposter --home-dir /app --shell /usr/sbin/nologin crossposter + +WORKDIR /app + +COPY requirements.txt ./requirements.txt +RUN pip install --no-cache-dir -r requirements.txt + +COPY crossposter ./crossposter + +USER crossposter + +HEALTHCHECK --interval=2m --timeout=5s --retries=3 --start-period=10m --start-interval=5s \ + CMD ["python", "-m", "crossposter", "health", "--config", "/config/crossposter.json"] + +CMD ["python", "-m", "crossposter", "run", "--config", "/config/crossposter.json"] diff --git a/roles/web-app-openpost/files/crossposter/requirements.txt b/roles/web-app-openpost/files/crossposter/requirements.txt new file mode 100644 index 0000000000..2398febb21 --- /dev/null +++ b/roles/web-app-openpost/files/crossposter/requirements.txt @@ -0,0 +1,2 @@ +psycopg[binary]==3.3.9 +pillow==13.0.0 diff --git a/roles/web-app-openpost/files/nginx/deny-password-registration.conf b/roles/web-app-openpost/files/nginx/deny-password-registration.conf new file mode 100644 index 0000000000..69c7dd217b --- /dev/null +++ b/roles/web-app-openpost/files/nginx/deny-password-registration.conf @@ -0,0 +1,3 @@ +location = /api/v1/auth/register { + return 403; +} diff --git a/roles/web-app-openpost/files/php/pixelfed/client_owner.php b/roles/web-app-openpost/files/php/pixelfed/client_owner.php new file mode 100644 index 0000000000..f3b6555556 --- /dev/null +++ b/roles/web-app-openpost/files/php/pixelfed/client_owner.php @@ -0,0 +1,18 @@ +make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); + +$owner = App\Models\User::where('username', getenv('OPENPOST_CLIENT_OWNER'))->firstOrFail(); +$client = Laravel\Passport\Client::whereKey(getenv('OPENPOST_CLIENT_ID'))->firstOrFail(); +if ((string) $client->user_id !== (string) $owner->id) { + $client->forceFill(['user_id' => $owner->id])->save(); + echo 'OWNER_SET' . PHP_EOL; +} diff --git a/roles/web-app-openpost/files/php/pixelfed/mint_token.php b/roles/web-app-openpost/files/php/pixelfed/mint_token.php new file mode 100644 index 0000000000..7bbd4bd900 --- /dev/null +++ b/roles/web-app-openpost/files/php/pixelfed/mint_token.php @@ -0,0 +1,25 @@ +. + +require getenv('PIXELFED_APP_DIR') . '/vendor/autoload.php'; +$app = require getenv('PIXELFED_APP_DIR') . '/bootstrap/app.php'; +$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); + +$user = App\Models\User::where('username', getenv('CROSSPOSTER_ACCOUNT'))->firstOrFail(); +$mint = fn () => $user->createToken('crossposter-ci', ['read', 'write'])->accessToken; +try { + $token = $mint(); +} catch (RuntimeException $missing) { + Illuminate\Support\Facades\Artisan::call('passport:client', [ + '--personal' => true, + '--provider' => 'users', + '--name' => 'Crossposter CI', + '--no-interaction' => true, + ]); + $token = $mint(); +} +echo 'CROSSPOSTER_TOKEN=' . $token . PHP_EOL; diff --git a/roles/web-app-openpost/files/playwright/.nocheck b/roles/web-app-openpost/files/playwright/.nocheck new file mode 100644 index 0000000000..9ceebc5e82 --- /dev/null +++ b/roles/web-app-openpost/files/playwright/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Playwright discovers this suite by path; the runner copies the tree as it stands and the specs import their helpers relatively. Sorting by extension would break discovery. diff --git a/roles/web-app-openpost/files/playwright/_shared.js b/roles/web-app-openpost/files/playwright/_shared.js new file mode 100644 index 0000000000..21a506d5ef --- /dev/null +++ b/roles/web-app-openpost/files/playwright/_shared.js @@ -0,0 +1,536 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +const { decodeDotenvQuotedValue, normalizeBaseUrl, performKeycloakLoginForm, gotoOnion } = require("./personas"); +const { isServiceEnabled, skipUnlessServiceEnabled } = require("./service-gating"); + +const env = { + appBaseUrl: normalizeBaseUrl(decodeDotenvQuotedValue(process.env.APP_BASE_URL)), + canonicalDomain: decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN), + oidcIssuerUrl: normalizeBaseUrl(decodeDotenvQuotedValue(process.env.OIDC_ISSUER_URL || "")), + adminUsername: decodeDotenvQuotedValue(process.env.ADMIN_USERNAME), + adminPassword: decodeDotenvQuotedValue(process.env.ADMIN_PASSWORD), + adminEmail: decodeDotenvQuotedValue(process.env.ADMIN_EMAIL), + biberUsername: decodeDotenvQuotedValue(process.env.BIBER_USERNAME), + biberPassword: decodeDotenvQuotedValue(process.env.BIBER_PASSWORD), + breakglassEmail: decodeDotenvQuotedValue(process.env.BREAKGLASS_EMAIL), + breakglassPassword: decodeDotenvQuotedValue(process.env.BREAKGLASS_PASSWORD), + mastodonBaseUrl: normalizeBaseUrl(decodeDotenvQuotedValue(process.env.MASTODON_BASE_URL || "")), + pixelfedBaseUrl: normalizeBaseUrl(decodeDotenvQuotedValue(process.env.PIXELFED_BASE_URL || "")), + linkedinFakeUrl: normalizeBaseUrl(decodeDotenvQuotedValue(process.env.LINKEDIN_FAKE_URL || "")), + organisationWorkspace: decodeDotenvQuotedValue(process.env.ORGANISATION_WORKSPACE), + oidcEnabled: isServiceEnabled("sso"), +}; + +const SAMPLE_PNG = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAGy0lEQVR4nBXVkb/GIBTG8ReHYTgMw+EwHIbDMBwOh8Pwh+FwOAyHYRiG4d3tD+jb53TOc36/H8MP8UP+GH+oH/rH9GP+YX4sP+yP9Yf74X9sP/Yfx4/zR/jBj/jj+nH/eH6kH++P/KP8qD/aj/7j9xsYBsSAHBgH1IAemAbmATOwDNiBdcAN+IFtYB84Bs6BMMBAHLgG7oFnIA28A3mgDNSBNtCHDxAMAiGQglGgBFowCWaBESwCK1gFTuAFm2AXHIJTEAQIouAS3IJHkASvIAuKoAqaoIsPkAwSIZGSUaIkWjJJZomRLBIrWSVO4iWbZJccklMSJEii5JLckkeSJK8kS4qkSpqkyw8YGUbEiBwZR9SIHplG5hEzsozYkXXEjfiRbWQfOUbOkTDCSBy5Ru6RZySNvCN5pIzUkTbSxw9QDAqhkIpRoRRaMSlmhVEsCqtYFU7hFZtiVxyKUxEUKKLiUtyKR5EUryIriqIqmqKrD9AMGqGRmlGjNFozaWaN0Swaq1k1TuM1m2bXHJpTEzRooubS3JpHkzSvJmuKpmqapusPmBgmxIScGCfUhJ6YJuYJM7FM2Il1wk34iW1inzgmzokwwUScuCbuiWciTbwTeaJM1Ik20acPmBlmxIycGWfUjJ6ZZuYZM7PM2Jl1xs34mW1mnzlmzpkww0ycuWbumWcmzbwzeabM1Jk20+cPMAwGYZCG0aAM2jAZZoMxLAZrWA3O4A2bYTcchtMQDBii4TLchseQDK8hG4qhGpqhmw9YGBbEglwYF9SCXpgW5gWzsCzYhXXBLfiFbWFfOBbOhbDAQly4Fu6FZyEtvAt5oSzUhbbQlw+wDBZhkZbRoizaMllmi7EsFmtZLc7iLZtltxyW0xIsWKLlstyWx5IsryVbiqVamqXbD1gZVsSKXBlX1IpemVbmFbOyrNiVdcWt+JVtZV85Vs6VsMJKXLlW7pVnJa28K3mlrNSVttLXD3AMDuGQjtGhHNoxOWaHcSwO61gdzuEdm2N3HI7TERw4ouNy3I7HkRyvIzuKozqao7sP8Awe4ZGe0aM82jN5Zo/xLB7rWT3O4z2bZ/ccntMTPHii5/LcnseTPK8ne4qnepqn+w/YGDbEhtwYN9SG3pg25g2zsWzYjXXDbfiNbWPfODbOjbDBRty4Nu6NZyNtvBt5o2zUjbbRtw/YGXbEjtwZd9SO3pl25h2zs+zYnXXH7fidbWffOXbOnbDDTty5du6dZyftvDt5p+zUnbbT9w84GA7EgTwYD9SBPpgO5gNzsBzYg/XAHfiD7WA/OA7Og3DAQTy4Du6D5yAdvAf5oBzUg3bQjw84GU7EiTwZT9SJPplO5hNzspzYk/XEnfiT7WQ/OU7Ok3DCSTy5Tu6T5ySdvCf5pJzUk3bSzw8IDAERkIExoAI6MAXmgAksARtYAy7gA1tgDxyBMxACBGLgCtyBJ5ACbyAHSqAGWqCHD/hffN9q+pbHF+9fAH8R+YXYFzNfEHyj+g3T1+5fQ34t833qV/avMN/Tv8v/T4QLbnggwQsZClRo0L+1/YsMERGRkTGiIjoyReaIiSwRG1kjLuIjW2SPHJEzEuL/9TFyRe7IE0mRN5IjJVIjLdLjB1wMF+JCXowX6kJfTBfzhblYLuzFeuEu/MV2sV8cF+dFuP4fHy+ui/viuUgX70W+KBf1ol306wNuhhtxI2/GG3Wjb6ab+cbcLDf2Zr1xN/5mu9lvjpvzJtz/pYk3181989ykm/cm35SbetNu+v0BD8ODeJAP44N60A/Tw/xgHpYH+7A+uAf/sD3sD8fD+RCe/8LHh+vhfnge0sP7kB/KQ31oD/35gMSQEAmZGBMqoRNTYk6YxJKwiTXhEj6xJfbEkTgTIf1/a0xciTvxJFLiTeRESdRES/T0AS/Di3iRL+OLetEv08v8Yl6WF/uyvrgX/7K97C/Hy/kS3v+miS/Xy/3yvKSX9yW/lJf60l76+wGZISMyMjNmVEZnpsycMZklYzNrxmV8ZsvsmSNzZkL+b8mYuTJ35smkzJvJmZKpmZbp+QMKQ0EUZGEsqIIuTIW5YApLwRbWgiv4wlbYC0fhLITy3/CxcBXuwlNIhbeQC6VQC63QywdUhoqoyMpYURVdmSpzxVSWiq2sFVfxla2yV47KWQn1f5xi5arclaeSKm8lV0qlVlql1w9oDA3RkI2xoRq6MTXmhmksDdtYG67hG1tjbxyNsxHa/7DGxtW4G08jNd5GbpRGbbRGbx/QGTqiIztjR3V0Z+rMHdNZOrazdlzHd7bO3jk6Zyf0/yiInatzd55O6ryd3Cmd2mmd3vkD4XNgW5DmDQMAAAAASUVORK5CYII=", + "base64", +); + +const LOGIN_PATH = "/login"; + +function onLoginPage(page) { + return new URL(page.url()).pathname.startsWith(LOGIN_PATH); +} + +async function gotoLogin(page) { + return gotoOnion(page, `${env.appBaseUrl}${LOGIN_PATH}`, { waitUntil: "domcontentloaded" }); +} + +function profileMenuTrigger(page) { + return page.locator('[data-testid="profile-menu-trigger"]').first(); +} + +async function assertAuthenticated(page, label) { + await expect + .poll(() => onLoginPage(page), { + timeout: resolveTimeout(60_000), + message: `${label}: expected to leave the OpenPost login page`, + }) + .toBe(false); + const onboarding = page.getByRole("heading", { name: /create your first workspace/i }); + await expect( + profileMenuTrigger(page).or(onboarding), + `${label}: the authenticated OpenPost desk or its first-run onboarding must render`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + if (await onboarding.isVisible()) { + await page.getByLabel(/workspace name/i).fill(`${label} workspace`); + await page.getByRole("button", { name: /create workspace/i }).click(); + } + await expect( + profileMenuTrigger(page), + `${label}: the authenticated OpenPost profile menu must be visible`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); +} + +async function signInViaLocal(page, email, password, label) { + await gotoLogin(page); + await page.locator("#email").fill(email); + await page.locator("#password").fill(password); + await page.locator("form").filter({ has: page.locator("#password") }).locator('button[type="submit"]').click(); + await assertAuthenticated(page, label); +} + +function oidcProviderButton(page) { + return page.locator("a, button").filter({ hasText: /sso|single sign-on|keycloak/i }).first(); +} + +async function signInViaOidc(page, username, password, label) { + await gotoLogin(page); + const button = oidcProviderButton(page); + await expect(button, `${label}: the Keycloak sign-in button must render on the OpenPost login page`).toBeVisible({ + timeout: resolveTimeout(30_000), + }); + await button.click(); + await expect + .poll(() => page.url(), { + timeout: resolveTimeout(60_000), + message: `${label}: expected redirect to Keycloak (${env.oidcIssuerUrl}/protocol/openid-connect/auth)`, + }) + .toContain(`${env.oidcIssuerUrl}/protocol/openid-connect/auth`); + await performKeycloakLoginForm(page, username, password); + await assertAuthenticated(page, label); +} + +async function logout(page, label) { + await profileMenuTrigger(page).click(); + await page.getByRole("menuitem", { name: /log\s*out|sign\s*out/i }).click(); + await expect + .poll(() => onLoginPage(page), { + timeout: resolveTimeout(60_000), + message: `${label}: expected logged-out landing on the OpenPost login page`, + }) + .toBe(true); +} + +async function openUsersPanel(page) { + await gotoOnion(page, `${env.appBaseUrl}/settings?tab=users`, { waitUntil: "domcontentloaded" }); + await expect(page.locator('[data-testid="settings-navigation"]')).toBeVisible({ timeout: resolveTimeout(60_000) }); +} + +async function openInstanceAdministration(page, label) { + await openUsersPanel(page); + await expect( + page.locator('[data-testid="instance-user-directory"]'), + `${label}: the instance user directory must render for an instance admin`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + await expect( + page.locator('[data-testid="instance-user-directory"]').getByText(env.breakglassEmail).first(), + `${label}: the instance user directory must list the break-glass admin`, + ).toBeVisible({ timeout: resolveTimeout(30_000) }); +} + +async function assertInstanceAdministrationDenied(page, label) { + await openUsersPanel(page); + await expect( + page.locator('[data-testid="instance-admin-users"]'), + `${label}: the instance user directory must stay hidden from a regular user`, + ).toHaveCount(0); + await expect( + page.locator('[data-testid="settings-navigation"]').getByText(/^instance$/i), + `${label}: the settings navigation must not offer the instance section`, + ).toHaveCount(0); +} + +async function openComposer(page, label) { + await page.locator('[data-testid="sidebar-new-post"]').click(); + await expect( + page.locator('[contenteditable="true"], textarea').first(), + `${label}: the composer must open with an editable text area`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); +} + +async function assertWorkspaceHidden(page, workspaceName, label) { + expect(workspaceName, "ORGANISATION_WORKSPACE must be set").toBeTruthy(); + await gotoOnion(page, `${env.appBaseUrl}/`, { waitUntil: "domcontentloaded" }); + await page.locator('[data-testid="workspace-menu-trigger"]').click(); + const menu = page.getByRole("menu"); + await expect(menu, `${label}: the workspace switcher must open`).toBeVisible({ timeout: resolveTimeout(30_000) }); + await expect( + menu.getByText(workspaceName, { exact: true }), + `${label}: the organisation workspace "${workspaceName}" must not be offered`, + ).toHaveCount(0); + await page.keyboard.press("Escape"); +} + +function crc32(buffer) { + let crc = 0xffffffff; + for (const byte of buffer) { + crc ^= byte; + for (let bit = 0; bit < 8; bit += 1) { + crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); + } + } + return (crc ^ 0xffffffff) >>> 0; +} + +function uniquePng(text) { + const data = Buffer.concat([Buffer.from("Comment\0", "latin1"), Buffer.from(text, "latin1")]); + const type = Buffer.from("tEXt", "latin1"); + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const checksum = Buffer.alloc(4); + checksum.writeUInt32BE(crc32(Buffer.concat([type, data]))); + const iend = SAMPLE_PNG.length - 12; + return Buffer.concat([SAMPLE_PNG.subarray(0, iend), length, type, data, checksum, SAMPLE_PNG.subarray(iend)]); +} + +async function uploadMedia(page, fileName, label) { + await gotoOnion(page, `${env.appBaseUrl}/media`, { waitUntil: "domcontentloaded" }); + const addMedia = page.getByRole("button", { name: /add media/i }); + await expect(addMedia, `${label}: the media library must offer "Add media"`).toBeVisible({ + timeout: resolveTimeout(60_000), + }); + await addMedia.click(); + const dialog = page.getByRole("dialog", { name: /upload media/i }); + await expect(dialog, `${label}: the upload dialog must open`).toBeVisible({ timeout: resolveTimeout(30_000) }); + const completed = page.waitForResponse( + (response) => + response.request().method() === "POST" && + /\/api\/v1\/media\/upload-session\/[^/]+\/complete$/.test(new URL(response.url()).pathname), + { timeout: resolveTimeout(60_000) }, + ); + await dialog.locator('input[type="file"]').first().setInputFiles({ + name: fileName, + mimeType: "image/png", + buffer: uniquePng(fileName), + }); + const confirm = dialog.getByRole("button", { name: /^(upload|add|save)/i }); + if (await confirm.first().isVisible().catch(() => false)) { + await confirm.first().click(); + } + expect((await completed).ok(), `${label}: OpenPost must complete the upload`).toBe(true); + await expect( + dialog.getByText(fileName).first(), + `${label}: the upload dialog must list the file it received`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + if (await dialog.isVisible().catch(() => false)) { + await page.keyboard.press("Escape"); + } + await expect(dialog, `${label}: the upload dialog must close`).toBeHidden({ timeout: resolveTimeout(30_000) }); + await gotoOnion(page, `${env.appBaseUrl}/media`, { waitUntil: "domcontentloaded" }); + await expect( + page.getByText(fileName).or(page.locator(`img[alt*="${fileName}"]`)).first(), + `${label}: the uploaded file must appear in the media library`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); +} + +async function openMastodonConnectDialog(page, label) { + await gotoOnion(page, `${env.appBaseUrl}/accounts`, { waitUntil: "domcontentloaded" }); + const card = page.locator('[data-testid="provider-card-mastodon"]'); + await expect(card, `${label}: the Mastodon provider card must render`).toBeVisible({ timeout: resolveTimeout(60_000) }); + await card.getByRole("button", { name: /^connect$/i }).click(); + const dialog = page.getByRole("dialog", { name: /connect mastodon/i }); + await dialog.getByRole("button", { name: /continue to mastodon/i }).click(); + await dialog.getByRole("textbox", { name: /server address/i }).fill(env.mastodonBaseUrl); + return dialog; +} + +function mastodonChannelActions(page, account) { + return page.getByRole("button", { name: new RegExp(`^actions for ${account.handle} · mastodon$`, "i") }); +} + +function skipOnOnionSibling(platform) { + test.skip( + env[`${platform}BaseUrl`].includes(".onion"), + `OpenPost cannot connect an onion ${platform} instance: its Go resolver refuses .onion names`, + ); +} + +async function disconnectAccount(page, account) { + const listed = page.waitForResponse( + (response) => response.request().method() === "GET" && new URL(response.url()).pathname === "/api/v1/accounts", + { timeout: resolveTimeout(60_000) }, + ); + await gotoOnion(page, `${env.appBaseUrl}/accounts`, { waitUntil: "domcontentloaded" }); + const response = await listed; + expect(response.ok(), `${account.handle}: OpenPost must list the workspace accounts, got HTTP ${response.status()}`).toBeTruthy(); + const username = account.handle.replace(/^@/, "").toLowerCase(); + const connected = (await response.json()).some( + (entry) => entry.platform === "mastodon" && String(entry.account_username).replace(/^@/, "").toLowerCase() === username, + ); + if (!connected) { + return; + } + const actions = mastodonChannelActions(page, account); + await expect(actions, `${account.handle}: the connected account must offer its actions`).toBeVisible({ + timeout: resolveTimeout(60_000), + }); + await actions.click(); + await page.getByRole("menuitem", { name: /remove connection/i }).click(); + const confirm = page.getByRole("alertdialog").or(page.getByRole("dialog")).first(); + await expect(confirm, `${account.handle}: OpenPost must ask before removing the connection`).toBeVisible({ + timeout: resolveTimeout(30_000), + }); + await confirm.getByRole("button", { name: /^remove connection$/i }).click(); + await expect(actions, `${account.handle} must disappear from the connected accounts`).toBeHidden({ + timeout: resolveTimeout(60_000), + }); +} + +async function connectMastodonAccount(page, context, label) { + const account = { handle: `@${env.adminUsername}` }; + await disconnectAccount(page, account); + const dialog = await openMastodonConnectDialog(page, label); + await dialog.getByRole("button", { name: /^connect$/i }).click(); + await expect + .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: `${label}: expected Mastodon's sign-in page` }) + .toContain(`${env.mastodonBaseUrl}/auth/sign_in`); + await page.getByRole("link", { name: /sso|single sign-on/i }).click(); + await page.waitForLoadState("domcontentloaded"); + if (page.url().includes(`${env.oidcIssuerUrl}/protocol/openid-connect/auth`)) { + await performKeycloakLoginForm(page, env.adminUsername, env.adminPassword); + } + const authorize = page.getByRole("button", { name: /^authorize$/i }); + await expect + .poll(async () => page.url().includes("/oauth/authorize/native") || (await authorize.isVisible()), { + timeout: resolveTimeout(60_000), + message: `${label}: expected Mastodon's consent screen or its authorization code page`, + }) + .toBe(true); + if (await authorize.isVisible()) { + await authorize.click(); + } + await expect + .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: `${label}: expected Mastodon's authorization code page` }) + .toContain(`${env.mastodonBaseUrl}/oauth/authorize/native`); + const code = await page.getByRole("textbox").first().inputValue(); + expect(code, `${label}: Mastodon must show an authorization code`).toBeTruthy(); + + const codeDialog = await openMastodonConnectDialog(page, label); + await codeDialog.getByRole("button", { name: /^code$/i }).click(); + await page.getByRole("textbox", { name: /authorization code/i }).fill(code); + await page.getByRole("button", { name: /connect account/i }).click(); + await expect + .poll(() => new URL(page.url()).pathname, { + timeout: resolveTimeout(60_000), + message: `${label}: OpenPost must leave the code page after the exchange`, + }) + .not.toContain("/accounts/mastodon/callback"); + await gotoOnion(page, `${env.appBaseUrl}/accounts`, { waitUntil: "domcontentloaded" }); + await expect( + mastodonChannelActions(page, account), + `${label}: ${account.handle} must be listed among the connected accounts`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + return account; +} + +async function publishNow(page, account, text) { + await page.getByRole("link", { name: /^new post$/i }).click(); + await page.getByRole("textbox", { name: /post text/i }).first().fill(text); + await page.getByRole("main").getByRole("button", { name: /^more$/i }).click(); + await page.getByRole("menuitem", { name: /^publish now$/i }).click(); + const confirm = page.getByRole("alertdialog").or(page.getByRole("dialog")); + if (await confirm.first().isVisible().catch(() => false)) { + await confirm.first().getByRole("button", { name: /publish/i }).first().click(); + } +} + +async function mastodonStatusExists(page, account, marker) { + const handle = account.handle.replace(/^@/, ""); + const lookup = await page.request.get(`${env.mastodonBaseUrl}/api/v1/accounts/lookup?acct=${encodeURIComponent(handle)}`); + if (!lookup.ok()) { + return false; + } + const { id } = await lookup.json(); + const statuses = await page.request.get(`${env.mastodonBaseUrl}/api/v1/accounts/${id}/statuses?limit=20`); + if (!statuses.ok()) { + return false; + } + return (await statuses.json()).some((status) => String(status.content || "").includes(marker)); +} + +async function openPixelfedConnectDialog(page, label) { + await gotoOnion(page, `${env.appBaseUrl}/accounts`, { waitUntil: "domcontentloaded" }); + const card = page.locator('[data-testid="provider-card-pixelfed"]'); + await expect(card, `${label}: the Pixelfed provider card must render`).toBeVisible({ timeout: resolveTimeout(60_000) }); + await card.getByRole("button", { name: /^connect$/i }).click(); + const dialog = page.getByRole("dialog", { name: /connect pixelfed/i }); + await dialog.getByRole("button", { name: /continue to pixelfed/i }).click(); + await dialog.getByRole("textbox", { name: /server address/i }).fill(env.pixelfedBaseUrl); + return dialog; +} + +function pixelfedChannelActions(page, account) { + return page.getByRole("button", { name: new RegExp(`^actions for ${account.handle} · pixelfed$`, "i") }); +} + +const OOB_REDIRECT = "urn:ietf:wg:oauth:2.0:oob"; + +async function pixelfedAuthorizationCode(page, label, redirectedCode) { + await expect + .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: `${label}: expected Pixelfed's sign-in or consent page` }) + .toContain(env.pixelfedBaseUrl); + const password = page.locator('input[name="password"]'); + const authorize = page.getByRole("button", { name: /^authorize$/i }); + const codeShown = async () => (await page.locator("body").innerText()).includes('"code"'); + const consented = async () => Boolean(redirectedCode()) || (await codeShown()) || (await authorize.isVisible()); + await expect + .poll(async () => (await consented()) || (await password.isVisible()), { + timeout: resolveTimeout(60_000), + message: `${label}: expected Pixelfed's sign-in form, consent screen or authorization code`, + }) + .toBe(true); + if (!(await consented()) && (await password.isVisible())) { + await page.locator('input[name="email"]').fill(env.adminEmail); + await password.fill(env.adminPassword); + await page.locator("form").filter({ has: password }).locator('button[type="submit"]').click(); + } + await expect + .poll(consented, { + timeout: resolveTimeout(60_000), + message: `${label}: expected Pixelfed's consent screen or its authorization code`, + }) + .toBe(true); + if (redirectedCode()) { + return redirectedCode(); + } + if (await authorize.isVisible()) { + await authorize.click(); + } + await expect + .poll(codeShown, { + timeout: resolveTimeout(60_000), + message: `${label}: Pixelfed must answer the out-of-band approval with the authorization code`, + }) + .toBe(true); + return JSON.parse(await page.locator("body").innerText()).code; +} + +async function connectPixelfedAccount(page, label) { + const account = { handle: `@${env.adminUsername}` }; + let redirected = ""; + const capture = (response) => { + const location = response.headers().location || ""; + if (location.startsWith(OOB_REDIRECT)) { + redirected = new URLSearchParams(location.split("?")[1] || "").get("code") || ""; + } + }; + page.on("response", capture); + const dialog = await openPixelfedConnectDialog(page, label); + await dialog.getByRole("button", { name: /^connect$/i }).click(); + const code = await pixelfedAuthorizationCode(page, label, () => redirected); + page.off("response", capture); + expect(code, `${label}: Pixelfed must issue an authorization code`).toBeTruthy(); + const codeDialog = await openPixelfedConnectDialog(page, label); + await codeDialog.getByRole("button", { name: /^code$/i }).click(); + await page.getByRole("textbox", { name: /authorization code/i }).fill(code); + await page.getByRole("button", { name: /connect account/i }).click(); + await expect + .poll(() => new URL(page.url()).pathname, { + timeout: resolveTimeout(60_000), + message: `${label}: OpenPost must leave the code page after the exchange`, + }) + .not.toContain("/accounts/pixelfed/callback"); + await gotoOnion(page, `${env.appBaseUrl}/accounts`, { waitUntil: "domcontentloaded" }); + await expect( + pixelfedChannelActions(page, account), + `${label}: ${account.handle} must be listed among the connected Pixelfed channels`, + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + return account; +} + +async function apiRequest(page, headers, method, path, data) { + const response = await page.request.fetch(`${env.appBaseUrl}/api/v1${path}`, { method, headers, data }); + expect(response.ok(), `${method} ${path} must succeed, got HTTP ${response.status()}`).toBeTruthy(); + return response.status() === 204 ? null : response.json(); +} + +function apiSession() { + return { Origin: new URL(env.appBaseUrl).origin }; +} + +async function apiAccount(page, headers, platform) { + for (const workspace of await apiRequest(page, headers, "GET", "/workspaces")) { + const accounts = await apiRequest(page, headers, "GET", `/accounts?workspace_id=${workspace.id}`); + const account = accounts.find((item) => item.platform === platform); + if (account) { + return { workspace: workspace.id, account: account.id }; + } + } + throw new Error(`no connected ${platform} account in any workspace`); +} + +async function apiUploadImage(page, headers, workspace, fileName) { + const buffer = uniquePng(fileName); + const session = await apiRequest(page, headers, "POST", "/media/upload-session", { + workspace_id: workspace, + filename: fileName, + mime_type: "image/png", + size: buffer.length, + }); + const target = new URL(session.upload.url, env.appBaseUrl); + const uploadHeaders = { ...(session.upload.headers || {}) }; + if (target.origin === new URL(env.appBaseUrl).origin) { + Object.assign(uploadHeaders, headers); + } + const upload = await page.request.fetch(target.toString(), { method: session.upload.method, headers: uploadHeaders, data: buffer }); + expect(upload.ok(), `the media upload must succeed, got HTTP ${upload.status()}`).toBeTruthy(); + const complete = new URL(session.complete_url, env.appBaseUrl).pathname.replace(/^\/api\/v1/, ""); + await apiRequest(page, headers, "POST", complete, { workspace_id: workspace }); + return session.media_id; +} + +async function apiPublishImage(page, headers, target, text, label) { + const media = await apiUploadImage(page, headers, target.workspace, `${label}-${Date.now()}.png`); + const publication = await apiRequest(page, headers, "POST", "/publications", { + workspace_id: target.workspace, + title: text, + content_profile: "image_post", + source_text: text, + social_account_ids: [target.account], + renditions: [{ social_account_id: target.account, settings: {} }], + media: [{ media_id: media }], + }); + await apiRequest(page, headers, "POST", `/publications/${publication.id}/publish-now`, { + expected_revision: publication.revision, + }); + let rendition = {}; + await expect + .poll( + async () => { + const current = await apiRequest(page, headers, "GET", `/publications/${publication.id}`); + rendition = (current.renditions || [])[0] || {}; + return rendition.status; + }, + { timeout: resolveTimeout(180_000), message: `${label}: the ${text} destination must end published` }, + ) + .toBe("published"); + return rendition; +} + +async function beforeEach({ page }) { + await page.setViewportSize({ width: 1440, height: 1100 }); + expect(env.appBaseUrl, "APP_BASE_URL must be set").toBeTruthy(); + expect(env.canonicalDomain, "CANONICAL_DOMAIN must be set").toBeTruthy(); + await page.context().clearCookies(); +} + +module.exports = { + env, + LOGIN_PATH, + gotoLogin, + onLoginPage, + assertAuthenticated, + signInViaLocal, + signInViaOidc, + oidcProviderButton, + openInstanceAdministration, + assertInstanceAdministrationDenied, + openComposer, + assertWorkspaceHidden, + uploadMedia, + connectMastodonAccount, + connectPixelfedAccount, + apiSession, + apiRequest, + apiAccount, + apiPublishImage, + disconnectAccount, + publishNow, + mastodonStatusExists, + logout, + beforeEach, + skipUnlessServiceEnabled, + skipOnOnionSibling, +}; diff --git a/roles/web-app-openpost/files/playwright/playwright.spec.js b/roles/web-app-openpost/files/playwright/playwright.spec.js new file mode 100644 index 0000000000..5fa2eb133e --- /dev/null +++ b/roles/web-app-openpost/files/playwright/playwright.spec.js @@ -0,0 +1,19 @@ +const { test } = require("@playwright/test"); + +const shared = require("./_shared"); + +test.use({ + ignoreHTTPSErrors: true, +}); + +test.beforeEach(shared.beforeEach); + +require("./test-guest").register(shared); +require("./test-login-native-administrator").register(shared); +require("./test-login-oidc-administrator").register(shared); +require("./test-login-oidc-biber").register(shared); +require("./test-publish-mastodon").register(shared); +require("./test-publish-pixelfed").register(shared); +require("./test-crossposter-draft").register(shared); +require("./test-crossposter-linkedin").register(shared); +require("./test-seaweedfs").register(shared); diff --git a/roles/web-app-openpost/files/playwright/test-crossposter-draft.js b/roles/web-app-openpost/files/playwright/test-crossposter-draft.js new file mode 100644 index 0000000000..36e5373a7e --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-crossposter-draft.js @@ -0,0 +1,118 @@ +const { test, expect } = require("@playwright/test"); +const { gotoOnion, performKeycloakLoginForm } = require("./personas"); +const { resolveTimeout } = require("./timeouts"); + +const REVIEW_ROUTE = "ci-review"; +const REVIEW_SET = "Crossposter review"; +const REVIEW_TAG = "crossposterreview"; + +async function routeReview(page, shared, headers, target) { + const sets = await shared.apiRequest(page, headers, "GET", `/social-sets?workspace_id=${target.workspace}`); + const reviewSet = (sets || []).find((item) => item.name === REVIEW_SET); + expect(reviewSet, `the deploy must create the "${REVIEW_SET}" social set`).toBeTruthy(); + await shared.apiRequest(page, headers, "PUT", `/social-sets/${reviewSet.id}`, { + name: reviewSet.name, + is_default: Boolean(reviewSet.is_default), + accounts: [{ social_account_id: target.account, default_settings: {} }], + }); + return target.workspace; +} + +async function postOnMastodon(page, shared, text, label) { + await gotoOnion(page, `${shared.env.mastodonBaseUrl}/auth/sign_in`, { waitUntil: "domcontentloaded" }); + await page.getByRole("link", { name: /sso|single sign-on/i }).click(); + await page.waitForLoadState("domcontentloaded"); + if (page.url().includes(`${shared.env.oidcIssuerUrl}/protocol/openid-connect/auth`)) { + await performKeycloakLoginForm(page, shared.env.adminUsername, shared.env.adminPassword); + } + await expect + .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: `${label}: expected Mastodon's home timeline` }) + .not.toContain("/auth/sign_in"); + await gotoOnion(page, `${shared.env.mastodonBaseUrl}/home`, { waitUntil: "domcontentloaded" }); + const token = await page.evaluate(() => JSON.parse(document.getElementById("initial-state").textContent).meta.access_token); + expect(token, `${label}: Mastodon's web client must hold a session token`).toBeTruthy(); + const response = await page.request.post(`${shared.env.mastodonBaseUrl}/api/v1/statuses`, { + headers: { Authorization: `Bearer ${token}` }, + form: { status: text, visibility: "public" }, + }); + expect(response.ok(), `${label}: Mastodon must accept the status, got HTTP ${response.status()}`).toBeTruthy(); +} + +async function crosspostedDraft(page, shared, headers, workspace, marker) { + const drafts = await shared.apiRequest( + page, + headers, + "GET", + `/publications?workspace_id=${workspace}&status=draft&search=${encodeURIComponent(marker)}&limit=10`, + ); + return (drafts || []).find((item) => (item.metadata || {}).crossposter_route === REVIEW_ROUTE) || null; +} + +async function awaitCrosspostedDraft(page, shared, headers, workspace, marker, label) { + let draft = null; + await expect + .poll( + async () => { + draft = await crosspostedDraft(page, shared, headers, workspace, marker); + return Boolean(draft); + }, + { timeout: resolveTimeout(180_000), message: `${label}: the crossposter must turn the status into a review draft` }, + ) + .toBe(true); + return draft; +} + +async function openDraftInDesk(page, shared, marker, label) { + await gotoOnion(page, `${shared.env.appBaseUrl}/publications?tab=drafts`, { waitUntil: "domcontentloaded" }); + await page.getByRole("searchbox", { name: /search posts/i }).fill(marker); + const listed = page.getByRole("link", { name: new RegExp(marker, "i") }).first(); + await expect(listed, `${label}: the crossposted draft must be listed among the drafts`).toBeVisible({ + timeout: resolveTimeout(60_000), + }); + await listed.click(); + const text = page.getByRole("textbox", { name: /post text/i }).first(); + await expect(text, `${label}: the draft must open in the composer`).toBeVisible({ timeout: resolveTimeout(60_000) }); + return text; +} + +exports.REVIEW_TAG = REVIEW_TAG; +exports.routeReview = routeReview; +exports.postOnMastodon = postOnMastodon; +exports.awaitCrosspostedDraft = awaitCrosspostedDraft; +exports.openDraftInDesk = openDraftInDesk; + +exports.register = function (shared) { + test("administrator: finds a crossposted draft in the desk, edits it and schedules it", async ({ page }) => { + shared.skipUnlessServiceEnabled("crossposter"); + shared.skipUnlessServiceEnabled("mastodon"); + shared.skipOnOnionSibling("mastodon"); + test.setTimeout(resolveTimeout(420_000)); + const label = "administrator"; + const marker = `cp-desk-${Date.now()}`; + const edited = `Edited in the desk ${marker}`; + + await shared.signInViaLocal(page, shared.env.breakglassEmail, shared.env.breakglassPassword, label); + const headers = shared.apiSession(); + const workspace = await routeReview(page, shared, headers, await shared.apiAccount(page, headers, "mastodon")); + await postOnMastodon(page, shared, `Desk review ${marker} #${REVIEW_TAG}`, label); + const draft = await awaitCrosspostedDraft(page, shared, headers, workspace, marker, label); + const text = await openDraftInDesk(page, shared, marker, label); + await text.fill(edited); + await page.getByRole("main").getByRole("button", { name: /^more$/i }).click(); + await page.getByRole("menuitem", { name: /^schedule$/i }).click(); + const dialog = page.getByRole("dialog"); + await dialog.getByRole("button", { name: /^in 3 hours$/i }).click(); + await dialog.getByRole("button", { name: /^schedule$/i }).click(); + + await expect + .poll( + async () => { + const current = await shared.apiRequest(page, headers, "GET", `/publications/${draft.id}`); + return `${current.status}|${String(current.source_text).includes(edited)}`; + }, + { timeout: resolveTimeout(60_000), message: `${label}: the edited draft must end scheduled` }, + ) + .toBe("scheduled|true"); + await shared.logout(page, label); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-crossposter-linkedin.js b/roles/web-app-openpost/files/playwright/test-crossposter-linkedin.js new file mode 100644 index 0000000000..67d0a2417f --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-crossposter-linkedin.js @@ -0,0 +1,141 @@ +const { test, expect } = require("@playwright/test"); +const { gotoOnion } = require("./personas"); +const { resolveTimeout } = require("./timeouts"); +const { REVIEW_TAG, routeReview, postOnMastodon, awaitCrosspostedDraft, openDraftInDesk } = require("./test-crossposter-draft"); + +const LINKEDIN_ORIGIN = "https://www.linkedin.com"; + +async function routeLinkedInToFake(page, shared) { + await page.route(`${LINKEDIN_ORIGIN}/**`, async (route) => { + const target = new URL(route.request().url()); + const response = await route.fetch({ url: `${shared.env.linkedinFakeUrl}${target.pathname}${target.search}`, maxRedirects: 0 }); + await route.fulfill({ response }); + }); +} + +async function signUpOnLinkedIn(page, member, label) { + await gotoOnion(page, `${LINKEDIN_ORIGIN}/signup`, { waitUntil: "domcontentloaded" }); + await page.getByLabel("Name").fill(member.name); + await page.getByLabel("Email").fill(member.email); + await page.getByLabel("Password").fill(member.password); + await page.getByRole("button", { name: /^create account$/i }).click(); + await expect(page.getByText(/your account is ready/i), `${label}: the fake LinkedIn must create the member`).toBeVisible({ + timeout: resolveTimeout(30_000), + }); +} + +async function linkedInAccountIds(page, shared, headers, workspace) { + const accounts = await shared.apiRequest(page, headers, "GET", `/accounts?workspace_id=${workspace}`); + return accounts.filter((item) => item.platform === "linkedin").map((item) => item.id); +} + +async function connectLinkedIn(page, shared, headers, workspace, member, label) { + const known = await linkedInAccountIds(page, shared, headers, workspace); + const { url } = await shared.apiRequest(page, headers, "GET", `/accounts/linkedin/auth-url?workspace_id=${workspace}`); + await gotoOnion(page, url, { waitUntil: "domcontentloaded" }); + await page.getByLabel("Email").fill(member.email); + await page.getByLabel("Password").fill(member.password); + await page.getByRole("button", { name: /^allow$/i }).click(); + await expect + .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: `${label}: OpenPost must finish the LinkedIn callback` }) + .not.toMatch(/linkedin\.com|\/accounts\/linkedin\/callback/); + expect(page.url(), `${label}: OpenPost must accept the LinkedIn consent`).not.toContain("failed"); + const selection = new URL(page.url()).searchParams.get("connection_id"); + if (selection) { + const offer = await shared.apiRequest(page, headers, "GET", `/accounts/selections/${selection}`); + const options = (offer.options || []).map((option) => String(option.id)); + expect(options.length, `${label}: LinkedIn must offer the member profile`).toBeGreaterThan(0); + await shared.apiRequest(page, headers, "POST", `/accounts/selections/${selection}/complete`, { + selection_ids: [options.find((id) => id.startsWith("person:")) || options[0]], + }); + } + let added = []; + await expect + .poll( + async () => { + added = (await linkedInAccountIds(page, shared, headers, workspace)).filter((id) => !known.includes(id)); + return added.length; + }, + { timeout: resolveTimeout(30_000), message: `${label}: the LinkedIn member must be connected in the review workspace` }, + ) + .toBe(1); + return { workspace, account: added[0] }; +} + +async function publishInDesk(page, label) { + await page.getByRole("main").getByRole("button", { name: /^more$/i }).click(); + await page.getByRole("menuitem", { name: /^publish now$/i }).click(); + const confirm = page.getByRole("alertdialog").or(page.getByRole("dialog")); + if (await confirm.first().isVisible().catch(() => false)) { + await confirm.first().getByRole("button", { name: /publish/i }).first().click(); + } + await expect(confirm.first(), `${label}: the publish confirmation must close`).toBeHidden({ timeout: resolveTimeout(30_000) }); +} + +exports.register = function (shared) { + test("administrator: a Mastodon status becomes a review draft, is edited in the desk and lands on LinkedIn", async ({ page }) => { + shared.skipUnlessServiceEnabled("crossposter"); + shared.skipUnlessServiceEnabled("mastodon"); + shared.skipUnlessServiceEnabled("provider"); + shared.skipOnOnionSibling("mastodon"); + test.skip( + shared.env.appBaseUrl.includes(".onion"), + "LinkedIn cannot redirect a member back to an onion OpenPost origin", + ); + test.setTimeout(resolveTimeout(480_000)); + const label = "administrator"; + const stamp = Date.now(); + const marker = `cp-linkedin-${stamp}`; + const edited = `Edited for LinkedIn ${marker}`; + const member = { + name: `Desk Pilot ${stamp}`, + email: `desk-pilot-${stamp}@linkedin.invalid`, + password: `fake-${stamp}-linkedin`, + }; + + await routeLinkedInToFake(page, shared); + await signUpOnLinkedIn(page, member, label); + await shared.signInViaLocal(page, shared.env.breakglassEmail, shared.env.breakglassPassword, label); + const headers = shared.apiSession(); + const { workspace } = await shared.apiAccount(page, headers, "mastodon"); + const target = await connectLinkedIn(page, shared, headers, workspace, member, label); + await routeReview(page, shared, headers, target); + await postOnMastodon(page, shared, `LinkedIn review ${marker} #${REVIEW_TAG}`, label); + const draft = await awaitCrosspostedDraft(page, shared, headers, workspace, marker, label); + + const text = await openDraftInDesk(page, shared, marker, label); + await text.fill(edited); + await expect + .poll( + async () => String((await shared.apiRequest(page, headers, "GET", `/publications/${draft.id}`)).source_text).includes(edited), + { timeout: resolveTimeout(60_000), message: `${label}: the desk must save the edited text` }, + ) + .toBe(true); + await publishInDesk(page, label); + + let rendition = {}; + await expect + .poll( + async () => { + const current = await shared.apiRequest(page, headers, "GET", `/publications/${draft.id}`); + rendition = (current.renditions || []).find((item) => item.social_account_id === target.account) || {}; + return rendition.status; + }, + { timeout: resolveTimeout(180_000), message: `${label}: the LinkedIn destination must end published` }, + ) + .toBe("published"); + expect(rendition.external_id, `${label}: OpenPost must record the id of the LinkedIn post`).toMatch(/^urn:li:share:/); + + await gotoOnion(page, `${LINKEDIN_ORIGIN}/feed/update/${rendition.external_id}`, { waitUntil: "domcontentloaded" }); + await expect(page.getByRole("article"), `${label}: the LinkedIn post must show the text edited in the desk`).toContainText(edited); + await expect(page, `${label}: the LinkedIn post must carry the member's name`).toHaveTitle(new RegExp(member.name)); + + const posts = await (await page.request.get(`${shared.env.linkedinFakeUrl}/__fake/linkedin/posts`)).json(); + const delivered = posts.filter((post) => String(post.text).includes(marker)); + expect(delivered.map((post) => post.text), `${label}: LinkedIn must receive the edited post exactly once`).toEqual([edited]); + expect(rendition.external_id, `${label}: OpenPost must record the post LinkedIn created`).toBe(delivered[0].id); + + await gotoOnion(page, `${shared.env.appBaseUrl}/publications`, { waitUntil: "domcontentloaded" }); + await shared.logout(page, label); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-guest.js b/roles/web-app-openpost/files/playwright/test-guest.js new file mode 100644 index 0000000000..2d70933f4b --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-guest.js @@ -0,0 +1,51 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +const { assertCspResponseHeader, assertCspMetaParity, gotoOnion } = require("./personas"); +const { isServiceEnabled } = require("./service-gating"); + +exports.register = function (shared) { + test("guest: login serves CSP, refuses wrong and empty credentials, never reaches the desk", async ({ page }) => { + test.setTimeout(resolveTimeout(90_000)); + const response = await shared.gotoLogin(page); + expect(response, "Expected an OpenPost login response").toBeTruthy(); + expect(response.status(), "Expected the OpenPost login status to be < 400").toBeLessThan(400); + expect( + response.url().includes(shared.env.canonicalDomain), + `Expected canonical domain "${shared.env.canonicalDomain}" to back the OpenPost URL`, + ).toBe(true); + + const directives = assertCspResponseHeader(response, "openpost login"); + await assertCspMetaParity(page, directives, "openpost login"); + + await page.locator("#email").fill("guest@invalid.example"); + await page.locator("#password").fill("not-a-valid-password"); + await page.locator("form").filter({ has: page.locator("#password") }).locator('button[type="submit"]').click(); + await expect(page.getByRole("alert").or(page.locator('[role="status"], .text-destructive')).first(), + "guest: wrong credentials must produce a visible error").toBeVisible({ timeout: resolveTimeout(30_000) }); + expect(shared.onLoginPage(page), "guest must remain on the login page after a rejected sign-in").toBe(true); + + await gotoOnion(page, `${shared.env.appBaseUrl}/settings`, { waitUntil: "domcontentloaded" }); + await expect + .poll(() => shared.onLoginPage(page), { + timeout: resolveTimeout(30_000), + message: "guest hitting /settings must be forced back to the login page", + }) + .toBe(true); + + if (isServiceEnabled("sso")) { + await shared.oidcProviderButton(page).click(); + await expect + .poll(() => page.url(), { timeout: resolveTimeout(60_000), message: "guest: expected the Keycloak login form" }) + .toContain(`${shared.env.oidcIssuerUrl}/protocol/openid-connect/auth`); + await page.locator("#kc-login, input[type='submit'], button[type='submit']").first().click(); + await expect(page.locator("#username, input[name='username']").first(), + "guest: Keycloak must reject the empty submission and keep its login form").toBeVisible({ + timeout: resolveTimeout(30_000), + }); + expect(page.url(), "guest: an empty Keycloak submission must not return to OpenPost").toContain( + shared.env.oidcIssuerUrl, + ); + } + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-login-native-administrator.js b/roles/web-app-openpost/files/playwright/test-login-native-administrator.js new file mode 100644 index 0000000000..1407bcd4dc --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-login-native-administrator.js @@ -0,0 +1,14 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +exports.register = function (shared) { + test("administrator: break-glass password login reaches the instance administration", async ({ page }) => { + test.setTimeout(resolveTimeout(90_000)); + expect(shared.env.breakglassEmail, "BREAKGLASS_EMAIL must be set").toBeTruthy(); + expect(shared.env.breakglassPassword, "BREAKGLASS_PASSWORD must be set").toBeTruthy(); + + await shared.signInViaLocal(page, shared.env.breakglassEmail, shared.env.breakglassPassword, "administrator-native"); + await shared.openInstanceAdministration(page, "administrator-native"); + await shared.logout(page, "administrator-native"); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-login-oidc-administrator.js b/roles/web-app-openpost/files/playwright/test-login-oidc-administrator.js new file mode 100644 index 0000000000..9db34aa3e9 --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-login-oidc-administrator.js @@ -0,0 +1,15 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +exports.register = function (shared) { + test("administrator: Keycloak login provisions an instance admin who reaches the instance administration", async ({ page }) => { + shared.skipUnlessServiceEnabled("sso"); + test.setTimeout(resolveTimeout(120_000)); + expect(shared.env.adminUsername, "ADMIN_USERNAME must be set").toBeTruthy(); + expect(shared.env.adminPassword, "ADMIN_PASSWORD must be set").toBeTruthy(); + + await shared.signInViaOidc(page, shared.env.adminUsername, shared.env.adminPassword, "administrator"); + await shared.openInstanceAdministration(page, "administrator"); + await shared.logout(page, "administrator"); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-login-oidc-biber.js b/roles/web-app-openpost/files/playwright/test-login-oidc-biber.js new file mode 100644 index 0000000000..3f9d657296 --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-login-oidc-biber.js @@ -0,0 +1,17 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +exports.register = function (shared) { + test("biber: Keycloak login opens the composer but never the organisation workspace", async ({ page }) => { + shared.skipUnlessServiceEnabled("sso"); + test.setTimeout(resolveTimeout(120_000)); + expect(shared.env.biberUsername, "BIBER_USERNAME must be set").toBeTruthy(); + expect(shared.env.biberPassword, "BIBER_PASSWORD must be set").toBeTruthy(); + + await shared.signInViaOidc(page, shared.env.biberUsername, shared.env.biberPassword, "biber"); + await shared.openComposer(page, "biber"); + await shared.assertWorkspaceHidden(page, shared.env.organisationWorkspace, "biber"); + await shared.assertInstanceAdministrationDenied(page, "biber"); + await shared.logout(page, "biber"); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-publish-mastodon.js b/roles/web-app-openpost/files/playwright/test-publish-mastodon.js new file mode 100644 index 0000000000..e910c37dd6 --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-publish-mastodon.js @@ -0,0 +1,27 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +exports.register = function (shared) { + test("administrator: connects the local Mastodon account through the OOB code flow and publishes to it", async ({ page, context }) => { + shared.skipUnlessServiceEnabled("sso"); + shared.skipUnlessServiceEnabled("mastodon"); + shared.skipOnOnionSibling("mastodon"); + test.setTimeout(resolveTimeout(300_000)); + const marker = `openpost-e2e ${Date.now()}`; + + await shared.signInViaOidc(page, shared.env.adminUsername, shared.env.adminPassword, "administrator"); + const account = await shared.connectMastodonAccount(page, context, "administrator"); + try { + await shared.publishNow(page, account, marker); + await expect + .poll(() => shared.mastodonStatusExists(page, account, marker), { + timeout: resolveTimeout(180_000), + message: `administrator: expected "${marker}" on ${shared.env.mastodonBaseUrl}`, + }) + .toBe(true); + } finally { + await shared.disconnectAccount(page, account).catch((error) => console.warn(`cleanup: ${error.message}`)); + } + await shared.logout(page, "administrator"); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-publish-pixelfed.js b/roles/web-app-openpost/files/playwright/test-publish-pixelfed.js new file mode 100644 index 0000000000..33bb9035f9 --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-publish-pixelfed.js @@ -0,0 +1,26 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +exports.register = function (shared) { + test("administrator: connects the local Pixelfed account through the OOB code flow and publishes an image to it", async ({ page }) => { + shared.skipUnlessServiceEnabled("pixelfed"); + shared.skipOnOnionSibling("pixelfed"); + test.setTimeout(resolveTimeout(300_000)); + const label = "break-glass administrator"; + const marker = `openpost-e2e-pixelfed ${Date.now()}`; + + await shared.signInViaLocal(page, shared.env.breakglassEmail, shared.env.breakglassPassword, label); + await shared.connectPixelfedAccount(page, label); + const headers = shared.apiSession(); + const target = await shared.apiAccount(page, headers, "pixelfed"); + const rendition = await shared.apiPublishImage(page, headers, target, marker, label); + expect(rendition.external_url, `${label}: OpenPost must record the URL of the Pixelfed post`).toBeTruthy(); + await expect + .poll(async () => (await page.request.get(rendition.external_url)).status(), { + timeout: resolveTimeout(60_000), + message: `${label}: expected the Pixelfed post at ${rendition.external_url}`, + }) + .toBe(200); + await shared.logout(page, label); + }); +}; diff --git a/roles/web-app-openpost/files/playwright/test-seaweedfs.js b/roles/web-app-openpost/files/playwright/test-seaweedfs.js new file mode 100644 index 0000000000..74bdd7c0a0 --- /dev/null +++ b/roles/web-app-openpost/files/playwright/test-seaweedfs.js @@ -0,0 +1,21 @@ +const { test } = require("@playwright/test"); +const { resolveTimeout, isOnionTarget } = require("./timeouts"); +const { runSeaweedfsStorageCheck } = require("./personas"); + +exports.register = function (shared) { + test("seaweedfs: an image uploaded to the OpenPost media library is stored in the SeaweedFS bucket", async ({ page, browser }) => { + test.skip(isOnionTarget(), "SeaweedFS filer UI is not a Tor surface on an onion node (headless backend)"); + shared.skipUnlessServiceEnabled("seaweedfs"); + shared.skipUnlessServiceEnabled("sso"); + test.setTimeout(resolveTimeout(300_000)); + + await runSeaweedfsStorageCheck(page, browser, { + label: "an OpenPost media library upload", + action: async (appPage) => { + await shared.signInViaOidc(appPage, shared.env.adminUsername, shared.env.adminPassword, "administrator"); + await shared.uploadMedia(appPage, `infinito-storage-check-${Date.now()}.png`, "administrator"); + await shared.logout(appPage, "administrator"); + }, + }); + }); +}; diff --git a/roles/web-app-openpost/files/provider/Dockerfile b/roles/web-app-openpost/files/provider/Dockerfile new file mode 100644 index 0000000000..44501dd51e --- /dev/null +++ b/roles/web-app-openpost/files/provider/Dockerfile @@ -0,0 +1,21 @@ +ARG PROVIDER_BASE_IMAGE +ARG PROVIDER_BASE_VERSION +FROM ${PROVIDER_BASE_IMAGE}:${PROVIDER_BASE_VERSION} + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +ARG PROVIDER_UID +RUN groupadd --system --gid "${PROVIDER_UID}" provider \ + && useradd --system --uid "${PROVIDER_UID}" --gid provider --home-dir /app --shell /usr/sbin/nologin provider + +WORKDIR /app + +COPY provider ./provider + +USER provider + +HEALTHCHECK --interval=2m --timeout=5s --retries=3 --start-period=10m --start-interval=5s \ + CMD ["python", "-m", "provider", "health", "--config", "/run/secrets/provider.json"] + +CMD ["python", "-m", "provider", "serve", "--config", "/run/secrets/provider.json"] diff --git a/roles/web-app-openpost/files/python/crossposter/__init__.py b/roles/web-app-openpost/files/python/crossposter/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/roles/web-app-openpost/files/python/crossposter/__main__.py b/roles/web-app-openpost/files/python/crossposter/__main__.py new file mode 100644 index 0000000000..2941de76b9 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/__main__.py @@ -0,0 +1,135 @@ +from __future__ import annotations + +import argparse +import json +import logging +import sys +import time +from pathlib import Path + +from . import config as settings +from . import web +from .openpost import OpenPost, TargetError + +LIST_COLUMNS = ( + "id", + "state", + "route", + "network", + "target", + "attempts", + "source_url", + "publication_id", + "last_error", +) +HEALTHY = ("active", "standby", "waiting") +STALE_INTERVALS = 3 +LOG = logging.getLogger("crossposter") + + +def _client(loaded: settings.Config) -> OpenPost: + return OpenPost( + loaded.openpost.base_url, + loaded.openpost.host, + loaded.openpost.token, + loaded.openpost.workspace, + ) + + +def validate(path: str) -> settings.Config: + loaded = settings.load(path) + client = _client(loaded) + for route in loaded.routes: + try: + client.destinations(route.targets) + except TargetError as error: + raise settings.ConfigError( + f"route '{route.name}': targets: {error}" + ) from error + return loaded + + +def command_validate(path: str) -> int: + try: + loaded = validate(path) + except settings.ConfigError as error: + print(f"invalid crossposter configuration: {error}", file=sys.stderr) + return 2 + except web.RequestError as error: + print( + f"OpenPost could not be asked about the targets: {error}", file=sys.stderr + ) + return 3 + print(f"{len(loaded.routes)} route(s) valid") + return 0 + + +def liveness(path: str) -> tuple[Path, float]: + raw = json.loads(Path(path).read_text()) + return Path(raw["heartbeat_file"]), float(raw["poll_interval_seconds"]) + + +def wait_for_configuration(path: str, error: Exception) -> float: + heartbeat, interval = liveness(path) + heartbeat.write_text(f"{time.time():.0f} waiting\n") + LOG.warning("crossposter waits for a valid configuration: %s", error) + return interval + + +def command_run(path: str) -> int: + from .service import Service + from .store import Store + + while True: + try: + loaded = validate(path) + break + except (settings.ConfigError, web.RequestError) as error: + time.sleep(wait_for_configuration(path, error)) + Service(loaded, Store(loaded.dsn), _client(loaded)).run_forever() + return 0 + + +def command_list(path: str) -> int: + from .store import Store + + loaded = settings.load(path) + rows = Store(loaded.dsn).everything() + print("\t".join(LIST_COLUMNS)) + for row in rows: + print( + "\t".join( + str(row[column]).replace("\n", " ")[:120] for column in LIST_COLUMNS + ) + ) + return 0 + + +def command_health(path: str) -> int: + heartbeat, interval = liveness(path) + if not heartbeat.is_file(): + return 1 + stamp, _, state = heartbeat.read_text().strip().partition(" ") + fresh = time.time() - float(stamp) < STALE_INTERVALS * interval + return 0 if fresh and state in HEALTHY else 1 + + +def main() -> int: + parser = argparse.ArgumentParser(prog="crossposter") + parser.add_argument("command", choices=("run", "validate", "list", "health")) + parser.add_argument("--config", required=True) + arguments = parser.parse_args() + logging.basicConfig( + level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s" + ) + commands = { + "run": command_run, + "validate": command_validate, + "list": command_list, + "health": command_health, + } + return commands[arguments.command](arguments.config) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/web-app-openpost/files/python/crossposter/adapt.py b/roles/web-app-openpost/files/python/crossposter/adapt.py new file mode 100644 index 0000000000..8841fdc050 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/adapt.py @@ -0,0 +1,277 @@ +from __future__ import annotations + +import re +import unicodedata +from dataclasses import dataclass +from html.parser import HTMLParser +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from crossposter.sources import Media, SourceItem + +FEDIVERSE = frozenset({"mastodon", "pixelfed", "peertube"}) +URL_WEIGHT = 23 +ELLIPSIS = "…" + +URL_RE = re.compile(r"https?://[^\s<>\"']+") +MENTION_RE = re.compile( + r"(? bool: + code = ord(char) + return ( + unicodedata.combining(char) > 0 + or 0xFE00 <= code <= 0xFE0F + or 0x1F3FB <= code <= 0x1F3FF + or 0xE0020 <= code <= 0xE007F + or char == _ZWJ + or previous.endswith(_ZWJ) + ) + + +def graphemes(text: str) -> list[str]: + clusters: list[str] = [] + for char in text: + if (clusters and _joins(clusters[-1], char)) or ( + clusters and _regional_pair(clusters[-1], char) + ): + clusters[-1] += char + else: + clusters.append(char) + return clusters + + +def _regional(char: str) -> bool: + return 0x1F1E6 <= ord(char) <= 0x1F1FF + + +def _regional_pair(cluster: str, char: str) -> bool: + return len(cluster) == 1 and _regional(cluster) and _regional(char) + + +def _emoji(cluster: str) -> bool: + return any( + ord(char) >= 0x1F000 + or 0x2600 <= ord(char) <= 0x27BF + or char in (_ZWJ, _EMOJI_PRESENTATION) + for char in cluster + ) + + +def _x_weight(cluster: str) -> int: + if _emoji(cluster): + return 2 + code = ord(cluster[0]) + return 1 if any(low <= code <= high for low, high in _X_SINGLE) else 2 + + +def _split_urls(text: str) -> tuple[str, int]: + urls = URL_RE.findall(text) + return URL_RE.sub("", text), len(urls) + + +def count(text: str, network: str, spoiler: str = "") -> int: + limit = LIMITS[network] + if limit.counter == "mastodon": + stripped, urls = _split_urls(MENTION_RE.sub(r"@\1", spoiler + text)) + return len(graphemes(stripped)) + urls * URL_WEIGHT + if limit.counter == "x": + stripped, urls = _split_urls(text) + return ( + sum(_x_weight(cluster) for cluster in graphemes(stripped)) + + urls * URL_WEIGHT + ) + return len(graphemes(text)) + + +def fits(text: str, network: str, spoiler: str = "") -> bool: + limit = LIMITS[network] + if limit.hashtags and len(HASHTAG_RE.findall(text)) > limit.hashtags: + return False + return count(text, network, spoiler) <= limit.characters + + +def _drop_excess_hashtags(text: str, allowed: int) -> str: + seen = 0 + + def keep(match: re.Match[str]) -> str: + nonlocal seen + seen += 1 + return match.group(0) if seen <= allowed else "" + + return re.sub(r"[ \t]{2,}", " ", HASHTAG_RE.sub(keep, text)).strip() + + +def shorten(text: str, network: str, reserve: int = 0) -> str: + limit = LIMITS[network] + if limit.hashtags: + text = _drop_excess_hashtags(text, limit.hashtags) + budget = limit.characters - reserve + if count(text, network) <= budget: + return text + tokens = re.findall(r"\S+|\s+", text) + while tokens: + candidate = "".join(tokens).rstrip() + ELLIPSIS + if count(candidate, network) <= budget: + return candidate + tokens.pop() + return ELLIPSIS + + +class _TextExtractor(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: list[str] = [] + self._link: dict[str, str] | None = None + self._link_text: list[str] = [] + self._hidden = 0 + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + values = {key: value or "" for key, value in attrs} + if tag == "br": + self.parts.append("\n") + elif tag == "p" and self.parts: + self.parts.append("\n\n") + elif tag == "a": + self._link = values + self._link_text = [] + elif tag == "span" and "invisible" in values.get("class", "").split(): + self._hidden += 1 + + def handle_endtag(self, tag: str) -> None: + if tag == "a" and self._link is not None: + self.parts.append(self._render_link(self._link, "".join(self._link_text))) + self._link = None + + def handle_data(self, data: str) -> None: + if self._link is not None: + self._link_text.append(data) + else: + self.parts.append(data) + + @staticmethod + def _render_link(attributes: dict[str, str], text: str) -> str: + classes = attributes.get("class", "").split() + href = attributes.get("href", "") + if "hashtag" in classes: + return text + if "mention" in classes and text.startswith("@"): + host = re.sub(r"^https?://([^/]+)/.*$", r"\1", href) + return f"{text}@{host}" if "@" not in text[1:] else text + return href or text + + +def html_to_text(html: str) -> str: + extractor = _TextExtractor() + extractor.feed(html) + extractor.close() + return "".join(extractor.parts).strip() + + +def mentions(text: str) -> list[str]: + return [f"@{user}@{host}" for user, host in MENTION_RE.findall(text)] + + +def rewrite_mentions(text: str, network: str) -> str: + if network in FEDIVERSE: + return text + if network == "x": + return MENTION_RE.sub(r"\1", text) + return MENTION_RE.sub(r"\1 (https://\2/@\1)", text) + + +def compose(template: str, text: str, source_url: str, network: str) -> str: + frame = template.replace("{source_url}", source_url) + overhead = count(frame.replace("{text}", ""), network) + body = shorten(rewrite_mentions(text, network), network, reserve=overhead) + return frame.replace("{text}", body) + + +@dataclass(frozen=True) +class Attachment: + media: Media + alt_text: str + jpeg: bool + + +@dataclass(frozen=True) +class Plan: + title: str + text: str + profile: str + media: tuple[Attachment, ...] + draft_only: bool + skip: str + + +MASTODON_VIDEO_BYTES = 99 * 1024 * 1024 +JPEG_ONLY = frozenset({"instagram"}) +NEEDS_MEDIA = frozenset({"pixelfed"}) + + +def _transferable(media: Media, network: str) -> bool: + return not ( + network == "mastodon" + and media.mime.startswith("video/") + and media.size > MASTODON_VIDEO_BYTES + ) + + +def prepare(item: SourceItem, network: str, template: str, mode: str) -> Plan: + body = f"{item.title}\n\n{item.text}".strip() if item.title else item.text + attachments = tuple( + Attachment( + media, + media.description, + network in JPEG_ONLY and media.mime.startswith("image/"), + ) + for media in item.media + if _transferable(media, network) + ) + if len(attachments) < len(item.media) and "{source_url}" not in template: + template = template + "\n\n{source_url}" + skip = ( + f"{network} accepts only posts with media" + if network in NEEDS_MEDIA and not attachments + else "" + ) + kinds = {attachment.media.mime.split("/", 1)[0] for attachment in attachments} + profile = "video" if "video" in kinds else "image_post" if kinds else "short_text" + unmappable = bool(mentions(item.text)) and network not in FEDIVERSE + return Plan( + title=item.title or body.split("\n", 1)[0][:100], + text=compose(template, body, item.url, network), + profile=profile, + media=attachments, + draft_only=mode == "review" or bool(item.spoiler) or unmappable, + skip=skip, + ) diff --git a/roles/web-app-openpost/files/python/crossposter/config.py b/roles/web-app-openpost/files/python/crossposter/config.py new file mode 100644 index 0000000000..81c90793e1 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/config.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +import json +import urllib.parse +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +from crossposter import adapt +from crossposter.notify import Mail + +if TYPE_CHECKING: + from crossposter.sources import SourceItem + +PLATFORMS = frozenset({"mastodon", "pixelfed", "peertube"}) +MODES = frozenset({"review", "auto"}) +VISIBILITIES = frozenset({"public", "unlisted", "private", "direct"}) +MEDIA_FILTERS = frozenset({"any", "required", "none"}) +REVIEW = "review" +LOOP_APPLICATION = "OpenPost" +RUNTIME = "" + + +class ConfigError(ValueError): + pass + + +@dataclass(frozen=True) +class Source: + platform: str + base_url: str + account: str + token: str + + +@dataclass(frozen=True) +class Filters: + visibility: frozenset[str] + exclude_replies: bool + exclude_reblogs: bool + tags: frozenset[str] + media: str + + +@dataclass(frozen=True) +class Targets: + accounts: tuple[str, ...] + social_set: str + + +@dataclass(frozen=True) +class Route: + name: str + source: Source + filters: Filters + targets: Targets + mode: str + attribution: dict[str, str] + + def template(self, network: str) -> str: + return self.attribution.get(network, self.attribution["default"]) + + def refusal(self, item: SourceItem, opt_out_tag: str) -> str | None: + tags = { + tag.lower().lstrip("#") + for tag in (*item.tags, *adapt.HASHTAG_RE.findall(item.text)) + } + if opt_out_tag.lower() in tags: + return "opt-out" + if item.application == LOOP_APPLICATION: + return "loop" + if item.visibility not in self.filters.visibility: + return "visibility" + if self.filters.exclude_replies and item.in_reply_to: + return "reply" + if self.filters.exclude_reblogs and item.reblog: + return "reblog" + if self.filters.tags and not self.filters.tags & tags: + return "tags" + if self.filters.media == "required" and not item.media: + return "media" + if self.filters.media == "none" and item.media: + return "media" + return None + + +@dataclass(frozen=True) +class Retry: + max_attempts: int + base_seconds: float + cap_seconds: float + + +@dataclass(frozen=True) +class OpenPostSettings: + base_url: str + host: str + token: str + workspace: str + + +@dataclass(frozen=True) +class Config: + openpost: OpenPostSettings + dsn: str + mail: Mail | None + heartbeat_file: str + poll_interval_seconds: int + opt_out_tag: str + retry: Retry + recipients: tuple[str, ...] + routes: tuple[Route, ...] + + +def _require(condition: bool, route: str, field: str, message: str) -> None: + if not condition: + raise ConfigError(f"route '{route}': {field}: {message}") + + +def _secrets_file(path: str) -> Path: + file = Path(path) + _require(file.is_file(), RUNTIME, "secrets_file", f"{path} does not exist") + return file + + +def _value(secrets: dict, key: str, owner: str, field: str) -> str: + value = str(secrets.get(key) or "").strip() + _require(bool(value), owner, field, "is missing from the secrets file") + return value + + +def _mail(raw: dict | None, secrets: dict) -> Mail | None: + if not raw: + return None + user = str(raw["user"]) + password = "" + if user: + password = _value(secrets, "mail_password", RUNTIME, "mail.password") + return Mail( + host=str(raw["host"]), + port=int(raw["port"]), + security=str(raw["security"]), + user=user, + password=password, + sender=str(raw["sender"]), + ) + + +def _route(raw: dict, tokens: dict) -> Route: + name = str(raw.get("name") or "") + _require(bool(name), "", "name", "every route needs a name") + source = raw.get("source") or {} + platform = str(source.get("platform") or "") + _require( + platform in PLATFORMS, + name, + "source.platform", + f"{platform!r} is not one of {sorted(PLATFORMS)}", + ) + base_url = str(source.get("base_url") or "").rstrip("/") + parts = urllib.parse.urlsplit(base_url) + _require( + parts.scheme == "https" + or (parts.scheme == "http" and (parts.hostname or "").endswith(".onion")), + name, + "source.base_url", + "must be an https:// URL, or http:// for an onion service", + ) + account = str(source.get("account") or "") + _require(bool(account), name, "source.account", "names no account") + filters = raw.get("filters") or {} + visibility = frozenset(filters.get("visibility") or []) + _require(bool(visibility), name, "filters.visibility", "lists no visibility") + _require( + visibility <= VISIBILITIES, + name, + "filters.visibility", + f"{sorted(visibility - VISIBILITIES)} are unknown", + ) + media = str(filters.get("media") or "") + _require( + media in MEDIA_FILTERS, + name, + "filters.media", + f"{media!r} is not one of {sorted(MEDIA_FILTERS)}", + ) + targets = raw.get("targets") or {} + accounts = tuple(str(account) for account in targets.get("accounts") or []) + social_set = str(targets.get("social_set") or "") + _require( + bool(accounts) != bool(social_set), + name, + "targets", + "name either accounts or one social_set", + ) + mode = str(raw.get("mode") or REVIEW) + _require(mode in MODES, name, "mode", f"{mode!r} is not one of {sorted(MODES)}") + attribution = { + str(key): str(value) for key, value in (raw.get("attribution") or {}).items() + } + _require( + "default" in attribution, + name, + "attribution.default", + "the default template is missing", + ) + for network, template in attribution.items(): + _require( + "{text}" in template, + name, + f"attribution.{network}", + "the template must contain {text}", + ) + return Route( + name=name, + source=Source( + platform, + base_url, + account, + _value(tokens, name, name, "source.token"), + ), + filters=Filters( + visibility=visibility, + exclude_replies=bool(filters.get("exclude_replies")), + exclude_reblogs=bool(filters.get("exclude_reblogs")), + tags=frozenset( + str(tag).lower().lstrip("#") for tag in filters.get("tags") or [] + ), + media=media, + ), + targets=Targets(accounts, social_set), + mode=mode, + attribution=attribution, + ) + + +def parse(raw: dict) -> Config: + secrets = json.loads(_secrets_file(str(raw["secrets_file"])).read_text()) + tokens = dict(secrets.get("routes") or {}) + routes = tuple(_route(item, tokens) for item in raw.get("routes") or []) + names = [route.name for route in routes] + duplicates = sorted({name for name in names if names.count(name) > 1}) + if duplicates: + raise ConfigError(f"route '{duplicates[0]}': name: is used more than once") + retry = raw["retry"] + openpost = raw["openpost"] + return Config( + openpost=OpenPostSettings( + base_url=str(openpost["base_url"]), + host=str(openpost["host"]), + token=_value(secrets, "openpost_token", RUNTIME, "openpost.token"), + workspace=str(openpost["workspace"]), + ), + dsn=_value(secrets, "database_dsn", RUNTIME, "database.dsn"), + mail=_mail(raw.get("mail"), secrets), + heartbeat_file=str(raw["heartbeat_file"]), + poll_interval_seconds=int(raw["poll_interval_seconds"]), + opt_out_tag=str(raw["opt_out_tag"]), + retry=Retry( + int(retry["max_attempts"]), + float(retry["base_seconds"]), + float(retry["cap_seconds"]), + ), + recipients=tuple( + str(item) for item in (raw.get("notify") or {}).get("recipients") or [] + ), + routes=routes, + ) + + +def load(path: str) -> Config: + return parse(json.loads(Path(path).read_text())) diff --git a/roles/web-app-openpost/files/python/crossposter/notify.py b/roles/web-app-openpost/files/python/crossposter/notify.py new file mode 100644 index 0000000000..7dac71c267 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/notify.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import smtplib +import ssl +from dataclasses import dataclass +from email.message import EmailMessage + + +@dataclass(frozen=True) +class Mail: + host: str + port: int + security: str + user: str + password: str + sender: str + + +def report(rows: list[dict]) -> str: + blocks = [ + "\n".join( + ( + f"Route: {row['route']}", + f"Source: {row['source_url']}", + f"Target: {row['network']} {row['target']}", + f"State: {row['state']} after {row['attempts']} attempt(s)", + f"Last error: {row['last_error']}", + ) + ) + for row in rows + ] + return ( + "The OpenPost crossposter could not deliver these posts:\n\n" + + "\n\n".join(blocks) + + "\n" + ) + + +def message(sender: str, recipients: tuple[str, ...], rows: list[dict]) -> EmailMessage: + mail = EmailMessage() + mail["From"] = sender + mail["To"] = ", ".join(recipients) + mail["Subject"] = f"OpenPost crossposter: {len(rows)} post(s) need attention" + mail.set_content(report(rows)) + return mail + + +def send(mail: Mail, recipients: tuple[str, ...], rows: list[dict]) -> None: + context = ssl.create_default_context() + if mail.security == "tls": + client: smtplib.SMTP = smtplib.SMTP_SSL( + mail.host, mail.port, context=context, timeout=60 + ) + else: + client = smtplib.SMTP(mail.host, mail.port, timeout=60) + with client: + if mail.security == "starttls": + client.starttls(context=context) + if mail.user: + client.login(mail.user, mail.password) + client.send_message(message(mail.sender, recipients, rows)) diff --git a/roles/web-app-openpost/files/python/crossposter/openpost.py b/roles/web-app-openpost/files/python/crossposter/openpost.py new file mode 100644 index 0000000000..0c290ed3c1 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/openpost.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import json +import time +import urllib.parse +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from crossposter import web + +if TYPE_CHECKING: + from pathlib import Path + + from crossposter.config import Targets + + +PUBLIC_MEDIA_POLLS = 24 +PUBLIC_MEDIA_POLL_SECONDS = 5 +ANALYSED = ("ready", "failed") + + +def publishable(medium: dict) -> bool: + public = bool( + medium.get("public_url_checked_at") and medium.get("public_url_ready") + ) + analysed = not str(medium.get("mime_type") or "").startswith("video/") or ( + medium.get("analysis_status") in ANALYSED + ) + return public and analysed + + +@dataclass(frozen=True) +class Destination: + account_id: str + slug: str + platform: str + settings: dict + + +class TargetError(ValueError): + pass + + +class OpenPost: + def __init__(self, base_url: str, host: str, token: str, workspace: str) -> None: + self.base_url = base_url.rstrip("/") + "/api/v1" + self.headers = { + "Authorization": f"Bearer {token}", + "Host": host, + "X-Forwarded-Proto": "https", + "Content-Type": "application/json", + } + self.workspace = workspace + + def _call( + self, method: str, path: str, body: object, key: str, accepted: tuple[int, ...] + ) -> object: + headers = {**self.headers, **({"Idempotency-Key": key} if key else {})} + data = json.dumps(body).encode() if body is not None else None + return web.request(method, self.base_url + path, headers, data, accepted).json() + + def get(self, path: str) -> object: + return self._call("GET", path, None, "", (200,)) + + def destinations(self, targets: Targets) -> list[Destination]: + accounts = { + str(item["id"]): item + for item in self.get(f"/accounts?workspace_id={self.workspace}") or [] + } + if targets.social_set: + sets = self.get(f"/social-sets?workspace_id={self.workspace}") or [] + chosen = [item for item in sets if item.get("name") == targets.social_set] + if not chosen: + raise TargetError(f"social set {targets.social_set!r} does not exist") + return [ + Destination( + account_id=str(entry["social_account_id"]), + slug=str( + accounts.get(str(entry["social_account_id"]), {}).get("slug") + or "" + ), + platform=str(entry["platform"]), + settings=dict(entry.get("default_settings") or {}), + ) + for entry in chosen[0].get("accounts") or [] + ] + by_slug = {str(item.get("slug")): item for item in accounts.values()} + missing = [slug for slug in targets.accounts if slug not in by_slug] + if missing: + raise TargetError(f"accounts {missing} are not connected in the workspace") + return [ + Destination( + str(by_slug[slug]["id"]), slug, str(by_slug[slug]["platform"]), {} + ) + for slug in targets.accounts + ] + + def upload(self, source: Path, filename: str, mime: str) -> str: + session = self._call( + "POST", + "/media/upload-session", + { + "workspace_id": self.workspace, + "filename": filename, + "mime_type": mime, + "size": source.stat().st_size, + }, + "", + (200, 201), + ) + target = session["upload"] + url = urllib.parse.urlparse(str(target["url"])) + headers = { + name: str(value) for name, value in (target.get("headers") or {}).items() + } + if url.netloc in ("", self.headers["Host"]): + headers.update( + { + key: value + for key, value in self.headers.items() + if key != "Content-Type" + } + ) + url = urllib.parse.urlparse( + self.base_url.rsplit("/api/v1", 1)[0] + + url.path + + (f"?{url.query}" if url.query else "") + ) + web.upload( + str(target["method"]), url.geturl(), headers, source, (200, 201, 204) + ) + complete = urllib.parse.urlparse(str(session["complete_url"])).path.split( + "/api/v1", 1 + )[1] + completed = self._call( + "POST", complete, {"workspace_id": self.workspace}, "", (200, 201) + ) + return str(completed["id"]) + + def create( + self, + destination: Destination, + title: str, + text: str, + profile: str, + media: list[tuple[str, str]], + key: str, + metadata: dict[str, str], + ) -> dict: + payload = { + "workspace_id": self.workspace, + "metadata": metadata, + "title": title, + "content_profile": profile, + "source_text": text, + "social_account_ids": [destination.account_id], + "renditions": [ + { + "social_account_id": destination.account_id, + "settings": destination.settings, + } + ], + "media": [ + {"media_id": media_id, "alt_text": alt} for media_id, alt in media + ], + } + return dict(self._call("POST", "/publications", payload, key, (200, 201))) + + def publication(self, publication_id: str) -> dict: + return dict(self.get(f"/publications/{publication_id}") or {}) + + def await_media(self, publication_id: str) -> None: + for _ in range(PUBLIC_MEDIA_POLLS): + self._call( + "POST", f"/publications/{publication_id}/validate", None, "", (200,) + ) + media = self.publication(publication_id).get("media") + if all(publishable(item) for item in media or []): + return + time.sleep(PUBLIC_MEDIA_POLL_SECONDS) + raise web.RequestError( + f"{self.base_url}/publications/{publication_id}", + 503, + {}, + "OpenPost has not confirmed the public media URLs or video analysis yet", + ) + + def publish_now(self, publication: dict) -> None: + self._call( + "POST", + f"/publications/{publication['id']}/publish-now", + {"expected_revision": publication["revision"]}, + "", + (200, 201, 202), + ) + + def renditions(self, publication_id: str) -> list[dict]: + return list(self.publication(publication_id).get("renditions") or []) diff --git a/roles/web-app-openpost/files/python/crossposter/retry.py b/roles/web-app-openpost/files/python/crossposter/retry.py new file mode 100644 index 0000000000..f9ca7a566c --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/retry.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from datetime import datetime +from email.utils import parsedate_to_datetime +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import random + from collections.abc import Mapping + +RETRY_AFTER = "retry-after" +RESET_HEADERS = ("x-rate-limit-reset", "x-ratelimit-reset", "ratelimit-reset") +EPOCH_THRESHOLD = 1_000_000_000 +TRANSIENT_STATUSES = frozenset({408, 425, 429}) + + +def backoff(attempt: int, base: float, cap: float, rng: random.Random) -> float: + window = min(cap, base * 2 ** max(attempt - 1, 0)) + return rng.uniform(0, window) + + +def _seconds_until(value: str, now: float) -> float: + value = value.strip() + if not value: + return 0 + try: + number = float(value) + except ValueError: + try: + moment = datetime.fromisoformat(value) + except ValueError: + moment = parsedate_to_datetime(value) + return moment.timestamp() - now + return number - now if number > EPOCH_THRESHOLD else number + + +def server_delay(headers: Mapping[str, str], now: float) -> float: + lowered = {name.lower(): value for name, value in headers.items()} + for name in (RETRY_AFTER, *RESET_HEADERS): + if name in lowered: + try: + return max(0.0, round(_seconds_until(lowered[name], now), 3)) + except (TypeError, ValueError): + continue + return 0 + + +def delay( + attempt: int, + headers: Mapping[str, str], + now: float, + base: float, + cap: float, + rng: random.Random, +) -> float: + return max(backoff(attempt, base, cap, rng), server_delay(headers, now)) + + +def transient(status: int | None) -> bool: + return status is None or status in TRANSIENT_STATUSES or status >= 500 diff --git a/roles/web-app-openpost/files/python/crossposter/service.py b/roles/web-app-openpost/files/python/crossposter/service.py new file mode 100644 index 0000000000..b7b0d90f81 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/service.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import logging +import random +import tempfile +import time +import urllib.parse +from pathlib import Path +from typing import TYPE_CHECKING + +from crossposter import adapt, notify, retry, store, web +from crossposter.sources.mastodon import MastodonSource +from crossposter.sources.peertube import PeerTubeSource +from crossposter.sources.pixelfed import PixelfedSource + +if TYPE_CHECKING: + from crossposter.config import Config, Route + from crossposter.openpost import Destination, OpenPost + from crossposter.sources import SourceItem + +LOG = logging.getLogger("crossposter") +SOURCES = { + "mastodon": MastodonSource, + "pixelfed": PixelfedSource, + "peertube": PeerTubeSource, +} +JPEG_QUALITY = 90 +SOURCE_MEDIA_UNAVAILABLE = 503 + + +def to_jpeg(source: Path) -> Path: + from PIL import Image + + target = source.with_suffix(".jpg") + with Image.open(source) as image: + image.convert("RGB").save(target, "JPEG", quality=JPEG_QUALITY) + return target + + +def credentials_for(source_url: str, media_url: str, headers: dict) -> dict: + source = urllib.parse.urlsplit(source_url) + media = urllib.parse.urlsplit(media_url) + same_origin = (source.scheme, source.netloc) == (media.scheme, media.netloc) + return dict(headers) if same_origin else {} + + +def failure(rendition: dict) -> str: + delivery = rendition.get("delivery") or {} + reason = ( + rendition.get("error_message") + or delivery.get("terminal_reason") + or delivery.get("recovery_action") + or "delivery failed" + ) + status = rendition.get("error_http_status") + return f"{reason} (HTTP {status})" if status else str(reason) + + +def resendable_failure(rendition: dict) -> bool: + if (rendition.get("delivery") or {}).get("recovery_action") == "manual_resolution": + return True + status = rendition.get("error_http_status") + return status is not None and retry.transient(int(status)) + + +class Service: + def __init__( + self, config: Config, database: store.Store, openpost: OpenPost + ) -> None: + self.config = config + self.store = database + self.openpost = openpost + self.routes = {route.name: route for route in config.routes} + self.sources = { + route.name: SOURCES[route.source.platform]( + route.source.base_url, route.source.account, route.source.token + ) + for route in config.routes + } + self.rng = random.SystemRandom() + + def heartbeat(self, state: str) -> None: + Path(self.config.heartbeat_file).write_text(f"{time.time():.0f} {state}\n") + + def run_forever(self) -> None: + self.store.migrate() + while not self.store.lock(): + LOG.info("another crossposter holds the lock; standing by") + self.heartbeat("standby") + time.sleep(self.config.poll_interval_seconds) + LOG.info("lock acquired; polling %d route(s)", len(self.routes)) + while True: + self.tick() + self.heartbeat("active") + time.sleep(self.config.poll_interval_seconds) + + def tick(self) -> None: + for route in self.routes.values(): + self.detect(route) + self.deliver_due() + self.follow() + self.report() + + def detect(self, route: Route) -> None: + source = self.sources[route.name] + try: + cursor = self.store.cursor(route.name) + if cursor is None: + self.store.advance(route.name, source.newest_cursor(), []) + LOG.info( + "route %s activated; existing posts are not forwarded", route.name + ) + return + items = source.fetch(cursor) + destinations = self.openpost.destinations(route.targets) + except web.RequestError as error: + LOG.warning( + "route %s: polling failed, retrying next interval: %s", + route.name, + error, + ) + return + enqueued = [ + (item, destination.account_id, destination.platform) + for item in items + if not self._refused(route, item) + for destination in destinations + if not self._plan(route, item, destination).skip + ] + self.store.advance(route.name, items[-1].cursor if items else cursor, enqueued) + if enqueued: + LOG.info("route %s: queued %d delivery(ies)", route.name, len(enqueued)) + + def _refused(self, route: Route, item: SourceItem) -> bool: + reason = route.refusal(item, self.config.opt_out_tag) + if reason: + LOG.info("route %s: %s not forwarded (%s)", route.name, item.url, reason) + return bool(reason) + + @staticmethod + def _plan(route: Route, item: SourceItem, destination: Destination) -> adapt.Plan: + return adapt.prepare( + item, destination.platform, route.template(destination.platform), route.mode + ) + + def _destination(self, route: Route, account_id: str) -> Destination: + for destination in self.openpost.destinations(route.targets): + if destination.account_id == account_id: + return destination + raise web.RequestError(account_id, 404, {}, "the target account left the route") + + def _media( + self, route: Route, plan: adapt.Plan, folder: Path + ) -> list[tuple[str, str]]: + uploaded = [] + headers = self.sources[route.name].headers + for index, attachment in enumerate(plan.media): + name = ( + Path(urllib.parse.urlparse(attachment.media.url).path).name + or f"media-{index}" + ) + try: + local = web.download( + attachment.media.url, + credentials_for( + route.source.base_url, attachment.media.url, headers + ), + folder / f"{index}-{name}", + ) + except web.RequestError as error: + raise web.RequestError( + attachment.media.url, + SOURCE_MEDIA_UNAVAILABLE, + error.headers, + f"the source media is not available yet: {error}", + ) from error + mime = attachment.media.mime + if attachment.jpeg and mime != "image/jpeg": + local, mime = to_jpeg(local), "image/jpeg" + uploaded.append( + (self.openpost.upload(local, local.name, mime), attachment.alt_text) + ) + return uploaded + + def deliver_due(self) -> None: + for row in self.store.due(): + self.deliver(row) + + def deliver(self, row: dict) -> None: + route = self.routes.get(row["route"]) + attempts = int(row["attempts"]) + 1 + if route is None: + state = store.transition("pending", "permanent") + self.store.update( + row["id"], + state, + str(row["publication_id"]), + attempts, + "the route was removed", + 0, + ) + return + item = store.item_from_json(row["payload"]) + publication_id = str(row["publication_id"]) + try: + if item.media and not publication_id: + item = self.sources[route.name].refresh(item) + destination = self._destination(route, row["target"]) + plan = self._plan(route, item, destination) + if publication_id: + publication = self.openpost.publication(publication_id) + else: + key = store.idempotency_key( + item.uri, destination.account_id, int(row["resends"]) + ) + with tempfile.TemporaryDirectory(prefix="crossposter-") as folder: + media = self._media(route, plan, Path(folder)) + publication = self.openpost.create( + destination, + plan.title, + plan.text, + plan.profile, + media, + key, + {"crossposter_route": route.name, "crossposter_source": item.url}, + ) + publication_id = str(publication["id"]) + if plan.draft_only: + state = store.transition("pending", "drafted") + else: + if str(publication.get("status")) == "draft": + if plan.media: + self.openpost.await_media(publication_id) + self.openpost.publish_now(publication) + state = store.transition("pending", "submitted") + self.store.update(row["id"], state, publication_id, attempts, "", 0) + LOG.info( + "%s -> %s %s: %s", + item.url, + destination.platform, + destination.slug, + state, + ) + except web.RequestError as error: + event = "transient" if error.transient else "permanent" + state = store.transition( + "pending", event, attempts, self.config.retry.max_attempts + ) + pause = retry.delay( + attempts, + error.headers, + time.time(), + self.config.retry.base_seconds, + self.config.retry.cap_seconds, + self.rng, + ) + self.store.update( + row["id"], + state, + publication_id, + attempts, + str(error), + pause, + ) + LOG.warning( + "%s -> %s: %s (%s, attempt %d)", + item.url, + row["target"], + state, + error, + attempts, + ) + + def follow(self) -> None: + for row in self.store.open_publications(): + try: + renditions = self.openpost.renditions(str(row["publication_id"])) + except web.RequestError as error: + LOG.warning( + "publication %s: status unavailable: %s", + row["publication_id"], + error, + ) + continue + states = {str(rendition.get("status")) for rendition in renditions} + failed = [ + rendition + for rendition in renditions + if rendition.get("status") == "failed" + and not rendition.get("error_retryable") + ] + if failed: + self._failed(row, failed) + elif renditions and states == {"published"}: + state = store.transition(str(row["state"]), "delivered") + self.store.update( + row["id"], + state, + str(row["publication_id"]), + int(row["attempts"]), + "", + 0, + ) + + def _failed(self, row: dict, failed: list[dict]) -> None: + detail = "; ".join(failure(rendition) for rendition in failed) + attempts = int(row["attempts"]) + 1 + resendable = row["state"] == "submitted" and all( + resendable_failure(rendition) for rendition in failed + ) + if not resendable: + event = "delivery_failed" + elif attempts >= self.config.retry.max_attempts: + event = "exhausted" + else: + pause = retry.delay( + attempts, + {}, + time.time(), + self.config.retry.base_seconds, + self.config.retry.cap_seconds, + self.rng, + ) + self.store.resend(row["id"], attempts, detail, pause) + LOG.warning( + "publication %s failed transiently, resending in %.0fs: %s", + row["publication_id"], + pause, + detail, + ) + return + state = store.transition(str(row["state"]), event) + self.store.update( + row["id"], state, str(row["publication_id"]), attempts, detail, 0 + ) + + def report(self) -> None: + rows = self.store.unnotified() + if not rows: + return + if self.config.mail and self.config.recipients: + try: + notify.send(self.config.mail, self.config.recipients, rows) + except OSError as error: + LOG.warning("notification failed, retrying next interval: %s", error) + return + for row in rows: + self.store.mark_notified(row["id"]) diff --git a/roles/web-app-openpost/files/python/crossposter/sources/__init__.py b/roles/web-app-openpost/files/python/crossposter/sources/__init__.py new file mode 100644 index 0000000000..879283d075 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/sources/__init__.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Media: + url: str + mime: str + description: str + size: int + + +@dataclass(frozen=True) +class SourceItem: + uri: str + url: str + platform: str + text: str + visibility: str + tags: tuple[str, ...] + media: tuple[Media, ...] + in_reply_to: str + reblog: bool + spoiler: str + application: str + title: str = "" + cursor: str = "" diff --git a/roles/web-app-openpost/files/python/crossposter/sources/mastodon.py b/roles/web-app-openpost/files/python/crossposter/sources/mastodon.py new file mode 100644 index 0000000000..ae9a99b316 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/sources/mastodon.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import mimetypes +import urllib.parse +from typing import ClassVar + +from crossposter import adapt, web +from crossposter.sources import Media, SourceItem + +PAGE_SIZE = 40 +MAX_PAGES = 5 +MEDIA_TYPES = { + "image": "image/jpeg", + "gifv": "video/mp4", + "video": "video/mp4", + "audio": "audio/mpeg", +} + + +def _mime(attachment: dict) -> str: + guessed, _ = mimetypes.guess_type( + urllib.parse.urlparse(str(attachment.get("url") or "")).path + ) + return guessed or MEDIA_TYPES.get( + str(attachment.get("type")), "application/octet-stream" + ) + + +def parse_status(status: dict, platform: str) -> SourceItem: + application = status.get("application") or {} + return SourceItem( + uri=str(status["uri"]), + url=str(status.get("url") or status["uri"]), + platform=platform, + text=adapt.html_to_text(str(status.get("content") or "")), + visibility=str(status.get("visibility") or ""), + tags=tuple(str(tag.get("name") or "") for tag in status.get("tags") or []), + media=tuple( + Media( + url=str(attachment.get("url") or ""), + mime=_mime(attachment), + description=str(attachment.get("description") or ""), + size=0, + ) + for attachment in status.get("media_attachments") or [] + ), + in_reply_to=str(status.get("in_reply_to_id") or ""), + reblog=bool(status.get("reblog")), + spoiler=str(status.get("spoiler_text") or ""), + application=str(application.get("name") or ""), + cursor=str(status["id"]), + ) + + +class MastodonSource: + platform = "mastodon" + filters: ClassVar[dict[str, str]] = { + "exclude_replies": "true", + "exclude_reblogs": "true", + } + + def __init__(self, base_url: str, account: str, token: str) -> None: + self.base_url = base_url.rstrip("/") + self.account = account + self.headers = {"Authorization": f"Bearer {token}"} + self._account_id = "" + + def _get(self, path: str, query: dict[str, str]) -> object: + return web.get_json( + f"{self.base_url}{path}?{urllib.parse.urlencode(query)}", self.headers + ) + + def account_id(self) -> str: + if not self._account_id: + found = self._get("/api/v1/accounts/lookup", {"acct": self.account}) + self._account_id = str(found["id"]) + return self._account_id + + def newest_cursor(self) -> str: + statuses = self._get( + f"/api/v1/accounts/{self.account_id()}/statuses", {"limit": "1"} + ) + return str(statuses[0]["id"]) if statuses else "0" + + def refresh(self, item: SourceItem) -> SourceItem: + status = self._get(f"/api/v1/statuses/{item.cursor}", {}) + return parse_status(dict(status), self.platform) + + def fetch(self, cursor: str) -> list[SourceItem]: + items: list[SourceItem] = [] + for _ in range(MAX_PAGES): + query = {"min_id": cursor, "limit": str(PAGE_SIZE), **self.filters} + page = self._get(f"/api/v1/accounts/{self.account_id()}/statuses", query) + if not page: + break + ordered = sorted(page, key=lambda status: int(status["id"])) + items.extend(parse_status(status, self.platform) for status in ordered) + cursor = str(ordered[-1]["id"]) + if len(page) < PAGE_SIZE: + break + return items diff --git a/roles/web-app-openpost/files/python/crossposter/sources/peertube.py b/roles/web-app-openpost/files/python/crossposter/sources/peertube.py new file mode 100644 index 0000000000..a08d2c714f --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/sources/peertube.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import urllib.parse + +from crossposter import web +from crossposter.sources import Media, SourceItem + +PAGE_SIZE = 25 +MAX_PAGES = 4 +PUBLIC = 1 +PUBLISHED = 1 +VISIBILITY = {1: "public", 2: "unlisted", 3: "private", 4: "internal"} + + +def _files(detail: dict) -> list[dict]: + files = list(detail.get("files") or []) + for playlist in detail.get("streamingPlaylists") or []: + files.extend(playlist.get("files") or []) + return [ + item for item in files if item.get("fileDownloadUrl") or item.get("fileUrl") + ] + + +def best_file(detail: dict) -> Media | None: + files = _files(detail) + if not files: + return None + chosen = max( + files, key=lambda item: int((item.get("resolution") or {}).get("id") or 0) + ) + return Media( + url=str(chosen.get("fileDownloadUrl") or chosen.get("fileUrl")), + mime="video/mp4", + description="", + size=int(chosen.get("size") or 0), + ) + + +def published_public(video: dict) -> bool: + privacy = int((video.get("privacy") or {}).get("id") or 0) + state = int((video.get("state") or {}).get("id") or PUBLISHED) + return privacy == PUBLIC and state == PUBLISHED + + +def parse_video(video: dict, detail: dict) -> SourceItem: + media = best_file(detail) + return SourceItem( + uri=str(video["url"]), + url=str(video["url"]), + platform="peertube", + text=str(detail.get("description") or video.get("description") or ""), + visibility=VISIBILITY.get(int((video.get("privacy") or {}).get("id") or 0), ""), + tags=tuple(str(tag) for tag in detail.get("tags") or []), + media=(media,) if media else (), + in_reply_to="", + reblog=False, + spoiler="", + application="", + title=str(video.get("name") or ""), + cursor=str(video.get("publishedAt") or ""), + ) + + +class PeerTubeSource: + platform = "peertube" + + def __init__(self, base_url: str, account: str, token: str) -> None: + self.base_url = base_url.rstrip("/") + self.channel = account + self.headers = {"Authorization": f"Bearer {token}"} + + def _page(self, start: int) -> list[dict]: + query = urllib.parse.urlencode( + {"sort": "-publishedAt", "count": PAGE_SIZE, "start": start} + ) + body = web.get_json( + f"{self.base_url}/api/v1/video-channels/{self.channel}/videos?{query}", + self.headers, + ) + return list(body.get("data") or []) + + def _detail(self, video: dict) -> dict: + return dict( + web.get_json(f"{self.base_url}/api/v1/videos/{video['uuid']}", self.headers) + ) + + def refresh(self, item: SourceItem) -> SourceItem: + return item + + def newest_cursor(self) -> str: + page = self._page(0) + return str(page[0].get("publishedAt") or "") if page else "" + + def fetch(self, cursor: str) -> list[SourceItem]: + fresh: list[dict] = [] + for index in range(MAX_PAGES): + page = self._page(index * PAGE_SIZE) + newer = [ + video for video in page if str(video.get("publishedAt") or "") > cursor + ] + fresh.extend(newer) + if len(newer) < len(page) or len(page) < PAGE_SIZE: + break + ordered = sorted(fresh, key=lambda video: str(video.get("publishedAt") or "")) + return [ + parse_video(video, self._detail(video)) + for video in ordered + if published_public(video) + ] diff --git a/roles/web-app-openpost/files/python/crossposter/sources/pixelfed.py b/roles/web-app-openpost/files/python/crossposter/sources/pixelfed.py new file mode 100644 index 0000000000..22b7f52846 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/sources/pixelfed.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from typing import ClassVar + +from crossposter.sources.mastodon import MastodonSource + + +class PixelfedSource(MastodonSource): + platform = "pixelfed" + filters: ClassVar[dict[str, str]] = {"exclude_replies": "true"} diff --git a/roles/web-app-openpost/files/python/crossposter/store.py b/roles/web-app-openpost/files/python/crossposter/store.py new file mode 100644 index 0000000000..b5d50e1630 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/store.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import dataclasses +import hashlib +import json +from datetime import UTC, datetime, timedelta +from pathlib import Path + +from .sources import Media, SourceItem + +LOCK_ID = 4_103_270_041 +SQL_DIR = Path(__file__).resolve().parent / "sql" +SCHEMA = ("create/schema", "create/cursors", "create/items") +QUERIES = ( + *SCHEMA, + "try_lock", + "select/cursor", + "insert_item", + "upsert_cursor", + "select/due", + "select/open_publications", + "select/unnotified", + "select/items", + "update_item", + "resend_item", + "mark_notified", +) + +STATES = ("pending", "drafted", "submitted", "published", "failed", "dead_lettered") +TRANSITIONS = { + ("pending", "drafted"): "drafted", + ("pending", "submitted"): "submitted", + ("pending", "permanent"): "dead_lettered", + ("submitted", "delivered"): "published", + ("drafted", "delivered"): "published", + ("submitted", "delivery_failed"): "failed", + ("drafted", "delivery_failed"): "failed", + ("submitted", "resend"): "pending", + ("submitted", "exhausted"): "dead_lettered", +} + + +class InvalidTransitionError(ValueError): + pass + + +def idempotency_key(source_uri: str, target: str, resends: int) -> str: + digest = hashlib.sha256( + f"{len(source_uri)}:{source_uri}|{target}".encode() + ).hexdigest() + return f"crossposter-{digest}" + (f"-r{resends}" if resends else "") + + +def transition(state: str, event: str, attempts: int = 0, max_attempts: int = 0) -> str: + if state == "pending" and event == "transient": + return "dead_lettered" if attempts >= max_attempts else "pending" + target = TRANSITIONS.get((state, event)) + if target is None: + raise InvalidTransitionError(f"{event} is not allowed in state {state}") + return target + + +def item_to_json(item: SourceItem) -> str: + return json.dumps(dataclasses.asdict(item)) + + +def item_from_json(raw: dict) -> SourceItem: + media = tuple(Media(**entry) for entry in raw["media"]) + return SourceItem(**{**raw, "media": media, "tags": tuple(raw["tags"])}) + + +def query(name: str) -> str: + """ + Args: + name: one of QUERIES, the path of a statement below SQL_DIR without ``.sql``. + + Returns: + The statement's text from SQL_DIR. + """ + if name not in QUERIES: + raise KeyError(f"unknown crossposter query {name!r}") + return (SQL_DIR / f"{name}.sql").read_text(encoding="utf-8") + + +class Store: + def __init__(self, dsn: str) -> None: + from psycopg import connect + from psycopg.rows import dict_row + + self.connection = connect(dsn, autocommit=True, row_factory=dict_row) + + def _rows(self, name: str) -> list[dict]: + return list(self.connection.execute(query(name)).fetchall()) + + def migrate(self) -> None: + for name in SCHEMA: + self.connection.execute(query(name)) + + def lock(self) -> bool: + row = self.connection.execute( + query("try_lock"), {"lock_id": LOCK_ID} + ).fetchone() + return bool(row["held"]) + + def cursor(self, route: str) -> str | None: + row = self.connection.execute( + query("select/cursor"), {"route": route} + ).fetchone() + return None if row is None else str(row["cursor"]) + + def advance( + self, route: str, cursor: str, enqueued: list[tuple[SourceItem, str, str]] + ) -> None: + with self.connection.transaction(): + for item, target, network in enqueued: + self.connection.execute( + query("insert_item"), + { + "route": route, + "source_uri": item.uri, + "source_url": item.url, + "target": target, + "network": network, + "payload": item_to_json(item), + }, + ) + self.connection.execute( + query("upsert_cursor"), {"route": route, "cursor": cursor} + ) + + def due(self) -> list[dict]: + return self._rows("select/due") + + def open_publications(self) -> list[dict]: + return self._rows("select/open_publications") + + def unnotified(self) -> list[dict]: + return self._rows("select/unnotified") + + def everything(self) -> list[dict]: + return self._rows("select/items") + + def update( + self, + row_id: int, + state: str, + publication_id: str, + attempts: int, + error: str, + delay_seconds: float, + ) -> None: + self.connection.execute( + query("update_item"), + { + "id": row_id, + "state": state, + "publication_id": publication_id, + "attempts": attempts, + "error": error, + "next_attempt_at": datetime.now(UTC) + timedelta(seconds=delay_seconds), + }, + ) + + def resend( + self, row_id: int, attempts: int, error: str, delay_seconds: float + ) -> None: + self.connection.execute( + query("resend_item"), + { + "id": row_id, + "attempts": attempts, + "error": error, + "next_attempt_at": datetime.now(UTC) + timedelta(seconds=delay_seconds), + }, + ) + + def mark_notified(self, row_id: int) -> None: + self.connection.execute(query("mark_notified"), {"id": row_id}) diff --git a/roles/web-app-openpost/files/python/crossposter/web.py b/roles/web-app-openpost/files/python/crossposter/web.py new file mode 100644 index 0000000000..5ee8083fa4 --- /dev/null +++ b/roles/web-app-openpost/files/python/crossposter/web.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import json +import shutil +import urllib.error +import urllib.request +from dataclasses import dataclass +from typing import IO, TYPE_CHECKING + +from crossposter import retry + +if TYPE_CHECKING: + from http.client import HTTPResponse + from pathlib import Path + +TIMEOUT_SECONDS = 60 +UPLOAD_TIMEOUT_SECONDS = 1800 +CHUNK_BYTES = 1024 * 1024 + + +@dataclass(frozen=True) +class Response: + status: int + headers: dict[str, str] + body: bytes + + def json(self) -> object: + return json.loads(self.body.decode()) if self.body else None + + +class RequestError(RuntimeError): + def __init__( + self, url: str, status: int | None, headers: dict[str, str], detail: str + ) -> None: + shown = status if status is not None else "unreachable" + super().__init__(f"{url}: HTTP {shown} {detail[:300]}") + self.status = status + self.headers = headers + self.detail = detail + + @property + def transient(self) -> bool: + return retry.transient(self.status) + + +def _outgoing( + url: str, method: str, headers: dict[str, str], body: bytes | IO[bytes] | None +) -> urllib.request.Request: + return urllib.request.Request(url, data=body, method=method, headers=headers) # noqa: S310 validated route and OpenPost URLs + + +def _open(outgoing: urllib.request.Request, timeout: float) -> HTTPResponse: + return urllib.request.urlopen(outgoing, timeout=timeout) # noqa: S310 validated route and OpenPost URLs + + +def _exchange( + outgoing: urllib.request.Request, timeout: float, accepted: tuple[int, ...] +) -> Response: + url = outgoing.full_url + try: + with _open(outgoing, timeout) as answer: + response = Response( + answer.status, dict(answer.headers.items()), answer.read() + ) + except urllib.error.HTTPError as error: + response = Response(error.code, dict(error.headers.items()), error.read()) + except (urllib.error.URLError, TimeoutError, ConnectionError) as error: + raise RequestError(url, None, {}, str(error)) from error + if response.status not in accepted: + raise RequestError( + url, + response.status, + response.headers, + response.body.decode(errors="replace"), + ) + return response + + +def request( + method: str, + url: str, + headers: dict[str, str], + body: bytes | None, + accepted: tuple[int, ...], +) -> Response: + return _exchange(_outgoing(url, method, headers, body), TIMEOUT_SECONDS, accepted) + + +def get_json(url: str, headers: dict[str, str]) -> object: + return request( + "GET", url, {**headers, "Accept": "application/json"}, None, (200,) + ).json() + + +def download(url: str, headers: dict[str, str], target: Path) -> Path: + try: + with ( + _open(_outgoing(url, "GET", headers, None), TIMEOUT_SECONDS) as answer, + target.open("wb") as sink, + ): + shutil.copyfileobj(answer, sink, CHUNK_BYTES) + except urllib.error.HTTPError as error: + detail = error.read().decode(errors="replace") + raise RequestError( + url, error.code, dict(error.headers.items()), detail + ) from error + except (urllib.error.URLError, TimeoutError, ConnectionError) as error: + raise RequestError(url, None, {}, str(error)) from error + return target + + +def upload( + method: str, + url: str, + headers: dict[str, str], + source: Path, + accepted: tuple[int, ...], +) -> Response: + sized = {**headers, "Content-Length": str(source.stat().st_size)} + with source.open("rb") as body: + return _exchange( + _outgoing(url, method, sized, body), UPLOAD_TIMEOUT_SECONDS, accepted + ) diff --git a/roles/web-app-openpost/files/python/provider/__init__.py b/roles/web-app-openpost/files/python/provider/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/roles/web-app-openpost/files/python/provider/__main__.py b/roles/web-app-openpost/files/python/provider/__main__.py new file mode 100644 index 0000000000..69c0a4da86 --- /dev/null +++ b/roles/web-app-openpost/files/python/provider/__main__.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import argparse +import json +import logging +import ssl +import sys +import threading +import urllib.error +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from provider.linkedin import Client, LinkedIn, Request +from provider.store import Store + +LOG = logging.getLogger("provider") +HEALTH_TIMEOUT_SECONDS = 5 + + +def load(path: str) -> dict: + return json.loads(Path(path).read_text()) + + +def application(config: dict) -> LinkedIn: + clients = { + client_id: Client( + secret=str(client["secret"]), + name=str(client["name"]), + redirect_uris=tuple(str(uri) for uri in client["redirect_uris"]), + ) + for client_id, client in config["linkedin"]["clients"].items() + } + return LinkedIn(Store(), clients) + + +def handler_for(app: LinkedIn) -> type[BaseHTTPRequestHandler]: + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def _dispatch(self) -> None: + url = urllib.parse.urlsplit(self.path) + length = int(self.headers.get("Content-Length") or 0) + request = Request( + method=self.command, + path=url.path, + query=dict(urllib.parse.parse_qsl(url.query, keep_blank_values=True)), + headers={key.lower(): value for key, value in self.headers.items()}, + body=self.rfile.read(length) if length else b"", + ) + response = app.handle(request) + self.send_response(response.status) + for name, value in response.headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(response.body))) + self.end_headers() + self.wfile.write(response.body) + + def do_GET(self) -> None: + self._dispatch() + + def do_POST(self) -> None: + self._dispatch() + + def do_PUT(self) -> None: + self._dispatch() + + def do_DELETE(self) -> None: + self._dispatch() + + def log_message(self, message: str, *args: object) -> None: + LOG.info("%s %s", self.address_string(), message % args) + + return Handler + + +def serve(config: dict) -> int: + handler = handler_for(application(config)) + plain = ThreadingHTTPServer(("0.0.0.0", int(config["http_port"])), handler) # noqa: S104 published only on the role network and the CI loopback + secure = ThreadingHTTPServer(("0.0.0.0", int(config["https_port"])), handler) # noqa: S104 published only on the role network and the CI loopback + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(config["certificate"], config["key"]) + secure.socket = context.wrap_socket(secure.socket, server_side=True) + threading.Thread(target=secure.serve_forever, daemon=True).start() + LOG.info("serving LinkedIn on %s and %s", config["http_port"], config["https_port"]) + plain.serve_forever() + return 0 + + +def health(config: dict) -> int: + url = f"http://127.0.0.1:{int(config['http_port'])}/__fake/health" + try: + with urllib.request.urlopen(url, timeout=HEALTH_TIMEOUT_SECONDS) as answer: + return 0 if answer.status == 200 else 1 + except (urllib.error.URLError, OSError): + return 1 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="provider") + parser.add_argument("command", choices=("serve", "health")) + parser.add_argument("--config", required=True) + args = parser.parse_args(argv) + logging.basicConfig( + level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s" + ) + config = load(args.config) + return serve(config) if args.command == "serve" else health(config) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/web-app-openpost/files/python/provider/linkedin.py b/roles/web-app-openpost/files/python/provider/linkedin.py new file mode 100644 index 0000000000..193f9a4556 --- /dev/null +++ b/roles/web-app-openpost/files/python/provider/linkedin.py @@ -0,0 +1,429 @@ +from __future__ import annotations + +import html +import json +import re +import urllib.parse +from dataclasses import asdict, dataclass + +from provider.store import Account, Store, StoreError + +API_HOST = "api.linkedin.com" +POST_VISIBILITIES = ("PUBLIC", "CONNECTIONS") +ESCAPED_MARKUP = re.compile(r"\\([|{}@\[\]()<>#\\*_~])") +SHARE_PATH = re.compile(r"^/rest/posts/(?P.+)$") +FEED_PATH = re.compile(r"^/feed/update/(?P.+)$") +UPLOAD_PATH = re.compile(r"^/upload/images/(?P[0-9a-f]+)$") + + +@dataclass(frozen=True) +class Client: + secret: str + name: str + redirect_uris: tuple[str, ...] + + +@dataclass(frozen=True) +class Request: + method: str + path: str + query: dict[str, str] + headers: dict[str, str] + body: bytes + + def form(self) -> dict[str, str]: + return dict(urllib.parse.parse_qsl(self.body.decode(), keep_blank_values=True)) + + def bearer(self) -> str: + value = self.headers.get("authorization", "") + return value[7:] if value.lower().startswith("bearer ") else "" + + +@dataclass(frozen=True) +class Response: + status: int + headers: dict[str, str] + body: bytes + + +def plain_text(commentary: str) -> str: + return ESCAPED_MARKUP.sub(r"\1", commentary) + + +def _json( + status: int, payload: object, headers: dict[str, str] | None = None +) -> Response: + return Response( + status, + {"Content-Type": "application/json", **(headers or {})}, + json.dumps(payload).encode(), + ) + + +def _error(status: int, code: str, message: str) -> Response: + return _json(status, {"status": status, "code": code, "message": message}) + + +def _redirect(location: str) -> Response: + return Response(302, {"Location": location}, b"") + + +def _page(status: int, title: str, body: str) -> Response: + document = ( + "" + f"{html.escape(title)}
" + f"

{html.escape(title)}

{body}
" + ) + return Response( + status, {"Content-Type": "text/html; charset=utf-8"}, document.encode() + ) + + +def _hidden(fields: dict[str, str]) -> str: + return "".join( + f"" + for name, value in fields.items() + ) + + +def _field(label: str, name: str, kind: str) -> str: + return ( + f"" + ) + + +def _with_query(url: str, params: dict[str, str]) -> str: + joiner = "&" if urllib.parse.urlsplit(url).query else "?" + return url + joiner + urllib.parse.urlencode(params) + + +class LinkedIn: + def __init__(self, store: Store, clients: dict[str, Client]) -> None: + self.store = store + self.clients = clients + + def handle(self, request: Request) -> Response: + routes = { + ("GET", "/signup"): self.signup_page, + ("POST", "/signup"): self.signup, + ("GET", "/oauth/v2/authorization"): self.authorization_page, + ("POST", "/oauth/v2/authorization"): self.authorize, + ("POST", "/oauth/v2/accessToken"): self.access_token, + ("GET", "/v2/userinfo"): self.userinfo, + ("POST", "/rest/images"): self.initialize_upload, + ("POST", "/rest/posts"): self.create_post, + ("GET", "/__fake/health"): self.health, + ("GET", "/__fake/linkedin/posts"): self.admin_posts, + ("GET", "/__fake/linkedin/accounts"): self.admin_accounts, + } + handler = routes.get((request.method, request.path)) + if handler is not None: + return handler(request) + for method, pattern, dynamic in ( + ("GET", SHARE_PATH, self.read_post), + ("GET", FEED_PATH, self.feed_page), + ("PUT", UPLOAD_PATH, self.upload), + ): + match = pattern.match(request.path) + if match and request.method == method: + return dynamic(request, urllib.parse.unquote(match.group("id"))) + return _error( + 404, "NOT_FOUND", f"{request.method} {request.path} is not served" + ) + + def health(self, request: Request) -> Response: + return Response(200, {"Content-Type": "text/plain"}, b"ok") + + def signup_page(self, request: Request, error: str = "") -> Response: + notice = f"

{html.escape(error)}

" if error else "" + form = ( + "
" + f"{_hidden({'next': request.query.get('next', '')})}" + f"{_field('Name', 'name', 'text')}{_field('Email', 'email', 'email')}" + f"{_field('Password', 'password', 'password')}" + "" + ) + return _page(400 if error else 200, "Join LinkedIn", notice + form) + + def signup(self, request: Request) -> Response: + form = request.form() + try: + self.store.create_account( + form.get("name", ""), form.get("email", ""), form.get("password", "") + ) + except StoreError as error: + return self.signup_page( + Request("GET", "/signup", {"next": form.get("next", "")}, {}, b""), + str(error), + ) + destination = form.get("next", "") + if destination.startswith("/oauth/v2/authorization?"): + return Response(303, {"Location": destination}, b"") + return _page(201, "Account created", "

Your account is ready.

") + + def _client(self, params: dict[str, str]) -> Client | None: + client = self.clients.get(params.get("client_id", "")) + if client is None or params.get("redirect_uri", "") not in client.redirect_uris: + return None + return client + + def authorization_page(self, request: Request, error: str = "") -> Response: + params = request.query + client = self._client(params) + if client is None or params.get("response_type") != "code": + return _page( + 400, "Invalid request", "

The application is not registered.

" + ) + here = "/oauth/v2/authorization?" + urllib.parse.urlencode(params) + notice = f"

{html.escape(error)}

" if error else "" + scopes = "".join( + f"
  • {html.escape(scope)}
  • " + for scope in params.get("scope", "").split() + ) + carried = { + key: params.get(key, "") + for key in ("client_id", "redirect_uri", "scope", "state", "response_type") + } + form = ( + f"

    {html.escape(client.name)} would like to access your account.

    " + f"
      {scopes}
    " + "
    " + f"{_hidden(carried)}{_field('Email', 'email', 'email')}" + f"{_field('Password', 'password', 'password')}" + "" + "" + "" + f"

    Join now

    " + ) + return _page(400 if error else 200, "Sign in to LinkedIn", notice + form) + + def authorize(self, request: Request) -> Response: + form = request.form() + client = self._client(form) + if client is None or form.get("response_type") != "code": + return _page( + 400, "Invalid request", "

    The application is not registered.

    " + ) + redirect_uri, state = form["redirect_uri"], form.get("state", "") + if form.get("decision") != "allow": + return _redirect( + _with_query( + redirect_uri, + {"error": "user_cancelled_authorize", "state": state}, + ) + ) + account = self.store.authenticate( + form.get("email", ""), form.get("password", "") + ) + if account is None: + carried = { + key: form.get(key, "") + for key in ( + "client_id", + "redirect_uri", + "scope", + "state", + "response_type", + ) + } + return self.authorization_page( + Request("GET", "/oauth/v2/authorization", carried, {}, b""), + "Wrong email or password.", + ) + code = self.store.issue_code( + account.member, form["client_id"], redirect_uri, form.get("scope", "") + ) + return _redirect(_with_query(redirect_uri, {"code": code, "state": state})) + + def access_token(self, request: Request) -> Response: + form = request.form() + client = self.clients.get(form.get("client_id", "")) + if client is None or client.secret != form.get("client_secret", ""): + return _json( + 401, + { + "error": "invalid_client", + "error_description": "Client authentication failed", + }, + ) + try: + if form.get("grant_type") == "authorization_code": + grant = self.store.redeem_code( + form.get("code", ""), + form["client_id"], + form.get("redirect_uri", ""), + ) + return _json(200, self.store.issue_tokens(grant.member, grant.scope)) + if form.get("grant_type") == "refresh_token": + return _json(200, self.store.refresh(form.get("refresh_token", ""))) + except StoreError as error: + return _json( + 400, {"error": "invalid_grant", "error_description": str(error)} + ) + return _json( + 400, + { + "error": "unsupported_grant_type", + "error_description": "Unsupported grant type", + }, + ) + + def _member(self, request: Request) -> Account | None: + return self.store.member_for(request.bearer()) + + def userinfo(self, request: Request) -> Response: + account = self._member(request) + if account is None: + return _error( + 401, + "REVOKED_ACCESS_TOKEN", + "The token used in the request has been revoked by the user", + ) + given, _, family = account.name.partition(" ") + return _json( + 200, + { + "sub": account.member, + "name": account.name, + "given_name": given, + "family_name": family, + "picture": "", + "email": account.email, + "email_verified": True, + "locale": {"country": "US", "language": "en"}, + }, + ) + + def initialize_upload(self, request: Request) -> Response: + account = self._member(request) + if account is None: + return _error( + 401, + "REVOKED_ACCESS_TOKEN", + "The token used in the request has been revoked by the user", + ) + if request.query.get("action") != "initializeUpload": + return _error(400, "ILLEGAL_ARGUMENT", "Unsupported action") + payload = json.loads(request.body or b"{}") + owner = str((payload.get("initializeUploadRequest") or {}).get("owner", "")) + if owner != account.urn: + return _error( + 403, "ACCESS_DENIED", "The owner is not the authenticated member" + ) + image = self.store.register_image(owner) + return _json( + 200, + { + "value": { + "uploadUrlExpiresAt": int((self.store.now() + 3600) * 1000), + "uploadUrl": f"https://{API_HOST}/upload/images/{image.upload_id}", + "image": image.urn, + } + }, + ) + + def upload(self, request: Request, upload_id: str) -> Response: + account = self._member(request) + if account is None: + return _error( + 401, + "REVOKED_ACCESS_TOKEN", + "The token used in the request has been revoked by the user", + ) + try: + self.store.store_upload(upload_id, account.urn, request.body) + except StoreError as error: + return _error(404, "NOT_FOUND", str(error)) + return Response(201, {}, b"") + + def create_post(self, request: Request) -> Response: + account = self._member(request) + if account is None: + return _error( + 401, + "REVOKED_ACCESS_TOKEN", + "The token used in the request has been revoked by the user", + ) + payload = json.loads(request.body or b"{}") + if payload.get("author") != account.urn: + return _error( + 403, "ACCESS_DENIED", "The author is not the authenticated member" + ) + visibility = payload.get("visibility") + if ( + visibility not in POST_VISIBILITIES + or payload.get("lifecycleState") != "PUBLISHED" + ): + return _error( + 422, "UNPROCESSABLE_ENTITY", "Unsupported visibility or lifecycle state" + ) + content = payload.get("content") or {} + media = (content.get("media") or {}).get("id") + if media and not self.store.uploaded(str(media), account.urn): + return _error( + 422, + "UNPROCESSABLE_ENTITY", + "The media was never uploaded by this member", + ) + post = self.store.create_post( + account.urn, str(payload.get("commentary", "")), visibility, content + ) + return Response(201, {"x-restli-id": post.id}, b"") + + def _post_body(self, post_id: str) -> dict | None: + post = self.store.post(post_id) + if post is None: + return None + return { + "id": post.id, + "author": post.author, + "commentary": post.commentary, + "visibility": post.visibility, + "lifecycleState": "PUBLISHED", + "content": post.content, + "createdAt": int(post.created_at * 1000), + } + + def read_post(self, request: Request, post_id: str) -> Response: + if self._member(request) is None: + return _error( + 401, + "REVOKED_ACCESS_TOKEN", + "The token used in the request has been revoked by the user", + ) + body = self._post_body(post_id) + if body is None: + return _error(404, "NOT_FOUND", f"Post {post_id} does not exist") + return _json(200, body) + + def feed_page(self, request: Request, post_id: str) -> Response: + post = self.store.post(post_id) + if post is None: + return _page(404, "Post not found", "

    This post does not exist.

    ") + member = post.author.rsplit(":", 1)[-1] + author = self.store.account(member) + name = author.name if author else member + return _page( + 200, + f"{name} on LinkedIn", + f"

    {html.escape(plain_text(post.commentary))}

    ", + ) + + def admin_posts(self, request: Request) -> Response: + return _json( + 200, + [ + {**asdict(post), "text": plain_text(post.commentary)} + for post in self.store.posts() + ], + ) + + def admin_accounts(self, request: Request) -> Response: + return _json( + 200, + [ + {"member": account.member, "name": account.name, "email": account.email} + for account in self.store.accounts() + ], + ) diff --git a/roles/web-app-openpost/files/python/provider/store.py b/roles/web-app-openpost/files/python/provider/store.py new file mode 100644 index 0000000000..725c6f0f7d --- /dev/null +++ b/roles/web-app-openpost/files/python/provider/store.py @@ -0,0 +1,230 @@ +from __future__ import annotations + +import hashlib +import hmac +import itertools +import secrets +import threading +import time +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable + +CODE_SECONDS = 600 +ACCESS_SECONDS = 5_184_000 +REFRESH_SECONDS = 31_536_000 +HASH_ROUNDS = 100_000 +FIRST_POST = 7_300_000_000_000_000_001 + + +class StoreError(ValueError): + pass + + +@dataclass(frozen=True) +class Account: + member: str + name: str + email: str + salt: str + password_hash: str + + @property + def urn(self) -> str: + return f"urn:li:person:{self.member}" + + +@dataclass(frozen=True) +class Grant: + member: str + client_id: str + redirect_uri: str + scope: str + expires_at: float + + +@dataclass(frozen=True) +class Token: + member: str + scope: str + expires_at: float + + +@dataclass(frozen=True) +class Image: + urn: str + owner: str + upload_id: str + size: int + + +@dataclass(frozen=True) +class Post: + id: str + author: str + commentary: str + visibility: str + content: dict + created_at: float + + +def _digest(password: str, salt: str) -> str: + return hashlib.pbkdf2_hmac( + "sha256", password.encode(), salt.encode(), HASH_ROUNDS + ).hex() + + +class Store: + def __init__(self, now: Callable[[], float] = time.time) -> None: + self.now = now + self._lock = threading.Lock() + self._accounts: dict[str, Account] = {} + self._codes: dict[str, Grant] = {} + self._access: dict[str, Token] = {} + self._refresh: dict[str, Token] = {} + self._images: dict[str, Image] = {} + self._uploads: dict[str, bytes] = {} + self._posts: dict[str, Post] = {} + self._post_ids = itertools.count(FIRST_POST) + + def create_account(self, name: str, email: str, password: str) -> Account: + name, email = name.strip(), email.strip().lower() + if not name or not email or not password: + raise StoreError("name, email and password are required") + with self._lock: + if email in self._accounts: + raise StoreError("an account with this email already exists") + salt = secrets.token_hex(16) + account = Account( + member=secrets.token_hex(6), + name=name, + email=email, + salt=salt, + password_hash=_digest(password, salt), + ) + self._accounts[email] = account + return account + + def authenticate(self, email: str, password: str) -> Account | None: + account = self._accounts.get(email.strip().lower()) + if account is None: + return None + if not hmac.compare_digest( + account.password_hash, _digest(password, account.salt) + ): + return None + return account + + def account(self, member: str) -> Account | None: + return next( + (item for item in self._accounts.values() if item.member == member), None + ) + + def accounts(self) -> list[Account]: + return list(self._accounts.values()) + + def issue_code( + self, member: str, client_id: str, redirect_uri: str, scope: str + ) -> str: + code = secrets.token_urlsafe(32) + with self._lock: + self._codes[code] = Grant( + member, client_id, redirect_uri, scope, self.now() + CODE_SECONDS + ) + return code + + def redeem_code(self, code: str, client_id: str, redirect_uri: str) -> Grant: + with self._lock: + grant = self._codes.pop(code, None) + if grant is None or grant.expires_at < self.now(): + raise StoreError("the authorization code is invalid or expired") + if grant.client_id != client_id or grant.redirect_uri != redirect_uri: + raise StoreError("the authorization code belongs to another client") + return grant + + def issue_tokens(self, member: str, scope: str) -> dict: + access, refresh = secrets.token_urlsafe(48), secrets.token_urlsafe(48) + now = self.now() + with self._lock: + self._access[access] = Token(member, scope, now + ACCESS_SECONDS) + self._refresh[refresh] = Token(member, scope, now + REFRESH_SECONDS) + return { + "access_token": access, + "expires_in": ACCESS_SECONDS, + "refresh_token": refresh, + "refresh_token_expires_in": REFRESH_SECONDS, + "scope": scope, + } + + def refresh(self, refresh_token: str) -> dict: + token = self._refresh.get(refresh_token) + now = self.now() + if token is None or token.expires_at < now: + raise StoreError("the refresh token is invalid or expired") + access = secrets.token_urlsafe(48) + with self._lock: + self._access[access] = Token( + token.member, token.scope, now + ACCESS_SECONDS + ) + return { + "access_token": access, + "expires_in": ACCESS_SECONDS, + "refresh_token": refresh_token, + "refresh_token_expires_in": int(token.expires_at - now), + "scope": token.scope, + } + + def member_for(self, access_token: str) -> Account | None: + token = self._access.get(access_token) + if token is None or token.expires_at < self.now(): + return None + return self.account(token.member) + + def register_image(self, owner: str) -> Image: + image = Image( + urn=f"urn:li:image:{secrets.token_hex(8)}", + owner=owner, + upload_id=secrets.token_hex(12), + size=0, + ) + with self._lock: + self._images[image.upload_id] = image + return image + + def store_upload(self, upload_id: str, owner: str, data: bytes) -> Image: + with self._lock: + image = self._images.get(upload_id) + if image is None or image.owner != owner: + raise StoreError("the upload belongs to no image of this member") + stored = Image(image.urn, image.owner, image.upload_id, len(data)) + self._images[upload_id] = stored + self._uploads[image.urn] = data + return stored + + def uploaded(self, urn: str, owner: str) -> bool: + return urn in self._uploads and any( + image.urn == urn and image.owner == owner for image in self._images.values() + ) + + def create_post( + self, author: str, commentary: str, visibility: str, content: dict + ) -> Post: + with self._lock: + post = Post( + id=f"urn:li:share:{next(self._post_ids)}", + author=author, + commentary=commentary, + visibility=visibility, + content=content, + created_at=self.now(), + ) + self._posts[post.id] = post + return post + + def post(self, post_id: str) -> Post | None: + return self._posts.get(post_id) + + def posts(self) -> list[Post]: + return list(self._posts.values()) diff --git a/roles/web-app-openpost/files/ruby/mastodon/grant_authorization.rb b/roles/web-app-openpost/files/ruby/mastodon/grant_authorization.rb new file mode 100644 index 0000000000..89181bb4d3 --- /dev/null +++ b/roles/web-app-openpost/files/ruby/mastodon/grant_authorization.rb @@ -0,0 +1,18 @@ +# nocheck: mirrored-unit-test - runs in Mastodon's `rails runner` against its live Doorkeeper tables; the models exist only inside the booted app +# Args (environment): +# CROSSPOSTER_ACCOUNT: local Mastodon username that grants the code. +# CROSSPOSTER_AUTHORIZE: authorization URL OpenPost started; its query names the client, redirect URI, scope and PKCE challenge. +# Prints CROSSPOSTER_GRANT=. +query = Rack::Utils.parse_query(URI.parse(ENV.fetch("CROSSPOSTER_AUTHORIZE")).query) +account = Account.find_local!(ENV.fetch("CROSSPOSTER_ACCOUNT")) +application = Doorkeeper::Application.find_by!(uid: query.fetch("client_id")) +grant = Doorkeeper::AccessGrant.create!( + application: application, + resource_owner_id: account.user.id, + redirect_uri: query.fetch("redirect_uri"), + scopes: query.fetch("scope", application.scopes.to_s), + code_challenge: query["code_challenge"], + code_challenge_method: query["code_challenge_method"], + expires_in: 600 +) +puts "CROSSPOSTER_GRANT=#{grant.plaintext_token}" diff --git a/roles/web-app-openpost/files/ruby/mastodon/mint_token.rb b/roles/web-app-openpost/files/ruby/mastodon/mint_token.rb new file mode 100644 index 0000000000..872e25c023 --- /dev/null +++ b/roles/web-app-openpost/files/ruby/mastodon/mint_token.rb @@ -0,0 +1,11 @@ +# nocheck: mirrored-unit-test - runs in Mastodon's `rails runner` against its live Doorkeeper tables; the models exist only inside the booted app +# Args (environment): +# CROSSPOSTER_ACCOUNT: local Mastodon username the token belongs to. +# Prints CROSSPOSTER_TOKEN=. +account = Account.find_local!(ENV.fetch("CROSSPOSTER_ACCOUNT")) +application = Doorkeeper::Application.find_or_create_by!(name: "Crossposter CI") do |created| + created.redirect_uri = "urn:ietf:wg:oauth:2.0:oob" + created.scopes = "read write" +end +token = Doorkeeper::AccessToken.create!(application: application, resource_owner_id: account.user.id, scopes: "read write") +puts "CROSSPOSTER_TOKEN=#{token.plaintext_token}" diff --git a/roles/web-app-openpost/files/simulator/openpost.json b/roles/web-app-openpost/files/simulator/openpost.json new file mode 100644 index 0000000000..183e91a91c --- /dev/null +++ b/roles/web-app-openpost/files/simulator/openpost.json @@ -0,0 +1,916 @@ +{ + "mappings": [ + { + "name": "x-request-token", + "request": { + "method": "POST", + "urlPath": "/oauth/request_token" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/x-www-form-urlencoded" + }, + "body": "oauth_token=simulator-request-token&oauth_token_secret=simulator-request-secret&oauth_callback_confirmed=true" + } + }, + { + "name": "x-access-token", + "request": { + "method": "POST", + "urlPath": "/oauth/access_token" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/x-www-form-urlencoded" + }, + "body": "oauth_token=simulator-access-token&oauth_token_secret=simulator-access-secret&user_id=4242&screen_name=openpost_simulator" + } + }, + { + "name": "x-users-me", + "request": { + "method": "GET", + "urlPath": "/2/users/me" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "id": "4242", + "name": "OpenPost Simulator", + "username": "openpost_simulator", + "subscription_type": "None" + } + } + } + }, + { + "name": "x-user-metrics", + "request": { + "method": "GET", + "urlPath": "/2/users/4242" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "id": "4242", + "public_metrics": { + "followers_count": 0, + "following_count": 0, + "tweet_count": 0, + "listed_count": 0 + } + } + } + } + }, + { + "name": "x-tweet-rate-limited-once", + "priority": 1, + "scenarioName": "x-rate-limited", + "requiredScenarioState": "Started", + "newScenarioState": "recovered", + "request": { + "method": "POST", + "urlPath": "/2/tweets", + "bodyPatterns": [ + { + "contains": "[simulate-429]" + } + ] + }, + "response": { + "status": 429, + "headers": { + "Content-Type": "application/json", + "x-rate-limit-remaining": "0", + "x-rate-limit-reset": "{{now offset='5 seconds' format='epoch'}}" + }, + "jsonBody": { + "title": "Too Many Requests", + "status": 429 + }, + "transformers": [ + "response-template" + ] + } + }, + { + "name": "x-tweet-unavailable-always", + "priority": 1, + "request": { + "method": "POST", + "urlPath": "/2/tweets", + "bodyPatterns": [ + { + "contains": "[simulate-503-always]" + } + ] + }, + "response": { + "status": 503, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "title": "Service Unavailable", + "status": 503 + } + } + }, + { + "name": "x-tweet-unavailable-once", + "priority": 1, + "scenarioName": "x-unavailable", + "requiredScenarioState": "Started", + "newScenarioState": "recovered", + "request": { + "method": "POST", + "urlPath": "/2/tweets", + "bodyPatterns": [ + { + "contains": "[simulate-503]" + } + ] + }, + "response": { + "status": 503, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "title": "Service Unavailable", + "status": 503 + } + } + }, + { + "name": "x-tweet-rejected", + "priority": 1, + "request": { + "method": "POST", + "urlPath": "/2/tweets", + "bodyPatterns": [ + { + "contains": "[simulate-400]" + } + ] + }, + "response": { + "status": 400, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "title": "Invalid Request", + "status": 400, + "detail": "Simulated permanent rejection", + "type": "https://api.twitter.com/2/problems/invalid-request" + } + } + }, + { + "name": "x-tweet-created", + "priority": 5, + "request": { + "method": "POST", + "urlPath": "/2/tweets" + }, + "response": { + "status": 201, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "id": "1840000000000000001", + "text": "simulated" + } + } + } + }, + { + "name": "x-media-upload", + "request": { + "method": "POST", + "urlPath": "/1.1/media/upload.json" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "media_id": 1880000000000000001, + "media_id_string": "1880000000000000001", + "expires_after_secs": 86400 + } + } + }, + { + "name": "x-media-metadata", + "request": { + "method": "POST", + "urlPath": "/1.1/media/metadata/create.json" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "body": "{}" + } + }, + { + "name": "meta-access-token", + "request": { + "method": "POST", + "urlPathPattern": "/v[0-9.]+/oauth/access_token" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "access_token": "simulator-meta-user-token", + "token_type": "bearer", + "expires_in": 5183944 + } + } + }, + { + "name": "meta-permissions", + "request": { + "method": "GET", + "urlPathPattern": "/v[0-9.]+/me/permissions" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": [ + { + "permission": "business_management", + "status": "granted" + }, + { + "permission": "pages_show_list", + "status": "granted" + }, + { + "permission": "pages_read_engagement", + "status": "granted" + }, + { + "permission": "pages_read_user_content", + "status": "granted" + }, + { + "permission": "pages_manage_engagement", + "status": "granted" + }, + { + "permission": "pages_manage_metadata", + "status": "granted" + }, + { + "permission": "pages_manage_posts", + "status": "granted" + }, + { + "permission": "pages_messaging", + "status": "granted" + }, + { + "permission": "instagram_basic", + "status": "granted" + }, + { + "permission": "instagram_content_publish", + "status": "granted" + }, + { + "permission": "instagram_manage_comments", + "status": "granted" + }, + { + "permission": "instagram_manage_messages", + "status": "granted" + }, + { + "permission": "instagram_manage_insights", + "status": "granted" + } + ] + } + } + }, + { + "name": "meta-me", + "request": { + "method": "GET", + "urlPathPattern": "/v[0-9.]+/me" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "4243", + "name": "OpenPost Simulator", + "username": "openpost.simulator", + "picture": { + "data": { + "url": "" + } + } + } + } + }, + { + "name": "meta-pages", + "request": { + "method": "GET", + "urlPathPattern": "/v[0-9.]+/me/accounts" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": [ + { + "id": "424242", + "name": "OpenPost Simulator Page", + "username": "openpostsimulator", + "access_token": "simulator-page-token", + "tasks": [ + "ADVERTISE", + "ANALYZE", + "CREATE_CONTENT", + "MESSAGING", + "MODERATE", + "MANAGE" + ], + "instagram_business_account": { + "id": "17841400000000000", + "username": "openpost_simulator", + "name": "OpenPost Simulator", + "profile_picture_url": "", + "account_type": "BUSINESS" + }, + "picture": { + "data": { + "url": "" + } + } + }, + { + "id": "525252", + "name": "OpenPost Simulator Second Page", + "username": "openpostsimulatorsecond", + "access_token": "simulator-second-page-token", + "tasks": [ + "ADVERTISE", + "ANALYZE", + "CREATE_CONTENT", + "MESSAGING", + "MODERATE", + "MANAGE" + ], + "picture": { + "data": { + "url": "" + } + } + } + ], + "paging": {} + } + } + }, + { + "name": "meta-businesses", + "request": { + "method": "GET", + "urlPathPattern": "/v[0-9.]+/me/businesses" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": [], + "paging": {} + } + } + }, + { + "name": "facebook-feed", + "request": { + "method": "POST", + "urlPathPattern": "/v[0-9.]+/(424242|525252)/feed" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "{{request.pathSegments.[1]}}_1001" + }, + "transformers": [ + "response-template" + ] + } + }, + { + "name": "facebook-photos", + "request": { + "method": "POST", + "urlPathPattern": "/v[0-9.]+/(424242|525252)/photos" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "2001", + "post_id": "{{request.pathSegments.[1]}}_2001" + }, + "transformers": [ + "response-template" + ] + } + }, + { + "name": "instagram-container", + "request": { + "method": "POST", + "urlPathPattern": "/v[0-9.]+/17841400000000000/media" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "18000000000000001" + } + } + }, + { + "name": "instagram-container-status", + "request": { + "method": "GET", + "urlPathPattern": "/v[0-9.]+/18000000000000001" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "18000000000000001", + "status_code": "FINISHED", + "status": "Finished: Media has been uploaded and it is ready to be published." + } + } + }, + { + "name": "instagram-publish", + "request": { + "method": "POST", + "urlPathPattern": "/v[0-9.]+/17841400000000000/media_publish" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "18000000000000002" + } + } + }, + { + "name": "instagram-media", + "request": { + "method": "GET", + "urlPathPattern": "/v[0-9.]+/18000000000000002" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "18000000000000002", + "permalink": "https://www.instagram.com/p/simulator/" + } + } + }, + { + "name": "google-token", + "request": { + "method": "POST", + "urlPath": "/token" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "access_token": "simulator-google-token", + "refresh_token": "simulator-google-refresh", + "expires_in": 3599, + "token_type": "Bearer", + "scope": "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtube.upload" + } + } + }, + { + "name": "google-userinfo", + "request": { + "method": "GET", + "urlPath": "/oauth2/v2/userinfo" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "simulator-google-user", + "name": "OpenPost Simulator", + "email": "simulator@example.org", + "picture": "" + } + } + }, + { + "name": "youtube-channels", + "request": { + "method": "GET", + "urlPath": "/youtube/v3/channels" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "items": [ + { + "id": "UCsimulator", + "snippet": { + "title": "OpenPost Simulator", + "customUrl": "@openpostsimulator", + "thumbnails": { + "default": { + "url": "" + } + } + }, + "statistics": { + "subscriberCount": "0", + "videoCount": "0", + "viewCount": "0" + } + } + ] + } + } + }, + { + "name": "youtube-playlists", + "request": { + "method": "GET", + "urlPath": "/youtube/v3/playlists" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "items": [ + { + "id": "PLsimulator", + "snippet": { + "title": "OpenPost Simulator Playlist" + } + } + ] + } + } + }, + { + "name": "youtube-video-categories", + "request": { + "method": "GET", + "urlPath": "/youtube/v3/videoCategories" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "items": [ + { + "id": "22", + "snippet": { + "assignable": true, + "title": "People & Blogs" + } + } + ] + } + } + }, + { + "name": "youtube-upload-session", + "request": { + "method": "POST", + "urlPath": "/upload/youtube/v3/videos", + "queryParameters": { + "uploadType": { + "equalTo": "resumable" + } + } + }, + "response": { + "status": 200, + "headers": { + "Location": "{{request.baseUrl}}/upload/youtube/v3/videos?uploadType=resumable&upload_id=simulator-upload" + }, + "transformers": [ + "response-template" + ] + } + }, + { + "name": "youtube-upload", + "request": { + "method": "PUT", + "urlPath": "/upload/youtube/v3/videos", + "queryParameters": { + "upload_id": { + "equalTo": "simulator-upload" + } + } + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "simulatorvid", + "status": { + "uploadStatus": "uploaded", + "privacyStatus": "private" + } + } + } + }, + { + "name": "youtube-videos", + "request": { + "method": "GET", + "urlPath": "/youtube/v3/videos" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "items": [ + { + "id": "simulatorvid", + "status": { + "uploadStatus": "processed", + "privacyStatus": "private" + }, + "processingDetails": { + "processingStatus": "succeeded" + } + } + ] + } + } + }, + { + "name": "tiktok-token", + "request": { + "method": "POST", + "urlPath": "/v2/oauth/token/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "access_token": "simulator-tiktok-token", + "refresh_token": "simulator-tiktok-refresh", + "expires_in": 86400, + "refresh_expires_in": 31536000, + "token_type": "Bearer", + "scope": "user.info.basic,user.info.profile,user.info.stats,video.list,video.publish,video.upload", + "open_id": "simulator-tiktok-open-id" + } + } + }, + { + "name": "tiktok-user-info", + "request": { + "method": "GET", + "urlPath": "/v2/user/info/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "user": { + "open_id": "simulator-tiktok-open-id", + "union_id": "simulator-tiktok-union-id", + "display_name": "OpenPost Simulator", + "username": "openpost_simulator", + "avatar_url": "" + } + }, + "error": { + "code": "ok", + "message": "", + "log_id": "simulator" + } + } + } + }, + { + "name": "tiktok-creator-info", + "request": { + "method": "POST", + "urlPath": "/v2/post/publish/creator_info/query/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "creator_avatar_url": "", + "creator_username": "openpost_simulator", + "creator_nickname": "OpenPost Simulator", + "privacy_level_options": ["PUBLIC_TO_EVERYONE", "MUTUAL_FOLLOW_FRIENDS", "SELF_ONLY"], + "comment_disabled": false, + "duet_disabled": false, + "stitch_disabled": false, + "max_video_post_duration_sec": 600 + }, + "error": { + "code": "ok", + "message": "", + "log_id": "simulator" + } + } + } + }, + { + "name": "tiktok-video-init", + "request": { + "method": "POST", + "urlPath": "/v2/post/publish/video/init/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "publish_id": "v_pub_url~simulator-video" + }, + "error": { + "code": "ok", + "message": "", + "log_id": "simulator" + } + } + } + }, + { + "name": "tiktok-photo-init", + "request": { + "method": "POST", + "urlPath": "/v2/post/publish/content/init/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "publish_id": "p_pub_url~simulator-photo" + }, + "error": { + "code": "ok", + "message": "", + "log_id": "simulator" + } + } + } + }, + { + "name": "tiktok-publish-status", + "request": { + "method": "POST", + "urlPath": "/v2/post/publish/status/fetch/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "status": "PUBLISH_COMPLETE", + "publicaly_available_post_id": ["7300000000000000001"] + }, + "error": { + "code": "ok", + "message": "", + "log_id": "simulator" + } + } + } + }, + { + "name": "tiktok-video-list", + "request": { + "method": "ANY", + "urlPath": "/v2/video/list/" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "data": { + "videos": [], + "cursor": 0, + "has_more": false + }, + "error": { + "code": "ok", + "message": "", + "log_id": "simulator" + } + } + } + }, + { + "name": "unmatched", + "priority": 10, + "request": { + "method": "ANY", + "urlPattern": ".*" + }, + "response": { + "status": 404, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "error": "simulator has no mapping for this request" + } + } + } + ] +} diff --git a/roles/web-app-openpost/files/sql/breakglass/password.sql b/roles/web-app-openpost/files/sql/breakglass/password.sql new file mode 100644 index 0000000000..17bd2a6648 --- /dev/null +++ b/roles/web-app-openpost/files/sql/breakglass/password.sql @@ -0,0 +1,4 @@ +UPDATE users + SET password_hash = %(password_hash)s + WHERE lower(email) = lower(%(email)s) + AND password_hash IS DISTINCT FROM %(password_hash)s; diff --git a/roles/web-app-openpost/files/sql/crossposter/create/cursors.sql b/roles/web-app-openpost/files/sql/crossposter/create/cursors.sql new file mode 100644 index 0000000000..00b81bd2aa --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/create/cursors.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS crossposter.cursors ( + route text PRIMARY KEY, + cursor text NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now() +); diff --git a/roles/web-app-openpost/files/sql/crossposter/create/items.sql b/roles/web-app-openpost/files/sql/crossposter/create/items.sql new file mode 100644 index 0000000000..c3eb712b3d --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/create/items.sql @@ -0,0 +1,19 @@ +CREATE TABLE IF NOT EXISTS crossposter.items ( + id bigserial PRIMARY KEY, + route text NOT NULL, + source_uri text NOT NULL, + source_url text NOT NULL, + target text NOT NULL, + network text NOT NULL, + state text NOT NULL, + payload jsonb NOT NULL, + publication_id text NOT NULL DEFAULT '', + attempts integer NOT NULL DEFAULT 0, + resends integer NOT NULL DEFAULT 0, + next_attempt_at timestamptz NOT NULL DEFAULT now(), + last_error text NOT NULL DEFAULT '', + notified_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (source_uri, target) +); diff --git a/roles/web-app-openpost/files/sql/crossposter/create/schema.sql b/roles/web-app-openpost/files/sql/crossposter/create/schema.sql new file mode 100644 index 0000000000..bd46255a40 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/create/schema.sql @@ -0,0 +1 @@ +CREATE SCHEMA IF NOT EXISTS crossposter; diff --git a/roles/web-app-openpost/files/sql/crossposter/insert_item.sql b/roles/web-app-openpost/files/sql/crossposter/insert_item.sql new file mode 100644 index 0000000000..a3741460bf --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/insert_item.sql @@ -0,0 +1,13 @@ +INSERT INTO crossposter.items ( + route, source_uri, source_url, target, network, state, payload +) +VALUES ( + %(route)s, + %(source_uri)s, + %(source_url)s, + %(target)s, + %(network)s, + 'pending', + %(payload)s +) +ON CONFLICT (source_uri, target) DO NOTHING; diff --git a/roles/web-app-openpost/files/sql/crossposter/mark_notified.sql b/roles/web-app-openpost/files/sql/crossposter/mark_notified.sql new file mode 100644 index 0000000000..46ff6fcb2b --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/mark_notified.sql @@ -0,0 +1,3 @@ +UPDATE crossposter.items +SET notified_at = now() +WHERE id = %(id)s; diff --git a/roles/web-app-openpost/files/sql/crossposter/resend_item.sql b/roles/web-app-openpost/files/sql/crossposter/resend_item.sql new file mode 100644 index 0000000000..20a393ba0a --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/resend_item.sql @@ -0,0 +1,10 @@ +UPDATE crossposter.items +SET + state = 'pending', + resends = resends + 1, + publication_id = '', + attempts = %(attempts)s, + last_error = %(error)s, + next_attempt_at = %(next_attempt_at)s, + updated_at = now() +WHERE id = %(id)s; diff --git a/roles/web-app-openpost/files/sql/crossposter/select/cursor.sql b/roles/web-app-openpost/files/sql/crossposter/select/cursor.sql new file mode 100644 index 0000000000..6206d98560 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/select/cursor.sql @@ -0,0 +1,3 @@ +SELECT cursor +FROM crossposter.cursors +WHERE route = %(route)s; diff --git a/roles/web-app-openpost/files/sql/crossposter/select/due.sql b/roles/web-app-openpost/files/sql/crossposter/select/due.sql new file mode 100644 index 0000000000..1549a29ff7 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/select/due.sql @@ -0,0 +1,4 @@ +SELECT * +FROM crossposter.items +WHERE state = 'pending' AND next_attempt_at <= now() +ORDER BY id; diff --git a/roles/web-app-openpost/files/sql/crossposter/select/items.sql b/roles/web-app-openpost/files/sql/crossposter/select/items.sql new file mode 100644 index 0000000000..726c055040 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/select/items.sql @@ -0,0 +1,3 @@ +SELECT * +FROM crossposter.items +ORDER BY id; diff --git a/roles/web-app-openpost/files/sql/crossposter/select/open_publications.sql b/roles/web-app-openpost/files/sql/crossposter/select/open_publications.sql new file mode 100644 index 0000000000..948b9289c6 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/select/open_publications.sql @@ -0,0 +1,4 @@ +SELECT * +FROM crossposter.items +WHERE state IN ('drafted', 'submitted') +ORDER BY id; diff --git a/roles/web-app-openpost/files/sql/crossposter/select/unnotified.sql b/roles/web-app-openpost/files/sql/crossposter/select/unnotified.sql new file mode 100644 index 0000000000..eb71516f81 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/select/unnotified.sql @@ -0,0 +1,4 @@ +SELECT * +FROM crossposter.items +WHERE state IN ('failed', 'dead_lettered') AND notified_at IS NULL +ORDER BY id; diff --git a/roles/web-app-openpost/files/sql/crossposter/try_lock.sql b/roles/web-app-openpost/files/sql/crossposter/try_lock.sql new file mode 100644 index 0000000000..40808b4b02 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/try_lock.sql @@ -0,0 +1 @@ +SELECT pg_try_advisory_lock(%(lock_id)s) AS held; diff --git a/roles/web-app-openpost/files/sql/crossposter/update_item.sql b/roles/web-app-openpost/files/sql/crossposter/update_item.sql new file mode 100644 index 0000000000..8854556274 --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/update_item.sql @@ -0,0 +1,9 @@ +UPDATE crossposter.items +SET + state = %(state)s, + publication_id = %(publication_id)s, + attempts = %(attempts)s, + last_error = %(error)s, + next_attempt_at = %(next_attempt_at)s, + updated_at = now() +WHERE id = %(id)s; diff --git a/roles/web-app-openpost/files/sql/crossposter/upsert_cursor.sql b/roles/web-app-openpost/files/sql/crossposter/upsert_cursor.sql new file mode 100644 index 0000000000..9df04f535f --- /dev/null +++ b/roles/web-app-openpost/files/sql/crossposter/upsert_cursor.sql @@ -0,0 +1,4 @@ +INSERT INTO crossposter.cursors (route, cursor) +VALUES (%(route)s, %(cursor)s) +ON CONFLICT (route) DO UPDATE + SET cursor = excluded.cursor, updated_at = now(); diff --git a/roles/web-app-openpost/files/test/.nocheck b/roles/web-app-openpost/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-openpost/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-openpost/files/test/openpost/__init__.py b/roles/web-app-openpost/files/test/openpost/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/roles/web-app-openpost/files/test/openpost/api.py b/roles/web-app-openpost/files/test/openpost/api.py new file mode 100644 index 0000000000..c90167f8c2 --- /dev/null +++ b/roles/web-app-openpost/files/test/openpost/api.py @@ -0,0 +1,402 @@ +"""Env (rendered into test.env from templates/test.env.j2): +OPENPOST_LOCAL_URL published OpenPost origin on the stack host +OPENPOST_API_HEADERS_B64 base64 JSON of the Host and proto headers the proxy would send +OPENPOST_ADMIN_EMAIL break-glass instance admin e-mail +OPENPOST_ADMIN_PASSWORD_B64 base64 break-glass password +OPENPOST_RELAY_TARGETS JSON map of sibling platform to the domain the relay carries +OPENPOST_DEADLINE_SECONDS readiness budget, below the harness timeout +OPENPOST_PUBLIC_URL public origin served by the shared proxy +OPENPOST_SSO_ENABLED true when Keycloak provisions users, so the proxy closes password sign-up +OPENPOST_CONTAINER resolved OpenPost container, used to reach the simulator admin API +OPENPOST_SIMULATOR_PLATFORMS JSON list of OpenPost platforms served by the provider simulator, empty without it +OPENPOST_SIMULATOR_HOST one simulator alias, whose /__admin API holds the request journal +OPENPOST_PROVIDER_URL published plain-HTTP origin of the fake provider that plays LinkedIn, empty without it +OPENPOST_UNCONFIGURED_PLATFORMS JSON list of commercial platforms without credentials, which must not connect +OPENPOST_S3_PUBLIC_URL public bucket URL with a trailing slash, empty when media stays in the role volume +OPENPOST_DB_CONTAINER Postgres container on the probe's node, empty when swarm placed it elsewhere +OPENPOST_DB_NAME OpenPost database name +OPENPOST_DB_USER OpenPost database user +OPENPOST_DB_PASSWORD_B64 base64 OpenPost database password +OPENPOST_MAIL_RECIPIENT platform mailbox that receives a probe invitation, empty without mail +OPENPOST_SMTP_ENABLED true when OpenPost itself is given an SMTP relay it can use +OPENPOST_SSO_ADMIN_EMAIL platform administrator the Playwright run provisions through SSO before the backup drill, empty without SSO +OPENPOST_PEERTUBE_USERNAME local PeerTube account OpenPost connects through its password login +OPENPOST_PEERTUBE_PASSWORD_B64 base64 password of that PeerTube account +OPENPOST_MEMBER_MAILBOX administrator mailbox whose per-run plus-address the probe's workspace member registers with +OPENPOST_PROXY_ADDRESS stack host address that serves every public vhost, empty when the probe runs on that host's network +""" + +from __future__ import annotations + +import base64 +import http.client +import ipaddress +import json +import os +import secrets +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +def public_url(url: str) -> str: + parts = urllib.parse.urlsplit(url) + if (parts.hostname or "").endswith(".onion") and parts.scheme == "https": + return urllib.parse.urlunsplit(("http", *parts[1:])) + return url + + +BASE = os.environ["OPENPOST_LOCAL_URL"].rstrip("/") + "/api/v1" +HEADERS = json.loads(base64.b64decode(os.environ["OPENPOST_API_HEADERS_B64"])) +ADMIN_EMAIL = os.environ["OPENPOST_ADMIN_EMAIL"] +ADMIN_PASSWORD = base64.b64decode(os.environ["OPENPOST_ADMIN_PASSWORD_B64"]).decode() +RELAY_TARGETS = json.loads(os.environ["OPENPOST_RELAY_TARGETS"]) +DEADLINE = time.monotonic() + int(os.environ["OPENPOST_DEADLINE_SECONDS"]) +PUBLIC_URL = os.environ["OPENPOST_PUBLIC_URL"].rstrip("/") +ONION_ORIGIN = (urllib.parse.urlparse(PUBLIC_URL).hostname or "").endswith(".onion") +SSO_ENABLED = os.environ["OPENPOST_SSO_ENABLED"] == "true" +CONTAINER = os.environ["OPENPOST_CONTAINER"] +SIMULATOR_PLATFORMS = json.loads(os.environ["OPENPOST_SIMULATOR_PLATFORMS"]) +UNCONFIGURED_PLATFORMS = json.loads(os.environ["OPENPOST_UNCONFIGURED_PLATFORMS"]) +S3_PUBLIC_URL = os.environ["OPENPOST_S3_PUBLIC_URL"] +SIMULATOR_ADMIN = "https://" + os.environ["OPENPOST_SIMULATOR_HOST"] + "/__admin" +PROVIDER_URL = os.environ["OPENPOST_PROVIDER_URL"].rstrip("/") +DB_CONTAINER = os.environ["OPENPOST_DB_CONTAINER"] +DB_NAME = os.environ["OPENPOST_DB_NAME"] +DB_USER = os.environ["OPENPOST_DB_USER"] +DB_PASSWORD = base64.b64decode(os.environ["OPENPOST_DB_PASSWORD_B64"]).decode() +MAIL_RECIPIENT = os.environ["OPENPOST_MAIL_RECIPIENT"] +SMTP_ENABLED = os.environ["OPENPOST_SMTP_ENABLED"] == "true" +SSO_ADMIN_EMAIL = os.environ["OPENPOST_SSO_ADMIN_EMAIL"] +PEERTUBE_USERNAME = os.environ["OPENPOST_PEERTUBE_USERNAME"] +PEERTUBE_PASSWORD = base64.b64decode( + os.environ["OPENPOST_PEERTUBE_PASSWORD_B64"] +).decode() +MEMBER_MAILBOX = os.environ["OPENPOST_MEMBER_MAILBOX"] +PROXY_ADDRESS = os.environ["OPENPOST_PROXY_ADDRESS"] + +SETTLE_SECONDS = 300 +PROFILES = {"text": "short_text", "image": "image_post", "video": "video"} +ANALYSED = ("ready", "failed") + +failures: list[str] = [] + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args: object, **kwargs: object) -> None: + return None + + +def dial(host: str) -> str: + try: + ipaddress.ip_address(host) + except ValueError: + return PROXY_ADDRESS + return host + + +class _ProxyConnection(http.client.HTTPConnection): + def connect(self) -> None: + self.sock = socket.create_connection((dial(self.host), self.port), self.timeout) + + +class _ProxyTlsConnection(http.client.HTTPSConnection): + def connect(self) -> None: + raw = socket.create_connection((dial(self.host), self.port), self.timeout) + self.sock = self._context.wrap_socket(raw, server_hostname=self.host) + + +class _ProxyHandler(urllib.request.HTTPHandler): + def http_open(self, req: urllib.request.Request) -> http.client.HTTPResponse: + return self.do_open(_ProxyConnection, req) + + +class _ProxyTlsHandler(urllib.request.HTTPSHandler): + def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse: + return self.do_open(_ProxyTlsConnection, req, context=self._context) + + +PROXY_HANDLERS = [_ProxyHandler(), _ProxyTlsHandler()] if PROXY_ADDRESS else [] +OPENER = urllib.request.build_opener(_NoRedirect, *PROXY_HANDLERS) +urllib.request.install_opener(urllib.request.build_opener(*PROXY_HANDLERS)) + + +def call( + method: str, path: str, body: object = None, token: str = "" +) -> tuple[int, object]: + status, _, payload = call_raw(method, path, body, token) + return status, payload + + +def call_raw( + method: str, path: str, body: object = None, token: str = "" +) -> tuple[int, str, object]: + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(BASE + path, data=data, method=method) # noqa: S310 fixed OpenPost origin + for name, value in HEADERS.items(): + request.add_header(name, value) + request.add_header("Content-Type", "application/json") + if token: + request.add_header("Authorization", "Bearer " + token) + return _open(request) + + +def provider( + path: str, fields: dict[str, str] | None = None +) -> tuple[int, str, object]: + data = urllib.parse.urlencode(fields).encode() if fields is not None else None + request = urllib.request.Request(PROVIDER_URL + path, data=data) # noqa: S310 fixed fake provider origin + return _open(request) + + +def _open(request: urllib.request.Request) -> tuple[int, str, object]: + try: + with OPENER.open(request, timeout=60) as response: + raw = response.read().decode() + status = response.status + location = response.headers.get("Location") or "" + except urllib.error.HTTPError as error: + raw = error.read().decode() + status = error.code + location = error.headers.get("Location") or "" + try: + return status, location, json.loads(raw) if raw else None + except ValueError: + return status, location, raw + + +def in_container( + container: str, *argv: str, env: dict[str, str] | None = None, user: str = "" +) -> bytes: + flags = [ + item + for name, value in (env or {}).items() + for item in ("-e", f"{name}={value}") + ] + flags += ["-u", user] if user else [] + result = subprocess.run( + ["container", "exec", *flags, container, *argv], + capture_output=True, + timeout=300, + check=False, + ) + if result.returncode != 0: + sys.exit( + f"[FAIL] {argv[0]} in {container} exited {result.returncode}: {result.stderr.decode()[-400:]}" + ) + return result.stdout + + +def check(label: str, ok: bool, detail: object = "") -> None: + print( + ("[OK] " if ok else "[FAIL] ") + + label + + (f": {detail}" if not ok and detail else "") + ) + if not ok: + failures.append(label) + + +def anonymous_jpeg(url: str) -> bool: + try: + with urllib.request.urlopen(url, timeout=60) as response: # noqa: S310 https media URL issued by OpenPost + return response.status == 200 and response.read(2) == b"\xff\xd8" + except (urllib.error.URLError, OSError): + return False + + +def accounts(token: str, workspace: str) -> dict[str, list[str]]: + status, body = call("GET", f"/accounts?workspace_id={workspace}", token=token) + if status != 200 or not isinstance(body, list): + sys.exit(f"[FAIL] cannot list connected accounts: HTTP {status}") + found: dict[str, list[str]] = {} + for item in sorted(body, key=lambda item: str(item.get("created_at"))): + found.setdefault(str(item["platform"]), []).append(str(item["id"])) + return found + + +def render_media(kind: str) -> tuple[str, str, bytes]: + nonce = secrets.token_hex(3) + colour = f"color=c=0x{nonce}" + if kind == "image": + name, mime = f"openpost-cli-{nonce}.jpg", "image/jpeg" + source = ["-f", "lavfi", "-i", f"{colour}:s=1080x1080", "-frames:v", "1"] + else: + name, mime = f"openpost-cli-{nonce}.mp4", "video/mp4" + source = [ + "-f", + "lavfi", + "-i", + f"{colour}:s=720x1280:d=3", + "-f", + "lavfi", + "-i", + "anullsrc=r=44100:cl=stereo", + "-t", + "3", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-shortest", + ] + target = f"/tmp/{name}" # noqa: S108 path inside the OpenPost container + in_container(CONTAINER, "ffmpeg", "-loglevel", "error", "-y", *source, target) + content = in_container(CONTAINER, "cat", target) + in_container(CONTAINER, "rm", "-f", target) + return name, mime, content + + +def media_state(token: str, workspace: str, media: str) -> str: + status, body = call( + "GET", f"/media?workspace_id={workspace}&limit=200", token=token + ) + items = body.get("media") if status == 200 and isinstance(body, dict) else None + for item in items or []: + if item.get("id") == media: + return str(item.get("analysis_status")) + return f"HTTP {status}" + + +def upload(token: str, workspace: str, kind: str) -> tuple[str, str]: + name, mime, content = render_media(kind) + status, session = call( + "POST", + "/media/upload-session", + { + "workspace_id": workspace, + "filename": name, + "mime_type": mime, + "size": len(content), + }, + token, + ) + if status != 200 or not isinstance(session, dict): + sys.exit(f"[FAIL] upload session for {name} returned HTTP {status}: {session}") + target = session["upload"] + url = urllib.parse.urlparse(str(target["url"])) + headers = dict(target["headers"] or {}) + if url.netloc in ("", urllib.parse.urlparse(PUBLIC_URL).netloc): + headers.update({**HEADERS, "Authorization": "Bearer " + token}) + url = urllib.parse.urlparse( + BASE.rsplit("/api/v1", 1)[0] + + url.path + + (f"?{url.query}" if url.query else "") + ) + request = urllib.request.Request( # noqa: S310 upload URL issued by OpenPost + url.geturl(), data=content, method=str(target["method"]) + ) + for header, value in headers.items(): + request.add_header(header, value if isinstance(value, str) else value[0]) + with urllib.request.urlopen(request, timeout=120) as response: # noqa: S310 upload URL issued by OpenPost + if response.status not in (200, 201, 204): + sys.exit(f"[FAIL] media PUT returned HTTP {response.status}") + complete = urllib.parse.urlparse(str(session["complete_url"])).path.split( + "/api/v1", 1 + )[1] + status, body = call("POST", complete, {"workspace_id": workspace}, token) + if status != 200: + sys.exit( + f"[FAIL] completing the upload of {name} returned HTTP {status}: {body}" + ) + media = str(session["media_id"]) + while ( + kind == "video" + and media_state(token, workspace, media) not in ANALYSED + and time.monotonic() < DEADLINE + ): + time.sleep(3) + return media, str(target["object_key"]) + + +def draft( + token: str, + workspace: str, + targets: list[str], + text: str, + kind: str, + media: str, + settings: dict, + at: str, +) -> dict: + payload: dict[str, object] = { + "workspace_id": workspace, + "title": text, + "content_profile": PROFILES[kind], + "source_text": text, + "social_account_ids": targets, + "renditions": [ + {"social_account_id": account, "settings": settings} for account in targets + ], + } + if media: + payload["media"] = [{"media_id": media}] + if at: + payload["scheduled_at"] = at + status, body = call("POST", "/publications", payload, token) + if status != 200 or not isinstance(body, dict): + sys.exit(f"[FAIL] creating publication {text!r} returned HTTP {status}: {body}") + return body + + +def release(token: str, publication: dict, action: str) -> tuple[int, object]: + return call( + "POST", + f"/publications/{publication['id']}/{action}", + {"expected_revision": publication["revision"]}, + token, + ) + + +def renditions(token: str, publication: str) -> list[dict]: + status, body = call("GET", f"/publications/{publication}", token=token) + found = body.get("renditions") if status == 200 and isinstance(body, dict) else None + return list(found or []) + + +def settled(rendition: dict) -> bool: + return rendition.get("status") == "published" or ( + rendition.get("status") == "failed" and not rendition.get("error_retryable") + ) + + +def settle(token: str, publications: dict[str, str]) -> dict[str, list[dict]]: + outcome: dict[str, list[dict]] = {} + budget = min(DEADLINE, time.monotonic() + SETTLE_SECONDS) + while len(outcome) < len(publications) and time.monotonic() < budget: + for label, publication in publications.items(): + if label in outcome: + continue + current = renditions(token, publication) + if current and all(settled(rendition) for rendition in current): + outcome[label] = current + if len(outcome) < len(publications): + time.sleep(5) + return outcome + + +def team(token: str, workspace: str) -> dict: + status, body = call("GET", f"/workspaces/{workspace}/team", token=token) + if status != 200 or not isinstance(body, dict): + sys.exit(f"[FAIL] cannot read the workspace team: HTTP {status}") + return body + + +def revoke_invitations(token: str, workspace: str, email: str) -> None: + for invitation in team(token, workspace).get("invitations") or []: + if invitation["email"] == email and invitation["status"] not in ( + "accepted", + "revoked", + "expired", + ): + call( + "DELETE", + f"/workspaces/{workspace}/invitations/{invitation['id']}", + token=token, + ) diff --git a/roles/web-app-openpost/files/test/openpost/crossposter.py b/roles/web-app-openpost/files/test/openpost/crossposter.py new file mode 100644 index 0000000000..f9f1d8918e --- /dev/null +++ b/roles/web-app-openpost/files/test/openpost/crossposter.py @@ -0,0 +1,484 @@ +"""Env (rendered into test.env from templates/test.env.j2): +OPENPOST_CROSSPOSTER_ROUTES_B64 base64 JSON list of the deployed routes without their tokens, empty list when the crossposter is off +OPENPOST_CROSSPOSTER_SECRETS_FILE host path of the rendered crossposter secrets, which carry the CI source tokens +OPENPOST_CROSSPOSTER_CONTAINER crossposter container on the probe's node, empty when swarm placed it elsewhere +OPENPOST_CROSSPOSTER_CONFIG configuration path inside the crossposter container +OPENPOST_CROSSPOSTER_POLL_SECONDS poll interval of the deployed crossposter +OPENPOST_CROSSPOSTER_RETRY_SECONDS upper bound of the deployed retry budget, from max_attempts and cap_seconds +""" + +from __future__ import annotations + +import base64 +import json +import os +import secrets +import subprocess +import time +import urllib.parse +from pathlib import Path + +from openpost.api import DEADLINE, accounts, call, check, render_media +from openpost.journal import hits, statuses +from openpost.simulator import SCENARIOS, simulator_admin +from openpost.sources import ( + mastodon_post, + mastodon_statuses, + peertube_upload, + pixelfed_post, +) + +ROUTES = json.loads(base64.b64decode(os.environ["OPENPOST_CROSSPOSTER_ROUTES_B64"])) +SECRETS_FILE = os.environ["OPENPOST_CROSSPOSTER_SECRETS_FILE"] +CROSSPOSTER = os.environ["OPENPOST_CROSSPOSTER_CONTAINER"] +CONFIG = os.environ["OPENPOST_CROSSPOSTER_CONFIG"] +POLL_SECONDS = int(os.environ["OPENPOST_CROSSPOSTER_POLL_SECONDS"]) +RETRY_SECONDS = int(os.environ["OPENPOST_CROSSPOSTER_RETRY_SECONDS"]) +QUIET_POLLS = 3 +MEMBERS = { + ("mastodon", "review"): ("x",), + ("mastodon", "auto"): ("mastodon", "x", "facebook", "instagram"), + ("pixelfed", "auto"): ("instagram", "x"), + ("peertube", "auto"): ("youtube",), +} +SETTINGS = {label: settings for label, _, _, _, settings in SCENARIOS if settings} +FORMATS = {"youtube": "youtube.video", "tiktok": "tiktok.photo"} +SQL = ( + "import json, sys, psycopg\n" + "from crossposter import config\n" + "dsn = config.load(sys.argv[1]).dsn\n" + "with psycopg.connect(dsn, autocommit=True) as connection:\n" + " cursor = connection.execute(sys.argv[2], json.loads(sys.argv[3]))\n" + " rows = cursor.fetchall() if cursor.description else []\n" + "print(json.dumps([list(map(str, row)) for row in rows]))\n" +) +HELD = ( + "import sys, time, psycopg\n" + "from crossposter import config\n" + "with psycopg.connect(config.load(sys.argv[1]).dsn) as connection:\n" + " connection.execute('LOCK TABLE crossposter.cursors IN ACCESS EXCLUSIVE MODE')\n" + " connection.execute('DELETE FROM crossposter.cursors WHERE route = %s', (sys.argv[2],))\n" + " print('held', flush=True)\n" + " time.sleep(float(sys.argv[3]))\n" +) + + +def crossposter(*argv: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["container", "exec", CROSSPOSTER, *argv], + capture_output=True, + timeout=300, + check=False, + ) + + +def sql(statement: str, *parameters: str) -> list[list[str]]: + result = crossposter( + "python", "-c", SQL, CONFIG, statement, json.dumps(list(parameters)) + ) + if result.returncode != 0: + check(f"SQL {statement[:40]}", False, result.stderr.decode()[-400:]) + return [] + return json.loads(result.stdout.decode()) + + +def items(source_url: str) -> list[list[str]]: + return sql( + "SELECT network, state, resends, publication_id, last_error" + " FROM crossposter.items WHERE source_url = %s ORDER BY id", + source_url, + ) + + +def reported(source_url: str) -> bool: + rows = sql( + "SELECT notified_at IS NOT NULL FROM crossposter.items" + " WHERE source_url = %s AND state IN ('failed', 'dead_lettered')", + source_url, + ) + return bool(rows) and all(row == ["True"] for row in rows) + + +def publications(token: str, workspace: str, nonce: str) -> list[dict]: + query = urllib.parse.urlencode( + {"workspace_id": workspace, "search": nonce, "limit": 50} + ) + status, body = call("GET", f"/publications?{query}", token=token) + return body if status == 200 and isinstance(body, list) else [] + + +def wait(probe, ready, budget: float) -> object: + end = min(DEADLINE, time.monotonic() + budget) + current = probe() + while not ready(current) and time.monotonic() < end: + time.sleep(5) + current = probe() + return current + + +def delivered(publication: dict) -> bool: + found = publication.get("renditions") or [] + return bool(found) and all(item.get("status") == "published" for item in found) + + +def social_sets(token: str, workspace: str) -> dict[str, dict]: + status, body = call("GET", f"/social-sets?workspace_id={workspace}", token=token) + found = body if status == 200 and isinstance(body, list) else [] + return {str(item["name"]): item for item in found} + + +def fill_sets(token: str, workspace: str) -> None: + connected = accounts(token, workspace) + existing = social_sets(token, workspace) + for route in ROUTES: + chosen = existing.get(route["social_set"]) + if chosen is None: + check(f"route {route['name']}: social set exists", False, route) + continue + members = [ + { + "social_account_id": connected[platform][0], + "default_settings": SETTINGS.get(platform, {}), + **( + {"default_output_profile": FORMATS[platform]} + if platform in SETTINGS + else {} + ), + } + for platform in MEMBERS[(route["platform"], route["mode"])] + if connected.get(platform) + ] + status, body = call( + "PUT", + f"/social-sets/{chosen['id']}", + { + "name": chosen["name"], + "is_default": bool(chosen.get("is_default")), + "accounts": members, + }, + token, + ) + check( + f"route {route['name']}: its social set takes {len(members)} target(s)", + status == 200 and bool(members), + f"HTTP {status} {body}", + ) + + +def check_instance() -> None: + result = crossposter("python", "-m", "crossposter", "health", "--config", CONFIG) + check( + "the crossposter reports itself healthy", result.returncode == 0, result.stderr + ) + second = crossposter( + "timeout", + str(POLL_SECONDS + 10), + "python", + "-m", + "crossposter", + "run", + "--config", + CONFIG, + ) + log = second.stderr.decode() + check( + "a second crossposter instance stands by while the first holds the lock", + "standing by" in log and "lock acquired" not in log, + log[-400:], + ) + + +def check_listing(states: set[str]) -> None: + result = crossposter("python", "-m", "crossposter", "list", "--config", CONFIG) + table = result.stdout.decode() + check( + "the list command shows every crossposted state seen in this run", + result.returncode == 0 and all(f"\t{state}\t" in table for state in states), + table[-600:], + ) + + +def mastodon_scenarios( + token: str, workspace: str, route: dict, source: str +) -> set[str]: + base, tag, seen = route["base_url"], route["tags"][0], set() + if route["mode"] == "review": + nonce = f"cp-{secrets.token_hex(4)}" + status = mastodon_post(base, source, f"Review {nonce} #{tag}", None, "") + check("a reviewed Mastodon status is posted", "error" not in status, status) + found = wait( + lambda: publications(token, workspace, nonce), + bool, + POLL_SECONDS * 4, + ) + check( + "a review route leaves an unscheduled OpenPost draft", + len(found) == 1 and found[0].get("status") == "draft", + found, + ) + seen.add("drafted") + return seen + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 1)) + simulator_admin("/scenarios/reset", post=True) + nonce = f"cp-{secrets.token_hex(4)}" + name, mime, image = render_media("image") + status = mastodon_post( + base, source, f"Auto {nonce} [simulate-503] #{tag}", (name, mime, image), "" + ) + check("an automatic Mastodon status is posted", "error" not in status, status) + targets = len(MEMBERS[("mastodon", "auto")]) + found = wait( + lambda: publications(token, workspace, nonce), + lambda found: sum(map(delivered, found)) >= targets, + POLL_SECONDS * 6 + 300, + ) + check( + "an auto route delivers the status to every target of its social set", + sum(map(delivered, found)) == targets, + [(item.get("status"), item.get("renditions")) for item in found], + ) + journal = simulator_admin( + "/requests?since=" + urllib.parse.quote(since), post=False + ) + entries = journal["requests"] if isinstance(journal, dict) else [] + tweets = hits(entries, "POST", "/2/tweets", nonce) + check( + "X answers 503 once and receives the resent post exactly once", + statuses(tweets) == [503, 201], + statuses(tweets), + ) + check( + "the X text carries no source link", + bool(tweets) + and status.get("url", "-") not in str(tweets[-1]["request"]["body"]), + ) + check( + "Facebook and Instagram receive the post", + bool(hits(entries, "POST", r"/v[0-9.]+/(424242|525252)/(feed|photos)", nonce)) + and bool(hits(entries, "POST", r"/v[0-9.]+/17841400000000000/media", nonce)), + ) + copies = [ + item + for item in mastodon_statuses(base, source, route["account"]) + if nonce in str(item.get("content")) + and (item.get("application") or {}).get("name") == "OpenPost" + ] + check( + "OpenPost delivers one copy to the local Mastodon target", + len(copies) == 1, + copies, + ) + seen.add("published") + optout = f"cp-{secrets.token_hex(4)}" + mastodon_post(base, source, f"Kept {optout} #{tag} #nocrosspost", None, "") + warned = f"cp-{secrets.token_hex(4)}" + mastodon_post(base, source, f"Spoiler {warned} #{tag}", None, "spoiler") + drafts = wait( + lambda: publications(token, workspace, warned), + bool, + POLL_SECONDS * 4, + ) + check( + "a status with a content warning stays a draft even on an auto route", + bool(drafts) and all(item.get("status") == "draft" for item in drafts), + drafts, + ) + time.sleep(POLL_SECONDS * QUIET_POLLS) + check( + "a status carrying the opt-out hashtag is never forwarded", + not publications(token, workspace, optout), + ) + check( + "the copy OpenPost published on Mastodon is not forwarded again", + len(publications(token, workspace, nonce)) == len(found), + len(publications(token, workspace, nonce)), + ) + seen.add("drafted") + if CROSSPOSTER: + replayed = {"nonce": nonce, "before": str(int(status["id"]) - 1)} + check_replay(token, workspace, route, source, replayed, len(found)) + return seen | check_failures(token, workspace, route, source) + + +def check_failures(token: str, workspace: str, route: dict, source: str) -> set[str]: + if not CROSSPOSTER: + print("[SKIP] crossposter failure reports: its task runs on another swarm node") + return set() + base, tag = route["base_url"], route["tags"][0] + rejected = mastodon_post( + base, + source, + f"Rejected cp-{secrets.token_hex(4)} [simulate-400] #{tag}", + None, + "", + ) + exhausted = mastodon_post( + base, + source, + f"Exhausted cp-{secrets.token_hex(4)} [simulate-503-always] #{tag}", + None, + "", + ) + urls = [str(rejected.get("url")), str(exhausted.get("url"))] + found = wait( + lambda: [url for url in urls if reported(url)], + lambda found: len(found) == len(urls), + POLL_SECONDS * 6 + RETRY_SECONDS, + ) + check( + "the mail server accepts the reports of a provider rejection and an exhausted retry budget for the administrator", + len(found) == len(urls), + {url: items(url) for url in urls}, + ) + states = { + state for url in urls for _, state, *_ in items(url) if state != "published" + } + check( + "the rejection ends failed and the outage ends dead-lettered", + states == {"failed", "dead_lettered"}, + states, + ) + return {"failed", "dead_lettered"} + + +def check_replay( + token: str, + workspace: str, + route: dict, + source: str, + replayed: dict[str, str], + expected: int, +) -> None: + nonce = replayed["nonce"] + sql( + "UPDATE crossposter.cursors SET cursor = %s WHERE route = %s", + replayed["before"], + route["name"], + ) + time.sleep(POLL_SECONDS * QUIET_POLLS) + check( + "replaying the source after a cursor reset creates no second publication", + len(publications(token, workspace, nonce)) == expected, + len(publications(token, workspace, nonce)), + ) + old = f"cp-{secrets.token_hex(4)}" + holder = subprocess.Popen( + [ + "container", + "exec", + CROSSPOSTER, + "python", + "-c", + HELD, + CONFIG, + route["name"], + "10", + ], + stdout=subprocess.PIPE, + ) + holder.stdout.readline() + mastodon_post(route["base_url"], source, f"Old {old} #{route['tags'][0]}", None, "") + holder.wait(timeout=60) + time.sleep(POLL_SECONDS * QUIET_POLLS) + check( + "re-activating a route forwards none of the posts that already exist", + not publications(token, workspace, old) + and bool( + sql( + "SELECT cursor FROM crossposter.cursors WHERE route = %s", route["name"] + ) + ), + ) + + +def pixelfed_scenarios( + token: str, workspace: str, route: dict, source: str +) -> set[str]: + nonce = f"cp-{secrets.token_hex(4)}" + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 1)) + name, mime, image = render_media("image") + status = pixelfed_post( + route["base_url"], + source, + f"Pixel {nonce} #{route['tags'][0]}", + (name, mime, image), + ) + check("a Pixelfed post is published", "error" not in status, status) + found = wait( + lambda: publications(token, workspace, nonce), + lambda found: len(found) >= 2 and all(map(delivered, found)), + POLL_SECONDS * 6 + 300, + ) + check( + "a Pixelfed post reaches Instagram and X", + len(found) >= 2 and all(map(delivered, found)), + [(item.get("status"), item.get("renditions")) for item in found], + ) + journal = simulator_admin( + "/requests?since=" + urllib.parse.quote(since), post=False + ) + entries = journal["requests"] if isinstance(journal, dict) else [] + check( + "Instagram receives a JPEG container for the Pixelfed image", + bool(hits(entries, "POST", r"/v[0-9.]+/17841400000000000/media", nonce)), + ) + return {"published"} + + +def peertube_scenarios( + token: str, workspace: str, route: dict, source: str +) -> set[str]: + nonce = f"cp-{secrets.token_hex(4)}" + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 1)) + name, mime, video = render_media("video") + uploaded = peertube_upload( + route["base_url"], + source, + route["account"], + f"Video {nonce}", + route["tags"][0], + (name, mime, video), + ) + check("a PeerTube video is uploaded", "error" not in uploaded, uploaded) + found = wait( + lambda: publications(token, workspace, nonce), + lambda found: bool(found) and all(map(delivered, found)), + POLL_SECONDS * 6 + 600, + ) + check( + "a PeerTube video reaches YouTube", + bool(found) and all(map(delivered, found)), + [(item.get("status"), item.get("renditions")) for item in found], + ) + journal = simulator_admin( + "/requests?since=" + urllib.parse.quote(since), post=False + ) + entries = journal["requests"] if isinstance(journal, dict) else [] + check( + "YouTube receives one upload of the PeerTube MP4", + len(hits(entries, "PUT", "/upload/youtube/v3/videos", "")) >= 1, + ) + return {"published"} + + +SCENARIO_RUNNERS = { + "mastodon": mastodon_scenarios, + "pixelfed": pixelfed_scenarios, + "peertube": peertube_scenarios, +} + + +def check_crossposter(token: str, workspace: str) -> None: + tokens = json.loads(Path(SECRETS_FILE).read_text())["routes"] + fill_sets(token, workspace) + if CROSSPOSTER: + check_instance() + else: + print("[SKIP] crossposter internals: its task runs on another swarm node") + seen: set[str] = set() + for route in sorted(ROUTES, key=lambda route: route["mode"] != "review"): + seen |= SCENARIO_RUNNERS[route["platform"]]( + token, workspace, route, tokens[route["name"]] + ) + if CROSSPOSTER: + check_listing(seen) diff --git a/roles/web-app-openpost/files/test/openpost/journal.py b/roles/web-app-openpost/files/test/openpost/journal.py new file mode 100644 index 0000000000..11258e9baa --- /dev/null +++ b/roles/web-app-openpost/files/test/openpost/journal.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import json +import re +import urllib.parse + +from openpost.api import anonymous_jpeg, check + +X_LIMIT = 280 +FACEBOOK_PAGES = ("424242", "525252") + + +def hits(journal: list[dict], method: str, path: str, tag: str) -> list[dict]: + found = [] + for entry in journal: + request = entry["request"] + text = urllib.parse.unquote_plus( + str(request.get("url")) + " " + str(request.get("body") or "") + ) + if ( + request["method"] == method + and re.fullmatch(path, str(request["url"]).split("?")[0]) + and tag in text + ): + found.append(entry) + return sorted(found, key=lambda entry: entry["request"]["loggedDate"]) + + +def statuses(entries: list[dict]) -> list[int]: + return [int(entry["responseDefinition"]["status"]) for entry in entries] + + +def form_value(entry: dict, key: str) -> str: + request = entry["request"] + fields = urllib.parse.parse_qs(urllib.parse.urlparse(str(request["url"])).query) + body = str(request.get("body") or "") + if body.startswith("{"): + value = json.loads(body).get(key) + return str(value) if value else "" + fields.update(urllib.parse.parse_qs(body)) + return fields.get(key, [""])[0] + + +def check_journal(journal: list[dict], label: str, tag: str) -> None: + if label in ("x", "scheduled", "member"): + posts = hits(journal, "POST", "/2/tweets", tag) + check( + f"X receives the {label} post exactly once", + statuses(posts) == [201], + statuses(posts), + ) + if label == "x": + text = ( + str(json.loads(posts[0]["request"]["body"]).get("text")) + if posts + else "" + ) + check( + f"the X post stays within {X_LIMIT} characters", + 0 < len(text) <= X_LIMIT, + len(text), + ) + elif label in ("x-429", "x-503"): + posts = statuses(hits(journal, "POST", "/2/tweets", tag)) + wanted = [int(label[2:]), 201] + check( + f"X answers {wanted[0]} once and then receives exactly one post", + posts == wanted, + posts, + ) + elif label == "x-400": + posts = statuses(hits(journal, "POST", "/2/tweets", tag)) + check( + "X rejects the post and its single retry, and nothing else is sent", + posts == [400, 400], + posts, + ) + elif label == "facebook": + for page in FACEBOOK_PAGES: + posts = statuses(hits(journal, "POST", rf"/v[0-9.]+/{page}/feed", tag)) + check( + f"Facebook Page {page} receives exactly one feed post", + posts == [200], + posts, + ) + elif label == "instagram": + containers = hits(journal, "POST", r"/v[0-9.]+/17841400000000000/media", tag) + published = hits( + journal, "POST", r"/v[0-9.]+/17841400000000000/media_publish", "" + ) + image = form_value(containers[0], "image_url") if containers else "" + check( + "Instagram receives one media container", + statuses(containers) == [200], + statuses(containers), + ) + check( + "Instagram receives a publish call after the container", + bool( + containers + and published + and published[-1]["request"]["loggedDate"] + >= containers[0]["request"]["loggedDate"] + ), + ) + check( + "the Instagram container carries a public JPEG URL", + image.startswith("https://") and anonymous_jpeg(image), + image, + ) + elif label == "youtube": + sessions = [ + entry + for entry in hits(journal, "POST", "/upload/youtube/v3/videos", tag) + if "uploadType=resumable" in entry["request"]["url"] + ] + uploads = hits( + journal, "PUT", "/upload/youtube/v3/videos", "upload_id=simulator-upload" + ) + check( + "YouTube receives one resumable upload session", + statuses(sessions) == [200], + statuses(sessions), + ) + check( + "YouTube receives the video on the resumable upload URL", + bool(uploads), + statuses(uploads), + ) + elif label == "tiktok": + inits = statuses(hits(journal, "POST", "/v2/post/publish/content/init/", tag)) + polls = hits(journal, "POST", "/v2/post/publish/status/fetch/", "") + check("TikTok receives exactly one photo post init", inits == [200], inits) + check("OpenPost polls the TikTok publish status", bool(polls)) diff --git a/roles/web-app-openpost/files/test/openpost/simulator.py b/roles/web-app-openpost/files/test/openpost/simulator.py new file mode 100644 index 0000000000..4032cf2b4b --- /dev/null +++ b/roles/web-app-openpost/files/test/openpost/simulator.py @@ -0,0 +1,430 @@ +from __future__ import annotations + +import json +import secrets +import sys +import time +import urllib.parse + +from openpost.api import ( + CONTAINER, + DB_CONTAINER, + DB_NAME, + DB_PASSWORD, + DB_USER, + MEMBER_MAILBOX, + ONION_ORIGIN, + SIMULATOR_ADMIN, + SIMULATOR_PLATFORMS, + SSO_ENABLED, + accounts, + call, + call_raw, + check, + draft, + in_container, + provider, + release, + renditions, + settle, + upload, +) +from openpost.journal import check_journal, hits + +SIMULATOR_TOKENS = ( + "simulator-access-token", + "simulator-access-secret", + "simulator-meta-user-token", + "simulator-page-token", + "simulator-second-page-token", + "simulator-google-token", + "simulator-google-refresh", + "simulator-tiktok-token", + "simulator-tiktok-refresh", +) +SCHEDULE_AHEAD_SECONDS = 120 +SCENARIOS = ( + ("scheduled", "x", "", "text", {}), + ("x", "x", "", "text", {}), + ("x-429", "x", "[simulate-429]", "text", {}), + ("x-503", "x", "[simulate-503]", "text", {}), + ("x-400", "x", "[simulate-400]", "text", {}), + ("facebook", "facebook", "", "text", {}), + ("instagram", "instagram", "", "image", {}), + ("linkedin", "linkedin", "", "text", {}), + ( + "tiktok", + "tiktok", + "", + "image", + { + "content_posting_method": "DIRECT_POST", + "privacy_level": "SELF_ONLY", + "music_usage_confirmed": True, + }, + ), + ( + "youtube", + "youtube", + "", + "video", + { + "privacy": "private", + "category_id": "22", + "playlist_id": "", + "self_declared_made_for_kids": False, + "title": "Simulated YouTube video", + }, + ), +) + + +def simulator_admin(path: str, post: bool) -> object: + argv = ["wget", "-q", "-O", "-", "--no-check-certificate"] + ( + ["--post-data="] if post else [] + ) + raw = in_container(CONTAINER, *argv, SIMULATOR_ADMIN + path) + return json.loads(raw) if raw.strip() else None + + +def linkedin_consent(url: str) -> dict[str, str] | str: + email = f"openpost-cli-{secrets.token_hex(4)}@linkedin.invalid" + password = secrets.token_urlsafe(18) + status, _, body = provider( + "/signup", + {"name": "OpenPost Probe", "email": email, "password": password, "next": ""}, + ) + if status != 201: + return f"fake LinkedIn sign-up HTTP {status} {body}" + carried = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query)) + status, location, body = provider( + "/oauth/v2/authorization", + {**carried, "email": email, "password": password, "decision": "allow"}, + ) + answer = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(location).query)) + if status != 302 or "code" not in answer: + return f"fake LinkedIn consent HTTP {status} {location or body}" + return {"code": answer["code"], "state": answer.get("state", "")} + + +def check_linkedin(tag: str) -> None: + status, _, body = provider("/__fake/linkedin/posts") + posts = [ + post + for post in (body if isinstance(body, list) else []) + if tag in str(post.get("text")) + ] + check( + "the fake LinkedIn holds exactly one post with the tag", + status == 200 and len(posts) == 1, + f"HTTP {status} {posts}", + ) + + +def connect(token: str, workspace: str, platform: str, pick: int) -> str: + status, body = call( + "GET", f"/accounts/{platform}/auth-url?workspace_id={workspace}", token=token + ) + if status != 200 or not isinstance(body, dict): + return f"auth-url HTTP {status} {body}" + query = urllib.parse.parse_qs(urllib.parse.urlparse(str(body["url"])).query) + if platform == "x": + params = { + "oauth_token": query["oauth_token"][0], + "oauth_verifier": "simulator-verifier", + } + elif platform == "linkedin": + consent = linkedin_consent(str(body["url"])) + if isinstance(consent, str): + return consent + params = consent + else: + params = {"code": "simulator-code", "state": query["state"][0]} + status, location, _ = call_raw( + "GET", + f"/accounts/{platform}/callback?{urllib.parse.urlencode(params)}", + token=token, + ) + if status not in (302, 303, 307) or "failed" in location: + return f"callback HTTP {status} {location}" + selection = urllib.parse.parse_qs(urllib.parse.urlparse(location).query).get( + "connection_id" + ) + if not selection: + return "" + status, body = call("GET", f"/accounts/selections/{selection[0]}", token=token) + if status != 200 or not isinstance(body, dict): + return f"selection HTTP {status} {body}" + options = [str(option["id"]) for option in body.get("options") or []] + if pick >= len(options): + return f"selection offers {len(options)} option(s), wanted option {pick + 1}" + status, body = call( + "POST", + f"/accounts/selections/{selection[0]}/complete", + {"selection_ids": [options[pick]]}, + token, + ) + return "" if status == 200 else f"selection complete HTTP {status} {body}" + + +def check_tokens_at_rest() -> None: + if not DB_CONTAINER: + print( + "[SKIP] tokens at rest: the database task runs on another swarm node than the probe" + ) + return + dump = in_container( + DB_CONTAINER, + "pg_dump", + "--data-only", + "-h", + "127.0.0.1", + "-U", + DB_USER, + "-d", + DB_NAME, + env={"PGPASSWORD": DB_PASSWORD}, + ).decode(errors="replace") + leaked = [value for value in SIMULATOR_TOKENS if value in dump] + check( + "the database holds rows for the connected accounts", + "openpost_simulator" in dump or "4242" in dump, + ) + check("no provider token is stored in plaintext", not leaked, leaked) + + +def member_session(tag: str) -> tuple[str, str, str]: + local, domain = MEMBER_MAILBOX.split("@", 1) + email = f"{local}+{tag}@{domain}" + status, body = call( + "POST", + "/auth/register", + { + "email": email, + "password": secrets.token_urlsafe(24), + "username": tag, + "accepted_legal": True, + }, + ) + if status != 200 or not isinstance(body, dict) or not body.get("token"): + sys.exit(f"[FAIL] the probe member cannot register: HTTP {status} {body}") + return str(body["token"]), str(body["user"]["id"]), email + + +def check_roles(token: str, workspace: str, account: str, tag: str) -> str: + member, member_id, email = member_session(tag) + status, invitation = call( + "POST", + f"/workspaces/{workspace}/invitations", + {"email": email, "role": "viewer"}, + token, + ) + if status != 200 or not isinstance(invitation, dict): + sys.exit( + f"[FAIL] inviting the probe member returned HTTP {status}: {invitation}" + ) + secret = urllib.parse.parse_qs( + urllib.parse.urlparse(str(invitation["accept_url"])).query + )["token"][0] + status, body = call( + "POST", "/workspace-invitations/accept", {"token": secret}, member + ) + if status != 200: + sys.exit( + f"[FAIL] the probe member cannot accept the invitation: HTTP {status} {body}" + ) + publication = draft( + token, workspace, [account], f"Member {tag}", "text", "", {}, "" + ) + status, body = release(member, publication, "publish-now") + check( + "a workspace viewer is refused when publishing", + status == 403, + f"HTTP {status} {body}", + ) + status, body = call( + "PATCH", + f"/workspaces/{workspace}/members/{member_id}", + {"role": "editor"}, + token, + ) + if status != 200: + sys.exit( + f"[FAIL] promoting the probe member to editor returned HTTP {status}: {body}" + ) + status, current = call("GET", f"/publications/{publication['id']}", token=member) + status, body = release( + member, current if isinstance(current, dict) else publication, "publish-now" + ) + check("a workspace editor may publish", status == 200, f"HTTP {status} {body}") + call("DELETE", f"/workspaces/{workspace}/members/{member_id}", token=token) + return str(publication["id"]) if status == 200 else "" + + +def check_failure_paths( + token: str, workspace: str, x: str, publications: dict, tags: dict, outcome: dict +) -> None: + if "x-400" in outcome: + rejected = outcome["x-400"][0] + check( + "a permanent X rejection leaves the destination failed with the provider error", + rejected.get("status") == "failed" + and rejected.get("error_http_status") == 400 + and (rejected.get("delivery") or {}).get("terminal_reason") + == "provider_rejected", + rejected, + ) + status, body = call( + "POST", + f"/publications/{publications['x-400']}/renditions/{x}/retry", + None, + token, + ) + check( + "the failed X destination can be retried alone", + status == 200, + f"HTTP {status} {body}", + ) + outcome.update(settle(token, {"x-400": publications["x-400"]})) + if "x-503" in outcome: + ambiguous = outcome["x-503"][0] + check( + "an ambiguous X 503 leaves the destination in manual review instead of resending", + ambiguous.get("status") == "failed" + and (ambiguous.get("delivery") or {}).get("recovery_action") + == "manual_resolution", + ambiguous, + ) + resend = draft( + token, workspace, [x], f"Resent {tags['x-503']}", "text", "", {}, "" + ) + status, body = release(token, resend, "publish-now") + check( + "the post can be published again to that X destination alone", + status == 200, + f"HTTP {status} {body}", + ) + publications["x-503-resend"] = str(resend["id"]) + outcome.update(settle(token, {"x-503-resend": publications["x-503-resend"]})) + + +def check_simulator(token: str, workspace: str) -> None: + simulator_admin("/scenarios/reset", post=True) + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 1)) + for platform in SIMULATOR_PLATFORMS: + error = connect(token, workspace, platform, 0) + check( + f"{platform} connects through OpenPost's callback against the simulator", + not error, + error, + ) + if "facebook" in SIMULATOR_PLATFORMS: + error = connect(token, workspace, "facebook", 1) + check( + "a second Facebook Page connects through its own callback", not error, error + ) + connected = accounts(token, workspace) + if "facebook" in SIMULATOR_PLATFORMS: + pages = connected.get("facebook") or [] + check( + "two Facebook Pages connect side by side in one workspace", + len(pages) >= 2, + pages, + ) + nonce = secrets.token_hex(4) + tags = {label: f"openpost-cli-{label}-{nonce}" for label, *_ in SCENARIOS} + publications: dict[str, str] = {} + due = 0.0 + if "x" in connected: + due = time.time() + SCHEDULE_AHEAD_SECONDS + at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(due)) + scheduled = draft( + token, + workspace, + connected["x"][:1], + f"Scheduled {tags['scheduled']}", + "text", + "", + {}, + at, + ) + status, body = release(token, scheduled, "schedule") + check( + "a post can be scheduled two minutes ahead", + status == 200, + f"HTTP {status} {body}", + ) + states = [ + rendition.get("status") + for rendition in renditions(token, str(scheduled["id"])) + ] + check( + "the scheduled destination shows the scheduled state", + states == ["scheduled"], + states, + ) + publications["scheduled"] = str(scheduled["id"]) + for label, platform, marker, kind, settings in SCENARIOS: + if ( + label == "scheduled" + or platform not in SIMULATOR_PLATFORMS + or platform not in connected + ): + continue + if ONION_ORIGIN and kind in ("image", "video"): + print(f"[SKIP] {label}: providers cannot fetch media from an onion origin") + continue + targets = ( + connected[platform] if label == "facebook" else connected[platform][:1] + ) + media = upload(token, workspace, kind)[0] if kind in ("image", "video") else "" + text = f"{marker} Simulated {platform} delivery {tags[label]}".strip() + publication = draft(token, workspace, targets, text, kind, media, settings, "") + status, body = release(token, publication, "publish-now") + if status != 200: + sys.exit(f"[FAIL] publish-now for {label} returned HTTP {status}: {body}") + publications[label] = str(publication["id"]) + if not SSO_ENABLED: + print( + "[SKIP] workspace roles: without SSO the role closes self-registration, so no second account can exist" + ) + elif "x" in connected: + tags["member"] = f"openpost-cli-member-{nonce}" + promoted = check_roles(token, workspace, connected["x"][0], tags["member"]) + if promoted: + publications["member"] = promoted + outcome = settle(token, publications) + if "x" in connected: + check_failure_paths( + token, workspace, connected["x"][0], publications, tags, outcome + ) + for label in publications: + if label in ("x-400", "x-503"): + continue + current = outcome.get(label) or [{}] + states = [rendition.get("status") for rendition in current] + check( + f"every {label} destination ends published", + set(states) == {"published"}, + current, + ) + journal = simulator_admin( + "/requests?since=" + urllib.parse.quote(since), post=False + ) + entries = journal["requests"] if isinstance(journal, dict) else [] + for label in publications: + if label == "linkedin": + check_linkedin(tags[label]) + elif label in tags: + check_journal(entries, label, tags[label]) + if "scheduled" in publications: + delivered = [ + entry["request"]["loggedDate"] / 1000 + for entry in hits(entries, "POST", "/2/tweets", tags["scheduled"]) + ] + check( + "the scheduled post is not delivered before its time", + bool(delivered) and min(delivered) >= due - 1, + delivered, + ) + check_tokens_at_rest() diff --git a/roles/web-app-openpost/files/test/openpost/sources.py b/roles/web-app-openpost/files/test/openpost/sources.py new file mode 100644 index 0000000000..52909edf9f --- /dev/null +++ b/roles/web-app-openpost/files/test/openpost/sources.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import json +import secrets +import time +import urllib.error +import urllib.parse +import urllib.request + +TIMEOUT = 120 + + +def request( + method: str, + url: str, + token: str, + fields: dict[str, str | list[str]] | None = None, + files: dict[str, tuple[str, str, bytes]] | None = None, +) -> tuple[int, object]: + headers = {"Authorization": f"Bearer {token}"} + data = None + if files: + boundary = secrets.token_hex(16) + data = multipart(boundary, fields or {}, files) + headers["Content-Type"] = f"multipart/form-data; boundary={boundary}" + elif fields: + data = urllib.parse.urlencode(fields, doseq=True).encode() + headers["Content-Type"] = "application/x-www-form-urlencoded" + outgoing = urllib.request.Request(url, data=data, headers=headers, method=method) # noqa: S310 https URL of a local Fediverse source + try: + with urllib.request.urlopen(outgoing, timeout=TIMEOUT) as response: # noqa: S310 https URL of a local Fediverse source + status, raw = response.status, response.read().decode() + except urllib.error.HTTPError as error: + status, raw = error.code, error.read().decode() + except (urllib.error.URLError, OSError) as error: + return 0, str(error) + try: + return status, json.loads(raw) if raw else None + except ValueError: + return status, raw + + +def multipart( + boundary: str, + fields: dict[str, str | list[str]], + files: dict[str, tuple[str, str, bytes]], +) -> bytes: + parts = [ + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{single}\r\n'.encode() + for name, value in fields.items() + for single in (value if isinstance(value, list) else [value]) + ] + for name, (filename, mime, content) in files.items(): + parts.append( + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{filename}"\r\n' + f"Content-Type: {mime}\r\n\r\n".encode() + + content + + b"\r\n" + ) + return b"".join(parts) + f"--{boundary}--\r\n".encode() + + +def mastodon_post( + base: str, + token: str, + text: str, + image: tuple[str, str, bytes] | None, + spoiler: str, +) -> dict: + fields: dict[str, str | list[str]] = {"status": text, "visibility": "public"} + if spoiler: + fields["spoiler_text"] = spoiler + if image: + status, media = request( + "POST", + f"{base}/api/v2/media", + token, + {"description": "A plain colour square"}, + {"file": image}, + ) + if status not in (200, 202) or not isinstance(media, dict): + return {"error": f"media upload HTTP {status} {media}"} + fields["media_ids[]"] = [str(media["id"])] + time.sleep(2) + status, body = request("POST", f"{base}/api/v1/statuses", token, fields) + if status != 200 or not isinstance(body, dict): + return {"error": f"status HTTP {status} {body}"} + return body + + +def mastodon_statuses(base: str, token: str, account: str) -> list[dict]: + status, found = request( + "GET", f"{base}/api/v1/accounts/lookup?acct={account}", token + ) + if status != 200 or not isinstance(found, dict): + return [] + status, body = request( + "GET", f"{base}/api/v1/accounts/{found['id']}/statuses?limit=40", token + ) + return body if status == 200 and isinstance(body, list) else [] + + +def pixelfed_post( + base: str, token: str, text: str, image: tuple[str, str, bytes] +) -> dict: + status, media = request( + "POST", + f"{base}/api/v1/media", + token, + {"description": "A plain colour square"}, + {"file": image}, + ) + if status != 200 or not isinstance(media, dict): + return {"error": f"media upload HTTP {status} {media}"} + status, body = request( + "POST", + f"{base}/api/v1/statuses", + token, + {"status": text, "visibility": "public", "media_ids[]": [str(media["id"])]}, + ) + if status != 200 or not isinstance(body, dict): + return {"error": f"status HTTP {status} {body}"} + return body + + +def peertube_upload( + base: str, + token: str, + channel: str, + name: str, + tag: str, + video: tuple[str, str, bytes], +) -> dict: + status, found = request("GET", f"{base}/api/v1/video-channels/{channel}", token) + if status != 200 or not isinstance(found, dict): + return {"error": f"channel HTTP {status} {found}"} + status, body = request( + "POST", + f"{base}/api/v1/videos/upload", + token, + { + "channelId": str(found["id"]), + "name": name, + "description": f"{name} #{tag}", + "privacy": "1", + "waitTranscoding": "false", + "tags[]": [tag], + }, + {"videofile": video}, + ) + if status != 200 or not isinstance(body, dict): + return {"error": f"upload HTTP {status} {body}"} + return body["video"] diff --git a/roles/web-app-openpost/files/test/probe.py b/roles/web-app-openpost/files/test/probe.py new file mode 100644 index 0000000000..fc3d4909fd --- /dev/null +++ b/roles/web-app-openpost/files/test/probe.py @@ -0,0 +1,428 @@ +from __future__ import annotations + +import json +import secrets +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +from openpost.api import ( + ADMIN_EMAIL, + ADMIN_PASSWORD, + CONTAINER, + DEADLINE, + MAIL_RECIPIENT, + ONION_ORIGIN, + OPENER, + PEERTUBE_PASSWORD, + PEERTUBE_USERNAME, + PUBLIC_URL, + RELAY_TARGETS, + S3_PUBLIC_URL, + SETTLE_SECONDS, + SIMULATOR_PLATFORMS, + SMTP_ENABLED, + SSO_ADMIN_EMAIL, + SSO_ENABLED, + UNCONFIGURED_PLATFORMS, + anonymous_jpeg, + call, + check, + draft, + failures, + in_container, + public_url, + release, + revoke_invitations, + settle, + team, + upload, +) +from openpost.crossposter import ROUTES, check_crossposter +from openpost.simulator import check_simulator + +PRIVATE_TARGETS = ("https://postgres", "https://10.0.0.1") +SQLITE_PATTERNS = ( + "-name", + "*.sqlite", + "-o", + "-name", + "*.sqlite3", + "-o", + "-name", + "*.db", +) + + +def wait_ready() -> None: + while True: + try: + status, _ = call("GET", "/ready") + except OSError as error: + last = str(error) + else: + if status == 200: + return + last = f"HTTP {status}" + if time.monotonic() > DEADLINE: + sys.exit(f"[FAIL] OpenPost never reported ready: {last}") + time.sleep(5) + + +def login() -> str: + status, body = call( + "POST", "/auth/login", {"email": ADMIN_EMAIL, "password": ADMIN_PASSWORD} + ) + if status != 200 or not isinstance(body, dict) or not body.get("token"): + sys.exit(f"[FAIL] break-glass login returned HTTP {status}") + print("[OK] break-glass instance admin signs in") + return str(body["token"]) + + +def flag(path: str, key: str) -> object: + status, body = call("GET", path) + if status != 200 or not isinstance(body, dict): + return f"HTTP {status}" + return body.get(key) + + +def public_status(method: str, path: str) -> int: + request = urllib.request.Request(PUBLIC_URL + path, data=b"{}", method=method) # noqa: S310 fixed public OpenPost origin + request.add_header("Content-Type", "application/json") + try: + with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 fixed public OpenPost origin + return response.status + except urllib.error.HTTPError as error: + return error.code + + +def anonymous_get(path: str) -> int: + request = urllib.request.Request(PUBLIC_URL + path) # noqa: S310 fixed public OpenPost origin + try: + with OPENER.open(request, timeout=60) as response: + return response.status + except urllib.error.HTTPError as error: + return error.code + + +def check_access() -> None: + status = anonymous_get("/api/v1/accounts/mastodon/callback") + check( + "the provider callback answers without a session", + status in (302, 303, 307), + f"HTTP {status}", + ) + status = anonymous_get("/api/v1/workspaces") + check("the API refuses anonymous requests", status == 401, f"HTTP {status}") + found = in_container( + CONTAINER, + "find", + "/", + "(", + "-path", + "/proc", + "-o", + "-path", + "/sys", + ")", + "-prune", + "-o", + "-type", + "f", + "(", + *SQLITE_PATTERNS, + ")", + "-print", + user="0", + ) + check( + "no SQLite database exists in the container", + not found.strip(), + found.decode()[:400], + ) + + +def check_sso_administrator(token: str) -> None: + status, body = call("GET", "/admin/users?per_page=100", token=token) + users = body.get("users") if status == 200 and isinstance(body, dict) else None + found = [ + user + for user in users or [] + if str(user.get("email")).lower() == SSO_ADMIN_EMAIL.lower() + ] + check( + "the SSO administrator from the bootstrap allowlist is an instance admin", + bool(found) and found[0].get("is_admin") is True, + found, + ) + mastodon = RELAY_TARGETS.get("mastodon") + if found and mastodon and not mastodon.endswith(".onion"): + count = found[0].get("publication_count") + check( + "the SSO administrator's publications survived the backup drill", + isinstance(count, int) and count >= 1, + count, + ) + + +def check_data_minimisation() -> None: + for label, path, key in ( + ("PostHog telemetry is off", "/telemetry/config", "enabled"), + ("diagnostics reports are off", "/diagnostics/public-config", "enabled"), + ("public profiles are off", "/auth/config", "public_profiles_enabled"), + ): + value = flag(path, key) + check(label, value is False, f"{path} {key}={value!r}") + if SSO_ENABLED: + status = public_status("POST", "/api/v1/auth/register") + check( + "the proxy refuses password self-registration", + status == 403, + f"HTTP {status}", + ) + else: + value = flag("/auth/config", "registration_enabled") + check( + "password self-registration is off", + value is False, + f"registration_enabled={value!r}", + ) + + +def workspace_id(token: str) -> str: + status, body = call("GET", "/workspaces", token=token) + if status == 200 and isinstance(body, list) and body: + return str(body[0]["id"]) + status, body = call("POST", "/workspaces", {"name": "CLI probe"}, token=token) + if status != 200 or not isinstance(body, dict): + sys.exit(f"[FAIL] cannot create a probe workspace: HTTP {status}") + return str(body["id"]) + + +def auth_url( + token: str, workspace: str, platform: str, instance_url: str +) -> tuple[int, object]: + query = urllib.parse.urlencode( + {"workspace_id": workspace, "instance_url": instance_url} + ) + return call("GET", f"/accounts/{platform}/auth-url?{query}", token=token) + + +def check_unconfigured(token: str, workspace: str) -> None: + for platform in UNCONFIGURED_PLATFORMS: + status, body = call( + "GET", + f"/accounts/{platform}/auth-url?workspace_id={workspace}", + token=token, + ) + check( + f"{platform} cannot be connected without provider credentials", + status != 200, + f"HTTP {status} {body}", + ) + + +def check_relay(token: str, workspace: str) -> None: + for platform, domain in RELAY_TARGETS.items(): + if platform == "peertube": + continue + if domain.endswith(".onion"): + print( + f"[SKIP] relay to {platform}: OpenPost cannot resolve the onion name {domain}" + ) + continue + status, body = auth_url(token, workspace, platform, f"https://{domain}") + check( + f"relay carries {platform} at {domain} past the guard", + status == 200, + f"HTTP {status} {body}", + ) + for target in PRIVATE_TARGETS: + status, body = auth_url(token, workspace, "mastodon", target) + check(f"guard still rejects {target}", status != 200, f"HTTP {status} {body}") + + +def check_media(token: str, workspace: str) -> None: + media, key = upload(token, workspace, "image") + publication = draft( + token, workspace, [], f"Media probe {media}", "image", media, {}, "" + ) + attached: dict = {} + budget = min(DEADLINE, time.monotonic() + 60) + while not attached.get("public_url_checked_at") and time.monotonic() < budget: + status, body = call("GET", f"/publications/{publication['id']}", token=token) + attached = ( + (body.get("media") if status == 200 and isinstance(body, dict) else None) + or [{}] + )[0] + time.sleep(0 if attached.get("public_url_checked_at") else 3) + if ONION_ORIGIN: + check( + "OpenPost flags media on an onion origin as unreachable for providers", + attached.get("public_url_ready") is False + and "OPENPOST_MEDIA_URL" in str(attached.get("public_url_error")), + attached, + ) + else: + check( + "OpenPost reaches the public URL of uploaded media without a session", + attached.get("public_url_ready") is True + and attached.get("public_url_status") == 200, + attached, + ) + if S3_PUBLIC_URL: + check( + f"uploaded media lands in S3 and is fetchable anonymously under {S3_PUBLIC_URL}", + anonymous_jpeg(S3_PUBLIC_URL + key), + key, + ) + else: + check( + "uploaded media is served under /media/", + str(attached.get("url")).startswith("/media/"), + attached.get("url"), + ) + call("DELETE", f"/publications/{publication['id']}", token=token) + + +def check_mail(token: str, workspace: str) -> None: + revoke_invitations(token, workspace, MAIL_RECIPIENT) + status, invitation = call( + "POST", + f"/workspaces/{workspace}/invitations", + {"email": MAIL_RECIPIENT, "role": "viewer"}, + token, + ) + if status != 200 or not isinstance(invitation, dict): + check("OpenPost sends an invitation mail", False, f"HTTP {status} {invitation}") + return + state = str(invitation["email_delivery_status"]) + while state in ("created", "queued") and time.monotonic() < DEADLINE: + time.sleep(5) + current = [ + item + for item in team(token, workspace).get("invitations") or [] + if item["id"] == invitation["id"] + ] + state = str(current[0]["email_delivery_status"]) if current else "revoked" + call( + "DELETE", f"/workspaces/{workspace}/invitations/{invitation['id']}", token=token + ) + check( + "OpenPost hands an invitation mail to the platform mail server", + state in ("sent", "delivered"), + state, + ) + + +def peertube_has(domain: str, tag: str) -> bool: + query = urllib.parse.urlencode({"count": 25, "sort": "-publishedAt"}) + try: + with OPENER.open( + public_url(f"https://{domain}") + + f"/api/v1/accounts/{PEERTUBE_USERNAME}/videos?{query}", + timeout=60, + ) as response: + videos = json.loads(response.read().decode()).get("data") or [] + except (urllib.error.URLError, OSError, ValueError): + return False + return any(tag in str(video.get("name")) for video in videos) + + +def check_peertube(token: str, workspace: str) -> None: + domain = RELAY_TARGETS["peertube"] + credentials = {"username": PEERTUBE_USERNAME, "password": PEERTUBE_PASSWORD} + status, body = call( + "POST", + "/accounts/peertube/login", + {"workspace_id": workspace, "instance_url": f"https://{domain}", **credentials}, + token, + ) + if status == 200 and isinstance(body, dict) and body.get("selection_required"): + choice = [str(option["id"]) for option in body.get("options") or []] + status, body = call( + "POST", + f"/accounts/selections/{body['connection_id']}/complete", + {"selection_ids": choice}, + token, + ) + check( + f"a local PeerTube account at {domain} connects with its password", + status == 200, + f"HTTP {status} {body}", + ) + listed = call("GET", f"/accounts?workspace_id={workspace}", token=token)[1] + channels = ( + [item for item in listed if item.get("platform") == "peertube"] + if isinstance(listed, list) + else [] + ) + if status != 200 or not channels: + return + tag = f"openpost-cli-peertube-{secrets.token_hex(4)}" + media, _ = upload(token, workspace, "video") + settings = {"channel": channels[0]["account_id"], "title": tag, "privacy": "public"} + publication = draft( + token, + workspace, + [str(channels[0]["id"])], + f"PeerTube delivery {tag}", + "video", + media, + settings, + "", + ) + status, body = release(token, publication, "publish-now") + check("the PeerTube video can be published", status == 200, f"HTTP {status} {body}") + if status != 200: + return + current = settle(token, {"peertube": str(publication["id"])}).get("peertube") or [ + {} + ] + check( + "the PeerTube destination ends published", + current[0].get("status") == "published", + current[0], + ) + budget = min(DEADLINE, time.monotonic() + SETTLE_SECONDS) + while not peertube_has(domain, tag) and time.monotonic() < budget: + time.sleep(5) + check("the video appears on the PeerTube instance", peertube_has(domain, tag), tag) + + +def main() -> int: + wait_ready() + print("[OK] /api/v1/ready answers 200") + token = login() + check_data_minimisation() + check_access() + if SSO_ADMIN_EMAIL: + check_sso_administrator(token) + workspace = workspace_id(token) + check_relay(token, workspace) + check_unconfigured(token, workspace) + check_media(token, workspace) + if MAIL_RECIPIENT and SMTP_ENABLED: + check_mail(token, workspace) + if SIMULATOR_PLATFORMS: + check_simulator(token, workspace) + if RELAY_TARGETS.get("peertube", "").endswith(".onion"): + print("[SKIP] PeerTube connect: OpenPost cannot resolve an onion PeerTube") + elif "peertube" in RELAY_TARGETS: + check_peertube(token, workspace) + if ROUTES and ONION_ORIGIN: + print( + "[SKIP] crossposter delivery: an onion OpenPost can neither hand media to providers nor connect onion Fediverse targets" + ) + elif ROUTES: + check_crossposter(token, workspace) + if failures: + print(f"[FAIL] {len(failures)} check(s) failed: {', '.join(failures)}") + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/web-app-openpost/files/test/test.sh b/roles/web-app-openpost/files/test/test.sh new file mode 100644 index 0000000000..764da62079 --- /dev/null +++ b/roles/web-app-openpost/files/test/test.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# Env (rendered into test.env from templates/test.env.j2): +# OPENPOST_CONTAINER resolved OpenPost container (CLI_LOCAL_CID) +# OPENPOST_RELAY_PORT port the relay listens on inside the role network +# every OPENPOST_* variable the openpost/ probe modules document + +set -uo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +[ -n "${OPENPOST_CONTAINER}" ] || { + echo "[FATAL] OPENPOST_CONTAINER unset; the OpenPost container was not resolved" >&2 + exit 2 +} + +python3 -E -s "${here}/probe.py" +rc=$? + +# nocheck: container-exec-resolver, shell-download-retry +unmapped="$(container exec "${OPENPOST_CONTAINER}" wget -S -T 10 -O /dev/null "https://relay:${OPENPOST_RELAY_PORT}/" 2>&1)" +case "${unmapped}" in +*"HTTP/"*) + echo "[FAIL] the relay forwarded a TLS connection whose SNI is not in its map" + echo "${unmapped}" + rc=1 + ;; +*) + echo "[OK] the relay refuses a TLS connection whose SNI is not in its map" + ;; +esac + +exit "${rc}" diff --git a/roles/web-app-openpost/meta/csp.yml b/roles/web-app-openpost/meta/csp.yml new file mode 100644 index 0000000000..030fc85c49 --- /dev/null +++ b/roles/web-app-openpost/meta/csp.yml @@ -0,0 +1,9 @@ +--- +flags: + script-src-elem: + unsafe-inline: true # nocheck: csp-unsafe Reason: OpenPost's SvelteKit shell boots through inline scripts whose hashes change with every upstream release, and the unmodified image cannot carry a nonce +whitelist: + connect-src: + - "{{ lookup('tls', 'web-svc-seaweedfs', 'protocols.web') }}://{{ lookup('config', 'web-svc-seaweedfs', 'domains.canonical.api') }}" + font-src: + - "data:" diff --git a/roles/web-app-openpost/meta/domains.yml b/roles/web-app-openpost/meta/domains.yml new file mode 100644 index 0000000000..15d4536b3d --- /dev/null +++ b/roles/web-app-openpost/meta/domains.yml @@ -0,0 +1,4 @@ +--- +canonical: + - publish.{{ DOMAIN_PRIMARY }} +aliases: [] diff --git a/roles/web-app-openpost/meta/info.yml b/roles/web-app-openpost/meta/info.yml new file mode 100644 index 0000000000..f1e380f10d --- /dev/null +++ b/roles/web-app-openpost/meta/info.yml @@ -0,0 +1,5 @@ +--- +logo: + class: fa-solid fa-paper-plane +homepage: https://openpo.st/ +video: https://www.youtube.com/watch?v=_mZf3HzQaN8 diff --git a/roles/web-app-openpost/meta/license.yml b/roles/web-app-openpost/meta/license.yml new file mode 100644 index 0000000000..ea019b393f --- /dev/null +++ b/roles/web-app-openpost/meta/license.yml @@ -0,0 +1,3 @@ +--- +spdx: AGPL-3.0-only +url: https://github.com/getopenpost/openpost/blob/main/LICENSE diff --git a/roles/web-app-openpost/meta/main.yml b/roles/web-app-openpost/meta/main.yml new file mode 100644 index 0000000000..63b3039617 --- /dev/null +++ b/roles/web-app-openpost/meta/main.yml @@ -0,0 +1,34 @@ +--- +galaxy_info: + author: Evangelos Tsakoudis + description: Self-hosted publishing desk that composes, schedules and publishes posts to Fediverse and commercial social networks + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - openpost + - social-media + - publishing + - fediverse + - docker + - compose + - sso + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all diff --git a/roles/web-app-openpost/meta/networks.yml b/roles/web-app-openpost/meta/networks.yml new file mode 100644 index 0000000000..92c875000f --- /dev/null +++ b/roles/web-app-openpost/meta/networks.yml @@ -0,0 +1,5 @@ +--- +meshes: [] +local: + subnet: 192.88.99.0/24 + outside_pool: true diff --git a/roles/web-app-openpost/meta/rbac.yml b/roles/web-app-openpost/meta/rbac.yml new file mode 100644 index 0000000000..0c37d62134 --- /dev/null +++ b/roles/web-app-openpost/meta/rbac.yml @@ -0,0 +1,2 @@ +--- +roles: {} diff --git a/roles/web-app-openpost/meta/secrets.yml b/roles/web-app-openpost/meta/secrets.yml new file mode 100644 index 0000000000..6863baf121 --- /dev/null +++ b/roles/web-app-openpost/meta/secrets.yml @@ -0,0 +1,12 @@ +--- +credentials: + jwt_secret: + description: Secret OpenPost signs its session and API JWTs with (OPENPOST_JWT_SECRET); upstream requires at least 32 characters. + algorithm: alphanumeric + encryption_key: + description: Key OpenPost encrypts stored provider tokens and provider-app secrets with (OPENPOST_ENCRYPTION_KEY); OpenPost refuses to start once stored rows no longer decrypt, so rotating it requires the upstream previous-keys procedure. + algorithm: alphanumeric + rotatable: false + media_signing_key: + description: Key OpenPost signs short-lived media URLs with (OPENPOST_MEDIA_SIGNING_KEY), pinned apart from the encryption key so a key rotation keeps media links valid. + algorithm: alphanumeric diff --git a/roles/web-app-openpost/meta/server.yml b/roles/web-app-openpost/meta/server.yml new file mode 100644 index 0000000000..8d25fc4bc9 --- /dev/null +++ b/roles/web-app-openpost/meta/server.yml @@ -0,0 +1,2 @@ +--- +client_max_body_size: 2g diff --git a/roles/web-app-openpost/meta/services.yml b/roles/web-app-openpost/meta/services.yml new file mode 100644 index 0000000000..abbad8dcd6 --- /dev/null +++ b/roles/web-app-openpost/meta/services.yml @@ -0,0 +1,225 @@ +--- +sso: + bond: 1 + enabled: "{{ 'web-app-keycloak' in group_names }}" + shared: "{{ 'web-app-keycloak' in group_names }}" + flavor: oidc +logout: + bond: 1 + enabled: "{{ 'web-svc-logout' in group_names }}" + shared: "{{ 'web-svc-logout' in group_names }}" +dashboard: + bond: 1 + enabled: "{{ 'web-app-dashboard' in group_names }}" + shared: "{{ 'web-app-dashboard' in group_names }}" +matomo: + bond: 1 + enabled: "{{ 'web-app-matomo' in group_names }}" + shared: "{{ 'web-app-matomo' in group_names }}" +email: + bond: 1 + enabled: "{{ MAIL_PROVIDER in group_names }}" + shared: "{{ MAIL_PROVIDER in group_names }}" +design: + bond: 1 + enabled: "{{ 'web-svc-design' in group_names }}" + shared: "{{ 'web-svc-design' in group_names }}" +prometheus: + bond: 1 + enabled: "{{ 'web-app-prometheus' in group_names }}" + shared: "{{ 'web-app-prometheus' in group_names }}" +# nocheck: playwright-service-flag +postgres: + bond: 1 + enabled: true # nocheck: dynamic-flag + shared: "{{ 'svc-db-postgres' in group_names }}" +seaweedfs: + bond: 1 + enabled: "{{ 'web-svc-seaweedfs' in group_names }}" + shared: "{{ 'web-svc-seaweedfs' in group_names }}" + public: true +mastodon: + bond: 1 + enabled: "{{ 'web-app-mastodon' in group_names }}" + shared: "{{ 'web-app-mastodon' in group_names }}" +# nocheck: playwright-service-flag +pixelfed: + bond: 0.5 + enabled: "{{ 'web-app-pixelfed' in group_names }}" + shared: "{{ 'web-app-pixelfed' in group_names }}" +# nocheck: playwright-service-flag +peertube: + bond: 0.5 + enabled: "{{ 'web-app-peertube' in group_names }}" + shared: "{{ 'web-app-peertube' in group_names }}" +# nocheck: playwright-service-flag +openpost: + # nocheck: single-replica one `all` process schedules and publishes; split web and worker scaling is out of scope + replicas: 1 + healthcheck: + flavor: wget + path: api/v1/health + modes: + compose: + enabled: true + swarm: + enabled: true + image: ghcr.io/getopenpost/openpost + version: "v7.42.2" + update: + type: registry_tags + image: ghcr.io/getopenpost/openpost + match: "v" + name: openpost + cpus: 1.0 + mem_reservation: 256m + mem_limit: 1g + pids_limit: 512 + min_storage: 600MB + backup: + stop_required: false + ports: + internal: + http: 8080 + local: + http: 8106 + run_after: + - svc-db-postgres + - web-app-keycloak + - web-svc-seaweedfs + - web-app-stalwart + - web-app-mailu + - web-app-mastodon + - web-app-pixelfed + - web-app-peertube + lifecycle: beta +# nocheck: playwright-service-flag, dynamic-flag +relay: + enabled: true + shared: false + modes: + compose: + enabled: true + swarm: + enabled: true + image: nginx + version: 1.31.9-alpine + name: openpost-relay + cpus: "0.2" + mem_reservation: 16m + mem_limit: 64m + pids_limit: 64 + ports: + internal: + http: 80 + https: 443 + siblings: + mastodon: web-app-mastodon + pixelfed: web-app-pixelfed + peertube: web-app-peertube + network_aliases: "{{ lookup('openpost_relay_domains') }}" +# nocheck: playwright-service-flag, dynamic-flag +simulator: + enabled: false + shared: false + modes: + compose: + enabled: true + swarm: + enabled: true + image: wiremock/wiremock + version: "3.13.2" + name: openpost-simulator + cpus: "0.5" + mem_reservation: 256m + mem_limit: 512m + pids_limit: 256 + ports: + internal: + http: 8080 + https: 443 + network_aliases: + - api.twitter.com + - upload.twitter.com + - graph.facebook.com + - rupload.facebook.com + - graph.instagram.com + - oauth2.googleapis.com + - www.googleapis.com + - open.tiktokapis.com + providers: + - x + - meta + - youtube + - tiktok + - linkedin + +# nocheck: dynamic-flag +provider: + enabled: "{{ lookup('config', 'web-app-openpost', 'services.simulator.enabled') | bool }}" + custom: true + modes: + compose: + enabled: true + swarm: + enabled: true + image: python + version: 3.13.18-slim + name: openpost-provider + uid: 10002 + cpus: "0.25" + mem_reservation: 64m + mem_limit: 128m + pids_limit: 64 + ports: + internal: + http: 8080 + https: 443 + local: + http: 8107 + network_aliases: + - www.linkedin.com + - api.linkedin.com + +# nocheck: dynamic-flag +crossposter: + enabled: "{{ (lookup('config', 'web-app-openpost', 'services.crossposter.routes') | length) > 0 }}" + custom: true + modes: + compose: + enabled: true + swarm: + enabled: true + image: python + version: 3.13.18-slim + name: openpost-crossposter + uid: 10001 + cpus: "0.25" + mem_reservation: 64m + mem_limit: 256m + pids_limit: 64 + poll_interval_seconds: 60 + opt_out_tag: nocrosspost + retry: + max_attempts: 8 + base_seconds: 30 + cap_seconds: 3600 + notify: + recipients: [] + routes: [] + +# nocheck: playwright-service-flag +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag +# nocheck: playwright-service-flag, dynamic-flag +container_backup: # nocheck: bond-baseline + bond: 1 + enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" + shared: true + +docs: + bond: 0.5 + enabled: "{{ 'web-app-docs' in group_names }}" + shared: "{{ 'web-app-docs' in group_names }}" diff --git a/roles/web-app-openpost/meta/tests.yml b/roles/web-app-openpost/meta/tests.yml new file mode 100644 index 0000000000..3ce199e8b5 --- /dev/null +++ b/roles/web-app-openpost/meta/tests.yml @@ -0,0 +1,4 @@ +--- +cli: + timeout: 900 + container_service_key: openpost diff --git a/roles/web-app-openpost/meta/users.yml b/roles/web-app-openpost/meta/users.yml new file mode 100644 index 0000000000..70b01e89e2 --- /dev/null +++ b/roles/web-app-openpost/meta/users.yml @@ -0,0 +1,8 @@ +--- +platform_administrator: {} +web-app-openpost-breakglass: + username: openpost-breakglass + password: + algorithm: alphanumeric + accounts: [] + description: OpenPost local break-glass instance admin; not provisioned to IAM, its mail goes to a plus-address of the platform administrator mailbox diff --git a/roles/web-app-openpost/meta/variants.yml b/roles/web-app-openpost/meta/variants.yml new file mode 100644 index 0000000000..e110658901 --- /dev/null +++ b/roles/web-app-openpost/meta/variants.yml @@ -0,0 +1,229 @@ +--- +# nocheck: clearnet-variant-tor +# nocheck: sso-variant-tor variant 0 runs clearnet only: OpenPost reaches an onion Keycloak only through Tor's SOCKS port, which svc-net-tor opens to the internal ranges and not to the role subnet 192.88.99.0/24 +- services: + container_backup: + enabled: true + crossposter: + poll_interval_seconds: 15 + retry: + max_attempts: 3 + base_seconds: 5 + cap_seconds: 30 + notify: + recipients: + - "{{ lookup('users', 'platform_administrator').email }}" + routes: + - name: ci-review + source: + platform: mastodon + base_url: "{{ lookup('tls', 'web-app-mastodon', 'url.origin') }}" + account: "{{ lookup('users', 'platform_administrator').username }}" + token: "" + filters: + visibility: [public] + exclude_replies: true + exclude_reblogs: true + tags: [crossposterreview] + media: any + targets: + social_set: Crossposter review + mode: review + attribution: + default: "{text}\n\n{source_url}" + x: "{text}" + - name: ci-auto + source: + platform: mastodon + base_url: "{{ lookup('tls', 'web-app-mastodon', 'url.origin') }}" + account: "{{ lookup('users', 'platform_administrator').username }}" + token: "" + filters: + visibility: [public] + exclude_replies: true + exclude_reblogs: true + tags: [crossposterauto] + media: any + targets: + social_set: Crossposter auto + mode: auto + attribution: + default: "{text}\n\n{source_url}" + x: "{text}" + design: + enabled: true + shared: true + dashboard: + enabled: true + shared: true + docs: + enabled: false + shared: false + email: + enabled: true + shared: true + logout: + enabled: true + shared: true + mastodon: + enabled: true + shared: true + matomo: + enabled: true + shared: true + peertube: + enabled: false + shared: false + pixelfed: + enabled: false + shared: false + postgres: + shared: true + prometheus: + enabled: true + shared: true + seaweedfs: + enabled: true + shared: true + simulator: + enabled: true # nocheck: variants-static-override + sso: + enabled: true + shared: true + tor: # nocheck: variant-tor-off, variant-tor-collateral the SSO round runs clearnet only: OpenPost reaches an onion Keycloak only through Tor's SOCKS port, which svc-net-tor opens to the internal ranges and not to the role subnet 192.88.99.0/24, so its partners ride along on clearnet and are proven over the onion in their own variants + enabled: false + +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override + crossposter: + poll_interval_seconds: 15 + retry: + max_attempts: 3 + base_seconds: 5 + cap_seconds: 30 + routes: + - name: ci-pixelfed + source: + platform: pixelfed + base_url: "{{ lookup('tls', 'web-app-pixelfed', 'url.origin') }}" + account: "{{ lookup('users', 'platform_administrator').username }}" + token: "" + filters: + visibility: [public] + exclude_replies: true + exclude_reblogs: true + tags: [crossposterpixelfed] + media: required + targets: + social_set: Crossposter pixelfed + mode: auto + attribution: + default: "{text}\n\n{source_url}" + x: "{text}" + - name: ci-peertube + source: + platform: peertube + base_url: "{{ lookup('tls', 'web-app-peertube', 'url.origin') }}" + account: root_channel + token: "" + filters: + visibility: [public] + exclude_replies: true + exclude_reblogs: true + tags: [crossposterpeertube] + media: required + targets: + social_set: Crossposter peertube + mode: auto + attribution: + default: "{text}\n\n{source_url}" + x: "{text}" + design: + enabled: false + shared: false + dashboard: + enabled: false + shared: false + docs: + enabled: false + shared: false + email: + enabled: false + shared: false + logout: + enabled: false + shared: false + mastodon: + enabled: false + shared: false + matomo: + enabled: false + shared: false + peertube: + enabled: true + shared: true + pixelfed: + enabled: true + shared: true + postgres: + shared: true + prometheus: + enabled: false + shared: false + seaweedfs: + enabled: false + shared: false + simulator: + enabled: true # nocheck: variants-static-override + sso: + enabled: false + shared: false + tor: + enabled: true + +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override + design: + enabled: false + shared: false + dashboard: + enabled: false + shared: false + docs: + enabled: true + shared: true + email: + enabled: false + shared: false + logout: + enabled: false + shared: false + mastodon: + enabled: false + shared: false + matomo: + enabled: false + shared: false + peertube: + enabled: false + shared: false + pixelfed: + enabled: false + shared: false + postgres: + shared: false + prometheus: + enabled: false + shared: false + seaweedfs: + enabled: false + shared: false + sso: + enabled: false + shared: false + tor: + enabled: true diff --git a/roles/web-app-openpost/meta/volumes.yml b/roles/web-app-openpost/meta/volumes.yml new file mode 100644 index 0000000000..3515301bb0 --- /dev/null +++ b/roles/web-app-openpost/meta/volumes.yml @@ -0,0 +1,102 @@ +--- +media: + type: volume + name: openpost_media + mounts: + - service: openpost + target: /data/media + +simulator_mappings: + type: config + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'simulator', 'openpost.json'] | path_join }}" + mode: "0444" + mounts: + - service: simulator + target: /home/wiremock/mappings/openpost.json + when: "{{ lookup('config', 'web-app-openpost', 'services.simulator.enabled') | bool }}" + +simulator_keystore: + type: secret + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'simulator', 'keystore.p12'] | path_join }}" + mode: "0400" + mounts: + - service: simulator + target: /home/wiremock/keystore.p12 + when: "{{ lookup('config', 'web-app-openpost', 'services.simulator.enabled') | bool }}" + +simulator_ca: + type: config + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'simulator', 'ca.crt'] | path_join }}" + mode: "0444" + mounts: + - service: openpost + target: /etc/ssl/openpost-trust/simulator-ca.crt + when: "{{ lookup('config', 'web-app-openpost', 'services.simulator.enabled') | bool }}" + +provider_config: + type: secret + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'provider', 'provider.json'] | path_join }}" + mode: "0400" + mounts: + - service: provider + target: /run/secrets/provider.json + uid: "{{ lookup('config', 'web-app-openpost', 'services.provider.uid') }}" + gid: "{{ lookup('config', 'web-app-openpost', 'services.provider.uid') }}" + when: "{{ lookup('config', 'web-app-openpost', 'services.provider.enabled') | bool }}" + +provider_certificate: + type: config + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'simulator', 'server.crt'] | path_join }}" + mode: "0444" + mounts: + - service: provider + target: /config/server.crt + when: "{{ lookup('config', 'web-app-openpost', 'services.provider.enabled') | bool }}" + +provider_key: + type: secret + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'provider', 'server.key'] | path_join }}" + mode: "0400" + mounts: + - service: provider + target: /run/secrets/server.key + uid: "{{ lookup('config', 'web-app-openpost', 'services.provider.uid') }}" + gid: "{{ lookup('config', 'web-app-openpost', 'services.provider.uid') }}" + when: "{{ lookup('config', 'web-app-openpost', 'services.provider.enabled') | bool }}" + +root_ca: + type: config + source: "{{ CA_TRUST.cert_host }}" + mode: "0444" + mounts: + - service: openpost + target: /etc/ssl/openpost-trust/root-ca.crt + when: "{{ TLS_MODE == 'self_signed' }}" + +crossposter_config: + type: config + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'crossposter', 'crossposter.json'] | path_join }}" + mode: "0444" + mounts: + - service: crossposter + target: /config/crossposter.json + when: "{{ lookup('config', 'web-app-openpost', 'services.crossposter.enabled') | bool }}" + +crossposter_secrets: + type: secret + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'crossposter', 'crossposter-secrets.json'] | path_join }}" + mode: "0400" + mounts: + - service: crossposter + target: /run/secrets/crossposter.json + uid: "{{ lookup('config', 'web-app-openpost', 'services.crossposter.uid') }}" + gid: "{{ lookup('config', 'web-app-openpost', 'services.crossposter.uid') }}" + when: "{{ lookup('config', 'web-app-openpost', 'services.crossposter.enabled') | bool }}" + +relay_conf: + type: config + source: "{{ [lookup('container', 'web-app-openpost', 'directories.config'), 'relay.conf'] | path_join }}" + mode: "0444" + mounts: + - service: relay + target: /etc/nginx/nginx.conf diff --git a/roles/web-app-openpost/tasks/00_core.yml b/roles/web-app-openpost/tasks/00_core.yml new file mode 100644 index 0000000000..e88f29b6b0 --- /dev/null +++ b/roles/web-app-openpost/tasks/00_core.yml @@ -0,0 +1,78 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "🧭 Remember the public view of this deploy for the CLI probe" + ansible.builtin.set_fact: + openpost_public_view: + proxy_address: "{{ hostvars[STACK_HOST].ansible_facts.default_ipv4.address if IS_SWARM_MODE else '' }}" + public_url: "{{ OPENPOST_URL }}" + api_headers: "{{ OPENPOST_API_HEADERS }}" + s3_public_url: "{{ lookup('objstore', application_id, 'public_url') | regex_replace('/?$', '/') if OPENPOST_OBJSTORE_ENABLED | bool else '' }}" + smtp_enabled: "{{ OPENPOST_SMTP_ENABLED | bool }}" + relay_targets: >- + {%- set _targets = {} -%} + {%- for _key, _role in OPENPOST_RELAY_SIBLINGS.items() if lookup('config', application_id, 'services.' ~ _key ~ '.enabled') | bool -%} + {%- set _ = _targets.update({_key: lookup('domain', _role)}) -%} + {%- endfor -%} + {{ _targets }} + routes: >- + {%- set _routes = [] -%} + {%- for _route in OPENPOST_CROSSPOSTER_ROUTES -%} + {%- set _ = _routes.append({'name': _route.name, 'platform': _route.source.platform, 'base_url': _route.source.base_url, 'account': _route.source.account, 'mode': _route.mode, 'tags': _route.filters.tags, 'social_set': _route.targets.social_set | default('', true)}) -%} + {%- endfor -%} + {{ _routes }} + +- name: "🔗 Pin OpenPost apps on the sibling Mastodon and Pixelfed instances" + include_tasks: 01_fediverse_apps.yml + +- name: "🧪 Prepare the provider simulator" + include_tasks: + file: 02_simulator.yml + apply: + delegate_to: "{{ STACK_HOST }}" + run_once: true + when: OPENPOST_SIMULATOR_ENABLED | bool + +- name: "🧩 load docker, db and proxy for {{ application_id }}" + include_role: + name: sys-stk-full + vars: + compose_handlers_flush: false + webserver_extra_configuration: >- + {{ lookup('template', 'nginx/echo_routes.conf.j2') + ~ (lookup('file', lookup('path_absolute', 'roles/web-app-openpost/files/nginx/deny-password-registration.conf')) + if OPENPOST_OIDC_ENABLED | bool else '') }} + +- name: "📄 Render the egress relay config (local + swarm peers)" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "relay.conf.j2" + dest: "{{ OPENPOST_RELAY_CONF_HOST }}" + mode: "0644" + +- name: "📮 Stage and render the crossposter" + include_tasks: crossposter/render.yml + when: OPENPOST_CROSSPOSTER_ENABLED | bool + +- name: "🎭 Stage and render the fake provider" + include_tasks: provider/render.yml + when: OPENPOST_PROVIDER_ENABLED | bool + +- name: "🚿 flush handlers for '{{ application_id }}'" + meta: flush_handlers + +- name: "🔑 Bootstrap the break-glass instance admin" + include_tasks: 03_breakglass.yml + when: IS_STACK_HOST | bool + +- name: "📮 Provision, apply and validate the crossposter" + when: OPENPOST_CROSSPOSTER_ENABLED | bool + block: + - name: "🔑 Provision the crossposter API token" + include_tasks: crossposter/provision.yml + when: IS_STACK_HOST | bool + + - name: "✅ Apply and validate the crossposter" + include_tasks: crossposter/apply.yml diff --git a/roles/web-app-openpost/tasks/01_fediverse_apps.yml b/roles/web-app-openpost/tasks/01_fediverse_apps.yml new file mode 100644 index 0000000000..c2c9b96a24 --- /dev/null +++ b/roles/web-app-openpost/tasks/01_fediverse_apps.yml @@ -0,0 +1,78 @@ +--- +- name: "🔎 Check for the OpenPost apps registered on sibling Fediverse instances" + ansible.builtin.stat: + path: "{{ OPENPOST_FEDIVERSE_APPS_HOST }}" + register: openpost_fediverse_apps_file + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "📖 Read the OpenPost apps already registered on the sibling Fediverse instances" + ansible.builtin.slurp: + src: "{{ OPENPOST_FEDIVERSE_APPS_HOST }}" + register: openpost_fediverse_apps_raw + when: openpost_fediverse_apps_file.stat.exists + delegate_to: "{{ STACK_HOST }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧾 Keep the registered apps" + ansible.builtin.set_fact: + openpost_fediverse_apps: >- + {{ (openpost_fediverse_apps_raw.content | b64decode | from_json) + if openpost_fediverse_apps_file.stat.exists else {} }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "📝 Register an OpenPost app on each sibling instance that has none yet" + uri_retry: + url: "{{ item.url }}/api/v1/apps" + method: POST + body_format: form-urlencoded + body: + client_name: OpenPost + redirect_uris: "urn:ietf:wg:oauth:2.0:oob" + scopes: "read write" + website: "{{ OPENPOST_URL }}" + validate_certs: true + status_code: 200 + loop: "{{ OPENPOST_PINNED_INSTANCES | rejectattr('url', 'in', openpost_fediverse_apps.keys() | list) | list }}" + loop_control: + label: "{{ item.url }}" + register: openpost_fediverse_registrations + delegate_to: "{{ STACK_HOST }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧾 Add the apps registered in this run" + ansible.builtin.set_fact: + openpost_fediverse_apps: "{{ openpost_fediverse_apps | combine(openpost_fediverse_new_apps) }}" + vars: + openpost_fediverse_new_apps: >- + {%- set _apps = {} -%} + {%- for _result in openpost_fediverse_registrations.results -%} + {%- set _ = _apps.update({_result.item.url: {'client_id': _result.json.client_id, 'client_secret': _result.json.client_secret}}) -%} + {%- endfor -%} + {{ _apps }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "👤 Give OpenPost's Pixelfed app an owner" + ansible.builtin.include_tasks: fediverse/pixelfed_owner.yml + when: OPENPOST_PINNED_PIXELFED | length > 0 + run_once: true + +- name: "💾 Persist the apps registered in this run" + when: openpost_fediverse_registrations.results | length > 0 + delegate_to: "{{ STACK_HOST }}" + run_once: true + block: + - name: "📁 Ensure the directory for the registered apps exists" + ansible.builtin.file: + path: "{{ OPENPOST_FEDIVERSE_APPS_HOST | dirname }}" + state: directory + mode: "0755" + + - name: "💾 Persist the registered apps" + ansible.builtin.copy: + dest: "{{ OPENPOST_FEDIVERSE_APPS_HOST }}" + content: "{{ openpost_fediverse_apps | to_nice_json }}" + mode: "0600" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/02_simulator.yml b/roles/web-app-openpost/tasks/02_simulator.yml new file mode 100644 index 0000000000..f804bc85b6 --- /dev/null +++ b/roles/web-app-openpost/tasks/02_simulator.yml @@ -0,0 +1,109 @@ +--- +- name: "📁 Ensure the provider simulator directory exists" + ansible.builtin.file: + path: "{{ OPENPOST_SIMULATOR_DIR }}" + state: directory + mode: "0750" + +- name: "🔐 Create the test CA the simulator certificate chains to" + ansible.builtin.command: + argv: + - openssl + - req + - -x509 + - -newkey + - rsa:2048 + - -nodes + - -days + - "365" + - -subj + - "/CN=OpenPost provider simulator CA" + - -keyout + - "{{ OPENPOST_SIMULATOR_DIR }}/ca.key" + - -out + - "{{ OPENPOST_SIMULATOR_DIR }}/ca.crt" + creates: "{{ OPENPOST_SIMULATOR_DIR }}/ca.crt" + +- name: "📄 Write the subject alternative names of the simulated provider hosts" + ansible.builtin.copy: + dest: "{{ OPENPOST_SIMULATOR_DIR }}/server.ext" + content: | + subjectAltName={{ (OPENPOST_SIMULATOR_HOSTS + OPENPOST_PROVIDER_HOSTS) | map('regex_replace', '^', 'DNS:') | join(',') }} + extendedKeyUsage=serverAuth + mode: "0640" + register: openpost_simulator_ext + +- name: "🗑️ Drop the simulator certificate when its host list changed" + ansible.builtin.file: + path: "{{ OPENPOST_SIMULATOR_DIR }}/{{ item }}" + state: absent + loop: + - server.crt + - keystore.p12 + when: openpost_simulator_ext.changed + +- name: "🔑 Create the simulator key and signing request" + ansible.builtin.command: + argv: + - openssl + - req + - -newkey + - rsa:2048 + - -nodes + - -subj + - "/CN=openpost-simulator" + - -keyout + - "{{ OPENPOST_SIMULATOR_DIR }}/server.key" + - -out + - "{{ OPENPOST_SIMULATOR_DIR }}/server.csr" + creates: "{{ OPENPOST_SIMULATOR_DIR }}/server.csr" + +- name: "✒️ Sign the simulator certificate with the test CA" + ansible.builtin.command: + argv: + - openssl + - x509 + - -req + - -in + - "{{ OPENPOST_SIMULATOR_DIR }}/server.csr" + - -CA + - "{{ OPENPOST_SIMULATOR_DIR }}/ca.crt" + - -CAkey + - "{{ OPENPOST_SIMULATOR_DIR }}/ca.key" + - -CAcreateserial + - -days + - "365" + - -sha256 + - -extfile + - "{{ OPENPOST_SIMULATOR_DIR }}/server.ext" + - -out + - "{{ OPENPOST_SIMULATOR_DIR }}/server.crt" + creates: "{{ OPENPOST_SIMULATOR_DIR }}/server.crt" + +- name: "📦 Bundle the simulator certificate into the WireMock keystore" + ansible.builtin.command: + argv: + - openssl + - pkcs12 + - -export + - -name + - simulator + - -in + - "{{ OPENPOST_SIMULATOR_DIR }}/server.crt" + - -inkey + - "{{ OPENPOST_SIMULATOR_DIR }}/server.key" + - -certfile + - "{{ OPENPOST_SIMULATOR_DIR }}/ca.crt" + - -passout + - stdin + - -out + - "{{ OPENPOST_SIMULATOR_DIR }}/keystore.p12" + stdin: "{{ OPENPOST_SIMULATOR_KEYSTORE_PASSWORD }}" + creates: "{{ OPENPOST_SIMULATOR_DIR }}/keystore.p12" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🗺️ Deploy the simulator stub mappings" + ansible.builtin.copy: + src: simulator/openpost.json + dest: "{{ OPENPOST_SIMULATOR_DIR }}/openpost.json" + mode: "0644" diff --git a/roles/web-app-openpost/tasks/03_breakglass.yml b/roles/web-app-openpost/tasks/03_breakglass.yml new file mode 100644 index 0000000000..d24ec03449 --- /dev/null +++ b/roles/web-app-openpost/tasks/03_breakglass.yml @@ -0,0 +1,59 @@ +--- +- name: "⏳ Wait until OpenPost reports ready" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/ready" + headers: "{{ OPENPOST_API_HEADERS }}" + status_code: 200 + timeout: "{{ lookup('timeout', 10) | int }}" + retries: 60 + delay: 5 + changed_when: false + +- name: "🔑 Sign in as the break-glass instance admin" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/auth/login" + method: POST + headers: "{{ OPENPOST_API_HEADERS }}" + body_format: json + body: + email: "{{ OPENPOST_ADMIN_EMAIL }}" + password: "{{ OPENPOST_ADMIN_PASSWORD }}" + status_code: [200, 401] + register: openpost_breakglass_login + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: false + +- name: "🛟 Create or recover the break-glass account that cannot sign in" + include_tasks: breakglass/recover.yml + when: openpost_breakglass_login.status == 401 + +- name: "🔐 Keep the break-glass session headers for the following API calls" + ansible.builtin.set_fact: + openpost_breakglass_headers: >- + {{ OPENPOST_API_HEADERS | combine({'Authorization': 'Bearer ' ~ + (openpost_breakglass_login.json.token if openpost_breakglass_login.status == 200 + else openpost_breakglass_register.json.token if openpost_breakglass_register.status == 200 + else openpost_breakglass_relogin.json.token)}) }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🔍 List the workspaces of the break-glass instance admin" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/workspaces" + headers: "{{ openpost_breakglass_headers }}" + status_code: 200 + register: openpost_breakglass_workspaces + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: false + +- name: "🏢 Create the organisation workspace owned by the break-glass instance admin" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/workspaces" + method: POST + headers: "{{ openpost_breakglass_headers }}" + body_format: json + body: + name: "{{ OPENPOST_ORGANISATION_WORKSPACE }}" + status_code: 200 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: true + when: OPENPOST_ORGANISATION_WORKSPACE not in (openpost_breakglass_workspaces.json | map(attribute='name') | list) diff --git a/roles/web-app-openpost/tasks/breakglass/recover.yml b/roles/web-app-openpost/tasks/breakglass/recover.yml new file mode 100644 index 0000000000..c4a2bc1992 --- /dev/null +++ b/roles/web-app-openpost/tasks/breakglass/recover.yml @@ -0,0 +1,53 @@ +--- +- name: "👤 Register the break-glass account as the first instance admin" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/auth/register" + method: POST + headers: "{{ OPENPOST_API_HEADERS }}" + body_format: json + body: + email: "{{ OPENPOST_ADMIN_EMAIL }}" + password: "{{ OPENPOST_ADMIN_PASSWORD }}" + username: "{{ OPENPOST_ADMIN_USERNAME }}" + status_code: [200, 403, 409] + register: openpost_breakglass_register + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: openpost_breakglass_register.status == 200 + +- name: "🔐 Recover the existing break-glass account" + when: openpost_breakglass_register.status != 200 + block: + - name: "🔐 Realign the password of the existing break-glass account with the inventory" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/breakglass/password.sql" + named_args: + email: "{{ OPENPOST_ADMIN_EMAIL }}" + password_hash: "{{ OPENPOST_ADMIN_PASSWORD | bcrypt_hash(application_id ~ ':breakglass') }}" + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: openpost_breakglass_realign + changed_when: openpost_breakglass_realign.stdout is search('UPDATE [1-9]') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + + - name: "🔑 Sign in as the break-glass instance admin with the realigned password" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/auth/login" + method: POST + headers: "{{ OPENPOST_API_HEADERS }}" + body_format: json + body: + email: "{{ OPENPOST_ADMIN_EMAIL }}" + password: "{{ OPENPOST_ADMIN_PASSWORD }}" + status_code: [200, 401] + register: openpost_breakglass_relogin + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: false + + - name: "❌ Fail when the break-glass account can neither sign in nor be created" + ansible.builtin.fail: + msg: >- + OpenPost refused the break-glass sign-in, its registration (HTTP + {{ openpost_breakglass_register.status }}) and the sign-in after the password + realignment. Another account already became the first instance admin; follow + the break-glass procedure in Administration.md. + when: openpost_breakglass_relogin.status != 200 diff --git a/roles/web-app-openpost/tasks/crossposter/apply.yml b/roles/web-app-openpost/tasks/crossposter/apply.yml new file mode 100644 index 0000000000..925cb7941e --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/apply.yml @@ -0,0 +1,42 @@ +--- +- name: "📄 Render the crossposter files from the current state" + ansible.builtin.include_tasks: crossposter/render.yml + +- name: "📁 Re-render the compose file with the crossposter" + stack_host_template: + src: compose.yml.j2 + dest: "{{ lookup('container', application_id, 'files.compose') }}" + mode: "0640" + force: true + notify: compose-up + +- name: "🚿 Flush handlers so the crossposter runs the current configuration" + ansible.builtin.meta: flush_handlers + +- name: "🔍 Resolve the crossposter container" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: crossposter + resolve_output_prefix: OPENPOST_CROSSPOSTER + resolve_compose_cid: "{{ OPENPOST_CROSSPOSTER_ADDRESS }}" + +- name: "✅ Validate the crossposter routes against OpenPost" + ansible.builtin.command: + argv: + - container + - exec + - "{{ OPENPOST_CROSSPOSTER_LOCAL_CID }}" # nocheck: container-exec-resolver + - python + - -m + - crossposter + - validate + - --config + - "{{ OPENPOST_CROSSPOSTER_CONFIG_TARGET }}" + register: openpost_crossposter_validation + changed_when: false + retries: 12 + delay: 5 + until: openpost_crossposter_validation.rc in [0, 2] + failed_when: openpost_crossposter_validation.rc != 0 + delegate_to: "{{ OPENPOST_CROSSPOSTER_HOST_NODE }}" + run_once: true diff --git a/roles/web-app-openpost/tasks/crossposter/provision.yml b/roles/web-app-openpost/tasks/crossposter/provision.yml new file mode 100644 index 0000000000..1bea7d9f18 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/provision.yml @@ -0,0 +1,64 @@ +--- +- name: "🔍 List the workspaces the crossposter may publish into" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/workspaces" + headers: "{{ openpost_breakglass_headers }}" + status_code: 200 + register: openpost_crossposter_workspaces + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🏢 Pick the organisation workspace for the crossposter" + ansible.builtin.set_fact: + openpost_crossposter_target_workspace: >- + {{ (openpost_crossposter_workspaces.json + | selectattr('name', 'equalto', OPENPOST_ORGANISATION_WORKSPACE) | first).id }} + +- name: "🔎 Check the stored crossposter API token" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/workspaces" + headers: "{{ OPENPOST_API_HEADERS | combine({'Authorization': 'Bearer ' ~ openpost_crossposter_token}) }}" + status_code: [200, 401, 403] + register: openpost_crossposter_token_check + changed_when: false + when: openpost_crossposter_token | length > 0 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🔑 Issue a workspace API token for the crossposter" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/api-tokens" + method: POST + headers: "{{ openpost_breakglass_headers }}" + body_format: json + body: + name: "{{ OPENPOST_CROSSPOSTER_TOKEN_NAME }}" + scope: "api:write" + workspace_id: "{{ openpost_crossposter_target_workspace }}" + status_code: [200, 201] + register: openpost_crossposter_issued + changed_when: true + when: >- + openpost_crossposter_token | length == 0 + or openpost_crossposter_token_check.status != 200 + or openpost_crossposter_workspace != openpost_crossposter_target_workspace + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧭 Adopt the newly issued crossposter API token" + ansible.builtin.set_fact: + openpost_crossposter_workspace: "{{ openpost_crossposter_target_workspace }}" + openpost_crossposter_token: "{{ openpost_crossposter_issued.json.token }}" + when: openpost_crossposter_issued is changed + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🌱 Seed the CI source tokens and social sets" + ansible.builtin.include_tasks: crossposter/seed.yml + when: OPENPOST_SIMULATOR_ENABLED | bool + +- name: "💾 Persist the crossposter workspace, API token and CI source tokens" + ansible.builtin.copy: + content: >- + {{ {'workspace': openpost_crossposter_workspace, 'token': openpost_crossposter_token, + 'sources': openpost_crossposter_sources} | to_json }} + dest: "{{ OPENPOST_CROSSPOSTER_STATE_FILE }}" + mode: "0600" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/crossposter/render.yml b/roles/web-app-openpost/tasks/crossposter/render.yml new file mode 100644 index 0000000000..90d14ee318 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/render.yml @@ -0,0 +1,58 @@ +--- +- name: "🔎 Check whether the crossposter was provisioned before" + ansible.builtin.stat: + path: "{{ OPENPOST_CROSSPOSTER_STATE_FILE }}" + register: openpost_crossposter_state_file + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "📖 Read the crossposter state" + ansible.builtin.slurp: + src: "{{ OPENPOST_CROSSPOSTER_STATE_FILE }}" + register: openpost_crossposter_state_raw + when: openpost_crossposter_state_file.stat.exists + delegate_to: "{{ STACK_HOST }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧭 Remember the provisioned workspace, API token and CI source tokens" + ansible.builtin.set_fact: + openpost_crossposter_workspace: "{{ openpost_crossposter_state.workspace }}" + openpost_crossposter_token: "{{ openpost_crossposter_state.token }}" + openpost_crossposter_sources: "{{ openpost_crossposter_state.sources }}" + vars: + openpost_crossposter_state: >- + {{ (openpost_crossposter_state_raw.content | b64decode | from_json) + if openpost_crossposter_state_file.stat.exists + else {'workspace': '', 'token': '', 'sources': {}} }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "📦 Stage the crossposter build context" + ansible.builtin.copy: + src: "{{ item.src }}" + dest: "{{ item.dest }}" + mode: preserve + loop: + - src: "{{ role_path }}/files/crossposter/" + dest: "{{ OPENPOST_CROSSPOSTER_BUILD_CONTEXT }}/" + - src: "{{ role_path }}/files/python/crossposter/" + dest: "{{ [OPENPOST_CROSSPOSTER_BUILD_CONTEXT, 'crossposter'] | path_join }}/" + - src: "{{ role_path }}/files/sql/crossposter/" + dest: "{{ [OPENPOST_CROSSPOSTER_BUILD_CONTEXT, 'crossposter', 'sql'] | path_join }}/" + notify: + - compose-build + - compose-up + +- name: "📄 Render the crossposter configuration and secrets" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "crossposter.json.j2" + dest: "{{ OPENPOST_CROSSPOSTER_CONFIG_HOST }}" + mode: "0644" + - src: "crossposter-secrets.json.j2" + dest: "{{ OPENPOST_CROSSPOSTER_SECRETS_HOST }}" + mode: "0400" + owner: "{{ OPENPOST_CROSSPOSTER_UID }}" + group: "{{ OPENPOST_CROSSPOSTER_UID }}" diff --git a/roles/web-app-openpost/tasks/crossposter/seed.yml b/roles/web-app-openpost/tasks/crossposter/seed.yml new file mode 100644 index 0000000000..ceae92edeb --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/seed.yml @@ -0,0 +1,85 @@ +--- +- name: "🧾 Pick the CI routes whose source token the deploy has to mint" + ansible.builtin.set_fact: + openpost_crossposter_seed_routes: "{{ OPENPOST_CROSSPOSTER_ROUTES | rejectattr('source.token') | list }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🔎 Check the source tokens minted by an earlier deploy" + uri_retry: + url: "{{ item.source.base_url }}{{ OPENPOST_CROSSPOSTER_SEED_PROBES[item.source.platform] }}" + headers: + Authorization: "Bearer {{ openpost_crossposter_sources[item.name] }}" + status_code: [200, 401, 403] + loop: "{{ openpost_crossposter_seed_routes | selectattr('name', 'in', openpost_crossposter_sources.keys() | list) | list }}" + loop_control: + label: "{{ item.name }}" + register: openpost_crossposter_seed_checks + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧾 Keep the minted source tokens that still authenticate" + ansible.builtin.set_fact: + openpost_crossposter_sources: >- + {%- set _kept = {} -%} + {%- for _check in openpost_crossposter_seed_checks.results if _check.status == 200 -%} + {%- set _ = _kept.update({_check.item.name: openpost_crossposter_sources[_check.item.name]}) -%} + {%- endfor -%} + {{ _kept }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧾 Pick the CI routes that still lack a working source token" + ansible.builtin.set_fact: + openpost_crossposter_seed_missing: "{{ openpost_crossposter_seed_routes | rejectattr('name', 'in', openpost_crossposter_sources.keys() | list) | list }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🐘 Mint the Mastodon source tokens" + ansible.builtin.include_tasks: crossposter/seed/mastodon.yml + when: openpost_crossposter_seed_missing | selectattr('source.platform', 'equalto', 'mastodon') | list | length > 0 + +- name: "📷 Mint the Pixelfed source tokens" + ansible.builtin.include_tasks: crossposter/seed/pixelfed.yml + when: openpost_crossposter_seed_missing | selectattr('source.platform', 'equalto', 'pixelfed') | list | length > 0 + +- name: "🎞️ Mint the PeerTube source tokens" + ansible.builtin.include_tasks: + file: crossposter/seed/peertube.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: openpost_crossposter_seed_missing | selectattr('source.platform', 'equalto', 'peertube') | list | length > 0 + +- name: "🐘 Connect the CI Mastodon account as a target" + ansible.builtin.include_tasks: crossposter/seed/target.yml + when: + - OPENPOST_CROSSPOSTER_ROUTES | selectattr('source.platform', 'equalto', 'mastodon') | list | length > 0 + - OPENPOST_PINNED_INSTANCES | selectattr('platform', 'equalto', 'mastodon') | list | length > 0 + +- name: "📚 List the social sets of the organisation workspace" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/social-sets?workspace_id={{ openpost_crossposter_target_workspace }}" + headers: "{{ openpost_breakglass_headers }}" + status_code: 200 + register: openpost_crossposter_social_sets + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🗂️ Create the social sets the CI routes target" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/social-sets" + method: POST + headers: "{{ openpost_breakglass_headers }}" + body_format: json + body: + name: "{{ item }}" + workspace_id: "{{ openpost_crossposter_target_workspace }}" + accounts: [] + status_code: [200, 201] + loop: >- + {{ OPENPOST_CROSSPOSTER_ROUTES + | map(attribute='targets') | selectattr('social_set', 'defined') + | map(attribute='social_set') | select | unique + | reject('in', openpost_crossposter_social_sets.json | map(attribute='name') | list) + | list }} + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/crossposter/seed/connect.yml b/roles/web-app-openpost/tasks/crossposter/seed/connect.yml new file mode 100644 index 0000000000..d7df6e9669 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/seed/connect.yml @@ -0,0 +1,56 @@ +--- +- name: "📌 Pick the pinned Mastodon server OpenPost connects through" + ansible.builtin.set_fact: + openpost_crossposter_mastodon_server: "{{ OPENPOST_PINNED_INSTANCES | selectattr('platform', 'equalto', 'mastodon') | map(attribute='name') | first }}" + +- name: "🔍 Resolve the Mastodon container that grants the OpenPost app" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: mastodon + resolve_service_name: "{{ lookup('container_service', 'web-app-mastodon', 'mastodon') if IS_SWARM_MODE else '' }}" + resolve_output_prefix: OPENPOST_SEED_MASTODON + resolve_compose_cid: "{{ lookup('container_address', 'web-app-mastodon', 'mastodon') }}" + +- name: "🧭 Ask OpenPost for the Mastodon authorization it would start" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/accounts/mastodon/auth-url?workspace_id={{ openpost_crossposter_target_workspace }}&server_name={{ openpost_crossposter_mastodon_server | urlencode }}" + headers: "{{ openpost_breakglass_headers }}" + status_code: 200 + register: openpost_crossposter_mastodon_authorize + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🎫 Grant OpenPost's pinned app the code that authorization asks for" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "CROSSPOSTER_ACCOUNT={{ openpost_crossposter_mastodon_route.source.account }}" + - -e + - "CROSSPOSTER_AUTHORIZE={{ openpost_crossposter_mastodon_authorize.json.url }}" + - "{{ OPENPOST_SEED_MASTODON_LOCAL_CID }}" # nocheck: container-exec-resolver + - bin/rails + - runner + - "-" + stdin: "{{ lookup('file', 'ruby/mastodon/grant_authorization.rb') }}" + register: openpost_crossposter_mastodon_grant + changed_when: true + delegate_to: "{{ OPENPOST_SEED_MASTODON_HOST_NODE }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🔁 Exchange the code through OpenPost" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/accounts/mastodon/exchange" + method: POST + headers: "{{ openpost_breakglass_headers }}" + body_format: json + body: + code: "{{ (openpost_crossposter_mastodon_grant.stdout_lines | select('match', 'CROSSPOSTER_GRANT=') | first) | replace('CROSSPOSTER_GRANT=', '') | trim }}" + instance_url: "" + server_name: "{{ openpost_crossposter_mastodon_server }}" + workspace_id: "{{ openpost_crossposter_target_workspace }}" + status_code: [200, 201] + retries: 0 + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/crossposter/seed/mastodon.yml b/roles/web-app-openpost/tasks/crossposter/seed/mastodon.yml new file mode 100644 index 0000000000..8ba1a8fe97 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/seed/mastodon.yml @@ -0,0 +1,40 @@ +--- +- name: "🔍 Resolve the Mastodon container that mints the CI source tokens" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: mastodon + resolve_service_name: "{{ lookup('container_service', 'web-app-mastodon', 'mastodon') if IS_SWARM_MODE else '' }}" + resolve_output_prefix: OPENPOST_SEED_MASTODON + resolve_compose_cid: "{{ lookup('container_address', 'web-app-mastodon', 'mastodon') }}" + +- name: "🔑 Mint a Mastodon token for each CI route" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "CROSSPOSTER_ACCOUNT={{ item.source.account }}" + - "{{ OPENPOST_SEED_MASTODON_LOCAL_CID }}" # nocheck: container-exec-resolver + - bin/rails + - runner + - "-" + stdin: "{{ lookup('file', 'ruby/mastodon/mint_token.rb') }}" + loop: "{{ openpost_crossposter_seed_missing | selectattr('source.platform', 'equalto', 'mastodon') | list }}" + loop_control: + label: "{{ item.name }}" + register: openpost_crossposter_mastodon_minted + changed_when: true + delegate_to: "{{ OPENPOST_SEED_MASTODON_HOST_NODE }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧾 Keep the minted Mastodon tokens" + ansible.builtin.set_fact: + openpost_crossposter_sources: >- + {%- set _minted = dict(openpost_crossposter_sources) -%} + {%- for _result in openpost_crossposter_mastodon_minted.results -%} + {%- set _line = _result.stdout_lines | select('match', 'CROSSPOSTER_TOKEN=') | first -%} + {%- set _ = _minted.update({_result.item.name: _line | replace('CROSSPOSTER_TOKEN=', '') | trim}) -%} + {%- endfor -%} + {{ _minted }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/crossposter/seed/peertube.yml b/roles/web-app-openpost/tasks/crossposter/seed/peertube.yml new file mode 100644 index 0000000000..cd8b121d87 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/seed/peertube.yml @@ -0,0 +1,40 @@ +--- +- name: "🪪 Read the local OAuth client of each PeerTube source" + uri_retry: + url: "{{ item.source.base_url }}/api/v1/oauth-clients/local" + status_code: 200 + loop: "{{ openpost_crossposter_seed_missing | selectattr('source.platform', 'equalto', 'peertube') | list }}" + loop_control: + label: "{{ item.name }}" + register: openpost_crossposter_peertube_clients + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "🔑 Log the administrator into each PeerTube source" + uri_retry: + url: "{{ item.item.source.base_url }}/api/v1/users/token" + method: POST + body_format: form-urlencoded + body: + client_id: "{{ item.json.client_id }}" + client_secret: "{{ item.json.client_secret }}" + grant_type: password + username: "{{ OPENPOST_SEED_PEERTUBE_USERNAME }}" + password: "{{ OPENPOST_SEED_PEERTUBE_PASSWORD }}" + status_code: 200 + loop: "{{ openpost_crossposter_peertube_clients.results }}" + loop_control: + label: "{{ item.item.name }}" + register: openpost_crossposter_peertube_minted + changed_when: true + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "🧾 Keep the minted PeerTube tokens" + ansible.builtin.set_fact: + openpost_crossposter_sources: >- + {%- set _minted = dict(openpost_crossposter_sources) -%} + {%- for _result in openpost_crossposter_peertube_minted.results -%} + {%- set _ = _minted.update({_result.item.item.name: _result.json.access_token}) -%} + {%- endfor -%} + {{ _minted }} diff --git a/roles/web-app-openpost/tasks/crossposter/seed/pixelfed.yml b/roles/web-app-openpost/tasks/crossposter/seed/pixelfed.yml new file mode 100644 index 0000000000..5bc7812565 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/seed/pixelfed.yml @@ -0,0 +1,42 @@ +--- +- name: "🔍 Resolve the Pixelfed container that mints the CI source tokens" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: pixelfed + resolve_service_name: "{{ lookup('container_service', 'web-app-pixelfed', 'pixelfed') if IS_SWARM_MODE else '' }}" + resolve_output_prefix: OPENPOST_SEED_PIXELFED + resolve_compose_cid: "{{ lookup('config', 'web-app-pixelfed', 'services.pixelfed.name') }}" + +- name: "🔑 Mint a Pixelfed personal access token for each CI route" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -u + - "{{ OPENPOST_PIXELFED_PHP_USER }}" + - -e + - "CROSSPOSTER_ACCOUNT={{ item.source.account }}" + - -e + - "PIXELFED_APP_DIR={{ OPENPOST_PIXELFED_APP_DIR }}" + - "{{ OPENPOST_SEED_PIXELFED_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + stdin: "{{ lookup('file', 'php/pixelfed/mint_token.php') }}" + loop: "{{ openpost_crossposter_seed_missing | selectattr('source.platform', 'equalto', 'pixelfed') | list }}" + loop_control: + label: "{{ item.name }}" + register: openpost_crossposter_pixelfed_minted + changed_when: true + delegate_to: "{{ OPENPOST_SEED_PIXELFED_HOST_NODE }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧾 Keep the minted Pixelfed tokens" + ansible.builtin.set_fact: + openpost_crossposter_sources: >- + {%- set _minted = dict(openpost_crossposter_sources) -%} + {%- for _result in openpost_crossposter_pixelfed_minted.results -%} + {%- set _line = _result.stdout_lines | select('match', 'CROSSPOSTER_TOKEN=') | first -%} + {%- set _ = _minted.update({_result.item.name: _line | replace('CROSSPOSTER_TOKEN=', '') | trim}) -%} + {%- endfor -%} + {{ _minted }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/crossposter/seed/target.yml b/roles/web-app-openpost/tasks/crossposter/seed/target.yml new file mode 100644 index 0000000000..4c6b93ef07 --- /dev/null +++ b/roles/web-app-openpost/tasks/crossposter/seed/target.yml @@ -0,0 +1,15 @@ +--- +- name: "🔎 List the accounts connected in the organisation workspace" + uri_retry: + url: "{{ OPENPOST_LOCAL_URL }}/api/v1/accounts?workspace_id={{ openpost_crossposter_target_workspace }}" + headers: "{{ openpost_breakglass_headers }}" + status_code: 200 + register: openpost_crossposter_connected + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🔗 Connect the CI Mastodon account as a crossposting target" + ansible.builtin.include_tasks: crossposter/seed/connect.yml + when: openpost_crossposter_connected.json | selectattr('platform', 'equalto', 'mastodon') | list | length == 0 + vars: + openpost_crossposter_mastodon_route: "{{ OPENPOST_CROSSPOSTER_ROUTES | selectattr('source.platform', 'equalto', 'mastodon') | first }}" diff --git a/roles/web-app-openpost/tasks/fediverse/pixelfed_owner.yml b/roles/web-app-openpost/tasks/fediverse/pixelfed_owner.yml new file mode 100644 index 0000000000..1d0dcb57d6 --- /dev/null +++ b/roles/web-app-openpost/tasks/fediverse/pixelfed_owner.yml @@ -0,0 +1,34 @@ +--- +- name: "🔍 Resolve the Pixelfed container that owns OpenPost's app" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: pixelfed + resolve_service_name: "{{ lookup('container_service', 'web-app-pixelfed', 'pixelfed') if IS_SWARM_MODE else '' }}" + resolve_output_prefix: OPENPOST_PIXELFED + resolve_compose_cid: "{{ lookup('config', 'web-app-pixelfed', 'services.pixelfed.name') }}" + +- name: "👤 Give OpenPost's Pixelfed app an owner so Passport accepts its tokens" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -u + - "{{ OPENPOST_PIXELFED_PHP_USER }}" + - -e + - "OPENPOST_CLIENT_ID={{ openpost_fediverse_apps[item.url].client_id }}" + - -e + - "OPENPOST_CLIENT_OWNER={{ lookup('users', 'platform_administrator').username }}" + - -e + - "PIXELFED_APP_DIR={{ OPENPOST_PIXELFED_APP_DIR }}" + - "{{ OPENPOST_PIXELFED_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + stdin: "{{ lookup('file', 'php/pixelfed/client_owner.php') }}" + loop: "{{ OPENPOST_PINNED_PIXELFED }}" + loop_control: + label: "{{ item.url }}" + register: openpost_pixelfed_app_owner + changed_when: "'OWNER_SET' in openpost_pixelfed_app_owner.stdout" + delegate_to: "{{ OPENPOST_PIXELFED_HOST_NODE }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openpost/tasks/main.yml b/roles/web-app-openpost/tasks/main.yml new file mode 100644 index 0000000000..96aa3b7dc7 --- /dev/null +++ b/roles/web-app-openpost/tasks/main.yml @@ -0,0 +1,3 @@ +--- +- include_tasks: 00_core.yml + when: run_once_web_app_openpost is not defined diff --git a/roles/web-app-openpost/tasks/provider/render.yml b/roles/web-app-openpost/tasks/provider/render.yml new file mode 100644 index 0000000000..ed05869b41 --- /dev/null +++ b/roles/web-app-openpost/tasks/provider/render.yml @@ -0,0 +1,45 @@ +--- +- name: "📁 Ensure the fake provider directory exists" + ansible.builtin.file: + path: "{{ OPENPOST_PROVIDER_DIR }}" + state: directory + mode: "0750" + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "🔑 Hand the fake provider its copy of the simulator key" + ansible.builtin.copy: + src: "{{ [OPENPOST_SIMULATOR_DIR, 'server.key'] | path_join }}" + dest: "{{ OPENPOST_PROVIDER_KEY_HOST }}" + remote_src: true + owner: "{{ OPENPOST_PROVIDER_UID }}" + group: "{{ OPENPOST_PROVIDER_UID }}" + mode: "0400" + delegate_to: "{{ STACK_HOST }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "📦 Stage the fake provider build context" + ansible.builtin.copy: + src: "{{ item.src }}" + dest: "{{ item.dest }}" + mode: preserve + loop: + - src: "{{ role_path }}/files/provider/" + dest: "{{ OPENPOST_PROVIDER_BUILD_CONTEXT }}/" + - src: "{{ role_path }}/files/python/provider/" + dest: "{{ [OPENPOST_PROVIDER_BUILD_CONTEXT, 'provider'] | path_join }}/" + notify: + - compose-build + - compose-up + +- name: "📄 Render the fake provider configuration" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "provider.json.j2" + dest: "{{ OPENPOST_PROVIDER_CONFIG_HOST }}" + mode: "0400" + owner: "{{ OPENPOST_PROVIDER_UID }}" + group: "{{ OPENPOST_PROVIDER_UID }}" diff --git a/roles/web-app-openpost/templates/compose.yml.j2 b/roles/web-app-openpost/templates/compose.yml.j2 new file mode 100644 index 0000000000..39ecb9a9f5 --- /dev/null +++ b/roles/web-app-openpost/templates/compose.yml.j2 @@ -0,0 +1,85 @@ +{% include 'roles/sys-svc-compose/templates/base.yml.j2' %} + {% set service_name = 'openpost' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'openpost') }} + {{ lookup('compose_only', 'container_name', OPENPOST_NAME) }} + {{ lookup('container_ports', ['openpost', 'http', DOCKER_BIND_HOST]) | indent(4) }} + {{ lookup('container_healthcheck', service_name) | indent(4) }} + + {{ lookup('container_depends_on', application_id) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_extra_hosts') | indent(4) }} + {{ lookup('container_networks') | indent(4) }} + + {% set service_name = 'relay' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'relay') }} + {{ lookup('compose_only', 'container_name', OPENPOST_RELAY_NAME) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_extra_hosts', host_alias=True) | indent(4) }} + {{ lookup('container_networks', service_name) | indent(4) }} + + {% if OPENPOST_CROSSPOSTER_ENABLED | bool %} + {% set service_name = 'crossposter' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} + build: + context: "{{ OPENPOST_CROSSPOSTER_BUILD_CONTEXT }}" + dockerfile: Dockerfile + args: + CROSSPOSTER_BASE_IMAGE: "{{ OPENPOST_CROSSPOSTER_BASE_IMAGE }}" + CROSSPOSTER_BASE_VERSION: "{{ OPENPOST_CROSSPOSTER_BASE_VERSION }}" + CROSSPOSTER_UID: "{{ OPENPOST_CROSSPOSTER_UID }}" + {{ lookup('container_image', application_id, service_name, image=OPENPOST_CROSSPOSTER_IMAGE) }} + {{ lookup('compose_only', 'container_name', OPENPOST_CROSSPOSTER_NAME) }} + {{ lookup('compose_only', 'pull_policy', 'never') }} + {{ lookup('compose_restart') }} + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_extra_hosts') | indent(4) }} + {{ lookup('container_networks') | indent(4) }} + {% endif %} + + {% if OPENPOST_SIMULATOR_ENABLED | bool %} + {% set service_name = 'simulator' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} + {{ lookup('container_image', application_id, 'simulator') }} + {{ lookup('compose_only', 'container_name', OPENPOST_SIMULATOR_NAME) }} + {{ lookup('compose_restart') }} + command: + - --https-port + - "{{ lookup('config', application_id, 'services.simulator.ports.internal.https') }}" + - --https-keystore + - "{{ lookup('volume', application_id, 'simulator_keystore').target }}" + - --keystore-type + - PKCS12 + - --disable-banner + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_networks', service_name) | indent(4) }} + {% endif %} + + {% if OPENPOST_PROVIDER_ENABLED | bool %} + {% set service_name = 'provider' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} + build: + context: "{{ OPENPOST_PROVIDER_BUILD_CONTEXT }}" + dockerfile: Dockerfile + args: + PROVIDER_BASE_IMAGE: "{{ OPENPOST_PROVIDER_BASE_IMAGE }}" + PROVIDER_BASE_VERSION: "{{ OPENPOST_PROVIDER_BASE_VERSION }}" + PROVIDER_UID: "{{ OPENPOST_PROVIDER_UID }}" + {{ lookup('container_image', application_id, service_name, image=OPENPOST_PROVIDER_IMAGE) }} + {{ lookup('compose_only', 'container_name', OPENPOST_PROVIDER_NAME) }} + {{ lookup('compose_only', 'pull_policy', 'never') }} + {{ lookup('compose_restart') }} + {{ lookup('container_ports', ['provider', 'http', DOCKER_BIND_HOST]) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_networks', service_name) | indent(4) }} + {% endif %} + +{{ lookup('compose_volumes') }} + +{{ lookup('compose_networks') }} diff --git a/roles/web-app-openpost/templates/crossposter-secrets.json.j2 b/roles/web-app-openpost/templates/crossposter-secrets.json.j2 new file mode 100644 index 0000000000..4a86216c47 --- /dev/null +++ b/roles/web-app-openpost/templates/crossposter-secrets.json.j2 @@ -0,0 +1,10 @@ +{% set _tokens = {} %} +{% for _route in OPENPOST_CROSSPOSTER_ROUTES %} +{% set _ = _tokens.update({_route.name: _route.source.token | default(openpost_crossposter_sources[_route.name] | default('', true), true)}) %} +{% endfor %} +{{ { + 'openpost_token': openpost_crossposter_token, + 'database_dsn': lookup('database', application_id, 'url_full'), + 'mail_password': lookup('email', application_id).password if OPENPOST_EMAIL_ENABLED | bool else '', + 'routes': _tokens +} | to_json }} diff --git a/roles/web-app-openpost/templates/crossposter.json.j2 b/roles/web-app-openpost/templates/crossposter.json.j2 new file mode 100644 index 0000000000..dd1da46793 --- /dev/null +++ b/roles/web-app-openpost/templates/crossposter.json.j2 @@ -0,0 +1,30 @@ +{% set _routes = [] %} +{% for _route in OPENPOST_CROSSPOSTER_ROUTES %} +{% set _ = _routes.append(_route | combine({'source': _route.source | dict2items | rejectattr('key', 'equalto', 'token') | items2dict})) %} +{% endfor %} +{% set _mail = none %} +{% if OPENPOST_EMAIL_ENABLED | bool %} +{% set _email = lookup('email', application_id) %} +{% set _mail = { + 'host': _email.host, + 'port': _email.port | int, + 'security': 'tls' if _email.tls | bool else 'starttls' if _email.start_tls | bool else 'none', + 'user': _email.username, + 'sender': _email['from'] +} %} +{% endif %} +{{ { + 'openpost': { + 'base_url': 'http://openpost:' ~ lookup('config', application_id, 'services.openpost.ports.internal.http'), + 'host': lookup('domain', application_id), + 'workspace': openpost_crossposter_workspace + }, + 'secrets_file': OPENPOST_CROSSPOSTER_SECRETS_TARGET, + 'mail': _mail, + 'heartbeat_file': '/tmp/crossposter-heartbeat', + 'poll_interval_seconds': OPENPOST_CROSSPOSTER.poll_interval_seconds, + 'opt_out_tag': OPENPOST_CROSSPOSTER.opt_out_tag, + 'retry': OPENPOST_CROSSPOSTER.retry, + 'notify': OPENPOST_CROSSPOSTER.notify, + 'routes': _routes +} | to_nice_json }} diff --git a/roles/web-app-openpost/templates/env.j2 b/roles/web-app-openpost/templates/env.j2 new file mode 100644 index 0000000000..8c435dd4ff --- /dev/null +++ b/roles/web-app-openpost/templates/env.j2 @@ -0,0 +1,84 @@ +{% include 'roles/sys-svc-container/templates/env.j2' %} + +OPENPOST_PORT={{ container_port }} +OPENPOST_EDITION=selfhost +OPENPOST_APP_URL={{ OPENPOST_URL }} +OPENPOST_PUBLIC_URL={{ OPENPOST_URL }} +OPENPOST_TRUSTED_PROXY_CIDRS={{ OPENPOST_TRUSTED_PROXY_CIDRS | join(',') }} +OPENPOST_DISABLE_REGISTRATIONS={{ (not (OPENPOST_OIDC_ENABLED | bool)) | string | lower }} +OPENPOST_OAUTH_DYNAMIC_REGISTRATION_ENABLED=false + +OPENPOST_DATABASE_DRIVER=postgres +OPENPOST_DATABASE_URL={{ (lookup('database', application_id, 'url_full') ~ '?sslmode=disable') | dotenv_quote }} + +OPENPOST_JWT_SECRET={{ OPENPOST_JWT_SECRET | dotenv_quote }} +OPENPOST_ENCRYPTION_KEY={{ OPENPOST_ENCRYPTION_KEY | dotenv_quote }} +OPENPOST_MEDIA_SIGNING_KEY={{ OPENPOST_MEDIA_SIGNING_KEY | dotenv_quote }} + +{% if OPENPOST_OBJSTORE_ENABLED | bool %} +OPENPOST_STORAGE_DRIVER=s3 +OPENPOST_S3_ENDPOINT={{ lookup('objstore', application_id, 'public_url') | regex_replace('/[^/]+/?$', '') }} +OPENPOST_S3_REGION={{ lookup('objstore', application_id, 'region') }} +OPENPOST_S3_BUCKET={{ lookup('objstore', application_id, 'bucket') }} +OPENPOST_S3_ACCESS_KEY_ID={{ lookup('objstore', application_id, 'access_key') }} +OPENPOST_S3_SECRET_ACCESS_KEY={{ lookup('objstore', application_id, 'secret_key') | dotenv_quote }} +OPENPOST_S3_PUBLIC_BASE_URL={{ lookup('objstore', application_id, 'public_url') }} +OPENPOST_S3_FORCE_PATH_STYLE=true +{% else %} +OPENPOST_STORAGE_DRIVER=local +OPENPOST_MEDIA_PATH={{ lookup('volume', application_id, 'media').target }} +OPENPOST_MEDIA_URL=/media +{% endif %} + +OPENPOST_DIAGNOSTICS_ENABLED=false +OPENPOST_UPDATE_CHECK_ENABLED=false +OPENPOST_TELEMETRY_ENABLED=false +OPENPOST_FEEDBACK_ENABLED=false +OPENPOST_PUBLIC_PROFILES_ENABLED=false +OPENPOST_STOCK_MEDIA_ENABLED=false +OPENPOST_WORKFLOWS_AI_ENABLED=false + +{% if OPENPOST_OIDC_ENABLED | bool %} +OPENPOST_OIDC_ISSUER={{ OIDC.CLIENT.ISSUER_URL }} +OPENPOST_OIDC_CLIENT_ID={{ OIDC.CLIENT.ID }} +OPENPOST_OIDC_CLIENT_SECRET={{ OIDC.CLIENT.SECRET | dotenv_quote }} +OPENPOST_OIDC_NAME={{ OIDC.BUTTON_TEXT | dotenv_quote }} +OPENPOST_OIDC_SCOPES=openid,profile,email +OPENPOST_OIDC_JIT_ENABLED=true +OPENPOST_OIDC_BOOTSTRAP_ALLOWLIST={{ OPENPOST_BOOTSTRAP_ADMINS | join(',') }} +{% if OPENPOST_OIDC_SOCKS_PROXY | length > 0 %} +http_proxy={{ OPENPOST_OIDC_SOCKS_PROXY }} +{% endif %} +{% endif %} + +{% if OPENPOST_SMTP_ENABLED | bool %} +{% set email = lookup('email', application_id) %} +OPENPOST_EMAIL_PROVIDER=smtp +OPENPOST_EMAIL_FROM={{ email['from'] }} +OPENPOST_SMTP_HOST={{ email.host }} +OPENPOST_SMTP_PORT={{ email.port }} +OPENPOST_SMTP_USERNAME={{ email.username }} +OPENPOST_SMTP_PASSWORD={{ email.password | dotenv_quote }} +OPENPOST_SMTP_TLS_MODE={{ 'tls' if email.tls | bool else 'starttls' }} +{% endif %} + +{% for _platform in ['mastodon', 'pixelfed'] %} +{% set _servers = [] %} +{% for _instance in OPENPOST_PINNED_INSTANCES if _instance.platform == _platform and _instance.url in openpost_fediverse_apps %} +{% set _ = _servers.append({'name': _instance.name, 'instance_url': _instance.url, 'client_id': openpost_fediverse_apps[_instance.url].client_id, 'client_secret': openpost_fediverse_apps[_instance.url].client_secret}) %} +{% endfor %} +{% if _servers %} +{{ _platform | upper }}_SERVERS={{ _servers | to_json(separators=[',', ':']) | dotenv_quote }} +{% endif %} +{% endfor %} + +{% for _provider in ['x', 'threads', 'linkedin'] if _provider in OPENPOST_PROVIDER_CREDENTIALS %} +{{ _provider | upper }}_CLIENT_ID={{ OPENPOST_PROVIDER_CREDENTIALS[_provider].client_id | dotenv_quote }} +{{ _provider | upper }}_CLIENT_SECRET={{ OPENPOST_PROVIDER_CREDENTIALS[_provider].client_secret | dotenv_quote }} +{% endfor %} +{% if OPENPOST_PROVIDER_APPS | length > 0 %} +OPENPOST_PROVIDER_APPS={{ OPENPOST_PROVIDER_APPS | to_json(separators=[',', ':']) | dotenv_quote }} +{% endif %} +{% if OPENPOST_SIMULATOR_ENABLED | bool or OPENPOST_ROOT_CA_TRUSTED | bool %} +SSL_CERT_DIR={{ lookup('volume', application_id, 'root_ca').target | dirname }}:/etc/ssl/certs +{% endif %} diff --git a/roles/web-app-openpost/templates/nginx/echo_routes.conf.j2 b/roles/web-app-openpost/templates/nginx/echo_routes.conf.j2 new file mode 100644 index 0000000000..c5fde8569f --- /dev/null +++ b/roles/web-app-openpost/templates/nginx/echo_routes.conf.j2 @@ -0,0 +1,11 @@ +{% set sso_proxy_enabled = lookup('sso', application_id, 'is_proxy_gated') %} +{% set location = '~ "^/api/v1/(media/(upload|batch-upload|metadata|upload-session/[^/]+/content)|auth/profile/avatar|admin/backup(/.*)?)$"' %} +{% set proxy_x_forwarded_proto = 'http' %} +{% set webserver_location_extra_configuration %} + set $openpost_origin $http_origin; + if ($http_origin = "https://$host") { + set $openpost_origin "http://$host"; + } + proxy_set_header Origin $openpost_origin; +{% endset %} +{% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} diff --git a/roles/web-app-openpost/templates/playwright.env.j2 b/roles/web-app-openpost/templates/playwright.env.j2 new file mode 100644 index 0000000000..ed3d2be3ae --- /dev/null +++ b/roles/web-app-openpost/templates/playwright.env.j2 @@ -0,0 +1,69 @@ +ADMIN_EMAIL={{ lookup('users', 'platform_administrator').email | dotenv_quote }} + +ADMIN_PASSWORD={{ lookup('users', 'platform_administrator').password | dotenv_quote }} + +ADMIN_USERNAME={{ lookup('users', 'platform_administrator').username | dotenv_quote }} + +APP_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} + +BIBER_PASSWORD={{ lookup('users', 'biber').password | dotenv_quote }} + +BIBER_USERNAME={{ lookup('users', 'biber').username | dotenv_quote }} + +BREAKGLASS_EMAIL={{ OPENPOST_ADMIN_EMAIL | dotenv_quote }} + +BREAKGLASS_PASSWORD={{ OPENPOST_ADMIN_PASSWORD | dotenv_quote }} + +CANONICAL_DOMAIN={{ lookup('domain', application_id) | dotenv_quote }} + +CROSSPOSTER_SERVICE_ENABLED={{ OPENPOST_CROSSPOSTER_ENABLED | string | lower }} + +# nocheck: playwright-service-gate +DASHBOARD_SERVICE_ENABLED={{ lookup('config', application_id, 'services.dashboard.enabled') | string | lower }} + +# nocheck: playwright-service-gate +DESIGN_SERVICE_ENABLED={{ lookup('config', application_id, 'services.design.enabled') | string | lower }} + +# nocheck: playwright-service-gate +EMAIL_SERVICE_ENABLED={{ OPENPOST_EMAIL_ENABLED | string | lower }} + +LINKEDIN_FAKE_URL={{ (OPENPOST_PROVIDER_BROWSER_URL if OPENPOST_PROVIDER_ENABLED | bool else '') | dotenv_quote }} + +# nocheck: playwright-service-gate +LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} + +MASTODON_BASE_URL={{ lookup('landing_url', 'web-app-mastodon') | dotenv_quote }} + +MASTODON_SERVICE_ENABLED={{ lookup('config', application_id, 'services.mastodon.enabled') | string | lower }} + +MATOMO_BASE_URL={{ lookup('landing_url', 'web-app-matomo') | dotenv_quote }} + +# nocheck: playwright-service-gate +MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} + +OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} + +ORGANISATION_WORKSPACE={{ OPENPOST_ORGANISATION_WORKSPACE | dotenv_quote }} + +PIXELFED_BASE_URL={{ lookup('landing_url', 'web-app-pixelfed') | dotenv_quote }} + +PIXELFED_SERVICE_ENABLED={{ lookup('config', application_id, 'services.pixelfed.enabled') | string | lower }} + +# nocheck: playwright-service-gate +PROMETHEUS_SERVICE_ENABLED={{ lookup('config', application_id, 'services.prometheus.enabled') | string | lower }} + +PROVIDER_SERVICE_ENABLED={{ OPENPOST_PROVIDER_ENABLED | string | lower }} + +SEAWEEDFS_APP_ACCESS_KEY={{ lookup('objstore', application_id, 'access_key') | dotenv_quote }} + +SEAWEEDFS_APP_BUCKET={{ lookup('objstore', application_id, 'bucket') | dotenv_quote }} + +SEAWEEDFS_APP_SECRET_KEY={{ lookup('objstore', application_id, 'secret_key') | dotenv_quote }} + +SEAWEEDFS_REGION={{ lookup('config', 'web-svc-seaweedfs', 'services.seaweedfs.region') }} + +SEAWEEDFS_S3_URL={{ lookup('canonical_url', 'web-svc-seaweedfs', 'api', consumer=application_id) | dotenv_quote }} + +SEAWEEDFS_SERVICE_ENABLED={{ lookup('config', application_id, 'services.seaweedfs.enabled') | string | lower }} + +SSO_SERVICE_ENABLED={{ OPENPOST_OIDC_ENABLED | string | lower }} diff --git a/roles/web-app-openpost/templates/provider.json.j2 b/roles/web-app-openpost/templates/provider.json.j2 new file mode 100644 index 0000000000..eac10e171d --- /dev/null +++ b/roles/web-app-openpost/templates/provider.json.j2 @@ -0,0 +1,15 @@ +{{ { + 'http_port': OPENPOST_PROVIDER.ports.internal.http, + 'https_port': OPENPOST_PROVIDER.ports.internal.https, + 'certificate': lookup('volume', application_id, 'provider_certificate').target, + 'key': lookup('volume', application_id, 'provider_key').target, + 'linkedin': { + 'clients': { + OPENPOST_PROVIDER_CREDENTIALS.linkedin.client_id: { + 'secret': OPENPOST_PROVIDER_CREDENTIALS.linkedin.client_secret, + 'name': 'OpenPost', + 'redirect_uris': [OPENPOST_LINKEDIN_CALLBACK], + }, + }, + }, +} | to_nice_json }} diff --git a/roles/web-app-openpost/templates/relay.conf.j2 b/roles/web-app-openpost/templates/relay.conf.j2 new file mode 100644 index 0000000000..65060ad611 --- /dev/null +++ b/roles/web-app-openpost/templates/relay.conf.j2 @@ -0,0 +1,44 @@ +worker_processes 1; +error_log /dev/stderr warn; + +events { + worker_connections 1024; +} + +stream { + log_format relay '$remote_addr sni=$ssl_preread_server_name upstream=$upstream_addr status=$status'; + access_log /dev/stdout relay; + map_hash_bucket_size 128; + + upstream shared_proxy { + server {{ OPENPOST_RELAY_UPSTREAM_HOST }}:{{ OPENPOST_RELAY_UPSTREAM_PORT }}; + } + + upstream shared_proxy_http { + server {{ OPENPOST_RELAY_UPSTREAM_HOST }}:{{ OPENPOST_RELAY_UPSTREAM_HTTP_PORT }}; + } + + upstream refused { + server 127.0.0.1:9; + } + + map $ssl_preread_server_name $relay_upstream { +{% for domain in OPENPOST_RELAY_DOMAINS %} + {{ domain }} shared_proxy; +{% endfor %} + default refused; + } + + server { + listen {{ lookup('config', application_id, 'services.relay.ports.internal.https') }}; + ssl_preread on; + proxy_pass $relay_upstream; + proxy_connect_timeout 5s; + } + + server { + listen {{ lookup('config', application_id, 'services.relay.ports.internal.http') }}; + proxy_pass shared_proxy_http; + proxy_connect_timeout 5s; + } +} diff --git a/roles/web-app-openpost/templates/test.env.j2 b/roles/web-app-openpost/templates/test.env.j2 new file mode 100644 index 0000000000..8faddd3b11 --- /dev/null +++ b/roles/web-app-openpost/templates/test.env.j2 @@ -0,0 +1,48 @@ +{% set _view = hostvars[STACK_HOST].openpost_public_view %} +{% set _node_local_cid = '"$(container ps -q --filter label=com.docker.swarm.service.name=%s --filter status=running)"' %} +OPENPOST_ADMIN_EMAIL={{ OPENPOST_ADMIN_EMAIL }} +OPENPOST_ADMIN_PASSWORD_B64={{ OPENPOST_ADMIN_PASSWORD | b64encode }} +OPENPOST_API_HEADERS_B64={{ _view.api_headers | to_json | b64encode }} +OPENPOST_CONTAINER={{ CLI_LOCAL_CID }} +OPENPOST_DEADLINE_SECONDS={{ lookup('timeout', 600) | int }} +OPENPOST_LOCAL_URL={{ OPENPOST_LOCAL_URL }} +OPENPOST_PROVIDER_URL={{ OPENPOST_PROVIDER_LOCAL_URL if OPENPOST_PROVIDER_ENABLED | bool else '' }} +OPENPOST_PUBLIC_URL={{ _view.public_url }} +OPENPOST_PROXY_ADDRESS={{ _view.proxy_address }} +OPENPOST_SSO_ENABLED={{ OPENPOST_OIDC_ENABLED | bool | string | lower }} +OPENPOST_RELAY_TARGETS='{{ _view.relay_targets | to_json }}' +OPENPOST_RELAY_PORT={{ lookup('config', application_id, 'services.relay.ports.internal.https') }} +{% set _platforms = [] %} +{% for _provider in (lookup('config', application_id, 'services.simulator.providers') if OPENPOST_SIMULATOR_ENABLED | bool else []) %} +{% set _ = _platforms.extend(OPENPOST_PROVIDER_APP_KEYS[_provider] if _provider in OPENPOST_PROVIDER_APP_KEYS else [_provider]) %} +{% endfor %} +OPENPOST_SIMULATOR_PLATFORMS='{{ _platforms | to_json }}' +{% set _unconfigured = [] %} +{% for _provider in ['x', 'meta', 'threads', 'linkedin', 'youtube', 'tiktok'] if _provider not in OPENPOST_PROVIDER_CREDENTIALS %} +{% set _ = _unconfigured.extend(OPENPOST_PROVIDER_APP_KEYS[_provider] if _provider in OPENPOST_PROVIDER_APP_KEYS else [_provider]) %} +{% endfor %} +OPENPOST_UNCONFIGURED_PLATFORMS='{{ _unconfigured | to_json }}' +OPENPOST_S3_PUBLIC_URL={{ _view.s3_public_url }} +OPENPOST_SIMULATOR_HOST={{ OPENPOST_SIMULATOR_HOSTS | first }} +OPENPOST_DB_CONTAINER={{ (_node_local_cid | format(lookup('database', application_id, 'service_name'))) if IS_SWARM_MODE else lookup('database', application_id, 'address') }} +OPENPOST_DB_NAME={{ lookup('database', application_id, 'name') }} +OPENPOST_DB_USER={{ lookup('database', application_id, 'username') }} +OPENPOST_DB_PASSWORD_B64={{ lookup('database', application_id, 'password') | b64encode }} +OPENPOST_PEERTUBE_USERNAME={{ OPENPOST_SEED_PEERTUBE_USERNAME }} +OPENPOST_PEERTUBE_PASSWORD_B64={{ OPENPOST_SEED_PEERTUBE_PASSWORD | b64encode }} +OPENPOST_MEMBER_MAILBOX={{ lookup('users', 'platform_administrator').email }} +OPENPOST_SSO_ADMIN_EMAIL={{ OPENPOST_BOOTSTRAP_ADMINS | first if OPENPOST_OIDC_ENABLED | bool else '' }} +OPENPOST_MAIL_RECIPIENT={{ OPENPOST_BOOTSTRAP_ADMINS | first if OPENPOST_EMAIL_ENABLED | bool else '' }} +OPENPOST_SMTP_ENABLED={{ _view.smtp_enabled | bool | string | lower }} +OPENPOST_CROSSPOSTER_ROUTES_B64={{ _view.routes | to_json | b64encode }} +OPENPOST_CROSSPOSTER_POLL_SECONDS={{ OPENPOST_CROSSPOSTER.poll_interval_seconds }} +OPENPOST_CROSSPOSTER_RETRY_SECONDS={{ (OPENPOST_CROSSPOSTER.retry.max_attempts | int) * (OPENPOST_CROSSPOSTER.retry.cap_seconds | int) }} +{% if OPENPOST_CROSSPOSTER_ENABLED | bool %} +OPENPOST_CROSSPOSTER_SECRETS_FILE={{ OPENPOST_CROSSPOSTER_SECRETS_HOST }} +OPENPOST_CROSSPOSTER_CONTAINER={{ (_node_local_cid | format(lookup('container_service', application_id, 'crossposter'))) if IS_SWARM_MODE else OPENPOST_CROSSPOSTER_ADDRESS }} +OPENPOST_CROSSPOSTER_CONFIG={{ OPENPOST_CROSSPOSTER_CONFIG_TARGET }} +{% else %} +OPENPOST_CROSSPOSTER_SECRETS_FILE= +OPENPOST_CROSSPOSTER_CONTAINER= +OPENPOST_CROSSPOSTER_CONFIG= +{% endif %} diff --git a/roles/web-app-openpost/vars/main.yml b/roles/web-app-openpost/vars/main.yml new file mode 100644 index 0000000000..a6bd0ff0e7 --- /dev/null +++ b/roles/web-app-openpost/vars/main.yml @@ -0,0 +1,139 @@ +--- +application_id: "web-app-openpost" +container_port: "{{ lookup('config', application_id, 'services.openpost.ports.internal.http') }}" + +OPENPOST_NAME: "{{ lookup('config', application_id, 'services.openpost.name') }}" +OPENPOST_RELAY_NAME: "{{ lookup('config', application_id, 'services.relay.name') }}" +OPENPOST_URL: "{{ lookup('tls', application_id, 'url.origin') }}" +OPENPOST_LOCAL_HOST: "{{ DOCKER_REACH_HOST if IS_COMPOSE_MODE else '127.0.0.1' }}" +OPENPOST_LOCAL_URL: "http://{{ OPENPOST_LOCAL_HOST }}:{{ lookup('config', application_id, 'services.openpost.ports.local.http') }}" +OPENPOST_API_HEADERS: + Host: "{{ lookup('domain', application_id) }}" + X-Forwarded-Proto: "{{ OPENPOST_URL | urlsplit('scheme') }}" +OPENPOST_RELAY_CONF_HOST: "{{ [lookup('container', application_id, 'directories.config'), 'relay.conf'] | path_join }}" + +OPENPOST_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" +OPENPOST_OIDC_ONION_ISSUER: "{{ lookup('tls', 'web-app-keycloak', 'domain').endswith('.onion') }}" +OPENPOST_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if OPENPOST_OIDC_ONION_ISSUER | bool else '' }}" +OPENPOST_EMAIL_ENABLED: "{{ lookup('config', application_id, 'services.email.enabled') }}" +OPENPOST_SMTP_ENABLED: "{{ OPENPOST_EMAIL_ENABLED | bool and (lookup('email', application_id).tls | bool or lookup('email', application_id).start_tls | bool) }}" +OPENPOST_OBJSTORE_ENABLED: "{{ lookup('objstore', application_id, 'enabled') }}" +OPENPOST_ROOT_CA_TRUSTED: "{{ OPENPOST_OBJSTORE_ENABLED | bool and TLS_MODE == 'self_signed' }}" + +OPENPOST_JWT_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.jwt_secret') }}" +OPENPOST_ENCRYPTION_KEY: "{{ lookup('config', application_id, 'secrets.credentials.encryption_key') }}" +OPENPOST_MEDIA_SIGNING_KEY: "{{ lookup('config', application_id, 'secrets.credentials.media_signing_key') }}" + +OPENPOST_TRUSTED_PROXY_CIDRS: >- + {%- set _cidrs = [] -%} + {%- for _entry in NETWORK_TRUSTED_PROXY_CIDRS + [lookup('config', application_id, 'networks.local.subnet')] -%} + {%- set _ = _cidrs.append(_entry if '/' in _entry else _entry ~ ('/128' if ':' in _entry else '/32')) -%} + {%- endfor -%} + {{ _cidrs }} + +OPENPOST_ADMIN_USERNAME: "{{ lookup('users', 'web-app-openpost-breakglass').username }}" +OPENPOST_ADMIN_PASSWORD: "{{ lookup('users', 'web-app-openpost-breakglass').password }}" +OPENPOST_ADMIN_EMAIL: "{{ lookup('users', 'platform_administrator').email | regex_replace('@', '+' ~ OPENPOST_ADMIN_USERNAME ~ '@') }}" +OPENPOST_ORGANISATION_WORKSPACE: "{{ SOFTWARE_NAME }}" + +OPENPOST_BOOTSTRAP_ADMINS: + - "{{ lookup('users', 'platform_administrator').email }}" + +OPENPOST_RELAY_SIBLINGS: "{{ lookup('config', application_id, 'services.relay.siblings') }}" +OPENPOST_RELAY_DOMAINS: "{{ lookup('config', application_id, 'services.relay.network_aliases') }}" +OPENPOST_PINNED_INSTANCES: >- + {%- set _instances = [] -%} + {%- for _key in ['mastodon', 'pixelfed'] -%} + {%- if lookup('config', application_id, 'services.' ~ _key ~ '.enabled') | bool -%} + {%- set _url = lookup('tls', OPENPOST_RELAY_SIBLINGS[_key], 'url.origin') -%} + {%- if _url is not search('\\.onion$') -%} + {%- set _ = _instances.append({'platform': _key, 'url': _url, 'name': _url ~ '/'}) -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {{ _instances }} +OPENPOST_PINNED_PIXELFED: "{{ OPENPOST_PINNED_INSTANCES | selectattr('platform', 'equalto', 'pixelfed') | list }}" +OPENPOST_FEDIVERSE_APPS_HOST: "{{ [lookup('container', application_id, 'directories.config'), 'fediverse-apps.json'] | path_join }}" +OPENPOST_RELAY_UPSTREAM_HOST: "host.docker.internal" +OPENPOST_RELAY_UPSTREAM_PORT: "{{ lookup('config', 'svc-prx-openresty', 'services.openresty.ports.public.https') }}" +OPENPOST_RELAY_UPSTREAM_HTTP_PORT: "{{ lookup('config', 'svc-prx-openresty', 'services.openresty.ports.public.http') }}" + +OPENPOST_SIMULATOR_ENABLED: "{{ lookup('config', application_id, 'services.simulator.enabled') | bool }}" +OPENPOST_SIMULATOR_NAME: "{{ lookup('config', application_id, 'services.simulator.name') }}" +OPENPOST_SIMULATOR_DIR: "{{ [lookup('container', application_id, 'directories.config'), 'simulator'] | path_join }}" +OPENPOST_SIMULATOR_HOSTS: "{{ lookup('config', application_id, 'services.simulator.network_aliases') }}" +OPENPOST_PROVIDER: "{{ lookup('config', application_id, 'services.provider') }}" +OPENPOST_PROVIDER_ENABLED: "{{ lookup('config', application_id, 'services.provider.enabled') | bool }}" +OPENPOST_PROVIDER_NAME: "{{ OPENPOST_PROVIDER.name }}" +OPENPOST_PROVIDER_UID: "{{ OPENPOST_PROVIDER.uid }}" +OPENPOST_PROVIDER_HOSTS: "{{ OPENPOST_PROVIDER.network_aliases }}" +OPENPOST_PROVIDER_DIR: "{{ [lookup('container', application_id, 'directories.config'), 'provider'] | path_join }}" +OPENPOST_PROVIDER_CONFIG_HOST: "{{ [OPENPOST_PROVIDER_DIR, 'provider.json'] | path_join }}" +OPENPOST_PROVIDER_KEY_HOST: "{{ [OPENPOST_PROVIDER_DIR, 'server.key'] | path_join }}" +OPENPOST_PROVIDER_BUILD_CONTEXT: "{{ [lookup('container', application_id, 'directories.services'), 'provider'] | path_join }}" +OPENPOST_PROVIDER_IMAGE: "openpost_provider_custom" +OPENPOST_PROVIDER_BASE_IMAGE: "{{ OPENPOST_PROVIDER.image }}" +OPENPOST_PROVIDER_BASE_VERSION: "{{ OPENPOST_PROVIDER.version }}" +OPENPOST_PROVIDER_LOCAL_URL: "http://{{ OPENPOST_LOCAL_HOST }}:{{ OPENPOST_PROVIDER.ports.local.http }}" +OPENPOST_PROVIDER_BROWSER_URL: "http://{{ 'host.docker.internal' if IS_COMPOSE_MODE else '127.0.0.1' }}:{{ OPENPOST_PROVIDER.ports.local.http }}" +OPENPOST_LINKEDIN_CALLBACK: "{{ OPENPOST_URL }}/api/v1/accounts/linkedin/callback" +OPENPOST_SIMULATOR_KEYSTORE_PASSWORD: "password" + +OPENPOST_PROVIDER_CREDENTIALS: >- + {%- set _credentials = {} -%} + {%- for _provider in ['x', 'meta', 'threads', 'linkedin', 'youtube', 'tiktok'] -%} + {%- if OPENPOST_SIMULATOR_ENABLED | bool and _provider in lookup('config', application_id, 'services.simulator.providers') -%} + {%- set _ = _credentials.update({_provider: {'client_id': 'simulator-' ~ _provider, 'client_secret': 'simulator-' ~ _provider ~ '-secret'}}) -%} + {%- elif lookup('api_enabled', _provider) -%} + {%- set _ = _credentials.update({_provider: {'client_id': lookup('api', _provider ~ '.client_id'), 'client_secret': lookup('api', _provider ~ '.client_secret')}}) -%} + {%- endif -%} + {%- endfor -%} + {{ _credentials }} +OPENPOST_PROVIDER_APP_KEYS: + meta: + - facebook + - instagram + youtube: + - youtube + tiktok: + - tiktok +OPENPOST_PROVIDER_APPS: >- + {%- set _apps = [] -%} + {%- for _provider, _keys in OPENPOST_PROVIDER_APP_KEYS.items() if _provider in OPENPOST_PROVIDER_CREDENTIALS -%} + {%- for _key in _keys -%} + {%- set _ = _apps.append({'provider': _key} | combine(OPENPOST_PROVIDER_CREDENTIALS[_provider])) -%} + {%- endfor -%} + {%- endfor -%} + {{ _apps }} + +OPENPOST_CROSSPOSTER: "{{ lookup('config', application_id, 'services.crossposter') }}" +OPENPOST_CROSSPOSTER_ROUTES: >- + {%- set _routes = [] -%} + {%- for _route in OPENPOST_CROSSPOSTER.routes + if lookup('config', application_id, 'services.' ~ _route.source.platform ~ '.enabled') | bool -%} + {%- set _ = _routes.append(_route) -%} + {%- endfor -%} + {{ _routes }} +OPENPOST_CROSSPOSTER_ENABLED: "{{ lookup('config', application_id, 'services.crossposter.enabled') | bool }}" +OPENPOST_CROSSPOSTER_NAME: "{{ OPENPOST_CROSSPOSTER.name }}" +OPENPOST_CROSSPOSTER_UID: "{{ OPENPOST_CROSSPOSTER.uid }}" +OPENPOST_CROSSPOSTER_TOKEN_NAME: "crossposter" +OPENPOST_CROSSPOSTER_DIR: "{{ [lookup('container', application_id, 'directories.config'), 'crossposter'] | path_join }}" +OPENPOST_CROSSPOSTER_STATE_FILE: "{{ [OPENPOST_CROSSPOSTER_DIR, 'state.json'] | path_join }}" +OPENPOST_CROSSPOSTER_CONFIG_HOST: "{{ [OPENPOST_CROSSPOSTER_DIR, 'crossposter.json'] | path_join }}" +OPENPOST_CROSSPOSTER_SECRETS_HOST: "{{ [OPENPOST_CROSSPOSTER_DIR, 'crossposter-secrets.json'] | path_join }}" +OPENPOST_CROSSPOSTER_CONFIG_TARGET: "{{ lookup('volume', application_id, 'crossposter_config').target }}" +OPENPOST_CROSSPOSTER_SECRETS_TARGET: "{{ lookup('volume', application_id, 'crossposter_secrets').target }}" +OPENPOST_CROSSPOSTER_BUILD_CONTEXT: "{{ [lookup('container', application_id, 'directories.services'), 'crossposter'] | path_join }}" +OPENPOST_CROSSPOSTER_IMAGE: "openpost_crossposter_custom" +OPENPOST_CROSSPOSTER_BASE_IMAGE: "{{ OPENPOST_CROSSPOSTER.image }}" +OPENPOST_CROSSPOSTER_BASE_VERSION: "{{ OPENPOST_CROSSPOSTER.version }}" +OPENPOST_CROSSPOSTER_ADDRESS: "{{ lookup('container_address', application_id, 'crossposter') }}" +OPENPOST_CROSSPOSTER_SEED_PROBES: + mastodon: /api/v1/accounts/verify_credentials + pixelfed: /api/v1/accounts/verify_credentials + peertube: /api/v1/users/me +OPENPOST_PIXELFED_PHP_USER: "33" +OPENPOST_PIXELFED_APP_DIR: "{{ lookup('volume', 'web-app-pixelfed', 'data').target | dirname }}" +OPENPOST_SEED_PEERTUBE_USERNAME: "root" +OPENPOST_SEED_PEERTUBE_PASSWORD: "{{ (lookup('users', 'platform_administrator').password | string)[:50] }}" diff --git a/roles/web-app-pixelfed/templates/env.j2 b/roles/web-app-pixelfed/templates/env.j2 index df3c2c92f3..884522bb5c 100644 --- a/roles/web-app-pixelfed/templates/env.j2 +++ b/roles/web-app-pixelfed/templates/env.j2 @@ -6,7 +6,7 @@ APP_KEY={{ lookup('config', application_id, 'secrets.credentials.app_key')}} APP_NAME="{{ PIXELFED_TITLE }}" APP_ENV={{ ENVIRONMENT | lower }} APP_DEBUG={{MODE_DEBUG | string | lower }} -APP_URL={{ lookup('tls', application_id, 'url.base') }} +APP_URL={{ lookup('tls', application_id, 'url.origin') }} FORCE_HTTPS_URLS={{ lookup('tls', application_id, 'enabled') | string | lower }} APP_DOMAIN={{ lookup('domain',application_id) }} ADMIN_DOMAIN={{ lookup('domain',application_id) }} diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 7dcdd200d5..32c1dc4a04 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -160,6 +160,12 @@ account (or the Keycloak SSO token when SSO is enabled). (`templates/jmap/*.json.j2`). - **Only authenticated sessions relay, with or without SSO.** Under SSO a bot authenticates with an app password. +- **Authenticated submissions skip the recipient throttle.** Stalwart's default + inbound throttle allows 25 mails per hour from one sender domain to one + recipient, and plus-addresses share their base address's budget. The role + limits it to unauthenticated sessions (`STALWART_RCPT_THROTTLE_RULE`, + `tasks/throttle.yml`), so the platform's own `no-reply` mail to the + administrator, alerts included, is never deferred with `452 4.4.5`. - **Accounts, app passwords and forwards are provisioned in batches.** Each phase (create, password update, app password list, mint, retire, drop, forward script list, read, upload, activate) is one JMAP request for all diff --git a/roles/web-app-stalwart/tasks/manager_ops.yml b/roles/web-app-stalwart/tasks/manager_ops.yml index ce1486c0ec..585e4f51aa 100644 --- a/roles/web-app-stalwart/tasks/manager_ops.yml +++ b/roles/web-app-stalwart/tasks/manager_ops.yml @@ -31,6 +31,9 @@ - name: "⏱️ Let Stalwart's address bans expire" include_tasks: security.yml +- name: "📮 Keep authenticated submissions out of the recipient throttle" + include_tasks: throttle.yml + - name: "⚙️ Provision the Stalwart WebUI (WebAdmin) bundle" include_tasks: 02_webadmin.yml diff --git a/roles/web-app-stalwart/tasks/security/apply.yml b/roles/web-app-stalwart/tasks/security/apply.yml index 016c530801..dc037b347d 100644 --- a/roles/web-app-stalwart/tasks/security/apply.yml +++ b/roles/web-app-stalwart/tasks/security/apply.yml @@ -34,8 +34,4 @@ - name: "🔄 Reload Stalwart's settings" include_tasks: "{{ role_path }}/tasks/jmap_call.yml" vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Action/set', - {'create': {'a': {'@type': 'ReloadSettings'}}}, - 'c0']]} | to_json }} + stalwart_jmap_body: "{{ STALWART_JMAP_RELOAD_SETTINGS }}" diff --git a/roles/web-app-stalwart/tasks/throttle.yml b/roles/web-app-stalwart/tasks/throttle.yml new file mode 100644 index 0000000000..d1994927d2 --- /dev/null +++ b/roles/web-app-stalwart/tasks/throttle.yml @@ -0,0 +1,34 @@ +--- +- name: "📖 Read Stalwart's inbound throttles" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:MtaInboundThrottle/get', {'ids': none}, 'c0']]} | to_json }} + +- name: "🔍 Resolve the recipient throttles that still count authenticated submissions" + ansible.builtin.set_fact: + stalwart_rcpt_throttle_ids: >- + {{ stalwart_jmap.methodResponses[0][1].list + | selectattr('key', 'equalto', STALWART_RCPT_THROTTLE_KEY) + | rejectattr('match.else', 'equalto', STALWART_RCPT_THROTTLE_RULE) + | map(attribute='id') + | list }} + +- name: "📮 Keep authenticated submissions out of the recipient throttle" + when: stalwart_rcpt_throttle_ids | length > 0 + block: + - name: "🔧 Count only unauthenticated sessions against the recipient throttle" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:MtaInboundThrottle/set', + {'update': dict(stalwart_rcpt_throttle_ids + | zip([{'match': {'else': STALWART_RCPT_THROTTLE_RULE}}] * (stalwart_rcpt_throttle_ids | length)))}, + 'c0']]} | to_json }} + + - name: "🔄 Reload Stalwart's settings" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ STALWART_JMAP_RELOAD_SETTINGS }}" diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index 8e33484388..0552a8f0f0 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -26,6 +26,9 @@ STALWART_BAN_TRACER: STALWART_JMAP_APPLICATION_GET: >- {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], 'methodCalls': [['x:Application/get', {'ids': none}, 'c0']]} | to_json }} +STALWART_JMAP_RELOAD_SETTINGS: >- + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], + 'methodCalls': [['x:Action/set', {'create': {'a': {'@type': 'ReloadSettings'}}}, 'c0']]} | to_json }} STALWART_JMAP_TRANSIENT_ERRORS: - serverUnavailable - rateLimit @@ -106,6 +109,10 @@ STALWART_BOT_APP_PASSWORD_DESCRIPTION: "Infinito.Nexus submission" STALWART_BOT_APP_PASSWORD_RETIRED_DESCRIPTION: "Infinito.Nexus submission, retired" stalwart_app_password_stale: {} STALWART_RELAY_RULE: "!is_empty(authenticated_as)" +STALWART_RCPT_THROTTLE_KEY: + senderDomain: true + rcpt: true +STALWART_RCPT_THROTTLE_RULE: "is_empty(authenticated_as)" STALWART_BAN_PERIOD_MS: "{{ (lookup('config', application_id, 'services.stalwart.ban_period_seconds') | int) * 1000 }}" STALWART_BAN_PERIODS: diff --git a/roles/web-app-wazuh/meta/services.yml b/roles/web-app-wazuh/meta/services.yml index 377b0e4c2e..062cfe8377 100644 --- a/roles/web-app-wazuh/meta/services.yml +++ b/roles/web-app-wazuh/meta/services.yml @@ -75,7 +75,7 @@ certs_generator: pids_limit: 128 manager: image: wazuh/wazuh-manager - version: "4.14.10" + version: "4.14.11" name: wazuh.manager # nocheck: min-storage-headroom Reason: budgets room for wazuh-manager's own operational data (var-ossec logs, alerts, agent queue/state) to grow well beyond the base image over the service's lifetime, not just the image itself. min_storage: 10GB @@ -105,7 +105,7 @@ indexer: # nocheck: healthcheck-timing-override covers the indexer's real boot without waiting out the curl flavor's 10m default, which would otherwise stall manager/dashboard's startup order far longer than the indexer actually needs. start_period: 90s image: wazuh/wazuh-indexer - version: "4.14.10" + version: "4.14.11" name: wazuh.indexer # nocheck: min-storage-headroom Reason: budgets room for the OpenSearch index data (security events/alerts Wazuh continuously ingests) to grow well beyond the base image over the service's lifetime, not just the image itself. min_storage: 20GB @@ -123,7 +123,7 @@ indexer: http: 8102 console: image: wazuh/wazuh-dashboard - version: "4.14.10" + version: "4.14.11" name: wazuh.dashboard # nocheck: min-storage-headroom Reason: budgets room for the dashboard's own runtime state (OpenSearch Dashboards bundle/build cache rebuilt on first boot, plus exported reports and saved-object data) to grow beyond the base image, not just the image itself. min_storage: 2GB diff --git a/roles/web-svc-libretranslate/tasks/00_core.yml b/roles/web-svc-libretranslate/tasks/00_core.yml index fa3a4307fa..57b2064c20 100644 --- a/roles/web-svc-libretranslate/tasks/00_core.yml +++ b/roles/web-svc-libretranslate/tasks/00_core.yml @@ -10,7 +10,7 @@ include_role: name: sys-stk-full -- name: "📦 Stage the model prefetch and the gunicorn worker-exit hook of {{ application_id }}" +- name: "📦 Stage the model prefetch and worker-exit hook of {{ application_id }}" stack_host_copy: src: "python/{{ item }}" dest: "{{ [lookup('container', application_id, 'directories.instance'), item] | path_join }}" diff --git a/scripts/tests/e2e/rerun-spec.sh b/scripts/tests/e2e/rerun-spec.sh index 29c12efb30..e77cdea08d 100755 --- a/scripts/tests/e2e/rerun-spec.sh +++ b/scripts/tests/e2e/rerun-spec.sh @@ -203,7 +203,7 @@ for sub in addons fixtures; do done run=(docker run --rm - --ipc=host --shm-size=1g + --ipc=host --shm-size=1g --ulimit=core=0 "${net_args[@]}" --env-file "$env_file" -e "INFINITO_PLAYWRIGHT_KEEP=${INFINITO_PLAYWRIGHT_KEEP:-}" diff --git a/tests/external/roles/test_openpost_netguard_allowlist.py b/tests/external/roles/test_openpost_netguard_allowlist.py new file mode 100644 index 0000000000..05c5de156a --- /dev/null +++ b/tests/external/roles/test_openpost_netguard_allowlist.py @@ -0,0 +1,99 @@ +"""The pinned OpenPost still offers no switch to allow private networks. + +web-app-openpost sends OpenPost's requests to its sibling roles through a +relay on 192.88.99.0/24, a block outside the role subnet pool, because +OpenPost's netguard refuses every private address and offers no switch +(infinito-nexus/core#2867, getopenpost/openpost#533). Once the pinned OpenPost +reads such a switch, the relay and the out-of-pool subnet are obsolete, and +this test fails so the workaround goes instead of outliving its reason. + +The switch would live in the upstream repository at the pinned tag, so the +check is external: it fetches OpenPost's config loader of that tag from +raw.githubusercontent.com and looks for any ``OPENPOST_*PRIVATE*`` variable, +because the name may change during upstream review. A refused connection, a +timeout, a rate limit or a server error skips it as unverified; any other +status than 200 fails it. +""" + +from __future__ import annotations + +import re +import unittest + +import requests + +from utils.annotations.message import warning +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_SERVICES = PROJECT_ROOT / "roles/web-app-openpost" / ROLE_FILE_META_SERVICES +_CONFIG_LOADER = "apps/server/internal/config/config.go" +_REGISTRY = "ghcr.io/" +_SWITCH = re.compile(r'"(OPENPOST_[A-Z0-9_]*PRIVATE[A-Z0-9_]*)"') +_TIMEOUT_SECONDS = 30 +_TRACKING_ISSUE = "https://github.com/infinito-nexus/core/issues/2867" + + +def private_network_switches(source: str) -> list[str]: + """ + Args: + source: Go source of OpenPost's config loader. + + Returns: + The sorted, distinct ``OPENPOST_*PRIVATE*`` variables it names. + """ + return sorted(set(_SWITCH.findall(source))) + + +def _pinned_config_loader_url() -> str: + openpost = load_yaml_any(str(_SERVICES))["openpost"] + repository = openpost["image"].removeprefix(_REGISTRY) + return f"https://raw.githubusercontent.com/{repository}/{openpost['version']}/{_CONFIG_LOADER}" + + +class TestOpenPostNetguardAllowlist(unittest.TestCase): + def test_the_detector_finds_a_private_network_switch(self) -> None: + self.assertEqual( + private_network_switches( + 'getEnvDefault("OPENPOST_ALLOWED_PRIVATE_CIDRS", "")\n' + 'getEnvDefault("OPENPOST_PRIVACY_URL", "")' + ), + ["OPENPOST_ALLOWED_PRIVATE_CIDRS"], + ) + + def test_the_pinned_openpost_offers_no_private_network_switch(self) -> None: + url = _pinned_config_loader_url() + try: + response = requests.get(url, timeout=_TIMEOUT_SECONDS) + except requests.RequestException as exc: + self._unverified(url, f"{type(exc).__name__}: {exc}") + if response.status_code == 429 or response.status_code >= 500: + self._unverified(url, f"HTTP {response.status_code}") + self.assertEqual( + response.status_code, + 200, + f"{url} answered HTTP {response.status_code}; the pinned OpenPost no " + "longer ships its config loader at this path", + ) + switches = private_network_switches(response.text) + self.assertEqual( + switches, + [], + f"the pinned OpenPost reads {', '.join(switches)}, so netguard can " + "allow private networks now; drop the relay workaround as described " + f"in {_TRACKING_ISSUE}", + ) + + def _unverified(self, url: str, reason: str) -> None: + warning( + f"{url} was not checked ({reason})", + title="OpenPost netguard pin unverified", + file=str(_SERVICES.relative_to(PROJECT_ROOT)), + ) + raise unittest.SkipTest(f"{url} unverified") + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py index d45f12251f..0f8b637cea 100644 --- a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py +++ b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py @@ -10,11 +10,12 @@ excludes that role. That is not hypothetical: a firewall range derived from the pool by eye would have cut BigBlueButton off, because its subnet is the one that sits outside. -A role that genuinely cannot choose its block is named in -``NETWORK_ROLE_SUBNET_EXCEPTION_ROLES``. The list carries role ids rather than -CIDRs on purpose: the block is already declared in that role's -``meta/networks.yml``, and repeating it here would be the same duplication one -layer up. Consumers resolve the ids through ``lookup('role_subnets', ...)``. +A role that genuinely cannot choose its block declares that next to the block, +with ``local.outside_pool: true`` in its ``meta/networks.yml``. +``NETWORK_ROLE_SUBNET_EXCEPTION_ROLES`` collects those roles through +``lookup('role_subnet_exceptions')`` rather than listing them, so the +declaration is never stated twice, and consumers resolve the ids through +``lookup('role_subnets', ...)``. """ from __future__ import annotations @@ -25,7 +26,7 @@ import unittest import jinja2 from utils.cache.yaml import load_yaml_any -from utils.meta.scan import iter_subnets +from utils.meta.scan import iter_outside_pool_roles, iter_subnets from . import PROJECT_ROOT @@ -40,20 +41,18 @@ def _declared_space() -> tuple[list[ipaddress.IPv4Network], list[str]]: pool = jinja2.Template( pool, autoescape=jinja2.select_autoescape(default_for_string=False) ).render(**data) - roles = data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES") or [] - if not isinstance(pool, str) or not isinstance(roles, list): + if not isinstance(pool, str): raise TypeError( - f"{NETWORKS_FILE} must declare NETWORK_ROLE_SUBNET_POOL as a string " - "and NETWORK_ROLE_SUBNET_EXCEPTION_ROLES as a list of role ids" + f"{NETWORKS_FILE} must declare NETWORK_ROLE_SUBNET_POOL as a string" ) declared = dict(iter_subnets()) raw = [pool] - for role in roles: - subnet = declared.get(str(role)) + for role in iter_outside_pool_roles(): + subnet = declared.get(role) if subnet is None: raise AssertionError( - f"{NETWORKS_FILE}: NETWORK_ROLE_SUBNET_EXCEPTION_ROLES names " - f"'{role}', which declares no networks.local.subnet" + f"{role} sets networks.local.outside_pool but declares no " + "networks.local.subnet" ) raw.append(str(subnet)) return [ipaddress.ip_network(entry, strict=True) for entry in raw], raw @@ -76,11 +75,20 @@ class TestRoleSubnetPool(unittest.TestCase): + ", ".join(raw) + "\n\nFix: pick a subnet inside the pool via " "`infinito contributing network address suggest`, or, when the " - "block is pinned by something outside this repository, name the " - "role in NETWORK_ROLE_SUBNET_EXCEPTION_ROLES in " - "group_vars/all/08_networks.yml." + "block is pinned by something outside this repository, set " + "networks.local.outside_pool: true in the role's " + "meta/networks.yml." ) + def test_the_exceptions_are_collected_from_the_roles(self) -> None: + data = load_yaml_any(str(NETWORKS_FILE), default_if_missing={}) or {} + self.assertEqual( + data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES"), + "{{ lookup('role_subnet_exceptions') }}", + f"{NETWORKS_FILE}: NETWORK_ROLE_SUBNET_EXCEPTION_ROLES must collect " + "the roles that set networks.local.outside_pool, not list them", + ) + def test_the_exceptions_are_not_already_covered(self) -> None: """An exception inside the pool is dead weight that outlives its reason.""" allowed, raw = _declared_space() @@ -88,10 +96,10 @@ class TestRoleSubnetPool(unittest.TestCase): redundant = [entry for entry in allowed[1:] if entry.subnet_of(pool)] if redundant: self.fail( - "NETWORK_ROLE_SUBNET_EXCEPTION_ROLES names role(s) whose subnet " + "networks.local.outside_pool is set on role(s) whose subnet " f"already sits inside {raw[0]}: " f"{', '.join(str(entry) for entry in redundant)}. " - "Remove them; the pool already admits those addresses." + "Drop the flag; the pool already admits those addresses." ) diff --git a/tests/unit/python/cli/administration/inventory/provision/test_passwords.py b/tests/unit/python/cli/administration/inventory/provision/test_passwords.py new file mode 100644 index 0000000000..7e1ae1692c --- /dev/null +++ b/tests/unit/python/cli/administration/inventory/provision/test_passwords.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from cli.administration.inventory.provision import passwords + + +class TestPasswordMasking(unittest.TestCase): + def test_a_user_password_is_registered_for_masking(self) -> None: + with patch.object(passwords, "mask") as masked: + password = passwords.generate_user_password() + masked.assert_called_once_with(password) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/gha/test_annotations.py b/tests/unit/python/cli/gha/test_annotations.py index b708aea649..9906f87248 100644 --- a/tests/unit/python/cli/gha/test_annotations.py +++ b/tests/unit/python/cli/gha/test_annotations.py @@ -5,7 +5,14 @@ import unittest from io import StringIO from unittest.mock import patch -from utils.annotations.message import error, error_each, notice, warning, warning_each +from utils.annotations.message import ( + error, + error_each, + mask, + notice, + warning, + warning_each, +) GHA_ENV = {"GITHUB_ACTIONS": "true"} NO_GHA_ENV = {"GITHUB_ACTIONS": ""} @@ -112,5 +119,35 @@ class TestAnnotationsPlainText(unittest.TestCase): self.assertIn("beta", lines[1]) +class TestMask(unittest.TestCase): + def _capture(self, env: dict[str, str], value: str) -> tuple[str, str]: + with ( + patch.dict(os.environ, env), + patch("sys.stdout", new_callable=StringIO) as out, + patch("sys.stderr", new_callable=StringIO) as err, + ): + mask(value) + return out.getvalue(), err.getvalue() + + def test_a_secret_is_registered_on_stderr_only(self) -> None: + out, err = self._capture(GHA_ENV, "s3cr€t") + self.assertEqual(out, "") + self.assertEqual(err, "::add-mask::s3cr€t\n") + + def test_each_line_of_a_multiline_secret_is_registered(self) -> None: + _, err = self._capture(GHA_ENV, "-----BEGIN-----\nabc\n\n-----END-----\n") + self.assertEqual( + err.splitlines(), + [ + "::add-mask::-----BEGIN-----", + "::add-mask::abc", + "::add-mask::-----END-----", + ], + ) + + def test_nothing_is_printed_outside_github_actions(self) -> None: + self.assertEqual(self._capture(NO_GHA_ENV, "s3cret"), ("", "")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_container_networks.py b/tests/unit/python/plugins/lookup/test_container_networks.py index a44e0f6d0e..c160db268e 100644 --- a/tests/unit/python/plugins/lookup/test_container_networks.py +++ b/tests/unit/python/plugins/lookup/test_container_networks.py @@ -32,10 +32,10 @@ def _make_lookup(vars_=None): class TestContainerNetworksLookup(unittest.TestCase): - def test_raises_when_positional_terms_supplied(self): + def test_raises_when_more_than_one_term_supplied(self): lm = _make_lookup({"application_id": "x", "DEPLOYMENT_MODE": "swarm"}) with self.assertRaises(AnsibleError): - lm.run(["unexpected"], variables=lm._templar.available_variables) + lm.run(["relay", "unexpected"], variables=lm._templar.available_variables) def test_raises_when_application_id_missing(self): lm = _make_lookup({"DEPLOYMENT_MODE": "swarm"}) @@ -71,6 +71,72 @@ class TestContainerNetworksLookup(unittest.TestCase): self.assertEqual(kwargs["application_id"], "web-app-baserow") self.assertEqual(kwargs["deployment_mode"], "compose") + def _run_with_configured_aliases(self, configured, render_mock=None): + vars_ = {"application_id": "web-app-x", "DEPLOYMENT_MODE": "compose"} + lm = _make_lookup(vars_) + config_calls: list[tuple] = [] + + def _config_run(args, **_): + config_calls.append(tuple(args)) + return [configured] + + def _get(name, **_): + if name == "config": + return mock.MagicMock(run=_config_run) + return mock.MagicMock(run=lambda *_a, **_k: [{}]) + + with ( + mock.patch( + "utils.networks.lookup_context.build_service_registry_from_applications", + return_value={}, + ), + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, + mock.patch( + "plugins.lookup.container_networks.render_container_networks", + render_mock or mock.MagicMock(return_value="RENDERED"), + ), + ): + loader_mock.get.side_effect = _get + lm.run(["relay"], variables=vars_) + return config_calls + + def test_reads_the_service_network_aliases_from_its_config(self): + render_mock = mock.MagicMock(return_value="RENDERED") + config_calls = self._run_with_configured_aliases(["a.example.com"], render_mock) + + self.assertIn( + ("web-app-x", "services.relay.network_aliases", None), config_calls + ) + self.assertEqual(render_mock.call_args.kwargs["aliases"], ["a.example.com"]) + + def test_without_a_service_no_aliases_are_read(self): + vars_ = {"application_id": "web-app-x", "DEPLOYMENT_MODE": "compose"} + lm = _make_lookup(vars_) + + with ( + mock.patch( + "utils.networks.lookup_context.build_service_registry_from_applications", + return_value={}, + ), + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, + mock.patch( + "plugins.lookup.container_networks.render_container_networks", + return_value="RENDERED", + ) as render_mock, + ): + loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [{}]) + lm.run([], variables=vars_) + + self.assertIsNone(render_mock.call_args.kwargs["aliases"]) + + def test_rejects_network_aliases_that_are_not_a_list_of_strings(self): + with self.assertRaises(AnsibleError): + self._run_with_configured_aliases("a.example.com") + + def test_rejects_a_service_without_network_aliases(self): + with self.assertRaises(AnsibleError): + self._run_with_configured_aliases(None) + def test_falls_back_to_compose_when_deployment_mode_unset(self): vars_ = {"application_id": "web-app-x"} lm = _make_lookup(vars_) diff --git a/tests/unit/python/plugins/lookup/test_container_volumes_render.py b/tests/unit/python/plugins/lookup/test_container_volumes_render.py index 906f9c84d2..922cec7a21 100644 --- a/tests/unit/python/plugins/lookup/test_container_volumes_render.py +++ b/tests/unit/python/plugins/lookup/test_container_volumes_render.py @@ -121,6 +121,52 @@ class TestContainerVolumesConfigSecret(unittest.TestCase): }, ) + def test_a_mount_hands_its_secret_to_the_service_user(self) -> None: + meta = { + "tlskey": { + "type": "secret", + "source": "/etc/ssl/key.pem", + "mode": "0400", + "mounts": [ + { + "service": "app", + "target": "/run/secrets/key", + "uid": "10001", + "gid": "10001", + } + ], + } + } + data = _parse(container_volumes(_apps(meta), "my-app", "app")) + self.assertEqual( + data["secrets"], + [ + { + "source": "tlskey", + "target": "/run/secrets/key", + "mode": 0o400, + "uid": "10001", + "gid": "10001", + } + ], + ) + + def test_a_mount_hands_its_config_to_the_service_user(self) -> None: + meta = { + "settings": { + "type": "config", + "source": "/etc/app.json", + "mounts": [ + {"service": "app", "target": "/config/app.json", "uid": "33"} + ], + } + } + data = _parse(container_volumes(_apps(meta), "my-app", "app")) + self.assertEqual( + data["configs"], + [{"source": "settings", "target": "/config/app.json", "uid": "33"}], + ) + class TestContainerVolumesTmpfs(unittest.TestCase): def test_tmpfs_size_renders_as_the_byte_count_the_long_form_takes(self) -> None: diff --git a/tests/unit/python/plugins/lookup/test_openpost_relay_domains.py b/tests/unit/python/plugins/lookup/test_openpost_relay_domains.py new file mode 100644 index 0000000000..2962de940b --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_openpost_relay_domains.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from plugins.lookup import openpost_relay_domains as relay + +SIBLINGS = { + "mastodon": "web-app-mastodon", + "pixelfed": "web-app-pixelfed", + "peertube": "web-app-peertube", +} +DOMAINS = { + "web-app-openpost": "publish.example", + "web-app-mastodon": "microblog.example", + "web-app-pixelfed": "picture.example", + "web-app-peertube": "video.example", +} + + +class TestRelayDomains(unittest.TestCase): + def test_own_domain_enabled_siblings_and_object_store_in_order(self): + enabled = {"mastodon": True, "pixelfed": "False", "peertube": "true"} + self.assertEqual( + relay.relay_domains( + "publish.example", + SIBLINGS, + enabled.__getitem__, + DOMAINS.__getitem__, + "s3.example", + ), + ["publish.example", "microblog.example", "video.example", "s3.example"], + ) + + def test_without_siblings_or_object_store_only_the_own_domain_remains(self): + self.assertEqual( + relay.relay_domains( + "publish.example", SIBLINGS, lambda _: False, DOMAINS.__getitem__, "" + ), + ["publish.example"], + ) + + def test_a_flag_that_is_not_a_boolean_fails(self): + with self.assertRaises(TypeError): + relay.relay_domains( + "publish.example", SIBLINGS, lambda _: "maybe", DOMAINS.__getitem__, "" + ) + + +class TestLookup(unittest.TestCase): + def _run(self, objstore_enabled): + answers = { + ("config", "web-app-openpost", "services.relay.siblings"): SIBLINGS, + ("config", "web-app-openpost", "services.mastodon.enabled"): True, + ("config", "web-app-openpost", "services.pixelfed.enabled"): False, + ("config", "web-app-openpost", "services.peertube.enabled"): False, + ("objstore", "web-app-openpost", "enabled"): objstore_enabled, + ("objstore", "web-app-openpost", "public_domain"): "s3.example", + } + + def _get(name, **_): + def _run(args, **__): + if name == "domain": + return [DOMAINS[args[0]]] + return [answers[(name, *args)]] + + return mock.MagicMock(run=_run) + + with mock.patch.object(relay, "lookup_loader") as loader: + loader.get.side_effect = _get + return relay.LookupModule().run([], variables={}) + + def test_reads_siblings_flags_and_the_object_store(self): + self.assertEqual( + self._run(True), + [["publish.example", "microblog.example", "s3.example"]], + ) + + def test_skips_the_object_store_when_openpost_uses_none(self): + self.assertEqual(self._run(False), [["publish.example", "microblog.example"]]) + + def test_rejects_terms(self): + with self.assertRaises(AnsibleError): + relay.LookupModule().run(["unexpected"], variables={}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_role_subnet_exceptions.py b/tests/unit/python/plugins/lookup/test_role_subnet_exceptions.py new file mode 100644 index 0000000000..8cb5316cfb --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_role_subnet_exceptions.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from plugins.lookup import role_subnet_exceptions +from plugins.lookup.role_subnet_exceptions import LookupModule, outside_pool_roles + + +def _app(local): + return {"networks": {"local": local}} + + +APPLICATIONS = { + "web-app-openpost": _app({"subnet": "192.88.99.0/24", "outside_pool": True}), + "web-app-bigbluebutton": _app({"subnet": "10.7.7.0/24", "outside_pool": True}), + "web-app-pooled": _app({"subnet": "192.168.10.0/24", "outside_pool": False}), + "web-app-plain": _app({"subnet": "192.168.11.0/24"}), + "svc-without-networks": {}, +} + + +class TestOutsidePoolRoles(unittest.TestCase): + def test_only_the_flagged_roles_in_sorted_order(self): + self.assertEqual( + outside_pool_roles(APPLICATIONS), + ["web-app-bigbluebutton", "web-app-openpost"], + ) + + def test_a_flag_that_is_not_a_boolean_fails(self): + with self.assertRaises(AnsibleError): + outside_pool_roles({"web-app-x": _app({"outside_pool": "yes"})}) + + +class TestLookup(unittest.TestCase): + def test_reads_the_merged_applications(self): + with mock.patch.object(role_subnet_exceptions, "lookup_loader") as loader: + loader.get.return_value = mock.MagicMock( + run=mock.MagicMock(return_value=[APPLICATIONS]) + ) + result = LookupModule().run([], variables={}) + + self.assertEqual(result, [["web-app-bigbluebutton", "web-app-openpost"]]) + self.assertEqual(loader.get.call_args.args, ("applications",)) + + def test_rejects_terms(self): + with self.assertRaises(AnsibleError): + LookupModule().run(["unexpected"], variables={}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_role_subnets.py b/tests/unit/python/plugins/lookup/test_role_subnets.py new file mode 100644 index 0000000000..9a9e74f4af --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_role_subnets.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from plugins.lookup import role_subnets +from plugins.lookup.role_subnets import LookupModule + +SUBNETS = { + "web-app-bigbluebutton": "10.7.7.0/24", + "web-app-openpost": "192.88.99.0/24", +} + + +class _Templar: + def __init__(self, rendered): + self.rendered = rendered + self.calls: list[str] = [] + + def template(self, value): + self.calls.append(str(value)) + return self.rendered + + +def _run(terms, templar=None): + lookup = LookupModule() + lookup._templar = templar + lookup._loader = mock.MagicMock() + config = mock.MagicMock( + run=lambda args, **_: [SUBNETS.get(args[0])], + ) + with mock.patch.object(role_subnets, "lookup_loader") as loader: + loader.get.return_value = config + return lookup.run(terms, variables={})[0] + + +class TestRoleSubnets(unittest.TestCase): + def test_role_ids_and_lists_of_them_resolve_in_order(self): + self.assertEqual( + _run(["web-app-openpost", ["web-app-bigbluebutton"]]), + ["192.88.99.0/24", "10.7.7.0/24"], + ) + + def test_an_unrendered_group_var_is_rendered_before_its_ids_are_read(self): + templar = _Templar(["web-app-bigbluebutton", "web-app-openpost"]) + self.assertEqual( + _run(["{{ lookup('role_subnet_exceptions') }}"], templar), + ["10.7.7.0/24", "192.88.99.0/24"], + ) + self.assertEqual(templar.calls, ["{{ lookup('role_subnet_exceptions') }}"]) + + def test_a_plain_role_id_is_not_templated(self): + templar = _Templar(["unused"]) + _run(["web-app-openpost"], templar) + self.assertEqual(templar.calls, []) + + def test_a_role_without_a_subnet_fails(self): + with self.assertRaises(AnsibleError): + _run(["web-app-unknown"]) + + def test_no_role_fails(self): + with self.assertRaises(AnsibleError): + _run([]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_container.py b/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_container.py index f0c62e8ce7..e40e924465 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_container.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_container.py @@ -148,6 +148,8 @@ def argv_triggers(stage: Path, run: Path) -> dict[str, tuple[str, list[str]]]: ), "entrypoint": ("-w", ["--entrypoint", "/bin/sh", "-w"]), "privileged": ("-w", ["--privileged", "-w"]), + "core_dumps": ("-w", ["--ulimit=core=-1", "-w"]), + "other_ulimit": ("-w", ["--ulimit", "nofile=1048576", "-w"]), "other_cidfile": (f"--cidfile={run}/.cid", ["--cidfile=/srv/x/.cid"]), "no_log_driver": ("--log-driver=none", []), "reports_elsewhere": (f"{run}/reports:/reports", ["/srv/x:/reports"]), @@ -212,6 +214,12 @@ class TestSpecSecretsContainer(unittest.TestCase): def test_the_command_a_run_with_spec_secrets_starts_passes(self) -> None: self.assertFalse(self.refused(container_argv(self.root, self.run_dir))) + def test_a_run_without_core_dumps_passes(self) -> None: + argv = container_argv(self.root, self.run_dir) + at = argv.index("-w") + argv[at:at] = ["--ulimit=core=0"] + self.assertFalse(self.refused(argv)) + def test_a_docker_config_the_caller_exports_stays_out_of_the_checks(self) -> None: argv = container_argv(self.root, self.run_dir) exported = {"DOCKER_CONFIG": str(open_config(self.root))} diff --git a/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_mount.py b/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_mount.py index 8feca6cef8..b3858b1e1a 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_mount.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_spec_secrets_mount.py @@ -3,6 +3,7 @@ from __future__ import annotations import copy import re import unittest +from itertools import pairwise from . import role_task from ._spec_secrets_wiring import ( @@ -27,6 +28,7 @@ from ._spec_secrets_wiring import ( mount_violations, prune_violations, render, + render_argv, role_tasks, run_argv, ) @@ -313,6 +315,14 @@ class TestSpecSecretsMount(unittest.TestCase): queued = role_task("03_run_pass.yml", "📬")["vars"]["_playwright_argv"] self.assertEqual(queued, run_argv()) + def test_every_run_disables_core_dumps_in_the_container(self) -> None: + for exists, directory in ((False, STALE_DIR), (True, SECRETS_DIR)): + with self.subTest(template=exists): + argv = render_argv(run_argv(), exists, directory) + self.assertIn( + ("--shm-size=1g", "--ulimit=core=0"), list(pairwise(argv)) + ) + def test_the_role_level_env_file_is_untouched(self) -> None: self.assertEqual(env_task()["ansible.builtin.copy"]["mode"], "0644") self.assertNotIn("secrets", str(env_task())) diff --git a/tests/unit/python/roles/update/files/test_alarm_mirror.py b/tests/unit/python/roles/update/files/test_alarm_mirror.py new file mode 100644 index 0000000000..0d5a5d2afe --- /dev/null +++ b/tests/unit/python/roles/update/files/test_alarm_mirror.py @@ -0,0 +1,234 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +SCRIPT = PROJECT_ROOT / "roles/update/files/shell/alarm_mirror.sh" +GEO = "Server = http://mirror.archlinuxarm.org/$arch/$repo" +GEO_HTTPS = "Server = https://mirror.archlinuxarm.org/$arch/$repo" +DE = "Server = http://de.mirror.archlinuxarm.org/$arch/$repo" +DE3 = "Server = http://de3.mirror.archlinuxarm.org/$arch/$repo" +DK = "Server = http://dk.mirror.archlinuxarm.org/$arch/$repo" +HEADER = ["#", "# Arch Linux ARM repository mirrorlist", "#", ""] +IMAGE = [ + *HEADER, + "## Geo-IP based mirror selection and load balancing", + GEO, + "", + "### Germany", + DE, + DE3, + "", + "### Denmark", + DK, +] +STOCK = [ + *HEADER, + "## Geo-IP based mirror selection and load balancing", + GEO, + "", + "### Germany", + f"# {DE}", + f"# {DE3}", +] +TWO_GEO = [*HEADER, GEO, GEO_HTTPS, "", DE, DE3, DK] +X86 = [ + "##", + "## Arch Linux repository mirrorlist", + "##", + "", + "Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch", + "Server = https://mirror.rackspace.com/archlinux/$repo/os/$arch", + "Server = https://mirrors.kernel.org/archlinux/$repo/os/$arch", +] +PACMAN_FAILED = 7 +DEMOTED = 3 +PACMAN_STUB = ( + "#!/bin/sh\n" + 'lead="$(grep -m 1 -E \'^[[:space:]]*Server[[:space:]]*=\' "${MIRRORLIST}")"\n' + 'printf \'%s|%s\\n\' "${lead}" "$*" >> "${PACMAN_LOG}"\n' + "echo 'resolving dependencies...'\n" + 'if [ -n "${PACMAN_SERVES}" ]; then\n' + '\tcase "${lead}" in *"${PACMAN_SERVES}"*) exit 0 ;; esac\n' + "fi\n" + f"exit {PACMAN_FAILED}\n" +) +RESYNC_UPGRADE = "--sync --refresh --refresh --sysupgrade --noconfirm" + + +def text(lines): + return "\n".join(lines) + "\n" + + +class TestAlarmMirror(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + bin_dir = self.root / "bin" + bin_dir.mkdir() + stub = bin_dir / "pacman" + stub.write_text(PACMAN_STUB) + stub.chmod(0o755) + self.mirrorlist = self.root / "mirrorlist" + self.pacman_log = self.root / "pacman.log" + self.env = dict(os.environ) + self.env["PATH"] = f"{bin_dir}{os.pathsep}{self.env['PATH']}" + self.env["MIRRORLIST"] = str(self.mirrorlist) + self.env["PACMAN_LOG"] = str(self.pacman_log) + + def run_helper(self, verb, lines=None, serves=""): + """Run the helper the way the role does, with a pacman stub on PATH. + + Args: + verb: demote or retry. + lines: the mirrorlist's lines before the run, or None to keep the + mirrorlist an earlier run left. + serves: the host whose upgrade the stub lets succeed while it is + the first Server; every other first Server, and every one when + empty, fails with PACMAN_FAILED. + + Returns: + Tuple of exit code, stdout, and the mirrorlist's lines after the + run, or None when there is no mirrorlist. + """ + if lines is not None: + self.mirrorlist.write_text(text(lines)) + env = dict(self.env, PACMAN_SERVES=serves) + done = subprocess.run( + ["bash", str(SCRIPT), verb, str(self.mirrorlist)], + env=env, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + if not self.mirrorlist.exists(): + return done.returncode, done.stdout, None + after = self.mirrorlist.read_text() # nocheck: cache-read rewritten + return done.returncode, done.stdout, after.splitlines() + + def pacman_calls(self): + """Read the pacman stub's log. + + Returns: + One (first Server, argv) pair per pacman call, in call order. + """ + if not self.pacman_log.exists(): + return [] + return [ + tuple(line.split("|", 1)) + for line in read_text(str(self.pacman_log)).splitlines() + ] + + def servers(self, lines): + return [line for line in lines if line.startswith("Server")] + + def test_demote_moves_the_geo_host_behind_the_last_server(self): + code, out, after = self.run_helper("demote", IMAGE) + self.assertEqual(code, DEMOTED) + self.assertEqual(self.servers(after), [DE, DE3, DK, GEO]) + self.assertEqual(out, f"{DE}\n") + + def test_demote_keeps_every_other_line_in_place(self): + _, _, after = self.run_helper("demote", IMAGE) + self.assertEqual(after, [line for line in IMAGE if line != GEO] + [GEO]) + + def test_demote_twice_changes_nothing_the_second_time(self): + self.run_helper("demote", IMAGE) + code, out, after = self.run_helper("demote") + self.assertEqual(code, 0) + self.assertEqual(out, "") + self.assertEqual(self.servers(after), [DE, DE3, DK, GEO]) + + def test_demote_leaves_a_geo_only_mirrorlist_untouched(self): + code, out, after = self.run_helper("demote", STOCK) + self.assertEqual((code, out, after), (0, "", STOCK)) + + def test_demote_moves_every_geo_line_behind_the_last_server(self): + code, out, after = self.run_helper("demote", TWO_GEO) + self.assertEqual(code, DEMOTED) + self.assertEqual(out, f"{DE}\n") + self.assertEqual(self.servers(after)[:3], [DE, DE3, DK]) + self.assertEqual(sorted(self.servers(after)[3:]), sorted([GEO, GEO_HTTPS])) + + def test_demote_keeps_the_mirrorlist_mode(self): + self.mirrorlist.write_text(text(IMAGE)) + self.mirrorlist.chmod(0o640) + code, _, _ = self.run_helper("demote") + self.assertEqual(code, DEMOTED) + self.assertEqual(self.mirrorlist.stat().st_mode & 0o777, 0o640) + self.assertEqual( + sorted(path.name for path in self.root.iterdir()), ["bin", "mirrorlist"] + ) + + def test_a_missing_mirrorlist_counts_as_one_without_the_geo_host(self): + for verb, expected in (("demote", 0), ("retry", 1)): + with self.subTest(verb=verb): + code, out, after = self.run_helper(verb) + self.assertEqual((code, out, after), (expected, "", None)) + self.assertEqual(self.pacman_calls(), []) + + def test_an_x86_64_mirrorlist_stays_untouched(self): + for verb, expected in (("demote", 0), ("retry", 1)): + with self.subTest(verb=verb): + code, out, after = self.run_helper(verb, X86) + self.assertEqual((code, out, after), (expected, "", X86)) + self.assertEqual(self.pacman_calls(), []) + + def test_retry_moves_on_resyncs_and_upgrades_from_the_next_mirror(self): + self.run_helper("demote", IMAGE) + code, out, after = self.run_helper("retry", serves="de3.mirror") + self.assertEqual(code, 0) + self.assertEqual(out, f"{DE3}\n") + self.assertEqual(self.pacman_calls(), [(DE3, RESYNC_UPGRADE)]) + self.assertEqual(self.servers(after), [DE3, DK, DE, GEO]) + + def test_retry_tries_every_further_concrete_mirror_once(self): + self.run_helper("demote", IMAGE) + code, out, after = self.run_helper("retry") + self.assertEqual(code, PACMAN_FAILED) + self.assertEqual(out, "") + self.assertEqual( + self.pacman_calls(), [(DE3, RESYNC_UPGRADE), (DK, RESYNC_UPGRADE)] + ) + self.assertEqual(self.servers(after)[0], DK) + + def test_retry_never_lets_the_geo_host_lead(self): + self.run_helper("demote", IMAGE) + self.run_helper("retry") + leads = [lead for lead, _ in self.pacman_calls()] + self.assertTrue(leads) + self.assertNotIn(GEO, leads) + + def test_retry_never_lets_a_second_geo_line_lead(self): + code, _, _ = self.run_helper("retry", TWO_GEO) + leads = [lead for lead, _ in self.pacman_calls()] + self.assertEqual(code, PACMAN_FAILED) + self.assertEqual(leads, [DE3, DK]) + + def test_retry_keeps_pacman_output_off_stdout(self): + self.run_helper("demote", IMAGE) + _, out, _ = self.run_helper("retry", serves="dk.mirror") + self.assertEqual(out, f"{DK}\n") + + def test_retry_without_a_further_concrete_mirror_fails_untouched(self): + lines = [*HEADER, DE, GEO] + code, out, after = self.run_helper("retry", lines) + self.assertEqual((code, out, after), (1, "", lines)) + self.assertEqual(self.pacman_calls(), []) + + def test_an_unknown_verb_fails_on_any_mirrorlist(self): + for lines in (IMAGE, X86): + with self.subTest(lines=lines[-1]): + code, _, after = self.run_helper("rotate", lines) + self.assertEqual(code, 2) + self.assertEqual(after, lines) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/update/test_arch.py b/tests/unit/python/roles/update/test_arch.py new file mode 100644 index 0000000000..33ccb1c3e9 --- /dev/null +++ b/tests/unit/python/roles/update/test_arch.py @@ -0,0 +1,73 @@ +import unittest + +from utils import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +TASKS = PROJECT_ROOT / "roles/update/tasks/arch.yml" +HELPER = "shell/alarm_mirror.sh" +DOWNLOAD_FAILED = "failed to retrieve some files" + + +def helper_verb(task): + script = task.get("ansible.builtin.script") or {} + words = (script.get("cmd", "") if isinstance(script, dict) else script).split() + return words[1] if words[:1] == [HELPER] else None + + +def index_of(tasks, match): + return next(index for index, task in enumerate(tasks) if match(task)) + + +def upgrade_block(tasks): + return next( + task + for task in tasks + if any( + (child.get("community.general.pacman") or {}).get("upgrade") + for child in task.get("block", []) + ) + ) + + +class ArchMirrorTests(unittest.TestCase): + def test_the_geo_host_is_demoted_before_the_databases_refresh(self): + tasks = load_yaml_any(str(TASKS)) + demote = index_of(tasks, lambda task: helper_verb(task) == "demote") + refresh = index_of( + tasks, + lambda task: (task.get("community.general.pacman") or {}).get( + "update_cache" + ), + ) + + self.assertLess(demote, refresh) + + def test_the_demote_decides_by_exit_code_never_by_output(self): + tasks = load_yaml_any(str(TASKS)) + demote = tasks[index_of(tasks, lambda task: helper_verb(task) == "demote")] + register = demote["register"] + + self.assertEqual(demote["changed_when"], f"{register}.rc == 3") + self.assertEqual(demote["failed_when"], f"{register}.rc not in [0, 3]") + + def test_only_a_failed_download_reaches_the_mirror_retry(self): + rescue = upgrade_block(load_yaml_any(str(TASKS)))["rescue"] + + self.assertIn("ansible.builtin.fail", rescue[0]) + self.assertIn(DOWNLOAD_FAILED, rescue[0]["when"]) + self.assertIn("not in", rescue[0]["when"]) + self.assertEqual(helper_verb(rescue[1]), "retry") + + def test_a_failure_no_mirror_retried_is_re_raised(self): + rescue = upgrade_block(load_yaml_any(str(TASKS)))["rescue"] + register = rescue[1]["register"] + + self.assertIs(rescue[1]["failed_when"], False) + self.assertIn("ansible.builtin.fail", rescue[-1]) + self.assertEqual( + rescue[-1]["when"], f"{register} is skipped or {register}.rc != 0" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openpost/__init__.py b/tests/unit/python/roles/web-app-openpost/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/files/__init__.py b/tests/unit/python/roles/web-app-openpost/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/__init__.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/__init__.py new file mode 100644 index 0000000000..241d1186c0 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/__init__.py @@ -0,0 +1,10 @@ +import sys +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] +PACKAGE_ROOT: Path = PROJECT_ROOT / "roles/web-app-openpost/files/python" + +if str(PACKAGE_ROOT) not in sys.path: + sys.path.insert(0, str(PACKAGE_ROOT)) + +__all__ = ["PACKAGE_ROOT", "PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/__init__.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/__init__.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/__init__.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/account.json b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/account.json new file mode 100644 index 0000000000..4bd2aa942b --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/account.json @@ -0,0 +1,10 @@ +{ + "id": "109000000000000099", + "username": "press", + "acct": "press", + "display_name": "Press", + "locked": false, + "bot": false, + "url": "https://microblog.example/@press", + "statuses_count": 4 +} diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/statuses.json b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/statuses.json new file mode 100644 index 0000000000..dfa7fc2d04 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/mastodon/statuses.json @@ -0,0 +1,83 @@ +[ + { + "id": "109000000000000101", + "created_at": "2026-10-22T08:00:00.000Z", + "in_reply_to_id": null, + "in_reply_to_account_id": null, + "sensitive": false, + "spoiler_text": "", + "visibility": "public", + "language": "en", + "uri": "https://microblog.example/users/press/statuses/109000000000000101", + "url": "https://microblog.example/@press/109000000000000101", + "content": "

    Launching our #fediverse presence

    ", + "reblog": null, + "application": {"name": "Web", "website": null}, + "media_attachments": [], + "mentions": [], + "tags": [{"name": "fediverse", "url": "https://microblog.example/tags/fediverse"}] + }, + { + "id": "109000000000000102", + "created_at": "2026-10-22T08:05:00.000Z", + "in_reply_to_id": null, + "in_reply_to_account_id": null, + "sensitive": false, + "spoiler_text": "", + "visibility": "public", + "language": "en", + "uri": "https://microblog.example/users/press/statuses/109000000000000102", + "url": "https://microblog.example/@press/109000000000000102", + "content": "

    A picture

    ", + "reblog": null, + "application": {"name": "Web", "website": null}, + "media_attachments": [ + { + "id": "109000000000000500", + "type": "image", + "url": "https://microblog.example/system/media_attachments/files/109/000/000/000/000/500/original/square.png", + "preview_url": "https://microblog.example/system/media_attachments/files/109/000/000/000/000/500/small/square.png", + "description": "A red square", + "meta": {"original": {"width": 32, "height": 32}} + } + ], + "mentions": [], + "tags": [] + }, + { + "id": "109000000000000103", + "created_at": "2026-10-22T08:10:00.000Z", + "in_reply_to_id": null, + "in_reply_to_account_id": null, + "sensitive": false, + "spoiler_text": "", + "visibility": "public", + "language": "en", + "uri": "https://microblog.example/users/press/statuses/109000000000000103", + "url": "https://microblog.example/@press/109000000000000103", + "content": "

    Published by the desk

    ", + "reblog": null, + "application": {"name": "OpenPost", "website": "https://publish.example"}, + "media_attachments": [], + "mentions": [], + "tags": [] + }, + { + "id": "109000000000000104", + "created_at": "2026-10-22T08:15:00.000Z", + "in_reply_to_id": "109000000000000001", + "in_reply_to_account_id": "109000000000000077", + "sensitive": true, + "spoiler_text": "politics", + "visibility": "public", + "language": "en", + "uri": "https://microblog.example/users/press/statuses/109000000000000104", + "url": "https://microblog.example/@press/109000000000000104", + "content": "

    @alice agreed

    ", + "reblog": null, + "application": {"name": "Web", "website": null}, + "media_attachments": [], + "mentions": [{"id": "109000000000000077", "username": "alice", "acct": "alice@social.example", "url": "https://social.example/@alice"}], + "tags": [] + } +] diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/__init__.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/video_detail.json b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/video_detail.json new file mode 100644 index 0000000000..6eb9f9a218 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/video_detail.json @@ -0,0 +1,29 @@ +{ + "id": 31, + "uuid": "6a1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "name": "Conference talk", + "description": "Full description of the conference talk", + "tags": ["talk", "fediverse"], + "files": [], + "streamingPlaylists": [ + { + "id": 7, + "type": 1, + "playlistUrl": "https://video.example/static/streaming-playlists/hls/6a1c6b54/master.m3u8", + "files": [ + { + "resolution": {"id": 480, "label": "480p"}, + "size": 20971520, + "fileUrl": "https://video.example/static/streaming-playlists/hls/6a1c6b54/6a1c6b54-480-fragmented.mp4", + "fileDownloadUrl": "https://video.example/download/streaming-playlists/hls/videos/6a1c6b54-480.mp4" + }, + { + "resolution": {"id": 1080, "label": "1080p"}, + "size": 52428800, + "fileUrl": "https://video.example/static/streaming-playlists/hls/6a1c6b54/6a1c6b54-1080-fragmented.mp4", + "fileDownloadUrl": "https://video.example/download/streaming-playlists/hls/videos/6a1c6b54-1080.mp4" + } + ] + } + ] +} diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/videos.json b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/videos.json new file mode 100644 index 0000000000..832975a46d --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/peertube/videos.json @@ -0,0 +1,41 @@ +{ + "total": 3, + "data": [ + { + "id": 31, + "uuid": "6a1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "shortUUID": "dK3h1qWvA8bQ2nPp", + "url": "https://video.example/videos/watch/6a1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "name": "Conference talk", + "description": "Short description", + "publishedAt": "2026-10-22T10:30:00.000Z", + "privacy": {"id": 1, "label": "Public"}, + "state": {"id": 1, "label": "Published"}, + "duration": 1800 + }, + { + "id": 30, + "uuid": "5f1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "shortUUID": "cK3h1qWvA8bQ2nPp", + "url": "https://video.example/videos/watch/5f1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "name": "Unlisted rehearsal", + "description": "Not for everyone", + "publishedAt": "2026-10-22T10:00:00.000Z", + "privacy": {"id": 2, "label": "Unlisted"}, + "state": {"id": 1, "label": "Published"}, + "duration": 600 + }, + { + "id": 29, + "uuid": "4e1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "shortUUID": "bK3h1qWvA8bQ2nPp", + "url": "https://video.example/videos/watch/4e1c6b54-0e3b-4c0e-9b9e-1a2b3c4d5e6f", + "name": "Still transcoding", + "description": "Soon", + "publishedAt": "2026-10-22T09:30:00.000Z", + "privacy": {"id": 1, "label": "Public"}, + "state": {"id": 2, "label": "To transcode"}, + "duration": 900 + } + ] +} diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/pixelfed_statuses.json b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/pixelfed_statuses.json new file mode 100644 index 0000000000..ab2f8e8ec4 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/fixtures/pixelfed_statuses.json @@ -0,0 +1,47 @@ +[ + { + "id": "802", + "uri": "https://picture.example/p/press/802", + "url": "https://picture.example/p/press/802", + "created_at": "2026-10-22T09:05:00.000000Z", + "content": "", + "spoiler_text": "", + "visibility": "public", + "in_reply_to_id": null, + "reblog": { + "id": "700", + "uri": "https://picture.example/p/alice/700", + "url": "https://picture.example/p/alice/700", + "content": "

    Original

    ", + "visibility": "public", + "media_attachments": [], + "tags": [] + }, + "application": {"name": "web", "website": null}, + "media_attachments": [], + "tags": [] + }, + { + "id": "801", + "uri": "https://picture.example/p/press/801", + "url": "https://picture.example/p/press/801", + "created_at": "2026-10-22T09:00:00.000000Z", + "content": "

    Harbour #sunset

    ", + "spoiler_text": "", + "visibility": "public", + "in_reply_to_id": null, + "reblog": null, + "application": {"name": "web", "website": null}, + "media_attachments": [ + { + "id": "9001", + "type": "image", + "url": "https://picture.example/storage/m/_v2/801/harbour.jpg", + "preview_url": "https://picture.example/storage/m/_v2/801/harbour_thumb.jpg", + "description": "Sunset over the harbour", + "meta": {"focus": {"x": 0, "y": 0}} + } + ], + "tags": [{"name": "sunset", "url": "https://picture.example/discover/tags/sunset"}] + } +] diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_mastodon.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_mastodon.py new file mode 100644 index 0000000000..39471cc113 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_mastodon.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import json +import unittest +import urllib.parse +from pathlib import Path +from unittest.mock import patch + +from crossposter.sources import mastodon + +from utils.cache.files import read_text + +FIXTURES = Path(__file__).parent / "fixtures" + + +def fixture(name: str) -> object: + return json.loads(read_text(str(FIXTURES / name))) + + +class FakeMastodon: + def __init__(self, statuses: list[dict]) -> None: + self.statuses = statuses + self.queries: list[dict[str, str]] = [] + + def __call__(self, url: str, headers: dict[str, str]) -> object: + parsed = urllib.parse.urlparse(url) + query = dict(urllib.parse.parse_qsl(parsed.query)) + if parsed.path == "/api/v1/accounts/lookup": + return fixture("mastodon/account.json") + self.queries.append(query) + ordered = sorted(self.statuses, key=lambda status: int(status["id"])) + limit = int(query["limit"]) + if "min_id" not in query: + return ordered[::-1][:limit] + newer = [ + status for status in ordered if int(status["id"]) > int(query["min_id"]) + ] + return newer[:limit][::-1] + + +class TestParse(unittest.TestCase): + def setUp(self) -> None: + self.statuses = fixture("mastodon/statuses.json") + + def test_a_status_becomes_a_source_item(self) -> None: + item = mastodon.parse_status(self.statuses[0], "mastodon") + self.assertEqual(item.uri, self.statuses[0]["uri"]) + self.assertEqual(item.visibility, "public") + self.assertIn("#fediverse", item.text) + self.assertEqual(item.tags, ("fediverse",)) + self.assertEqual(item.cursor, self.statuses[0]["id"]) + + def test_media_carries_type_and_alt_text(self) -> None: + item = mastodon.parse_status(self.statuses[1], "mastodon") + self.assertEqual(item.media[0].mime, "image/png") + self.assertEqual(item.media[0].description, "A red square") + + def test_the_posting_application_is_kept_for_loop_prevention(self) -> None: + self.assertEqual( + mastodon.parse_status(self.statuses[2], "mastodon").application, "OpenPost" + ) + + def test_content_warnings_and_replies_are_kept(self) -> None: + item = mastodon.parse_status(self.statuses[3], "mastodon") + self.assertEqual(item.spoiler, "politics") + self.assertEqual(item.in_reply_to, "109000000000000001") + + +class TestPolling(unittest.TestCase): + def test_the_newest_status_becomes_the_activation_cursor(self) -> None: + fake = FakeMastodon(fixture("mastodon/statuses.json")) + with patch.object(mastodon.web, "get_json", fake): + cursor = mastodon.MastodonSource( + "https://microblog.example", "press", "token" + ).newest_cursor() + self.assertEqual( + cursor, max(fake.statuses, key=lambda status: int(status["id"]))["id"] + ) + + def test_fetch_returns_newer_statuses_oldest_first_and_excludes_replies_and_boosts( + self, + ) -> None: + fake = FakeMastodon(fixture("mastodon/statuses.json")) + with patch.object(mastodon.web, "get_json", fake): + items = mastodon.MastodonSource( + "https://microblog.example", "press", "token" + ).fetch("0") + cursors = [int(item.cursor) for item in items] + self.assertEqual(cursors, sorted(cursors)) + self.assertEqual(fake.queries[0]["exclude_replies"], "true") + self.assertEqual(fake.queries[0]["exclude_reblogs"], "true") + + def test_fetch_pages_with_the_min_id_cursor(self) -> None: + many = [ + dict( + fixture("mastodon/statuses.json")[0], + id=str(200 + index), + uri=f"https://m/{index}", + ) + for index in range(45) + ] + fake = FakeMastodon(many) + with patch.object(mastodon.web, "get_json", fake): + items = mastodon.MastodonSource( + "https://microblog.example", "press", "token" + ).fetch("0") + self.assertEqual(len(items), 45) + self.assertEqual(fake.queries[1]["min_id"], "239") + + def test_refresh_rereads_the_status_with_its_current_media(self) -> None: + stale = mastodon.parse_status(fixture("mastodon/statuses.json")[1], "mastodon") + current = dict(fixture("mastodon/statuses.json")[1]) + current["media_attachments"] = [ + dict(current["media_attachments"][0], url="https://m/optimised.png") + ] + asked: list[str] = [] + + def get_json(url: str, headers: dict[str, str]) -> object: + asked.append(urllib.parse.urlparse(url).path) + return current + + with patch.object(mastodon.web, "get_json", get_json): + fresh = mastodon.MastodonSource( + "https://microblog.example", "press", "token" + ).refresh(stale) + self.assertEqual(asked, [f"/api/v1/statuses/{stale.cursor}"]) + self.assertEqual(fresh.media[0].url, "https://m/optimised.png") + self.assertEqual(fresh.cursor, stale.cursor) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_peertube.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_peertube.py new file mode 100644 index 0000000000..beabfca299 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_peertube.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import json +import unittest +import urllib.parse +from pathlib import Path +from unittest.mock import patch + +from crossposter.sources import peertube + +from utils.cache.files import read_text + +FIXTURES = Path(__file__).parent / "fixtures" + + +def fixture(name: str) -> object: + return json.loads(read_text(str(FIXTURES / name))) + + +def fake_get_json(url: str, headers: dict[str, str]) -> object: + parsed = urllib.parse.urlparse(url) + if parsed.path.startswith("/api/v1/videos/"): + detail = fixture("peertube/video_detail.json") + return dict(detail, uuid=parsed.path.rsplit("/", 1)[-1]) + start = int(dict(urllib.parse.parse_qsl(parsed.query))["start"]) + listing = fixture("peertube/videos.json") + return dict(listing, data=listing["data"][start:]) + + +class TestParse(unittest.TestCase): + def test_a_published_public_video_carries_title_description_tags_and_one_mp4( + self, + ) -> None: + video = fixture("peertube/videos.json")["data"][0] + item = peertube.parse_video(video, fixture("peertube/video_detail.json")) + self.assertEqual(item.title, video["name"]) + self.assertTrue(item.text.startswith("Full description")) + self.assertEqual(item.tags, ("talk", "fediverse")) + self.assertEqual(item.media[0].mime, "video/mp4") + self.assertEqual(item.media[0].size, 52_428_800) + self.assertTrue(item.media[0].url.endswith("-1080.mp4")) + self.assertEqual(item.cursor, video["publishedAt"]) + + def test_only_published_public_videos_pass(self) -> None: + videos = fixture("peertube/videos.json")["data"] + self.assertEqual( + [peertube.published_public(video) for video in videos], [True, False, False] + ) + + +class TestPolling(unittest.TestCase): + def test_the_newest_video_becomes_the_activation_cursor(self) -> None: + with patch.object(peertube.web, "get_json", fake_get_json): + cursor = peertube.PeerTubeSource( + "https://video.example", "press_channel", "token" + ).newest_cursor() + self.assertEqual(cursor, "2026-10-22T10:30:00.000Z") + + def test_fetch_forwards_only_newer_published_public_videos_oldest_first( + self, + ) -> None: + with patch.object(peertube.web, "get_json", fake_get_json): + items = peertube.PeerTubeSource( + "https://video.example", "press_channel", "token" + ).fetch("2026-10-22T09:00:00.000Z") + self.assertEqual([item.title for item in items], ["Conference talk"]) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_pixelfed.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_pixelfed.py new file mode 100644 index 0000000000..d794fc41e0 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/sources/test_pixelfed.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import json +import unittest +import urllib.parse +from pathlib import Path +from unittest.mock import patch + +from crossposter.sources import mastodon, pixelfed + +from utils.cache.files import read_text + +FIXTURES = Path(__file__).parent / "fixtures" + + +def fixture(name: str) -> object: + return json.loads(read_text(str(FIXTURES / name))) + + +class TestPixelfed(unittest.TestCase): + def test_pixelfed_polls_without_the_unsupported_reblog_filter(self) -> None: + queries: list[dict[str, str]] = [] + + def fake(url: str, headers: dict[str, str]) -> object: + parsed = urllib.parse.urlparse(url) + if parsed.path == "/api/v1/accounts/lookup": + return {"id": "42"} + queries.append(dict(urllib.parse.parse_qsl(parsed.query))) + return fixture("pixelfed_statuses.json") + + with patch.object(mastodon.web, "get_json", fake): + items = pixelfed.PixelfedSource( + "https://picture.example", "press", "token" + ).fetch("0") + self.assertNotIn("exclude_reblogs", queries[0]) + self.assertEqual(queries[0]["exclude_replies"], "true") + self.assertEqual([item.platform for item in items], ["pixelfed", "pixelfed"]) + + def test_a_reblog_is_flagged_for_the_route_filter(self) -> None: + statuses = { + status["id"]: status for status in fixture("pixelfed_statuses.json") + } + own = mastodon.parse_status(statuses["801"], pixelfed.PixelfedSource.platform) + boosted = mastodon.parse_status( + statuses["802"], pixelfed.PixelfedSource.platform + ) + self.assertFalse(own.reblog) + self.assertTrue(boosted.reblog) + self.assertEqual(own.media[0].mime, "image/jpeg") + self.assertEqual(own.media[0].description, "Sunset over the harbour") diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test___main__.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test___main__.py new file mode 100644 index 0000000000..17ed64204a --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test___main__.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import time +import unittest +from pathlib import Path + +from crossposter import __main__ as cli + + +class CliFixture: + def setUp(self) -> None: + self.directory = tempfile.TemporaryDirectory() + folder = Path(self.directory.name) + secrets = { + "openpost_token": "op-token", + "database_dsn": "postgresql://crossposter@db/openpost", + "routes": {"press": "source-token"}, + } + (folder / "crossposter-secrets.json").write_text(json.dumps(secrets)) + self.heartbeat = folder / "heartbeat" + self.raw = { + "openpost": { + "base_url": "http://openpost:8080", + "host": "publish.example", + "workspace": "workspace-1", + }, + "secrets_file": str(folder / "crossposter-secrets.json"), + "mail": None, + "heartbeat_file": str(self.heartbeat), + "poll_interval_seconds": 60, + "opt_out_tag": "nocrosspost", + "retry": {"max_attempts": 8, "base_seconds": 30, "cap_seconds": 3600}, + "notify": {"recipients": []}, + "routes": [], + } + self.config = folder / "crossposter.json" + self.write() + + def tearDown(self) -> None: + self.directory.cleanup() + + def write(self) -> None: + self.config.write_text(json.dumps(self.raw)) + + +class TestHealth(CliFixture, unittest.TestCase): + def test_a_fresh_active_heartbeat_is_healthy(self) -> None: + self.heartbeat.write_text(f"{time.time():.0f} active\n") + self.assertEqual(cli.command_health(str(self.config)), 0) + + def test_a_standby_instance_is_healthy(self) -> None: + self.heartbeat.write_text(f"{time.time():.0f} standby\n") + self.assertEqual(cli.command_health(str(self.config)), 0) + + def test_a_stale_heartbeat_is_unhealthy(self) -> None: + self.heartbeat.write_text(f"{time.time() - 600:.0f} active\n") + self.assertEqual(cli.command_health(str(self.config)), 1) + + def test_a_missing_heartbeat_is_unhealthy(self) -> None: + self.assertEqual(cli.command_health(str(self.config)), 1) + + def test_a_waiting_instance_stays_healthy_while_its_configuration_is_incomplete( + self, + ) -> None: + self.raw["routes"] = [{"name": "press", "source": {"platform": "mastodon"}}] + self.write() + self.heartbeat.write_text(f"{time.time():.0f} waiting\n") + self.assertEqual(cli.command_health(str(self.config)), 0) + + def test_waiting_for_provisioning_stays_healthy(self) -> None: + pause = cli.wait_for_configuration(str(self.config), ValueError("no token yet")) + self.assertEqual(pause, 60) + written = self.heartbeat.read_text() # nocheck: cache-read + self.assertTrue(written.strip().endswith("waiting")) + self.assertEqual(cli.command_health(str(self.config)), 0) + + +class TestValidate(CliFixture, unittest.TestCase): + def test_an_invalid_route_names_route_and_field(self) -> None: + self.raw["routes"] = [ + { + "name": "press", + "source": { + "platform": "myspace", + "base_url": "https://microblog.example", + "account": "press", + }, + "filters": {"visibility": ["public"], "media": "any"}, + "targets": {"accounts": ["x-press"]}, + "mode": "review", + "attribution": {"default": "{text}"}, + } + ] + self.write() + errors = io.StringIO() + with contextlib.redirect_stderr(errors): + self.assertEqual(cli.command_validate(str(self.config)), 2) + self.assertIn("route 'press': source.platform", errors.getvalue()) + + def test_no_routes_validate_without_asking_openpost(self) -> None: + output = io.StringIO() + with contextlib.redirect_stdout(output): + self.assertEqual(cli.command_validate(str(self.config)), 0) + self.assertIn("0 route(s) valid", output.getvalue()) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_adapt.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_adapt.py new file mode 100644 index 0000000000..dd81e4ad9c --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_adapt.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +import unittest + +from crossposter import adapt +from crossposter.sources import Media, SourceItem + +URL = "https://example.org/a/very/long/path/that/would/count/far/more/than/twenty/three" +PICTURE = Media( + url="https://microblog.example/a.png", + mime="image/png", + description="A red square", + size=2048, +) +SMALL_VIDEO = Media( + url="https://video.example/a.mp4", + mime="video/mp4", + description="", + size=10 * 1024 * 1024, +) +LARGE_VIDEO = Media( + url="https://video.example/b.mp4", + mime="video/mp4", + description="", + size=200 * 1024 * 1024, +) +TEMPLATES = {"default": "{text}\n\n{source_url}", "x": "{text}"} + + +def item(**overrides) -> SourceItem: + values = { + "uri": "https://microblog.example/users/press/statuses/1", + "url": "https://microblog.example/@press/1", + "platform": "mastodon", + "text": "Hello world", + "visibility": "public", + "tags": (), + "media": (), + "in_reply_to": "", + "reblog": False, + "spoiler": "", + "application": "", + } + values.update(overrides) + return SourceItem(**values) + + +def prepare(source: SourceItem, network: str, mode: str = "auto") -> adapt.Plan: + return adapt.prepare( + source, network, TEMPLATES.get(network, TEMPLATES["default"]), mode + ) + + +class TestCounting(unittest.TestCase): + def test_mastodon_counts_a_link_as_twenty_three(self) -> None: + self.assertEqual(adapt.count(f"see {URL}", "mastodon"), 4 + 23) + + def test_mastodon_counts_a_remote_mention_by_its_username(self) -> None: + self.assertEqual( + adapt.count("@alice@social.example hi", "mastodon"), len("@alice hi") + ) + + def test_mastodon_counts_graphemes_not_code_points(self) -> None: + family = ( + "\U0001f468\N{ZERO WIDTH JOINER}\U0001f469\N{ZERO WIDTH JOINER}\U0001f467" + ) + self.assertEqual(adapt.count(family, "mastodon"), 1) + self.assertEqual(adapt.count("é", "mastodon"), 1) + + def test_mastodon_adds_the_content_warning(self) -> None: + self.assertEqual(adapt.count("body", "mastodon", spoiler="cw"), 6) + + def test_x_weights_cjk_and_emoji_double(self) -> None: + self.assertEqual(adapt.count("abc", "x"), 3) + self.assertEqual(adapt.count("日本", "x"), 4) + self.assertEqual(adapt.count("\U0001f600", "x"), 2) + self.assertEqual(adapt.count("\U0001f44d\U0001f3fd", "x"), 2) + + def test_x_counts_a_link_as_twenty_three(self) -> None: + self.assertEqual(adapt.count(URL, "x"), 23) + + def test_fits_respects_the_network_limit(self) -> None: + self.assertTrue(adapt.fits("a" * 280, "x")) + self.assertFalse(adapt.fits("a" * 281, "x")) + self.assertTrue(adapt.fits("a" * 500, "threads")) + self.assertFalse(adapt.fits("a" * 501, "threads")) + + +class TestShorten(unittest.TestCase): + def test_text_within_the_limit_is_unchanged(self) -> None: + self.assertEqual(adapt.shorten("short", "x"), "short") + + def test_shortening_never_splits_a_word(self) -> None: + text = " ".join(["word"] * 100) + shortened = adapt.shorten(text, "x") + self.assertTrue(adapt.fits(shortened, "x")) + self.assertTrue(shortened.endswith("…")) + self.assertTrue(all(token == "word" for token in shortened[:-1].split())) + + def test_shortening_keeps_links_and_hashtags_whole(self) -> None: + text = ("lorem " * 50) + URL + " #fediverse " + ("ipsum " * 50) + shortened = adapt.shorten(text, "x") + self.assertTrue(adapt.fits(shortened, "x")) + for token in shortened.rstrip("…").split(): + self.assertIn(token, text.split()) + + def test_instagram_keeps_at_most_thirty_hashtags(self) -> None: + text = "caption " + " ".join(f"#tag{index}" for index in range(40)) + shortened = adapt.shorten(text, "instagram") + self.assertEqual( + len([token for token in shortened.split() if token.startswith("#")]), 30 + ) + + def test_reserve_leaves_room_for_the_attribution(self) -> None: + shortened = adapt.shorten("a " * 400, "x", reserve=30) + self.assertLessEqual(adapt.count(shortened, "x"), 250) + + +class TestHtml(unittest.TestCase): + def test_mastodon_html_becomes_text_with_links_and_mentions(self) -> None: + html = ( + '

    Hello ' + "@alice see " + '' + 'example.org/page

    second
    line ' + '#news

    ' + ) + self.assertEqual( + adapt.html_to_text(html), + "Hello @alice@social.example see https://example.org/page\n\nsecond\nline #news", + ) + + +class TestMentions(unittest.TestCase): + def test_finds_fediverse_handles(self) -> None: + self.assertEqual( + adapt.mentions("hi @alice@social.example and @bob@pix.example."), + ["@alice@social.example", "@bob@pix.example"], + ) + + def test_fediverse_targets_keep_handles(self) -> None: + self.assertEqual( + adapt.rewrite_mentions("hi @alice@social.example", "mastodon"), + "hi @alice@social.example", + ) + + def test_x_gets_plain_names(self) -> None: + self.assertEqual( + adapt.rewrite_mentions("hi @alice@social.example", "x"), "hi alice" + ) + + def test_other_commercial_targets_get_profile_links(self) -> None: + self.assertEqual( + adapt.rewrite_mentions("hi @alice@social.example", "linkedin"), + "hi alice (https://social.example/@alice)", + ) + + +class TestCompose(unittest.TestCase): + def test_renders_the_template_with_the_source_link(self) -> None: + self.assertEqual( + adapt.compose( + "{text}\n\n{source_url}", + "hello", + "https://social.example/@press/1", + "linkedin", + ), + "hello\n\nhttps://social.example/@press/1", + ) + + def test_the_composed_text_fits_the_target(self) -> None: + composed = adapt.compose( + "{text}\n\n{source_url}", + "word " * 200, + "https://social.example/@press/1", + "x", + ) + self.assertTrue(adapt.fits(composed, "x")) + self.assertTrue(composed.endswith("https://social.example/@press/1")) + + +class TestPrepare(unittest.TestCase): + def test_a_text_post_becomes_short_text_with_attribution(self) -> None: + plan = prepare(item(), "linkedin") + self.assertEqual(plan.profile, "short_text") + self.assertEqual(plan.text, "Hello world\n\nhttps://microblog.example/@press/1") + self.assertFalse(plan.draft_only) + self.assertEqual(plan.skip, "") + + def test_the_x_template_omits_the_link(self) -> None: + self.assertEqual(prepare(item(), "x").text, "Hello world") + + def test_review_routes_always_draft(self) -> None: + self.assertTrue(prepare(item(), "linkedin", mode="review").draft_only) + + def test_a_content_warning_forces_a_draft(self) -> None: + self.assertTrue(prepare(item(spoiler="politics"), "linkedin").draft_only) + + def test_unmappable_mentions_force_a_draft_on_commercial_targets(self) -> None: + mentioned = item(text="thanks @alice@social.example") + self.assertTrue(prepare(mentioned, "linkedin").draft_only) + self.assertFalse(prepare(mentioned, "mastodon").draft_only) + + def test_images_keep_their_alt_text(self) -> None: + plan = prepare(item(media=(PICTURE,)), "facebook") + self.assertEqual(plan.profile, "image_post") + self.assertEqual( + [(entry.media.url, entry.alt_text) for entry in plan.media], + [(PICTURE.url, "A red square")], + ) + self.assertFalse(plan.media[0].jpeg) + + def test_instagram_images_are_converted_to_jpeg(self) -> None: + self.assertTrue(prepare(item(media=(PICTURE,)), "instagram").media[0].jpeg) + + def test_pixelfed_skips_posts_without_media(self) -> None: + self.assertEqual( + prepare(item(), "pixelfed").skip, "pixelfed accepts only posts with media" + ) + self.assertEqual(prepare(item(media=(PICTURE,)), "pixelfed").skip, "") + + def test_a_large_video_reaches_mastodon_as_a_link(self) -> None: + video = item( + platform="peertube", + media=(LARGE_VIDEO,), + title="Talk", + text="About the talk", + url="https://video.example/w/abc", + ) + plan = prepare(video, "mastodon") + self.assertEqual(plan.media, ()) + self.assertEqual(plan.profile, "short_text") + self.assertIn("https://video.example/w/abc", plan.text) + + def test_a_small_video_travels_as_a_file(self) -> None: + video = item( + platform="peertube", + media=(SMALL_VIDEO,), + title="Talk", + text="About the talk", + url="https://video.example/w/abc", + ) + plan = prepare(video, "youtube") + self.assertEqual(plan.profile, "video") + self.assertEqual([entry.media for entry in plan.media], [SMALL_VIDEO]) + self.assertEqual(plan.title, "Talk") + self.assertTrue(plan.text.startswith("Talk\n\nAbout the talk")) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_config.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_config.py new file mode 100644 index 0000000000..c0c4deefbe --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_config.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from crossposter import config +from crossposter.sources import Media, SourceItem + +SECRETS = { + "openpost_token": "op-token", + "database_dsn": "postgresql://crossposter@db/openpost", + "mail_password": "mail-secret", + "routes": {"press-mastodon": "secret"}, +} + + +def route() -> dict: + return { + "name": "press-mastodon", + "source": { + "platform": "mastodon", + "base_url": "https://microblog.example", + "account": "press", + }, + "filters": { + "visibility": ["public"], + "exclude_replies": True, + "exclude_reblogs": True, + "tags": [], + "media": "any", + }, + "targets": {"accounts": ["x-press"]}, + "mode": "review", + "attribution": {"default": "{text}\n\n{source_url}", "x": "{text}"}, + } + + +class ConfigFixture: + def setUp(self) -> None: + self.directory = tempfile.TemporaryDirectory() + folder = Path(self.directory.name) + self.secrets = folder / "crossposter-secrets.json" + self.write_secrets(SECRETS) + self.raw = { + "openpost": { + "base_url": "http://openpost:8080", + "host": "publish.example", + "workspace": "workspace-1", + }, + "secrets_file": str(self.secrets), + "mail": { + "host": "mail.example", + "port": 587, + "security": "starttls", + "user": "crossposter", + "sender": "crossposter@example.org", + }, + "heartbeat_file": str(folder / "heartbeat"), + "poll_interval_seconds": 60, + "opt_out_tag": "nocrosspost", + "retry": {"max_attempts": 8, "base_seconds": 30, "cap_seconds": 3600}, + "notify": {"recipients": ["press@example.org"]}, + "routes": [route()], + } + + def tearDown(self) -> None: + self.directory.cleanup() + + def write_secrets(self, values: dict) -> None: + self.secrets.write_text(json.dumps(values)) + + def broken(self, mutate) -> str: + raw = copy.deepcopy(self.raw) + mutate(raw["routes"][0]) + with self.assertRaises(config.ConfigError) as caught: + config.parse(raw) + return str(caught.exception) + + +class TestParse(ConfigFixture, unittest.TestCase): + def test_a_complete_route_parses(self) -> None: + parsed = config.parse(self.raw) + self.assertEqual(parsed.routes[0].source.token, "secret") + self.assertEqual(parsed.routes[0].targets.accounts, ("x-press",)) + self.assertEqual(parsed.retry.max_attempts, 8) + + def test_secrets_are_read_from_the_secrets_file(self) -> None: + parsed = config.parse(self.raw) + self.assertEqual(parsed.openpost.token, "op-token") + self.assertEqual(parsed.dsn, "postgresql://crossposter@db/openpost") + self.assertEqual(parsed.mail.password, "mail-secret") + + def test_mail_is_optional(self) -> None: + raw = copy.deepcopy(self.raw) + raw["mail"] = None + self.assertIsNone(config.parse(raw).mail) + + def test_an_unknown_platform_names_route_and_field(self) -> None: + message = self.broken(lambda item: item["source"].update(platform="myspace")) + self.assertIn("press-mastodon", message) + self.assertIn("source.platform", message) + + def test_a_missing_token_names_route_and_field(self) -> None: + self.write_secrets({**SECRETS, "routes": {"press-mastodon": ""}}) + message = self.broken(lambda item: None) + self.assertIn("press-mastodon", message) + self.assertIn("source.token", message) + + def test_targets_need_accounts_or_a_social_set(self) -> None: + message = self.broken(lambda item: item.update(targets={})) + self.assertIn("targets", message) + + def test_a_mode_outside_review_and_auto_is_refused(self) -> None: + message = self.broken(lambda item: item.update(mode="yolo")) + self.assertIn("mode", message) + + def test_an_attribution_template_needs_the_text(self) -> None: + message = self.broken(lambda item: item["attribution"].update(x="{source_url}")) + self.assertIn("attribution.x", message) + + def test_the_source_must_use_https(self) -> None: + message = self.broken( + lambda item: item["source"].update(base_url="http://microblog.example") + ) + self.assertIn("source.base_url", message) + + def test_an_onion_source_may_use_plain_http(self) -> None: + raw = copy.deepcopy(self.raw) + onion = "http://microblog." + "a" * 56 + ".onion" + raw["routes"][0]["source"]["base_url"] = onion + self.assertEqual(config.parse(raw).routes[0].source.base_url, onion) + + def test_route_names_are_unique(self) -> None: + raw = copy.deepcopy(self.raw) + raw["routes"].append(copy.deepcopy(raw["routes"][0])) + with self.assertRaises(config.ConfigError): + config.parse(raw) + + def test_new_routes_default_to_review_mode(self) -> None: + raw = copy.deepcopy(self.raw) + del raw["routes"][0]["mode"] + self.assertEqual(config.parse(raw).routes[0].mode, "review") + + def test_attribution_falls_back_to_the_default_template(self) -> None: + parsed = config.parse(self.raw).routes[0] + self.assertEqual(parsed.template("linkedin"), "{text}\n\n{source_url}") + self.assertEqual(parsed.template("x"), "{text}") + + +def item(**overrides) -> SourceItem: + values = { + "uri": "https://microblog.example/users/press/statuses/1", + "url": "https://microblog.example/@press/1", + "platform": "mastodon", + "text": "Hello #news", + "visibility": "public", + "tags": ("news",), + "media": (), + "in_reply_to": "", + "reblog": False, + "spoiler": "", + "application": "", + } + values.update(overrides) + return SourceItem(**values) + + +class TestRouting(ConfigFixture, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + self.route = config.parse(self.raw).routes[0] + + def test_a_public_post_is_admitted(self) -> None: + self.assertIsNone(self.route.refusal(item(), "nocrosspost")) + + def test_the_opt_out_hashtag_is_never_forwarded(self) -> None: + self.assertEqual( + self.route.refusal(item(tags=("news", "NoCrossPost")), "nocrosspost"), + "opt-out", + ) + + def test_other_visibilities_are_refused(self) -> None: + self.assertEqual( + self.route.refusal(item(visibility="unlisted"), "nocrosspost"), "visibility" + ) + + def test_replies_and_boosts_are_refused(self) -> None: + self.assertEqual( + self.route.refusal(item(in_reply_to="https://x/1"), "nocrosspost"), "reply" + ) + self.assertEqual(self.route.refusal(item(reblog=True), "nocrosspost"), "reblog") + + def test_posts_published_by_openpost_are_refused(self) -> None: + self.assertEqual( + self.route.refusal(item(application="OpenPost"), "nocrosspost"), "loop" + ) + + def test_required_tags_filter(self) -> None: + raw = copy.deepcopy(self.raw) + raw["routes"][0]["filters"]["tags"] = ["press"] + tagged = config.parse(raw).routes[0] + self.assertEqual(tagged.refusal(item(), "nocrosspost"), "tags") + self.assertIsNone(tagged.refusal(item(tags=("Press",)), "nocrosspost")) + + def test_hashtags_in_the_text_count_when_the_source_lists_no_tags(self) -> None: + raw = copy.deepcopy(self.raw) + raw["routes"][0]["filters"]["tags"] = ["press"] + tagged = config.parse(raw).routes[0] + self.assertIsNone( + tagged.refusal(item(text="Launch day #Press", tags=()), "nocrosspost") + ) + self.assertEqual( + tagged.refusal(item(text="Press day", tags=()), "nocrosspost"), "tags" + ) + + def test_the_opt_out_hashtag_in_the_text_is_never_forwarded(self) -> None: + self.assertEqual( + self.route.refusal(item(text="Hi #NoCrossPost", tags=()), "nocrosspost"), + "opt-out", + ) + + def test_media_filters(self) -> None: + raw = copy.deepcopy(self.raw) + raw["routes"][0]["filters"]["media"] = "required" + required = config.parse(raw).routes[0] + self.assertEqual(required.refusal(item(), "nocrosspost"), "media") + picture = Media( + url="https://microblog.example/a.png", + mime="image/png", + description="", + size=1024, + ) + self.assertIsNone(required.refusal(item(media=(picture,)), "nocrosspost")) + raw["routes"][0]["filters"]["media"] = "none" + self.assertEqual( + config.parse(raw).routes[0].refusal(item(media=(picture,)), "nocrosspost"), + "media", + ) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_notify.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_notify.py new file mode 100644 index 0000000000..2cbc1c6705 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_notify.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import unittest +from email.message import EmailMessage + +from crossposter import notify + +ROW = { + "route": "press-mastodon", + "source_url": "https://microblog.example/@press/1", + "network": "x", + "target": "x-press", + "state": "dead_lettered", + "attempts": 8, + "last_error": "https://api.twitter.com/2/tweets: HTTP 503 unavailable", +} + + +class TestReport(unittest.TestCase): + def test_the_report_names_source_target_and_error(self) -> None: + report = notify.report([ROW]) + for expected in ( + "https://microblog.example/@press/1", + "x-press", + "HTTP 503 unavailable", + "dead_lettered", + "press-mastodon", + ): + self.assertIn(expected, report) + + def test_the_message_carries_subject_and_recipients(self) -> None: + message = notify.message( + "crossposter@example.org", ("press@example.org", "pr@example.org"), [ROW] + ) + self.assertIsInstance(message, EmailMessage) + self.assertEqual(message["To"], "press@example.org, pr@example.org") + self.assertIn("1", message["Subject"]) + self.assertIn("x-press", message.get_content()) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_openpost.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_openpost.py new file mode 100644 index 0000000000..8455a4e4bf --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_openpost.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from crossposter import openpost, web +from crossposter.config import Targets + +ACCOUNTS = [ + {"id": "acc-x", "slug": "x-press", "platform": "x"}, + {"id": "acc-li", "slug": "linkedin-press", "platform": "linkedin"}, +] +SOCIAL_SETS = [ + { + "name": "Commercial", + "accounts": [ + {"social_account_id": "acc-x", "platform": "x", "default_settings": {}}, + { + "social_account_id": "acc-li", + "platform": "linkedin", + "default_settings": {"visibility": "PUBLIC"}, + }, + ], + } +] + + +class FakeOpenPost: + def __init__(self) -> None: + self.calls: list[tuple[str, str, dict, bytes | None]] = [] + + def __call__( + self, + method: str, + url: str, + headers: dict, + body: bytes | None, + accepted: tuple[int, ...], + ) -> web.Response: + self.calls.append((method, url, headers, body)) + path = url.split("/api/v1", 1)[-1] + if path.startswith("/accounts"): + return web.Response(200, {}, json.dumps(ACCOUNTS).encode()) + if path.startswith("/social-sets"): + return web.Response(200, {}, json.dumps(SOCIAL_SETS).encode()) + if path == "/publications": + return web.Response( + 201, + {}, + json.dumps({"id": "pub-1", "revision": 1, "status": "draft"}).encode(), + ) + if path == "/media/upload-session": + session = { + "media_id": "media-1", + "complete_url": "/api/v1/media/upload-session/media-1/complete", + "upload": { + "url": "/media/upload/media-1", + "method": "PUT", + "headers": {}, + }, + } + return web.Response(200, {}, json.dumps(session).encode()) + if path.endswith("/complete"): + completed = {"id": "media-0", "deduped": True} + return web.Response(200, {}, json.dumps(completed).encode()) + return web.Response(200, {}, b"{}") + + +def client() -> openpost.OpenPost: + return openpost.OpenPost( + "http://openpost:8080", "publish.example", "op-token", "workspace-1" + ) + + +class TestDestinations(unittest.TestCase): + def test_accounts_resolve_by_slug(self) -> None: + with patch.object(openpost.web, "request", FakeOpenPost()): + found = client().destinations(Targets(("linkedin-press",), "")) + self.assertEqual( + [(item.account_id, item.platform) for item in found], + [("acc-li", "linkedin")], + ) + + def test_an_unknown_slug_is_refused(self) -> None: + with ( + patch.object(openpost.web, "request", FakeOpenPost()), + self.assertRaises(openpost.TargetError), + ): + client().destinations(Targets(("myspace-press",), "")) + + def test_a_social_set_expands_to_its_accounts_with_their_defaults(self) -> None: + with patch.object(openpost.web, "request", FakeOpenPost()): + found = client().destinations(Targets((), "Commercial")) + self.assertEqual([item.slug for item in found], ["x-press", "linkedin-press"]) + self.assertEqual(found[1].settings, {"visibility": "PUBLIC"}) + + def test_an_unknown_social_set_is_refused(self) -> None: + with ( + patch.object(openpost.web, "request", FakeOpenPost()), + self.assertRaises(openpost.TargetError), + ): + client().destinations(Targets((), "Nowhere")) + + +class TestRequests(unittest.TestCase): + def test_create_sends_the_idempotency_key_and_the_alt_text(self) -> None: + fake = FakeOpenPost() + destination = openpost.Destination("acc-x", "x-press", "x", {}) + with patch.object(openpost.web, "request", fake): + client().create( + destination, + "Title", + "Body", + "image_post", + [("media-1", "A red square")], + "crossposter-abc", + {"crossposter_source": "https://microblog.example/@press/1"}, + ) + method, url, headers, body = fake.calls[-1] + self.assertEqual( + (method, url), ("POST", "http://openpost:8080/api/v1/publications") + ) + self.assertEqual(headers["Idempotency-Key"], "crossposter-abc") + self.assertEqual(headers["Authorization"], "Bearer op-token") + payload = json.loads(body) + self.assertEqual( + payload["media"], [{"media_id": "media-1", "alt_text": "A red square"}] + ) + self.assertEqual(payload["social_account_ids"], ["acc-x"]) + self.assertEqual( + payload["metadata"], + {"crossposter_source": "https://microblog.example/@press/1"}, + ) + + def test_local_uploads_go_to_openpost_with_its_credentials(self) -> None: + fake = FakeOpenPost() + uploads: list[tuple[str, dict]] = [] + + def upload( + method: str, + url: str, + headers: dict, + source: Path, + accepted: tuple[int, ...], + ) -> web.Response: + uploads.append((url, headers)) + return web.Response(200, {}, b"") + + with tempfile.TemporaryDirectory() as folder: + image = Path(folder) / "a.jpg" + image.write_bytes(b"\xff\xd8 image") + with ( + patch.object(openpost.web, "request", fake), + patch.object(openpost.web, "upload", upload), + ): + media = client().upload(image, "a.jpg", "image/jpeg") + self.assertEqual(media, "media-0") + self.assertEqual(uploads[0][0], "http://openpost:8080/media/upload/media-1") + self.assertEqual(uploads[0][1]["Authorization"], "Bearer op-token") + self.assertTrue( + fake.calls[-1][1].endswith("/media/upload-session/media-1/complete") + ) + + +class TestPublicMedia(unittest.TestCase): + def answers(self, states: list[list[dict]]) -> list[str]: + asked: list[str] = [] + self.validated: list[str] = [] + + def request(method, url, headers, body, accepted) -> web.Response: + if method == "POST": + self.validated.append(url) + return web.Response(200, {}, b'{"valid": true, "issues": []}') + asked.append(url) + media = states[min(len(asked), len(states)) - 1] + return web.Response(200, {}, json.dumps({"media": media}).encode()) + + self.request = request + return asked + + def test_publishing_waits_until_every_medium_is_public(self) -> None: + asked = self.answers( + [ + [{"public_url_checked_at": None}], + [{"public_url_checked_at": "now", "public_url_ready": False}], + [{"public_url_checked_at": "now", "public_url_ready": True}], + ] + ) + with ( + patch.object(openpost.web, "request", self.request), + patch.object(openpost.time, "sleep", lambda seconds: None), + ): + client().await_media("pub-1") + self.assertEqual(len(asked), 3) + self.assertTrue(asked[0].endswith("/publications/pub-1")) + self.assertEqual(len(self.validated), 3) + self.assertTrue(self.validated[0].endswith("/publications/pub-1/validate")) + + def test_media_that_never_turns_public_is_a_transient_error(self) -> None: + self.answers([[{"public_url_checked_at": "now", "public_url_ready": False}]]) + with ( + patch.object(openpost.web, "request", self.request), + patch.object(openpost.time, "sleep", lambda seconds: None), + self.assertRaises(web.RequestError) as raised, + ): + client().await_media("pub-1") + self.assertTrue(raised.exception.transient) + + def test_a_video_also_waits_for_its_analysis(self) -> None: + public = {"public_url_checked_at": "now", "public_url_ready": True} + asked = self.answers( + [ + [{**public, "mime_type": "video/mp4", "analysis_status": "pending"}], + [{**public, "mime_type": "video/mp4", "analysis_status": "ready"}], + ] + ) + with ( + patch.object(openpost.web, "request", self.request), + patch.object(openpost.time, "sleep", lambda seconds: None), + ): + client().await_media("pub-1") + self.assertEqual(len(asked), 2) + + def test_an_image_needs_no_analysis(self) -> None: + self.assertTrue( + openpost.publishable( + { + "public_url_checked_at": "now", + "public_url_ready": True, + "mime_type": "image/jpeg", + "analysis_status": "pending", + } + ) + ) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_retry.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_retry.py new file mode 100644 index 0000000000..3e0f671a25 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_retry.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import random +import unittest +from datetime import UTC, datetime +from email.utils import format_datetime + +from crossposter import retry + +NOW = 1_800_000_000.0 + + +def seeded(seed: int) -> random.Random: + return random.Random(seed) # noqa: S311 reproducible jitter for the assertions + + +class TestBackoff(unittest.TestCase): + def test_the_jitter_stays_within_the_exponential_window(self) -> None: + rng = seeded(7) + for attempt in range(1, 8): + window = min(3600, 30 * 2 ** (attempt - 1)) + for _ in range(50): + self.assertLessEqual(retry.backoff(attempt, 30, 3600, rng), window) + + def test_the_window_is_capped(self) -> None: + rng = seeded(1) + self.assertLessEqual( + max(retry.backoff(40, 30, 3600, rng) for _ in range(200)), 3600 + ) + + def test_jitter_spreads_the_delays(self) -> None: + rng = seeded(3) + self.assertGreater( + len({round(retry.backoff(4, 30, 3600, rng), 3) for _ in range(20)}), 10 + ) + + +class TestServerHints(unittest.TestCase): + def test_retry_after_seconds(self) -> None: + self.assertEqual(retry.server_delay({"Retry-After": "120"}, NOW), 120) + + def test_retry_after_http_date(self) -> None: + when = format_datetime(datetime.fromtimestamp(NOW + 90, tz=UTC), usegmt=True) + self.assertEqual(retry.server_delay({"retry-after": when}, NOW), 90) + + def test_epoch_rate_limit_reset(self) -> None: + self.assertEqual( + retry.server_delay({"x-rate-limit-reset": str(int(NOW + 45))}, NOW), 45 + ) + + def test_iso_rate_limit_reset(self) -> None: + iso = ( + datetime.fromtimestamp(NOW + 30, tz=UTC).isoformat().replace("+00:00", "Z") + ) + self.assertEqual(retry.server_delay({"X-RateLimit-Reset": iso}, NOW), 30) + + def test_delta_rate_limit_reset(self) -> None: + self.assertEqual(retry.server_delay({"RateLimit-Reset": "12"}, NOW), 12) + + def test_without_hints_there_is_no_server_delay(self) -> None: + self.assertEqual(retry.server_delay({}, NOW), 0) + + def test_a_reset_in_the_past_means_no_wait(self) -> None: + self.assertEqual( + retry.server_delay({"x-rate-limit-reset": str(int(NOW - 10))}, NOW), 0 + ) + + +class TestDelay(unittest.TestCase): + def test_the_server_hint_wins_over_a_shorter_backoff(self) -> None: + rng = seeded(5) + self.assertGreaterEqual( + retry.delay(1, {"Retry-After": "600"}, NOW, 30, 3600, rng), 600 + ) + + def test_without_a_hint_the_backoff_applies(self) -> None: + rng = seeded(5) + self.assertLessEqual(retry.delay(2, {}, NOW, 30, 3600, rng), 60) + + +class TestTransient(unittest.TestCase): + def test_network_errors_rate_limits_and_server_errors_are_transient(self) -> None: + for status in (None, 408, 425, 429, 500, 502, 503, 504): + self.assertTrue(retry.transient(status), status) + + def test_client_errors_are_permanent(self) -> None: + for status in (400, 401, 403, 404, 409, 422): + self.assertFalse(retry.transient(status), status) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_service.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_service.py new file mode 100644 index 0000000000..7f2b70feb6 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_service.py @@ -0,0 +1,492 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from dataclasses import replace +from pathlib import Path +from unittest.mock import patch + +from crossposter import service, store, web +from crossposter.config import ( + Config, + Filters, + OpenPostSettings, + Retry, + Route, + Source, + Targets, +) +from crossposter.notify import Mail +from crossposter.openpost import Destination +from crossposter.sources import Media, SourceItem + +DESTINATIONS = [ + Destination("acc-x", "x-press", "x", {}), + Destination("acc-li", "linkedin-press", "linkedin", {}), +] + + +def post(number: int, tags: tuple[str, ...] = ()) -> SourceItem: + return SourceItem( + uri=f"https://microblog.example/users/press/statuses/{number}", + url=f"https://microblog.example/@press/{number}", + platform="mastodon", + text=f"Post {number}", + visibility="public", + tags=tags, + media=(), + in_reply_to="", + reblog=False, + spoiler="", + application="", + cursor=str(number), + ) + + +SOURCE_TOKEN = {"Authorization": "Bearer source-token"} + + +class TestMediaCredentials(unittest.TestCase): + def test_media_on_the_source_origin_gets_the_source_token(self) -> None: + self.assertEqual( + service.credentials_for( + "https://microblog.example", + "https://microblog.example/system/media/1.png", + SOURCE_TOKEN, + ), + SOURCE_TOKEN, + ) + + def test_media_in_an_object_store_never_sees_the_source_token(self) -> None: + self.assertEqual( + service.credentials_for( + "https://microblog.example", + "https://s3.example/mastodon/media/1.png", + SOURCE_TOKEN, + ), + {}, + ) + + +def picture(number: int, url: str) -> SourceItem: + return replace(post(number), media=(Media(url, "image/jpeg", "", 0),)) + + +class FakeSource: + def __init__(self, items: list[SourceItem]) -> None: + self.items = items + self.headers: dict[str, str] = {} + self.fresh_url = "" + + def refresh(self, item: SourceItem) -> SourceItem: + if not self.fresh_url: + return item + return replace( + item, media=tuple(replace(m, url=self.fresh_url) for m in item.media) + ) + + def newest_cursor(self) -> str: + return "100" + + def fetch(self, cursor: str) -> list[SourceItem]: + return [item for item in self.items if int(item.cursor) > int(cursor)] + + +class FakeStore: + def __init__(self) -> None: + self.cursors: dict[str, str] = {} + self.items: list[dict] = [] + self.notified: list[int] = [] + + def cursor(self, route: str) -> str | None: + return self.cursors.get(route) + + def advance( + self, route: str, cursor: str, enqueued: list[tuple[SourceItem, str, str]] + ) -> None: + for item, target, network in enqueued: + if any( + row["source_uri"] == item.uri and row["target"] == target + for row in self.items + ): + continue + self.items.append( + { + "id": len(self.items) + 1, + "route": route, + "source_uri": item.uri, + "source_url": item.url, + "target": target, + "network": network, + "state": "pending", + "payload": json.loads(store.item_to_json(item)), + "publication_id": "", + "attempts": 0, + "resends": 0, + "last_error": "", + "delay": 0.0, + "notified": False, + } + ) + self.cursors[route] = cursor + + def due(self) -> list[dict]: + return [dict(row) for row in self.items if row["state"] == "pending"] + + def open_publications(self) -> list[dict]: + return [ + dict(row) for row in self.items if row["state"] in ("drafted", "submitted") + ] + + def unnotified(self) -> list[dict]: + return [ + dict(row) + for row in self.items + if row["state"] in ("failed", "dead_lettered") and not row["notified"] + ] + + def update( + self, + row_id: int, + state: str, + publication_id: str, + attempts: int, + error: str, + delay_seconds: float, + ) -> None: + row = self.items[row_id - 1] + row.update( + state=state, + publication_id=publication_id, + attempts=attempts, + last_error=error, + delay=delay_seconds, + ) + + def resend( + self, row_id: int, attempts: int, error: str, delay_seconds: float + ) -> None: + row = self.items[row_id - 1] + row.update( + state="pending", + resends=row["resends"] + 1, + publication_id="", + attempts=attempts, + last_error=error, + delay=delay_seconds, + ) + + def mark_notified(self, row_id: int) -> None: + self.items[row_id - 1]["notified"] = True + + +REJECTED = { + "status": "failed", + "error_retryable": False, + "error_http_status": 400, + "delivery": {"terminal_reason": "provider_rejected"}, +} +UNAVAILABLE = { + "status": "failed", + "error_retryable": False, + "error_http_status": 503, + "delivery": {"recovery_action": "manual_resolution"}, +} + + +class FakeOpenPost: + def __init__(self) -> None: + self.created: list[tuple[str, str, str]] = [] + self.metadata: list[dict] = [] + self.published: list[str] = [] + self.failure: web.RequestError | None = None + self.publish_failure: web.RequestError | None = None + self.outcome: list[dict] = [] + + def destinations(self, targets: Targets) -> list[Destination]: + return DESTINATIONS + + def create(self, destination, title, text, profile, media, key, metadata) -> dict: + if self.failure: + raise self.failure + self.created.append((destination.account_id, text, key)) + self.metadata.append(metadata) + return {"id": f"pub-{len(self.created)}", "revision": 1, "status": "draft"} + + def publication(self, publication_id: str) -> dict: + return {"id": publication_id, "revision": 1, "status": "draft"} + + def upload(self, source: Path, filename: str, mime: str) -> str: + return f"media-{filename}" + + def publish_now(self, publication: dict) -> None: + if self.publish_failure: + raise self.publish_failure + self.published.append(publication["id"]) + + def renditions(self, publication_id: str) -> list[dict]: + return self.outcome + + +def route(mode: str) -> Route: + return Route( + name="press", + source=Source("mastodon", "https://microblog.example", "press", "token"), + filters=Filters(frozenset({"public"}), True, True, frozenset(), "any"), + targets=Targets(("x-press", "linkedin-press"), ""), + mode=mode, + attribution={"default": "{text}\n\n{source_url}", "x": "{text}"}, + ) + + +class ServiceFixture: + def build( + self, mode: str, items: list[SourceItem], database: FakeStore | None = None + ) -> tuple[service.Service, FakeStore, FakeOpenPost]: + folder = tempfile.mkdtemp() + config = Config( + openpost=OpenPostSettings( + "http://openpost:8080", "publish.example", "op-token", "workspace-1" + ), + dsn="postgresql://unused", + mail=Mail( + "mail.example", 587, "starttls", "", "", "crossposter@example.org" + ), + heartbeat_file=str(Path(folder) / "heartbeat"), + poll_interval_seconds=60, + opt_out_tag="nocrosspost", + retry=Retry(3, 30, 3600), + recipients=("press@example.org",), + routes=(route(mode),), + ) + database = database or FakeStore() + client = FakeOpenPost() + runner = service.Service(config, database, client) + runner.sources["press"] = FakeSource(items) + return runner, database, client + + +class TestDetection(ServiceFixture, unittest.TestCase): + def test_activation_forwards_no_existing_post(self) -> None: + runner, database, _ = self.build("auto", [post(1), post(2)]) + runner.tick() + self.assertEqual(database.cursors["press"], "100") + self.assertEqual(database.items, []) + + def test_new_posts_are_queued_per_target_and_the_opt_out_is_skipped(self) -> None: + runner, database, _ = self.build( + "review", [post(101), post(102, ("nocrosspost",))] + ) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + self.assertEqual( + [(row["source_uri"][-3:], row["target"]) for row in database.items], + [("101", "acc-x"), ("101", "acc-li")], + ) + self.assertEqual(database.cursors["press"], "102") + + def test_a_restart_queues_nothing_twice(self) -> None: + runner, database, _ = self.build("review", [post(101)]) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + database.cursors["press"] = "100" + again, _, _ = self.build("review", [post(101)], database) + again.detect(again.routes["press"]) + self.assertEqual(len(database.items), 2) + + +class TestDelivery(ServiceFixture, unittest.TestCase): + def queued(self, mode: str) -> tuple[service.Service, FakeStore, FakeOpenPost]: + runner, database, client = self.build(mode, [post(101)]) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + return runner, database, client + + def test_review_mode_creates_drafts_without_publishing(self) -> None: + runner, database, client = self.queued("review") + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"drafted"}) + self.assertEqual(client.published, []) + self.assertEqual( + client.created[0][2], store.idempotency_key(post(101).uri, "acc-x", 0) + ) + self.assertEqual( + client.metadata[0], + {"crossposter_route": "press", "crossposter_source": post(101).url}, + ) + + def test_auto_mode_publishes_and_the_x_text_carries_no_link(self) -> None: + runner, database, client = self.queued("auto") + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"submitted"}) + self.assertEqual(client.published, ["pub-1", "pub-2"]) + self.assertEqual(client.created[0][1], "Post 101") + self.assertEqual( + client.created[1][1], "Post 101\n\nhttps://microblog.example/@press/101" + ) + + def test_transient_errors_back_off_until_the_budget_is_spent(self) -> None: + runner, database, client = self.queued("auto") + client.failure = web.RequestError( + "https://openpost/api/v1/publications", 503, {"Retry-After": "120"}, "busy" + ) + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"pending"}) + self.assertGreaterEqual(database.items[0]["delay"], 120) + runner.deliver_due() + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"dead_lettered"}) + self.assertIn("HTTP 503", database.items[0]["last_error"]) + + def test_a_retry_after_creation_reuses_the_publication(self) -> None: + runner, database, client = self.queued("auto") + client.publish_failure = web.RequestError( + "https://openpost/api/v1/publications/pub-1/publish-now", 503, {}, "busy" + ) + runner.deliver_due() + self.assertEqual( + [row["publication_id"] for row in database.items], ["pub-1", "pub-2"] + ) + client.publish_failure = None + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"submitted"}) + self.assertEqual(len(client.created), 2) + self.assertEqual(client.published, ["pub-1", "pub-2"]) + + def test_media_is_fetched_from_the_refreshed_source_post(self) -> None: + runner, database, _ = self.build( + "review", [picture(101, "https://microblog.example/m/original.jpg")] + ) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + runner.sources["press"].fresh_url = "https://microblog.example/m/optimised.jpg" + fetched: list[str] = [] + + def download(url: str, headers: dict, target: Path) -> Path: + fetched.append(url) + target.write_bytes(b"\xff\xd8 image") + return target + + with patch.object(service.web, "download", download): + runner.deliver_due() + self.assertEqual(set(fetched), {"https://microblog.example/m/optimised.jpg"}) + self.assertEqual({row["state"] for row in database.items}, {"drafted"}) + + def test_source_media_that_is_not_ready_is_retried(self) -> None: + runner, database, _ = self.build( + "review", [picture(101, "https://microblog.example/m/original.jpg")] + ) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + + def download(url: str, headers: dict, target: Path) -> Path: + raise web.RequestError(url, 403, {}, "no-preview") + + with patch.object(service.web, "download", download): + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"pending"}) + self.assertIn("not available yet", database.items[0]["last_error"]) + + def test_permanent_errors_dead_letter_at_once(self) -> None: + runner, database, client = self.queued("auto") + client.failure = web.RequestError( + "https://openpost/api/v1/publications", 422, {}, "invalid" + ) + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"dead_lettered"}) + + +class TestFollowUp(ServiceFixture, unittest.TestCase): + def submitted(self) -> tuple[service.Service, FakeStore, FakeOpenPost]: + runner, database, client = self.build("auto", [post(101)]) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + runner.deliver_due() + return runner, database, client + + def test_published_destinations_close_the_item(self) -> None: + runner, database, client = self.submitted() + client.outcome = [{"status": "published"}] + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"published"}) + + def test_failed_destinations_keep_the_provider_error(self) -> None: + runner, database, client = self.submitted() + client.outcome = [ + { + "status": "failed", + "error_retryable": False, + "error_message": "rejected by X", + } + ] + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"failed"}) + self.assertEqual(database.items[0]["last_error"], "rejected by X") + + def test_a_provider_rejection_fails_without_a_resend(self) -> None: + runner, database, client = self.submitted() + client.outcome = [REJECTED] + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"failed"}) + self.assertEqual( + database.items[0]["last_error"], "provider_rejected (HTTP 400)" + ) + self.assertEqual(len(client.created), 2) + + def test_an_unavailable_provider_is_resent_under_a_new_key(self) -> None: + runner, database, client = self.submitted() + client.outcome = [UNAVAILABLE] + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"pending"}) + self.assertEqual(database.items[0]["resends"], 1) + runner.deliver_due() + self.assertEqual({row["state"] for row in database.items}, {"submitted"}) + self.assertEqual( + client.created[2][2], + store.idempotency_key(post(101).uri, "acc-x", 1), + ) + self.assertEqual(client.published, ["pub-1", "pub-2", "pub-3", "pub-4"]) + client.outcome = [{"status": "published"}] + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"published"}) + + def test_resends_dead_letter_once_the_attempts_are_spent(self) -> None: + runner, database, client = self.submitted() + client.outcome = [UNAVAILABLE] + runner.follow() + runner.deliver_due() + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"dead_lettered"}) + self.assertEqual( + database.items[0]["last_error"], "manual_resolution (HTTP 503)" + ) + + def test_a_reviewed_draft_is_never_resent(self) -> None: + runner, database, client = self.build("review", [post(101)]) + database.cursors["press"] = "100" + runner.detect(runner.routes["press"]) + runner.deliver_due() + client.outcome = [UNAVAILABLE] + runner.follow() + self.assertEqual({row["state"] for row in database.items}, {"failed"}) + self.assertEqual(len(client.created), 2) + + def test_failures_are_reported_once(self) -> None: + runner, _, client = self.submitted() + client.outcome = [ + { + "status": "failed", + "error_retryable": False, + "error_message": "rejected by X", + } + ] + runner.follow() + sent: list[list[dict]] = [] + with patch.object( + service.notify, "send", lambda mail, recipients, rows: sent.append(rows) + ): + runner.report() + runner.report() + self.assertEqual(len(sent), 1) + self.assertEqual(len(sent[0]), 2) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_store.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_store.py new file mode 100644 index 0000000000..23e88db187 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_store.py @@ -0,0 +1,197 @@ +from __future__ import annotations + +import contextlib +import json +import re +import unittest +import unittest.mock +from pathlib import Path + +from crossposter import store +from crossposter.sources import Media, SourceItem + +from utils.cache.files import iter_project_files + +from . import PROJECT_ROOT + +SOURCE = "https://microblog.example/users/press/statuses/1" +SQL_SOURCE = PROJECT_ROOT / "roles/web-app-openpost/files/sql/crossposter" +PLACEHOLDER = re.compile(r"%\((\w+)\)s") +ITEM = SourceItem( + uri=SOURCE, + url="https://microblog.example/@press/1", + platform="mastodon", + text="Hello", + visibility="public", + tags=("news",), + media=( + Media( + url="https://microblog.example/a.png", + mime="image/png", + description="alt", + size=12, + ), + ), + in_reply_to="", + reblog=False, + spoiler="", + application="", + cursor="1", +) + + +class _Connection: + def __init__(self) -> None: + self.calls: list[tuple[str, dict | None]] = [] + + def execute(self, text: str, parameters: dict | None = None) -> _Connection: + self.calls.append((text, parameters)) + return self + + def fetchone(self) -> dict: + return {"held": True, "cursor": "1"} + + def fetchall(self) -> list[dict]: + return [] + + def transaction(self) -> contextlib.nullcontext: + return contextlib.nullcontext() + + +class TestPayload(unittest.TestCase): + def test_a_stored_item_comes_back_unchanged(self) -> None: + self.assertEqual( + store.item_from_json(json.loads(store.item_to_json(ITEM))), ITEM + ) + + +class TestQueries(unittest.TestCase): + def setUp(self) -> None: + patcher = unittest.mock.patch.object(store, "SQL_DIR", SQL_SOURCE) + patcher.start() + self.addCleanup(patcher.stop) + + def test_every_query_has_one_file_and_every_file_a_query(self) -> None: + statements = (Path(path) for path in iter_project_files(extensions=(".sql",))) + self.assertEqual( + sorted( + path.relative_to(SQL_SOURCE).with_suffix("").as_posix() + for path in statements + if path.is_relative_to(SQL_SOURCE) + ), + sorted(store.QUERIES), + ) + + def test_an_unknown_query_is_refused(self) -> None: + with self.assertRaises(KeyError): + store.query("select_items; DROP SCHEMA crossposter") + + def test_every_call_binds_exactly_the_placeholders_of_its_statement( + self, + ) -> None: + connection = _Connection() + crossposter_store = store.Store.__new__(store.Store) + crossposter_store.connection = connection + + crossposter_store.migrate() + crossposter_store.lock() + crossposter_store.cursor("press") + crossposter_store.advance("press", "2", [(ITEM, "x-press", "x")]) + crossposter_store.due() + crossposter_store.open_publications() + crossposter_store.unnotified() + crossposter_store.everything() + crossposter_store.update(1, "drafted", "pub-1", 1, "", 0) + crossposter_store.resend(1, 0, "HTTP 503", 30) + crossposter_store.mark_notified(1) + + self.assertEqual( + sorted(text for text, _ in connection.calls), + sorted(store.query(name) for name in store.QUERIES), + ) + for text, parameters in connection.calls: + with self.subTest(statement=text.splitlines()[0]): + self.assertEqual(set(PLACEHOLDER.findall(text)), set(parameters or {})) + + +class TestIdempotencyKey(unittest.TestCase): + def test_the_key_is_stable_for_one_pair(self) -> None: + self.assertEqual( + store.idempotency_key(SOURCE, "account-1", 0), + store.idempotency_key(SOURCE, "account-1", 0), + ) + + def test_the_key_differs_per_target_and_per_source(self) -> None: + keys = { + store.idempotency_key(SOURCE, "account-1", 0), + store.idempotency_key(SOURCE, "account-2", 0), + store.idempotency_key(SOURCE + "0", "account-1", 0), + } + self.assertEqual(len(keys), 3) + + def test_the_key_cannot_collide_through_concatenation(self) -> None: + self.assertNotEqual( + store.idempotency_key("ab", "c", 0), store.idempotency_key("a", "bc", 0) + ) + + def test_the_key_fits_an_http_header(self) -> None: + key = store.idempotency_key(SOURCE, "account-1", 0) + self.assertRegex(key, r"^crossposter-[0-9a-f]{64}$") + + def test_every_resend_gets_its_own_key_of_the_same_pair(self) -> None: + first = store.idempotency_key(SOURCE, "account-1", 0) + resent = store.idempotency_key(SOURCE, "account-1", 1) + self.assertEqual(resent, f"{first}-r1") + self.assertNotEqual(resent, store.idempotency_key(SOURCE, "account-1", 2)) + + +class TestTransitions(unittest.TestCase): + def test_review_mode_drafts(self) -> None: + self.assertEqual(store.transition("pending", "drafted"), "drafted") + + def test_auto_mode_submits_then_publishes(self) -> None: + self.assertEqual(store.transition("pending", "submitted"), "submitted") + self.assertEqual(store.transition("submitted", "delivered"), "published") + + def test_a_draft_published_in_the_desk_becomes_published(self) -> None: + self.assertEqual(store.transition("drafted", "delivered"), "published") + + def test_a_reported_delivery_failure_is_failed(self) -> None: + self.assertEqual(store.transition("submitted", "delivery_failed"), "failed") + self.assertEqual(store.transition("drafted", "delivery_failed"), "failed") + + def test_transient_errors_stay_pending_until_the_budget_is_spent(self) -> None: + self.assertEqual( + store.transition("pending", "transient", attempts=3, max_attempts=8), + "pending", + ) + self.assertEqual( + store.transition("pending", "transient", attempts=8, max_attempts=8), + "dead_lettered", + ) + + def test_a_submitted_item_can_be_resent_or_exhausted(self) -> None: + self.assertEqual(store.transition("submitted", "resend"), "pending") + self.assertEqual(store.transition("submitted", "exhausted"), "dead_lettered") + + def test_a_reviewed_draft_is_never_resent(self) -> None: + with self.assertRaises(store.InvalidTransitionError): + store.transition("drafted", "resend") + + def test_permanent_errors_dead_letter_at_once(self) -> None: + self.assertEqual(store.transition("pending", "permanent"), "dead_lettered") + + def test_terminal_states_do_not_move(self) -> None: + for state in ("published", "dead_lettered"): + with self.assertRaises(store.InvalidTransitionError): + store.transition(state, "submitted") + + def test_unknown_events_are_refused(self) -> None: + with self.assertRaises(store.InvalidTransitionError): + store.transition("pending", "teleported") + + def test_every_state_is_listed(self) -> None: + self.assertEqual( + set(store.STATES), + {"pending", "drafted", "submitted", "published", "failed", "dead_lettered"}, + ) diff --git a/tests/unit/python/roles/web-app-openpost/files/crossposter/test_web.py b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_web.py new file mode 100644 index 0000000000..83f921ce53 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/crossposter/test_web.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from crossposter import web + +RECEIVED: dict[str, bytes] = {} + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: object) -> None: + return None + + def _answer(self, status: int, body: bytes, headers: dict[str, str]) -> None: + self.send_response(status) + for name, value in headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: + if self.path == "/json": + self._answer(200, b'{"ok": true}', {"Content-Type": "application/json"}) + elif self.path == "/busy": + self._answer(503, b"busy", {"Retry-After": "30"}) + elif self.path == "/media": + self._answer(200, b"\xff\xd8" + b"x" * 4096, {}) + else: + self._answer(404, b"missing", {}) + + def do_PUT(self) -> None: + RECEIVED[self.path] = self.rfile.read(int(self.headers["Content-Length"])) + self._answer(201, b"", {}) + + +class ServerFixture: + @classmethod + def setUpClass(cls) -> None: + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + cls.base = f"http://127.0.0.1:{cls.server.server_address[1]}" + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + + @classmethod + def tearDownClass(cls) -> None: + cls.server.shutdown() + cls.server.server_close() + + +class TestRequest(ServerFixture, unittest.TestCase): + def test_json_answers_are_decoded(self) -> None: + self.assertEqual(web.get_json(self.base + "/json", {}), {"ok": True}) + + def test_a_server_error_is_transient_and_keeps_its_headers(self) -> None: + with self.assertRaises(web.RequestError) as caught: + web.request("GET", self.base + "/busy", {}, None, (200,)) + self.assertTrue(caught.exception.transient) + self.assertEqual(caught.exception.headers.get("Retry-After"), "30") + + def test_a_client_error_is_permanent(self) -> None: + with self.assertRaises(web.RequestError) as caught: + web.request("GET", self.base + "/gone", {}, None, (200,)) + self.assertFalse(caught.exception.transient) + + def test_an_unreachable_host_is_transient(self) -> None: + with self.assertRaises(web.RequestError) as caught: + web.request("GET", "http://127.0.0.1:9/", {}, None, (200,)) + self.assertTrue(caught.exception.transient) + + +class TestStreaming(ServerFixture, unittest.TestCase): + def test_media_streams_to_disk_and_back(self) -> None: + with tempfile.TemporaryDirectory() as folder: + local = web.download(self.base + "/media", {}, Path(folder) / "media.jpg") + self.assertEqual(local.stat().st_size, 4098) + web.upload("PUT", self.base + "/target", {}, local, (201,)) + self.assertEqual(RECEIVED["/target"][:2], b"\xff\xd8") + self.assertEqual(len(RECEIVED["/target"]), 4098) diff --git a/tests/unit/python/roles/web-app-openpost/files/provider/__init__.py b/tests/unit/python/roles/web-app-openpost/files/provider/__init__.py new file mode 100644 index 0000000000..241d1186c0 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/provider/__init__.py @@ -0,0 +1,10 @@ +import sys +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] +PACKAGE_ROOT: Path = PROJECT_ROOT / "roles/web-app-openpost/files/python" + +if str(PACKAGE_ROOT) not in sys.path: + sys.path.insert(0, str(PACKAGE_ROOT)) + +__all__ = ["PACKAGE_ROOT", "PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-openpost/files/provider/test___main__.py b/tests/unit/python/roles/web-app-openpost/files/provider/test___main__.py new file mode 100644 index 0000000000..496722cb45 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/provider/test___main__.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import json +import tempfile +import threading +import unittest +import urllib.request +from http.server import ThreadingHTTPServer +from pathlib import Path + +from provider import __main__ as entry + +CONFIG = { + "http_port": 0, + "https_port": 0, + "certificate": "/unused.crt", + "key": "/unused.key", + "linkedin": { + "clients": { + "simulator-linkedin": { + "secret": "s", + "name": "OpenPost", + "redirect_uris": ["https://publish.example/cb"], + } + } + }, +} + + +class TestEntry(unittest.TestCase): + def test_the_config_registers_its_clients(self) -> None: + app = entry.application(CONFIG) + client = app.clients["simulator-linkedin"] + self.assertEqual(client.redirect_uris, ("https://publish.example/cb",)) + + def test_the_http_handler_serves_the_app(self) -> None: + server = ThreadingHTTPServer( + ("127.0.0.1", 0), entry.handler_for(entry.application(CONFIG)) + ) + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.shutdown) + url = f"http://127.0.0.1:{server.server_address[1]}/__fake/health" + with urllib.request.urlopen(url, timeout=5) as answer: + self.assertEqual((answer.status, answer.read()), (200, b"ok")) + + def test_health_fails_without_a_server(self) -> None: + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "provider.json" + path.write_text(json.dumps({**CONFIG, "http_port": 1})) + self.assertEqual(entry.health(entry.load(str(path))), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openpost/files/provider/test_linkedin.py b/tests/unit/python/roles/web-app-openpost/files/provider/test_linkedin.py new file mode 100644 index 0000000000..ce11bd1932 --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/provider/test_linkedin.py @@ -0,0 +1,323 @@ +from __future__ import annotations + +import json +import unittest +import urllib.parse + +from provider.linkedin import Client, LinkedIn, Request, plain_text +from provider.store import Store + +CLIENT_ID = "simulator-linkedin" +SECRET = "simulator-linkedin-secret" +CALLBACK = "https://publish.example/api/v1/accounts/linkedin/callback" +AUTHORIZE = { + "response_type": "code", + "client_id": CLIENT_ID, + "redirect_uri": CALLBACK, + "scope": "openid profile w_member_social", + "state": "state-1", +} + + +def form( + method: str, path: str, fields: dict[str, str], headers: dict | None = None +) -> Request: + return Request( + method, path, {}, headers or {}, urllib.parse.urlencode(fields).encode() + ) + + +def call( + method: str, path: str, token: str, body: object = None, query: dict | None = None +) -> Request: + return Request( + method, + path, + query or {}, + {"authorization": f"Bearer {token}"}, + json.dumps(body).encode() if body is not None else b"", + ) + + +class Fixture: + def setUp(self) -> None: + self.app = LinkedIn( + Store(), {CLIENT_ID: Client(SECRET, "OpenPost", (CALLBACK,))} + ) + + def sign_up(self, email: str = "ada@example.org") -> None: + response = self.app.handle( + form( + "POST", + "/signup", + {"name": "Ada Lovelace", "email": email, "password": "pw", "next": ""}, + ) + ) + self.assertEqual(response.status, 201) + + def code(self, email: str = "ada@example.org") -> str: + response = self.app.handle( + form( + "POST", + "/oauth/v2/authorization", + {**AUTHORIZE, "email": email, "password": "pw", "decision": "allow"}, + ) + ) + self.assertEqual(response.status, 302) + location = urllib.parse.urlsplit(response.headers["Location"]) + query = dict(urllib.parse.parse_qsl(location.query)) + self.assertEqual(query["state"], "state-1") + self.assertTrue(response.headers["Location"].startswith(CALLBACK + "?")) + return query["code"] + + def tokens(self) -> dict: + self.sign_up() + response = self.app.handle( + form( + "POST", + "/oauth/v2/accessToken", + { + "grant_type": "authorization_code", + "code": self.code(), + "redirect_uri": CALLBACK, + "client_id": CLIENT_ID, + "client_secret": SECRET, + }, + ) + ) + self.assertEqual(response.status, 200) + return json.loads(response.body) + + +class TestSignUpAndConsent(Fixture, unittest.TestCase): + def test_the_sign_up_page_offers_a_form(self) -> None: + page = self.app.handle(Request("GET", "/signup", {"next": ""}, {}, b"")) + self.assertEqual(page.status, 200) + self.assertIn(b"Create account", page.body) + + def test_a_sign_up_from_the_consent_page_returns_to_it(self) -> None: + back = "/oauth/v2/authorization?" + urllib.parse.urlencode(AUTHORIZE) + response = self.app.handle( + form( + "POST", + "/signup", + { + "name": "Ada", + "email": "ada@example.org", + "password": "pw", + "next": back, + }, + ) + ) + self.assertEqual((response.status, response.headers["Location"]), (303, back)) + + def test_a_sign_up_never_redirects_off_the_fake(self) -> None: + response = self.app.handle( + form( + "POST", + "/signup", + { + "name": "Ada", + "email": "ada@example.org", + "password": "pw", + "next": "https://evil.example/", + }, + ) + ) + self.assertEqual(response.status, 201) + + def test_the_consent_page_names_the_client_and_its_scopes(self) -> None: + page = self.app.handle( + Request("GET", "/oauth/v2/authorization", AUTHORIZE, {}, b"") + ) + self.assertEqual(page.status, 200) + self.assertIn(b"OpenPost", page.body) + self.assertIn(b"w_member_social", page.body) + self.assertIn(b"/signup?next=", page.body) + + def test_an_unregistered_redirect_uri_is_refused(self) -> None: + page = self.app.handle( + Request( + "GET", + "/oauth/v2/authorization", + {**AUTHORIZE, "redirect_uri": "https://evil/cb"}, + {}, + b"", + ) + ) + self.assertEqual(page.status, 400) + + def test_wrong_credentials_stay_on_the_consent_page(self) -> None: + self.sign_up() + response = self.app.handle( + form( + "POST", + "/oauth/v2/authorization", + { + **AUTHORIZE, + "email": "ada@example.org", + "password": "wrong", + "decision": "allow", + }, + ) + ) + self.assertEqual(response.status, 400) + self.assertIn(b"Wrong email or password", response.body) + + def test_cancelling_returns_an_error_to_the_client(self) -> None: + response = self.app.handle( + form("POST", "/oauth/v2/authorization", {**AUTHORIZE, "decision": "deny"}) + ) + query = dict( + urllib.parse.parse_qsl( + urllib.parse.urlsplit(response.headers["Location"]).query + ) + ) + self.assertEqual( + query, {"error": "user_cancelled_authorize", "state": "state-1"} + ) + + +class TestTokens(Fixture, unittest.TestCase): + def test_a_code_becomes_tokens_that_describe_the_member(self) -> None: + tokens = self.tokens() + profile = json.loads( + self.app.handle(call("GET", "/v2/userinfo", tokens["access_token"])).body + ) + self.assertEqual( + (profile["name"], profile["given_name"]), ("Ada Lovelace", "Ada") + ) + self.assertTrue(profile["sub"]) + + def test_a_wrong_client_secret_is_refused(self) -> None: + self.sign_up() + response = self.app.handle( + form( + "POST", + "/oauth/v2/accessToken", + { + "grant_type": "authorization_code", + "code": self.code(), + "redirect_uri": CALLBACK, + "client_id": CLIENT_ID, + "client_secret": "wrong", + }, + ) + ) + self.assertEqual(response.status, 401) + + def test_a_refresh_token_yields_a_working_access_token(self) -> None: + tokens = self.tokens() + response = self.app.handle( + form( + "POST", + "/oauth/v2/accessToken", + { + "grant_type": "refresh_token", + "refresh_token": tokens["refresh_token"], + "client_id": CLIENT_ID, + "client_secret": SECRET, + }, + ) + ) + refreshed = json.loads(response.body) + self.assertEqual( + self.app.handle( + call("GET", "/v2/userinfo", refreshed["access_token"]) + ).status, + 200, + ) + + def test_an_unknown_token_is_refused(self) -> None: + self.assertEqual( + self.app.handle(call("GET", "/v2/userinfo", "nope")).status, 401 + ) + + +class TestPosts(Fixture, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + self.token = self.tokens()["access_token"] + profile = json.loads( + self.app.handle(call("GET", "/v2/userinfo", self.token)).body + ) + self.author = f"urn:li:person:{profile['sub']}" + + def post(self, body: dict) -> object: + return self.app.handle(call("POST", "/rest/posts", self.token, body)) + + def body(self, **extra: object) -> dict: + return { + "author": self.author, + "commentary": r"Hello \#world", + "visibility": "PUBLIC", + "lifecycleState": "PUBLISHED", + **extra, + } + + def test_a_post_is_stored_and_read_back_by_its_id(self) -> None: + response = self.post(self.body()) + self.assertEqual(response.status, 201) + post_id = response.headers["x-restli-id"] + read = self.app.handle( + call( + "GET", f"/rest/posts/{urllib.parse.quote(post_id, safe='')}", self.token + ) + ) + self.assertEqual(json.loads(read.body)["commentary"], r"Hello \#world") + + def test_the_feed_page_shows_the_unescaped_text_without_a_token(self) -> None: + post_id = self.post(self.body()).headers["x-restli-id"] + page = self.app.handle(Request("GET", f"/feed/update/{post_id}", {}, {}, b"")) + self.assertEqual(page.status, 200) + self.assertIn(b"Hello #world", page.body) + self.assertIn(b"Ada Lovelace on LinkedIn", page.body) + + def test_posting_as_someone_else_is_refused(self) -> None: + self.assertEqual(self.post(self.body(author="urn:li:person:other")).status, 403) + + def test_an_image_post_needs_an_uploaded_image(self) -> None: + initialized = self.app.handle( + call( + "POST", + "/rest/images", + self.token, + {"initializeUploadRequest": {"owner": self.author}}, + {"action": "initializeUpload"}, + ) + ) + value = json.loads(initialized.body)["value"] + media = {"content": {"media": {"id": value["image"]}}} + self.assertEqual(self.post(self.body(**media)).status, 422) + upload_path = urllib.parse.urlsplit(value["uploadUrl"]).path + self.assertEqual( + self.app.handle( + Request( + "PUT", + upload_path, + {}, + {"authorization": f"Bearer {self.token}"}, + b"\xff\xd8", + ) + ).status, + 201, + ) + self.assertEqual(self.post(self.body(**media)).status, 201) + + def test_the_admin_listing_shows_posts_with_plain_text(self) -> None: + self.post(self.body()) + posts = json.loads( + self.app.handle(Request("GET", "/__fake/linkedin/posts", {}, {}, b"")).body + ) + self.assertEqual([post["text"] for post in posts], ["Hello #world"]) + + +class TestPlainText(unittest.TestCase): + def test_linkedin_markup_escapes_are_removed(self) -> None: + self.assertEqual( + plain_text(r"a \#tag \@name \(x\) \\ end"), r"a #tag @name (x) \ end" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openpost/files/provider/test_store.py b/tests/unit/python/roles/web-app-openpost/files/provider/test_store.py new file mode 100644 index 0000000000..ed0e2fc2bd --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/files/provider/test_store.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import unittest + +from provider import store + + +class Clock: + def __init__(self) -> None: + self.value = 1_000.0 + + def __call__(self) -> float: + return self.value + + +class TestAccounts(unittest.TestCase): + def setUp(self) -> None: + self.store = store.Store() + + def test_an_account_signs_in_with_its_password_only(self) -> None: + account = self.store.create_account("Ada Lovelace", "Ada@Example.org", "s3cret") + self.assertEqual(self.store.authenticate("ada@example.org", "s3cret"), account) + self.assertIsNone(self.store.authenticate("ada@example.org", "wrong")) + self.assertIsNone(self.store.authenticate("nobody@example.org", "s3cret")) + + def test_the_password_is_never_stored_in_plaintext(self) -> None: + account = self.store.create_account("Ada", "ada@example.org", "s3cret") + self.assertNotIn("s3cret", account.password_hash) + + def test_an_email_belongs_to_one_account(self) -> None: + self.store.create_account("Ada", "ada@example.org", "s3cret") + with self.assertRaises(store.StoreError): + self.store.create_account("Ada Again", "ADA@example.org", "other") + + def test_empty_fields_are_refused(self) -> None: + with self.assertRaises(store.StoreError): + self.store.create_account(" ", "ada@example.org", "s3cret") + + +class TestGrants(unittest.TestCase): + def setUp(self) -> None: + self.clock = Clock() + self.store = store.Store(now=self.clock) + self.member = self.store.create_account("Ada", "ada@example.org", "pw").member + + def test_a_code_is_redeemed_once_by_its_client(self) -> None: + code = self.store.issue_code(self.member, "client", "https://app/cb", "openid") + grant = self.store.redeem_code(code, "client", "https://app/cb") + self.assertEqual(grant.member, self.member) + with self.assertRaises(store.StoreError): + self.store.redeem_code(code, "client", "https://app/cb") + + def test_a_code_for_another_client_or_redirect_is_refused(self) -> None: + code = self.store.issue_code(self.member, "client", "https://app/cb", "openid") + with self.assertRaises(store.StoreError): + self.store.redeem_code(code, "client", "https://evil/cb") + + def test_an_expired_code_is_refused(self) -> None: + code = self.store.issue_code(self.member, "client", "https://app/cb", "openid") + self.clock.value += store.CODE_SECONDS + 1 + with self.assertRaises(store.StoreError): + self.store.redeem_code(code, "client", "https://app/cb") + + def test_tokens_identify_the_member_until_they_expire(self) -> None: + tokens = self.store.issue_tokens(self.member, "openid") + self.assertEqual( + self.store.member_for(tokens["access_token"]).member, self.member + ) + self.clock.value += store.ACCESS_SECONDS + 1 + self.assertIsNone(self.store.member_for(tokens["access_token"])) + + def test_a_refresh_keeps_the_refresh_token_and_issues_a_new_access_token( + self, + ) -> None: + tokens = self.store.issue_tokens(self.member, "openid") + refreshed = self.store.refresh(tokens["refresh_token"]) + self.assertEqual(refreshed["refresh_token"], tokens["refresh_token"]) + self.assertNotEqual(refreshed["access_token"], tokens["access_token"]) + self.assertEqual( + self.store.member_for(refreshed["access_token"]).member, self.member + ) + + def test_an_unknown_refresh_token_is_refused(self) -> None: + with self.assertRaises(store.StoreError): + self.store.refresh("nope") + + +class TestContent(unittest.TestCase): + def setUp(self) -> None: + self.store = store.Store() + self.owner = self.store.create_account("Ada", "ada@example.org", "pw").urn + + def test_an_image_counts_as_uploaded_only_after_its_bytes_arrive(self) -> None: + image = self.store.register_image(self.owner) + self.assertFalse(self.store.uploaded(image.urn, self.owner)) + self.store.store_upload(image.upload_id, self.owner, b"\xff\xd8") + self.assertTrue(self.store.uploaded(image.urn, self.owner)) + self.assertFalse(self.store.uploaded(image.urn, "urn:li:person:other")) + + def test_another_member_cannot_upload_into_an_image(self) -> None: + image = self.store.register_image(self.owner) + with self.assertRaises(store.StoreError): + self.store.store_upload(image.upload_id, "urn:li:person:other", b"x") + + def test_posts_get_distinct_share_urns_and_can_be_read_back(self) -> None: + first = self.store.create_post(self.owner, "one", "PUBLIC", {}) + second = self.store.create_post(self.owner, "two", "PUBLIC", {}) + self.assertNotEqual(first.id, second.id) + self.assertRegex(first.id, r"^urn:li:share:[0-9]+$") + self.assertEqual(self.store.post(second.id).commentary, "two") + self.assertEqual(len(self.store.posts()), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openpost/templates/__init__.py b/tests/unit/python/roles/web-app-openpost/templates/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openpost/templates/test_echo_routes.py b/tests/unit/python/roles/web-app-openpost/templates/test_echo_routes.py new file mode 100644 index 0000000000..e949b7256a --- /dev/null +++ b/tests/unit/python/roles/web-app-openpost/templates/test_echo_routes.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import re +import tempfile +import unittest +from pathlib import Path + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template +from jinja2 import ( + ChoiceLoader, + DictLoader, + Environment, + FileSystemLoader, + StrictUndefined, + select_autoescape, +) + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.networks.proxy import render_proxy_pass + +ROLE_DIR = PROJECT_ROOT / "roles/web-app-openpost" +TEMPLATE = "roles/web-app-openpost/templates/nginx/echo_routes.conf.j2" +DOMAIN = "publish.example.test" +LOCAL_HTTP_PORT = 8106 + +STUBBED_INCLUDES = { + "roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2": "SSO_GATE\n", + "roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2": "", + "roles/sys-svc-proxy/templates/headers/access_control_allow.conf.j2": "", + "roles/sys-svc-proxy/templates/headers/untrusted_identity_strips.conf.j2": "", + "roles/sys-front-inj-all/templates/location.lua.j2": "", +} + +ECHO_ROUTES = ( + "/api/v1/media/upload", + "/api/v1/media/batch-upload", + "/api/v1/media/metadata", + "/api/v1/media/upload-session/0b6f/content", + "/api/v1/auth/profile/avatar", + "/api/v1/admin/backup", + "/api/v1/admin/backup/export", + "/api/v1/admin/backup/restore/upload", + "/api/v1/admin/backup/restore-points/nightly", +) +OTHER_ROUTES = ( + "/", + "/api/v1/media", + "/api/v1/media/upload-session", + "/api/v1/media/upload-session/0b6f/complete", + "/api/v1/media/uploads", + "/api/v1/accounts", + "/api/v1/publications", + "/api/v1/admin/backups", + "/media/0b6f", +) + + +def stub_lookup(deployment_mode: str, proxy_gated: bool): + """Return a `lookup` that answers what the location template asks for. + + Args: + deployment_mode: the mode `proxy_pass` renders for. + proxy_gated: what `lookup('sso', ..., 'is_proxy_gated')` answers. + """ + tls = {"protocols.web": "https", "ports.web": 443, "enabled": True} + + def lookup(kind, *args, **kwargs): + if kind == "sso": + return proxy_gated + if kind == "config": + return args[2] + if kind == "network_handover": + return False + if kind == "tls": + return tls[args[1]] + if kind == "proxy_pass": + return render_proxy_pass( + f"127.0.0.1:{kwargs['local_port']}", + deployment_mode, + tail=kwargs["tail"], + ) + raise AssertionError(f"unexpected lookup({kind!r}, ...)") + + return lookup + + +def render(deployment_mode: str = "compose", proxy_gated: bool = False) -> str: + """Render the location the OpenPost vhost carries for its Echo routes. + + Args: + deployment_mode: the mode `proxy_pass` renders for. + proxy_gated: whether the application sits behind the SSO proxy gate. + """ + env = Environment( + loader=ChoiceLoader( + [DictLoader(STUBBED_INCLUDES), FileSystemLoader(str(PROJECT_ROOT))] + ), + undefined=StrictUndefined, + autoescape=select_autoescape(), + trim_blocks=True, + ) + env.filters["bool"] = lambda value: ( + value + if isinstance(value, bool) + else str(value).strip().lower() in {"true", "1", "yes", "on"} + ) + env.filters["on_off"] = lambda value: "on" if value else "off" + env.filters["entity_name"] = lambda value: value.rsplit("-", 1)[-1] + return env.get_template(TEMPLATE).render( + application_id="web-app-openpost", + domain=DOMAIN, + http_port=LOCAL_HTTP_PORT, + lookup=stub_lookup(deployment_mode, proxy_gated), + ) + + +def location_block(rendered: str) -> tuple[str, list[str]]: + """Return the matcher and the directives, one per line, of the only location. + + Args: + rendered: the rendered fragment. + """ + blocks = re.findall( + r"^location\s+([^{\n]+?)\s*\{((?:[^{}]|\{[^{}]*\})*)\}", rendered, re.MULTILINE + ) + if len(blocks) != 1: + raise AssertionError(f"expected one location, rendered:\n{rendered}") + matcher, body = blocks[0] + return matcher.strip(), [line.strip() for line in body.splitlines() if line.strip()] + + +def matcher_pattern(matcher: str) -> re.Pattern[str]: + """Return the regular expression of a case-sensitive regex location matcher. + + Args: + matcher: the location matcher, modifier included. + """ + modifier, expression = matcher.split(" ", 1) + if modifier != "~": + raise AssertionError(f"'{matcher}' is not a case-sensitive regex location") + return re.compile(expression.strip('"')) + + +def extra_configuration(oidc_enabled: bool) -> str: + """Evaluate the vhost extras `tasks/00_core.yml` hands to `sys-stk-full`. + + Args: + oidc_enabled: the resolved `OPENPOST_OIDC_ENABLED`. + """ + task = next( + task + for task in load_yaml_any(ROLE_DIR / "tasks/00_core.yml") + if "vars" in task and "webserver_extra_configuration" in task["vars"] + ) + with tempfile.TemporaryDirectory() as search_path: + fragments = Path(search_path, "templates", "nginx") + fragments.mkdir(parents=True) + (fragments / "echo_routes.conf.j2").write_text( + "ECHO_ROUTES\n", encoding="utf-8" + ) + templar = Templar( + loader=DataLoader(), + variables={ + "ansible_search_path": [search_path], + "OPENPOST_OIDC_ENABLED": oidc_enabled, + }, + ) + return templar.template( + trust_as_template(task["vars"]["webserver_extra_configuration"]) + ) + + +class TestEchoRoutesLocation(unittest.TestCase): + def test_every_cookie_echo_route_is_covered(self): + matcher, _ = location_block(render()) + pattern = matcher_pattern(matcher) + for path in ECHO_ROUTES: + with self.subTest(path=path): + self.assertRegex(path, pattern) + + def test_no_other_route_is_covered(self): + matcher, _ = location_block(render()) + pattern = matcher_pattern(matcher) + for path in OTHER_ROUTES: + with self.subTest(path=path): + self.assertNotRegex(path, pattern) + + def test_the_upstream_is_told_plain_http(self): + _, directives = location_block(render()) + self.assertIn("proxy_set_header X-Forwarded-Proto http;", directives) + self.assertNotIn("proxy_set_header X-Forwarded-Proto $scheme;", directives) + + def test_only_the_vhost_own_https_origin_is_downgraded(self): + _, directives = location_block(render()) + rewrite = [ + "set $openpost_origin $http_origin;", + 'if ($http_origin = "https://$host") {', + 'set $openpost_origin "http://$host";', + "}", + "proxy_set_header Origin $openpost_origin;", + ] + start = directives.index(rewrite[0]) + self.assertEqual(directives[start : start + len(rewrite)], rewrite) + + def test_both_modes_proxy_without_a_static_uri(self): + for mode in ("compose", "swarm"): + with self.subTest(mode=mode): + _, directives = location_block(render(mode)) + proxy_pass = [d for d in directives if d.startswith("proxy_pass ")] + self.assertEqual(len(proxy_pass), 1) + self.assertRegex( + proxy_pass[0], r"^proxy_pass http://[^/;]+(\$request_uri)?;$" + ) + + def test_the_location_follows_the_application_sso_gate(self): + self.assertNotIn("SSO_GATE", render(proxy_gated=False)) + self.assertIn("SSO_GATE", render(proxy_gated=True)) + + +class TestVhostExtras(unittest.TestCase): + def test_the_echo_routes_location_reaches_the_vhost(self): + self.assertEqual(extra_configuration(False), "ECHO_ROUTES\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/test_rcpt_throttle.py b/tests/unit/python/roles/web-app-stalwart/test_rcpt_throttle.py new file mode 100644 index 0000000000..ed1829af00 --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/test_rcpt_throttle.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import json +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN +from utils.templating.ansible import _trust_as_template + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart" +TASKS = load_yaml_any(str(ROLE / "tasks" / "throttle.yml"), default_if_missing=[]) +MANAGER_OPS = load_yaml_any( + str(ROLE / "tasks" / "manager_ops.yml"), default_if_missing=[] +) +VARS = load_yaml_any(str(ROLE / ROLE_FILE_VARS_MAIN), default_if_missing={}) +RULE = VARS["STALWART_RCPT_THROTTLE_RULE"] + +SENDER_IP = { + "id": "a", + "description": "Sender IP throttle", + "enable": True, + "key": {"remoteIp": True}, + "match": {"match": {}, "else": ""}, + "rate": {"count": 5, "period": 1000}, +} +RECIPIENT = { + "id": "b", + "description": "Sender address to recipient throttle", + "enable": True, + "key": {"senderDomain": True, "rcpt": True}, + "match": {"match": {}, "else": ""}, + "rate": {"count": 25, "period": 3600000}, +} + + +def _render(template: str, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _selected(throttles: list[dict]) -> list[str]: + facts = next( + task["ansible.builtin.set_fact"] + for task in TASKS + if "ansible.builtin.set_fact" in task + ) + return _render( + facts["stalwart_rcpt_throttle_ids"], + STALWART_RCPT_THROTTLE_KEY=VARS["STALWART_RCPT_THROTTLE_KEY"], + STALWART_RCPT_THROTTLE_RULE=RULE, + stalwart_jmap={ + "methodResponses": [["x:MtaInboundThrottle/get", {"list": throttles}, "c0"]] + }, + ) + + +def _update_body(ids: list[str]) -> dict: + block = next(task["block"] for task in TASKS if "block" in task) + return json.loads( + _render( + block[0]["vars"]["stalwart_jmap_body"], + stalwart_rcpt_throttle_ids=ids, + STALWART_RCPT_THROTTLE_RULE=RULE, + ) + ) + + +class TestRecipientThrottle(unittest.TestCase): + def test_only_the_recipient_throttle_is_selected(self): + self.assertEqual(_selected([SENDER_IP, RECIPIENT]), ["b"]) + + def test_a_limited_recipient_throttle_is_left_alone(self): + limited = {**RECIPIENT, "match": {"match": {}, "else": RULE}} + self.assertEqual(_selected([SENDER_IP, limited]), []) + + def test_the_update_counts_only_unauthenticated_sessions(self): + self.assertEqual( + _update_body(["b"])["methodCalls"], + [ + [ + "x:MtaInboundThrottle/set", + { + "update": { + "b": {"match": {"else": "is_empty(authenticated_as)"}} + } + }, + "c0", + ] + ], + ) + + def test_the_rule_is_the_complement_of_the_relay_rule(self): + self.assertEqual(VARS["STALWART_RELAY_RULE"], "!" + RULE) + + def test_the_settings_reload_after_the_update(self): + block = next(task["block"] for task in TASKS if "block" in task) + self.assertEqual( + block[-1]["vars"]["stalwart_jmap_body"], + "{{ STALWART_JMAP_RELOAD_SETTINGS }}", + ) + + def test_the_manager_runs_the_throttle_tasks(self): + self.assertIn( + "throttle.yml", [task.get("include_tasks") for task in MANAGER_OPS] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/manager/test_value_generator.py b/tests/unit/python/utils/manager/test_value_generator.py index 46e2d08478..97ebddf6bd 100644 --- a/tests/unit/python/utils/manager/test_value_generator.py +++ b/tests/unit/python/utils/manager/test_value_generator.py @@ -1,6 +1,7 @@ import base64 import re import unittest +from unittest.mock import patch from cryptography.hazmat.primitives.asymmetric import ec, rsa from cryptography.hazmat.primitives.serialization import ( @@ -9,6 +10,7 @@ from cryptography.hazmat.primitives.serialization import ( load_pem_private_key, ) +from utils.manager import value_generator from utils.manager.value_generator import ValueGenerator @@ -20,6 +22,22 @@ class TestValueGenerator(unittest.TestCase): def setUp(self): self.vg = ValueGenerator() + def test_every_generated_value_is_registered_for_masking(self): + with patch.object(value_generator, "mask") as masked: + values = [ + self.vg.generate_strong_password(32), + self.vg.generate_secure_alphanumeric(16), + self.vg.generate_value("random_hex_16"), + ] + registered = [call.args[0] for call in masked.call_args_list] + for value in values: + self.assertIn(value, registered) + + def test_an_unknown_algorithm_masks_nothing(self): + with patch.object(value_generator, "mask") as masked: + self.assertEqual(self.vg.generate_value("nope"), "undefined") + masked.assert_not_called() + def test_generate_secure_alphanumeric(self): s = self.vg.generate_secure_alphanumeric(64) self.assertEqual(len(s), 64) diff --git a/tests/unit/python/utils/networks/test_render_container_networks.py b/tests/unit/python/utils/networks/test_render_container_networks.py index 8e4cf6295e..fd79828633 100644 --- a/tests/unit/python/utils/networks/test_render_container_networks.py +++ b/tests/unit/python/utils/networks/test_render_container_networks.py @@ -169,6 +169,55 @@ class TestRenderContainerNetworks(unittest.TestCase): ) self.assertEqual(rendered, "\nnetworks:\n default:") + def test_caller_aliases_land_on_the_default_network(self): + rendered = render_container_networks( + application_id="web-app-plain", + deployment_mode="compose", + registry={}, + entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + aliases=["microblog.example.com", "video.example.com"], + ) + self.assertEqual( + rendered, + "\nnetworks:\n default:\n aliases:\n" + " - microblog.example.com\n - video.example.com", + ) + + def test_caller_aliases_follow_beacon_aliases_without_duplicates(self): + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": {"modes": ["swarm"], "topology": "default_net"}, + }, + "sso": { + "role": "web-app-keycloak", + "entity_name": "keycloak", + "provides": "sso", + "overlay": { + "modes": ["swarm"], + "proxy_resolvable": True, + "aliases": ["auth.example.com"], + }, + }, + } + rendered = render_container_networks( + application_id="svc-prx-openresty", + deployment_mode="swarm", + registry=registry, + entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + aliases=["auth.example.com", "extra.example.com"], + ) + self.assertEqual(rendered.count("- auth.example.com"), 1) + self.assertLess( + rendered.index("- auth.example.com"), + rendered.index("- extra.example.com"), + ) + class TestRenderEncryption(unittest.TestCase): def test_swarm_encrypted_false_emits_lowercase_quoted_literal(self): diff --git a/utils/annotations/message.py b/utils/annotations/message.py index b4712b1f50..b3c1d257f5 100644 --- a/utils/annotations/message.py +++ b/utils/annotations/message.py @@ -9,6 +9,7 @@ See: https://docs.github.com/en/actions/writing-workflows/choosing-what-your-wor from __future__ import annotations import os +import sys from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -48,6 +49,19 @@ def _emit( print(f"{label}: {message}", flush=True) +def mask(value: str) -> None: + """Register a secret with GitHub Actions so every later log line redacts it. + + Args: + value: the secret; each non-blank line is registered on its own. + """ + if not in_github_actions(): + return + for line in value.splitlines(): + if line.strip(): + print(f"::add-mask::{line}", file=sys.stderr, flush=True) + + def warning( message: str, *, diff --git a/utils/manager/value_generator.py b/utils/manager/value_generator.py index d797dd7a0e..4d1f2c6ff1 100644 --- a/utils/manager/value_generator.py +++ b/utils/manager/value_generator.py @@ -13,6 +13,10 @@ from cryptography.hazmat.primitives.serialization import ( PublicFormat, ) +from utils.annotations.message import mask + +UNDEFINED = "undefined" + class ValueGenerator: PASSWORD_REGEX = re.compile( @@ -31,6 +35,7 @@ class ValueGenerator: for _ in range(10_000): password = "".join(secrets.choice(characters) for _ in range(length)) if self._is_valid_password(password): + mask(password) return password raise RuntimeError("Failed to generate a valid password after many attempts") @@ -41,7 +46,9 @@ class ValueGenerator: def generate_secure_alphanumeric(self, length: int) -> str: """Generate a cryptographically secure random alphanumeric string of the given length.""" characters = string.ascii_letters + string.digits - return "".join(secrets.choice(characters) for _ in range(length)) + value = "".join(secrets.choice(characters) for _ in range(length)) + mask(value) + return value def generate_vapid_keypair(self) -> tuple[str, str]: """Return a linked (private, public) VAPID keypair, cached per instance. @@ -81,7 +88,17 @@ class ValueGenerator: • "vapid_private" • "vapid_public" • "rsa_pem_2048" + + Returns: + the value, already registered with GitHub Actions for masking, or + ``"undefined"`` for an unknown algorithm. """ + value = self._generate(algorithm) + if value != UNDEFINED: + mask(value) + return value + + def _generate(self, algorithm: str) -> str: if algorithm == "random_hex": return secrets.token_hex(64) if algorithm == "random_hex_32": @@ -119,4 +136,4 @@ class ValueGenerator: return key.private_bytes( Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption() ).decode() - return "undefined" + return UNDEFINED diff --git a/utils/meta/scan.py b/utils/meta/scan.py index caf2e33d7e..cf7bdd801c 100644 --- a/utils/meta/scan.py +++ b/utils/meta/scan.py @@ -115,6 +115,15 @@ def iter_subnets() -> Iterable[tuple[str, ipaddress.IPv4Network]]: continue +def iter_outside_pool_roles() -> Iterable[str]: + """Yield every role whose ``meta/networks.yml`` sets ``local.outside_pool``.""" + for role_dir in iter_role_dirs(): + networks = _load_yaml(role_dir / ROLE_FILE_META_NETWORKS) + local = networks.get("local") if isinstance(networks, dict) else None + if isinstance(local, dict) and local.get("outside_pool") is True: + yield role_dir.name + + def occupied_ports_for(scope: str, category: str) -> list[int]: """Return the sorted, de-duplicated list of host-bound ports in use for ``.``. diff --git a/utils/networks/render.py b/utils/networks/render.py index a5f8905eac..d0775197a2 100644 --- a/utils/networks/render.py +++ b/utils/networks/render.py @@ -204,12 +204,15 @@ def render_container_networks( provider_self_alias: bool = True, node_local: bool = False, own_network_only: bool = False, + aliases: list[str] | None = None, ) -> str: if node_local: deployment_mode = "compose" attachments, default_aliases = _compute_attachments( registry, application_id, deployment_mode, lookup_config, lookup_database ) + if aliases: + default_aliases = list(dict.fromkeys([*default_aliases, *aliases])) lines: list[str] = ["networks:"] for att in attachments: if att["is_provider"] and att["topology"] == "default_net":