Compare commits
11
Commits
v1.6.0-rc.2
...
v2.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16925663a3 | ||
|
|
e92c27a84c | ||
|
|
ed63e70c46 | ||
|
|
57b02ad6c7 | ||
|
|
94e8c672df | ||
|
|
011f7cc87d | ||
|
|
f46130569f | ||
|
|
b4e6cf3cc3 | ||
|
|
2d0568d9c2 | ||
|
|
f117913797 | ||
|
|
b84cf23e1a |
No files matched your search
+31
-5
@@ -22,11 +22,24 @@ SITE_DESCRIPTION=My personal IndieWeb site
|
||||
# AUTHENTICATION
|
||||
# =============================================================================
|
||||
|
||||
# Your IndieWeb identity URL (REQUIRED)
|
||||
# This is YOUR personal website URL that you authenticate with
|
||||
# Example: https://yourname.com or https://github.com/yourname
|
||||
# Your identity URL (REQUIRED)
|
||||
# Your personal website. Used as the author h-card source and as the "me"
|
||||
# value in Micropub tokens. It should link to this site's IndieAuth metadata
|
||||
# (see docs/decisions/ADR-064) so Micropub apps can find StarPunk.
|
||||
ADMIN_ME=https://your-website.com
|
||||
|
||||
# Admin login via OpenID Connect (REQUIRED in production)
|
||||
# Register StarPunk as a confidential client with your provider (e.g. Pocket ID)
|
||||
# using the callback URL: <SITE_URL>/auth/callback
|
||||
OIDC_ISSUER=https://id.example.com
|
||||
OIDC_CLIENT_ID=
|
||||
OIDC_CLIENT_SECRET=
|
||||
# The provider's subject ("sub") of the one account allowed to log in.
|
||||
# Pocket ID: the user's ID shown in the admin user list.
|
||||
OIDC_ADMIN_SUB=
|
||||
# Name shown on the login button (default: "single sign-on")
|
||||
OIDC_PROVIDER_NAME=Pocket ID
|
||||
|
||||
# Session secret key (REQUIRED - GENERATE A RANDOM VALUE)
|
||||
# Generate with: python3 -c "import secrets; print(secrets.token_hex(32))"
|
||||
SESSION_SECRET=REPLACE_WITH_RANDOM_SECRET
|
||||
@@ -34,8 +47,21 @@ SESSION_SECRET=REPLACE_WITH_RANDOM_SECRET
|
||||
# Session lifetime in days (default: 30)
|
||||
SESSION_LIFETIME=30
|
||||
|
||||
# IndieLogin service URL (usually don't change this)
|
||||
INDIELOGIN_URL=https://indielogin.com
|
||||
# Lifetime of Micropub access tokens StarPunk issues, in days (default: 90)
|
||||
INDIEAUTH_TOKEN_LIFETIME_DAYS=90
|
||||
|
||||
# =============================================================================
|
||||
# CROSSPOSTING (optional, v2.1.0)
|
||||
# =============================================================================
|
||||
|
||||
# GoToSocial or Mastodon account to copy new notes to. Create an app token
|
||||
# with scopes: write:statuses write:media
|
||||
GOTOSOCIAL_URL=
|
||||
GOTOSOCIAL_ACCESS_TOKEN=
|
||||
# Name shown in the editor and Micropub apps (default: GoToSocial)
|
||||
GOTOSOCIAL_NAME=GoToSocial
|
||||
# public, unlisted, private (default: public)
|
||||
GOTOSOCIAL_VISIBILITY=public
|
||||
|
||||
# =============================================================================
|
||||
# DATA STORAGE
|
||||
|
||||
@@ -1,58 +1,42 @@
|
||||
# Gitea Actions workflow for StarPunk
|
||||
# Builds and pushes container images on version tags
|
||||
|
||||
# Builds and pushes container images on version tags.
|
||||
#
|
||||
# The runner has no Docker daemon (that would give workflows root on the
|
||||
# server). Images are built by the rootless BuildKit container next to it,
|
||||
# reached through its socket.
|
||||
name: Build Container
|
||||
|
||||
on:
|
||||
# Trigger on version tags
|
||||
push:
|
||||
tags:
|
||||
- 'v[0-9]+.[0-9]+.[0-9]+'
|
||||
# Allow manual trigger from Gitea UI
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: git.thesatelliteoflove.com
|
||||
BUILDKIT: unix:///run/buildkit/buildkit/buildkitd.sock
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: docker
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
if command -v apk > /dev/null; then
|
||||
apk add --no-cache nodejs npm docker git
|
||||
elif command -v apt-get > /dev/null; then
|
||||
apt-get update && apt-get install -y nodejs npm docker.io git
|
||||
elif command -v yum > /dev/null; then
|
||||
yum install -y nodejs npm docker git
|
||||
fi
|
||||
|
||||
run: apk add --no-cache nodejs git docker-cli docker-cli-buildx
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Extract registry URL
|
||||
id: registry
|
||||
run: |
|
||||
# Extract hostname from server URL (remove protocol)
|
||||
REGISTRY_URL=$(echo "${{ github.server_url }}" | sed 's|https://||' | sed 's|http://||')
|
||||
echo "url=${REGISTRY_URL}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ steps.registry.outputs.url }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# The automatic Actions token can't log in to the container registry, so
|
||||
# this uses a personal access token with only the write:package scope,
|
||||
# stored as the repository secret REGISTRY_TOKEN.
|
||||
- name: Log in to the Gitea registry
|
||||
run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "$REGISTRY" -u "${{ github.repository_owner }}" --password-stdin
|
||||
- name: Use the BuildKit socket
|
||||
run: docker buildx create --name ci --driver remote "$BUILDKIT" --use
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Containerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ steps.registry.outputs.url }}/${{ github.repository }}:${{ github.ref_name }}
|
||||
${{ steps.registry.outputs.url }}/${{ github.repository }}:latest
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
run: |
|
||||
image="$REGISTRY/$(echo '${{ github.repository }}' | tr '[:upper:]' '[:lower:]')"
|
||||
docker buildx build --push -f Containerfile \
|
||||
-t "$image:${{ github.ref_name }}" -t "$image:latest" .
|
||||
- name: Clean up
|
||||
if: always()
|
||||
run: |
|
||||
docker buildx rm ci || true
|
||||
docker logout "$REGISTRY" || true
|
||||
@@ -7,6 +7,84 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.2.0] - 2026-10-31
|
||||
|
||||
### Added
|
||||
|
||||
- **Crossposting to Bluesky**, ADR-066
|
||||
- Plain-text note (Markdown stripped) with clickable link and hashtag facets, shortened to 300 characters with the permalink kept
|
||||
- Images (up to 4, shrunk under Bluesky's 1 MB limit) with alt text; notes without images get a link card
|
||||
- Unpublishing, unticking and deleting remove the Bluesky post; edits don't follow (Bluesky has no edits)
|
||||
- Logs in with an app password: `BLUESKY_HANDLE`, `BLUESKY_APP_PASSWORD` (optional `BLUESKY_SERVICE`, default `https://bsky.social`)
|
||||
- Shown in the editor and Micropub `syndicate-to` next to GoToSocial
|
||||
|
||||
## [2.1.0] - 2026-10-31
|
||||
|
||||
### Added
|
||||
|
||||
- **Crossposting to GoToSocial** (or any Mastodon-API server), ADR-065
|
||||
- Full note as Markdown with images (alt text from captions), permalink and hashtags
|
||||
- Edits, unpublishing and deletes follow the note
|
||||
- On by default for new notes; untick in the editor, or send `mp-syndicate-to` from Micropub apps
|
||||
- Micropub `q=syndicate-to` and `q=config` list the target
|
||||
- Editor shows crosspost status, errors and a retry button; note pages link the copy with `u-syndication`
|
||||
- Configure with `GOTOSOCIAL_URL` and `GOTOSOCIAL_ACCESS_TOKEN` (scopes `write:statuses write:media`)
|
||||
- Migration 012: `syndications`
|
||||
|
||||
### Fixed
|
||||
|
||||
- Micropub `Location` header pointed at `/notes/<slug>` (404); now the real permalink
|
||||
- "Delete Note" on the edit page submitted the edit form (nested forms)
|
||||
- Search results linked to `/notes/<slug>` (404); now `/note/<slug>`
|
||||
|
||||
## [2.0.2] - 2026-10-31
|
||||
|
||||
### Fixed
|
||||
|
||||
- Container builds in Gitea Actions log in to the registry with the
|
||||
`REGISTRY_TOKEN` secret (a `write:package` token); the automatic Actions
|
||||
token is refused by the registry. No application changes.
|
||||
|
||||
## [2.0.1] - 2026-10-31
|
||||
|
||||
### Fixed
|
||||
|
||||
- Page links built from the request said `http://` behind an HTTPS reverse proxy
|
||||
(RSS/OPML `<link>`s and microformats `u-url`/`u-uid` permalinks). All absolute
|
||||
URLs in templates now come from `SITE_URL` via `absolute_url_for()`.
|
||||
- Container builds in Gitea Actions: build through the server's rootless BuildKit
|
||||
and log in to the public registry name (the old workflow never succeeded).
|
||||
|
||||
## [2.0.0] - 2026-10-31
|
||||
|
||||
### Changed (breaking)
|
||||
|
||||
- **Admin login uses OpenID Connect** instead of IndieAuth (ADR-064)
|
||||
- Works with Pocket ID or any OIDC provider; authorization code flow with PKCE and nonce
|
||||
- Only the account whose subject matches `OIDC_ADMIN_SUB` can log in
|
||||
- New required settings: `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, `OIDC_ADMIN_SUB`
|
||||
- `INDIELOGIN_URL` and `TOKEN_ENDPOINT` are ignored
|
||||
- **Micropub tokens are issued by StarPunk**, not an external IndieAuth server
|
||||
- Your `ADMIN_ME` page must point Micropub apps at StarPunk's
|
||||
`/.well-known/oauth-authorization-server` (or its `/auth/authorize` and `/auth/token`)
|
||||
- Apps authorized through an external server must be authorized again
|
||||
|
||||
### Added
|
||||
|
||||
- Built-in IndieAuth server: metadata, consent screen, token, revocation endpoints
|
||||
- **Connected Apps** admin page (`/admin/tokens`) to review and revoke Micropub tokens
|
||||
- Discovery links (`micropub`, `indieauth-metadata`, `authorization_endpoint`, `token_endpoint`) on every page
|
||||
- Migration 011: `oidc_login_state`, `indieauth_codes`, `indieauth_tokens`
|
||||
|
||||
### Removed
|
||||
|
||||
- IndieAuth endpoint discovery and external token verification (`starpunk/auth_external.py`)
|
||||
|
||||
### Notes
|
||||
|
||||
- Existing notes, media, tags, webmentions, author profile and admin sessions are preserved
|
||||
- v1.6.0 source (webmentions) recovered from the production image; it had not been committed
|
||||
|
||||
## [1.5.0] - 2025-12-17
|
||||
|
||||
### Added
|
||||
|
||||
@@ -27,7 +27,8 @@ StarPunk is designed for a single user who wants to:
|
||||
## Features
|
||||
|
||||
- **File-based storage**: Notes are markdown files, owned by you
|
||||
- **IndieAuth authentication**: Use your own website as identity
|
||||
- **OIDC admin login**: Sign in through your identity provider (e.g. Pocket ID)
|
||||
- **Built-in IndieAuth server**: Approve Micropub apps without a separate auth service
|
||||
- **Micropub support**: Full W3C Micropub specification compliance
|
||||
- **Media attachments**: Upload and display images with your notes
|
||||
- **Microformats2**: Full h-entry, h-card, and h-feed markup for IndieWeb compatibility
|
||||
@@ -62,7 +63,7 @@ uv pip install -r requirements.txt
|
||||
|
||||
# Configure
|
||||
cp .env.example .env
|
||||
# Edit .env and set ADMIN_ME and SESSION_SECRET
|
||||
# Edit .env and set ADMIN_ME, SESSION_SECRET and the OIDC_* values
|
||||
|
||||
# Initialize database
|
||||
mkdir -p data/notes
|
||||
@@ -82,6 +83,8 @@ All configuration is in the `.env` file. Required settings:
|
||||
- `ADMIN_ME` - Your IndieWeb identity URL (e.g., https://yoursite.com)
|
||||
- `SESSION_SECRET` - Random secret key (generate with `python3 -c "import secrets; print(secrets.token_hex(32))"`)
|
||||
- `SITE_URL` - Public URL of your site
|
||||
- `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` - OIDC client for admin login (callback: `<SITE_URL>/auth/callback`)
|
||||
- `OIDC_ADMIN_SUB` - Subject ID of the one account allowed to log in
|
||||
|
||||
See `.env.example` for all options.
|
||||
|
||||
@@ -110,7 +113,7 @@ starpunk/
|
||||
|
||||
**Via Micropub Client**:
|
||||
1. Configure client with your site URL
|
||||
2. Authenticate via IndieAuth
|
||||
2. Sign in with your OIDC provider
|
||||
3. Publish from any Micropub-compatible app
|
||||
|
||||
### Backing Up Your Data
|
||||
@@ -192,7 +195,6 @@ Built with:
|
||||
- [python-markdown](https://python-markdown.github.io/) - Markdown processing
|
||||
- [feedgen](https://feedgen.kiesow.be/) - RSS generation
|
||||
- [httpx](https://www.python-httpx.org/) - HTTP client
|
||||
- [IndieLogin](https://indielogin.com/) - Authentication service
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# ADR-064: OIDC Admin Login and Built-in IndieAuth Server
|
||||
|
||||
## Status
|
||||
|
||||
Accepted (v2.0.0, 2026-10-31)
|
||||
|
||||
Supersedes the login parts of ADR-021, ADR-025, ADR-027 and ADR-043, and the
|
||||
external token verification of ADR-030 and ADR-036.
|
||||
|
||||
## Context
|
||||
|
||||
Up to v1.6.0 StarPunk was an IndieAuth *client*. Admin login discovered an
|
||||
authorization endpoint from `ADMIN_ME` and used the authentication-only
|
||||
flow; Micropub verified bearer tokens by calling the token endpoint
|
||||
discovered from `ADMIN_ME`. In practice both pointed at Gondulf, a separate
|
||||
self-hosted IndieAuth server.
|
||||
|
||||
The operator now runs Pocket ID (OIDC, passkeys) for every other
|
||||
self-hosted service and wants StarPunk to use it too. Pocket ID cannot act
|
||||
as an IndieAuth server: IndieAuth clients identify themselves by URL
|
||||
(`client_id` = their homepage) and are not pre-registered, while OIDC
|
||||
clients must be registered with the provider.
|
||||
|
||||
Micropub apps such as Quill and Indigenous only speak IndieAuth, so moving
|
||||
login to OIDC alone would end Micropub posting.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Admin login uses OIDC** (authorization code flow, PKCE S256, nonce).
|
||||
StarPunk is a confidential client. The ID token's signature (provider
|
||||
JWKS), `iss`, `aud`, `exp` and `nonce` are verified, and only the
|
||||
configured `OIDC_ADMIN_SUB` may log in. A successful login creates the
|
||||
same local session as before, for `ADMIN_ME`.
|
||||
2. **StarPunk becomes its own IndieAuth server** for Micropub clients:
|
||||
`/.well-known/oauth-authorization-server`, `/auth/authorize` (consent
|
||||
screen, admin session required, so approval is protected by OIDC),
|
||||
`/auth/token` and `/auth/revoke`. Only `response_type=code` with PKCE
|
||||
S256 is supported. Tokens are stored as SHA-256 hashes and verified
|
||||
locally by `/micropub` and `/media`.
|
||||
3. **`ADMIN_ME` stays** as the site owner's identity URL: it is the author
|
||||
h-card source and the `me` in issued tokens. That page must advertise
|
||||
StarPunk's IndieAuth metadata (or `authorization_endpoint` /
|
||||
`token_endpoint` links) so Micropub apps discover StarPunk.
|
||||
4. **New tables** (`oidc_login_state`, `indieauth_codes`,
|
||||
`indieauth_tokens`, migration 011). The legacy `auth_state`, `tokens`
|
||||
and `authorization_codes` tables are not reused because migration 004
|
||||
drops the last two after `INITIAL_SCHEMA_SQL` creates them.
|
||||
5. Client `redirect_uri` must share the `client_id` origin, or be published
|
||||
by the client (JSON `redirect_uris` or `rel="redirect_uri"`). The fetch
|
||||
reuses the webmention SSRF guard.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Gondulf is no longer needed and can be retired.
|
||||
- Existing admin sessions stay valid (sessions are keyed by `ADMIN_ME`, which
|
||||
does not change). Notes, media, tags and webmentions are untouched.
|
||||
- Micropub apps must be re-authorized once, since their old tokens were
|
||||
issued by Gondulf. Tokens are visible and revocable at `/admin/tokens`.
|
||||
- Production requires `OIDC_ISSUER`, `OIDC_CLIENT_ID`,
|
||||
`OIDC_CLIENT_SECRET`, `OIDC_ADMIN_SUB`. `INDIELOGIN_URL` and
|
||||
`TOKEN_ENDPOINT` are ignored.
|
||||
- New dependency: `PyJWT[crypto]`.
|
||||
- Major version bump (2.0.0): configuration and endpoint discovery change
|
||||
incompatibly.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
- **Keep Gondulf for Micropub only**: two auth systems to run and patch.
|
||||
- **Drop Micropub**: simplest, but loses posting from apps.
|
||||
- **Manually created API tokens**: Quill and most apps require IndieAuth.
|
||||
@@ -0,0 +1,45 @@
|
||||
# ADR-065: Direct Syndication (POSSE) to GoToSocial
|
||||
|
||||
## Status
|
||||
|
||||
Accepted (v2.1.0, 2026-10-31)
|
||||
|
||||
## Context
|
||||
|
||||
StarPunk posts were copied to other networks by Echofeed reading the feed.
|
||||
That gives no control per post, no record of where a post went, and edits
|
||||
and deletes never follow. The operator runs GoToSocial locally and wants
|
||||
StarPunk to post there directly, with Bluesky likely next.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Publish here, copy out (POSSE).** Each (note, target) has a row in
|
||||
`syndications` (migration 012). Creating, editing, unpublishing or
|
||||
deleting a note marks its rows pending; a background worker reconciles
|
||||
the remote post: create, update (`PUT /api/v1/statuses/:id`) or delete.
|
||||
2. **Defaults.** New notes go to every configured target unless unticked in
|
||||
the editor or a Micropub client sends `mp-syndicate-to` (an explicit
|
||||
list, possibly empty). Existing notes are never backfilled.
|
||||
3. **Content.** The full note as Markdown (`content_type: text/markdown`),
|
||||
then the permalink and the note's tags as hashtags. Longer than the
|
||||
target's limit: shortened at a word boundary with the link kept.
|
||||
Images are uploaded first (the `large` variant) with their captions as
|
||||
alt text.
|
||||
4. **Delivery.** Rows are claimed atomically so the four gunicorn workers'
|
||||
threads never send twice; an `Idempotency-Key` guards retries; a row
|
||||
`version` keeps edits made during a send. Network errors and 5xx/429
|
||||
retry with exponential backoff (8 attempts); other 4xx fail at once.
|
||||
A remote post deleted by hand is posted again on the next edit.
|
||||
5. **Backlinks.** Synced URLs are shown on the note page as `u-syndication`
|
||||
links, and in the editor with status, last error and a retry button.
|
||||
6. **Targets** are config-driven. One kind exists, a Mastodon-API client
|
||||
(`GOTOSOCIAL_URL`, `GOTOSOCIAL_ACCESS_TOKEN`); it also works for
|
||||
Mastodon. A Bluesky target would add a second client behind the same
|
||||
reconcile loop.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Echofeed must stop posting to GoToSocial or posts appear twice.
|
||||
- The token needs only `write:statuses write:media`.
|
||||
- `syndications.note_id` has no foreign key so a hard-deleted note's
|
||||
remote post can still be deleted.
|
||||
@@ -0,0 +1,37 @@
|
||||
# ADR-066: Crossposting to Bluesky
|
||||
|
||||
## Status
|
||||
|
||||
Accepted (v2.2.0, 2026-10-31)
|
||||
|
||||
## Context
|
||||
|
||||
ADR-065 added direct crossposting to GoToSocial. Bluesky was still fed by
|
||||
Echofeed, with the same problems: no per-post control, no record of the
|
||||
copy, deletes never follow.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Second client, same loop.** `BlueskyClient` sits behind the reconcile
|
||||
loop and `syndications` table from ADR-065, as target id `bluesky`.
|
||||
Clients share a small interface: `create`, `update`, `delete`, `can_edit`.
|
||||
2. **Auth.** An app password (`BLUESKY_HANDLE`, `BLUESKY_APP_PASSWORD`).
|
||||
`createSession` against `BLUESKY_SERVICE` (default `https://bsky.social`);
|
||||
writes go to the PDS named in the returned DID document. Expired access
|
||||
tokens are refreshed, falling back to a new session.
|
||||
3. **Content.** Plain text (Markdown rendered and stripped), then the
|
||||
permalink and hashtags (at most a third of the space), shortened to 300
|
||||
characters at a word boundary. Link and hashtag facets use UTF-8 byte
|
||||
offsets. Images (up to 4) are re-encoded as JPEG if over 1 MB, with alt
|
||||
text and aspect ratio; a note without images gets a link card.
|
||||
4. **Edits don't follow.** Bluesky has no edit; rewriting the record would
|
||||
break likes and replies, and delete-and-repost would lose them. The post
|
||||
stays as first sent. Unpublish, untick and delete remove it.
|
||||
5. **No double posts.** When a create is retried, recent posts are checked
|
||||
for one already linking to the note (a send whose reply was lost).
|
||||
|
||||
## Consequences
|
||||
|
||||
- Echofeed is no longer needed; it must stop posting to Bluesky or posts
|
||||
appear twice.
|
||||
- A post deleted by hand on Bluesky is not re-created.
|
||||
@@ -0,0 +1,56 @@
|
||||
# v2.0.0 Implementation Report: OIDC Login and Built-in IndieAuth Server
|
||||
|
||||
Date: 2026-10-31
|
||||
Decision: ADR-064
|
||||
|
||||
## Summary
|
||||
|
||||
Admin login moved from IndieAuth (via Gondulf) to OIDC (Pocket ID).
|
||||
StarPunk now issues and verifies its own Micropub tokens, so Gondulf is no
|
||||
longer needed. No data migration is required: notes, media, tags,
|
||||
webmentions, the author profile and admin sessions are unchanged.
|
||||
|
||||
## Source recovery
|
||||
|
||||
Production ran `starpunk:v1.6.0-rc.2`, but the v1.6.0 code was never
|
||||
committed (`main` was at v1.5.0). The application code was copied out of
|
||||
the running container's `/app` and committed as `v1.6.0-rc.2` before any
|
||||
v2.0.0 changes. The v1.6.0 tests and docs were not in the image, so ADR-063
|
||||
(webmentions) and the v1.6.0 design folder are still missing.
|
||||
|
||||
## Changes
|
||||
|
||||
| Area | Change |
|
||||
|---|---|
|
||||
| `starpunk/auth.py` | OIDC client: discovery (cached), PKCE S256, nonce, ID token check against the provider JWKS, `OIDC_ADMIN_SUB` check. Session functions unchanged. |
|
||||
| `starpunk/indieauth.py` | New: authorization codes, access tokens (hashed), client `redirect_uri` checks, revocation. |
|
||||
| `starpunk/routes/auth.py` | Login is a single "Sign in with ..." button; callback handles provider errors and `next`. |
|
||||
| `starpunk/routes/indieauth.py` | New: metadata, consent, approve, token, legacy token verify, revoke. |
|
||||
| `starpunk/routes/micropub.py` | Verifies tokens locally. |
|
||||
| `starpunk/routes/admin.py`, `templates/admin/tokens.html` | Connected Apps page with revoke. |
|
||||
| `templates/base.html` | Discovery links built from `SITE_URL` (not the request host, which is `http://` behind the proxy). |
|
||||
| `migrations/011_*.sql` | `oidc_login_state`, `indieauth_codes`, `indieauth_tokens`. |
|
||||
| `starpunk/auth_external.py` | Removed. |
|
||||
|
||||
## Testing
|
||||
|
||||
- New: `tests/test_auth_oidc.py` (real RS256-signed ID tokens: bad audience, issuer,
|
||||
key, expiry, nonce, subject; state reuse; routes) and `tests/test_indieauth.py`
|
||||
(validation, PKCE, single-use codes, consent, full Micropub post with an issued
|
||||
token, revocation, admin page).
|
||||
- `tests/test_auth.py` keeps the session tests; IndieLogin flow tests removed.
|
||||
- Full suite: 905 passed. Remaining failures predate this work and are in the
|
||||
recovered v1.6.0 baseline: seven in `test_media_upload.py` (image
|
||||
validation, HEIC, MPO) and one or two timing-sensitive tests in
|
||||
`test_migration_race_condition.py` that fail on a different test each run.
|
||||
- Migration rehearsed on a copy of the production database: 011 applied,
|
||||
row counts for notes, media, tags, sessions and author profile unchanged.
|
||||
|
||||
## Deployment notes
|
||||
|
||||
- Pocket ID client "StarPunk": confidential, PKCE on, callback
|
||||
`https://starpunk.thesatelliteoflove.com/auth/callback`.
|
||||
- The container needs `id.thesatelliteoflove.com` mapped to Caddy in
|
||||
`extra_hosts` (hairpin NAT does not work from the `lava` network).
|
||||
- `thesatelliteoflove.com` (static file in `/opt/stacks/caddy/site/tsol/`)
|
||||
must advertise StarPunk's IndieAuth endpoints instead of Gondulf's.
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Migration 011: OIDC admin login + built-in IndieAuth server
|
||||
-- Version: 2.0.0
|
||||
-- Per ADR-064: Replace IndieAuth login with OIDC, issue Micropub tokens locally
|
||||
--
|
||||
-- New tables only. The legacy auth_state, tokens and authorization_codes
|
||||
-- tables are left alone: INITIAL_SCHEMA_SQL recreates tokens and
|
||||
-- authorization_codes on every start while migration 004 drops them, so
|
||||
-- nothing new can depend on them.
|
||||
|
||||
-- Pending OIDC logins (state, nonce and PKCE verifier for one round trip)
|
||||
CREATE TABLE IF NOT EXISTS oidc_login_state (
|
||||
state TEXT PRIMARY KEY,
|
||||
nonce TEXT NOT NULL,
|
||||
code_verifier TEXT NOT NULL,
|
||||
next_url TEXT,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMP NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_oidc_login_state_expires ON oidc_login_state(expires_at);
|
||||
|
||||
-- Authorization codes issued to IndieAuth (Micropub) clients
|
||||
CREATE TABLE IF NOT EXISTS indieauth_codes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code_hash TEXT UNIQUE NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
redirect_uri TEXT NOT NULL,
|
||||
scope TEXT NOT NULL DEFAULT '',
|
||||
code_challenge TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMP NOT NULL,
|
||||
used_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_indieauth_codes_expires ON indieauth_codes(expires_at);
|
||||
|
||||
-- Access tokens issued to IndieAuth (Micropub) clients
|
||||
CREATE TABLE IF NOT EXISTS indieauth_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
token_hash TEXT UNIQUE NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMP NOT NULL,
|
||||
last_used_at TIMESTAMP,
|
||||
revoked_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_indieauth_tokens_expires ON indieauth_tokens(expires_at);
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Migration 012: Crossposting (POSSE) to syndication targets
|
||||
-- Version: 2.1.0
|
||||
-- Per ADR-065: Direct syndication to GoToSocial / Mastodon-API servers
|
||||
--
|
||||
-- One row per (note, target). The worker reconciles the remote post with the
|
||||
-- note: create, update, or delete as needed. note_id has no foreign key on
|
||||
-- purpose: a row must outlive a hard-deleted note so the remote post can be
|
||||
-- deleted too.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS syndications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
note_id INTEGER NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
remote_id TEXT,
|
||||
remote_url TEXT,
|
||||
state TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (state IN ('pending', 'synced', 'failed')),
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
next_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
claimed_until TIMESTAMP,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (note_id, target)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_syndications_due ON syndications(state, next_attempt_at);
|
||||
@@ -39,3 +39,4 @@ pillow-heif==0.18.*
|
||||
|
||||
# HTML Sanitization (v1.6.0 - Webmention content)
|
||||
nh3==0.2.*
|
||||
PyJWT[crypto]==2.10.*
|
||||
+15
-2
@@ -191,6 +191,10 @@ def create_app(config=None):
|
||||
register_routes(app)
|
||||
|
||||
# Template context processor - Inject author profile (v1.2.0 Phase 2)
|
||||
from starpunk.utils import absolute_url_for
|
||||
|
||||
app.jinja_env.globals["absolute_url_for"] = absolute_url_for
|
||||
|
||||
@app.context_processor
|
||||
def inject_author():
|
||||
"""
|
||||
@@ -332,6 +336,15 @@ def create_app(config=None):
|
||||
if hasattr(app, 'webmention_worker') and app.webmention_worker.is_alive():
|
||||
app.webmention_worker.stop()
|
||||
|
||||
# Start syndication worker when a target is configured (v2.1.0)
|
||||
from starpunk.syndication import SyndicationWorker, targets_configured
|
||||
if targets_configured(app.config) and not app.config.get("TESTING", False):
|
||||
app.syndication_worker = SyndicationWorker(
|
||||
app, poll_interval=app.config["SYNDICATION_POLL_INTERVAL"]
|
||||
)
|
||||
app.syndication_worker.start()
|
||||
app.logger.info("Syndication worker started")
|
||||
|
||||
# Health check endpoint for containers and monitoring
|
||||
@app.route("/health")
|
||||
def health_check():
|
||||
@@ -436,5 +449,5 @@ def create_app(config=None):
|
||||
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "1.6.0"
|
||||
__version_info__ = (1, 6, 0)
|
||||
__version__ = "2.2.0"
|
||||
__version_info__ = (2, 1, 0)
|
||||
+233
-395
@@ -1,20 +1,21 @@
|
||||
"""
|
||||
Authentication module for StarPunk
|
||||
|
||||
Implements IndieLogin authentication for admin access using indielogin.com
|
||||
as a delegated authentication provider. No passwords are stored locally.
|
||||
Admin login uses OpenID Connect (authorization code flow with PKCE) against
|
||||
a configured provider such as Pocket ID. Exactly one OIDC subject
|
||||
(OIDC_ADMIN_SUB) may log in; a successful login creates a local session
|
||||
for the site owner's identity URL (ADMIN_ME). No passwords are stored.
|
||||
|
||||
Security features:
|
||||
- CSRF protection via state tokens
|
||||
- Secure session tokens (cryptographically random)
|
||||
- Token hashing in database (SHA-256)
|
||||
- CSRF protection via single-use state tokens
|
||||
- PKCE (S256) and nonce binding of the ID token to the login attempt
|
||||
- ID token signature, issuer, audience and expiry checks
|
||||
- Session tokens hashed in the database (SHA-256)
|
||||
- HttpOnly, Secure, SameSite cookies
|
||||
- Single-admin authorization
|
||||
- Automatic session cleanup
|
||||
|
||||
Functions:
|
||||
initiate_login: Start IndieLogin authentication flow
|
||||
handle_callback: Process IndieLogin callback
|
||||
initiate_login: Start the OIDC login flow
|
||||
handle_callback: Finish the OIDC login flow and create a session
|
||||
create_session: Create authenticated session
|
||||
verify_session: Check if session is valid
|
||||
destroy_session: Logout and cleanup
|
||||
@@ -24,153 +25,50 @@ Exceptions:
|
||||
AuthError: Base authentication exception
|
||||
InvalidStateError: CSRF state validation failed
|
||||
UnauthorizedError: User not authorized as admin
|
||||
IndieLoginError: External service error
|
||||
OIDCError: Identity provider error
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import logging
|
||||
import secrets
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from functools import wraps
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
import jwt
|
||||
from flask import current_app, g, redirect, request, session, url_for
|
||||
|
||||
from starpunk.auth_external import discover_endpoints, DiscoveryError, normalize_url
|
||||
from starpunk.database import get_db
|
||||
from starpunk.utils import is_valid_url
|
||||
|
||||
# Cached provider metadata: {issuer: (fetched_at, metadata)}
|
||||
_METADATA_CACHE: Dict[str, Tuple[float, dict]] = {}
|
||||
_METADATA_TTL = 3600
|
||||
# One JWKS client per jwks_uri; PyJWKClient caches the keys itself
|
||||
_JWKS_CLIENTS: Dict[str, jwt.PyJWKClient] = {}
|
||||
|
||||
LOGIN_STATE_MINUTES = 10
|
||||
|
||||
|
||||
# Custom exceptions
|
||||
class AuthError(Exception):
|
||||
"""Base exception for authentication errors"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class InvalidStateError(AuthError):
|
||||
"""CSRF state validation failed"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class UnauthorizedError(AuthError):
|
||||
"""User not authorized as admin"""
|
||||
|
||||
pass
|
||||
|
||||
class OIDCError(AuthError):
|
||||
"""Identity provider error"""
|
||||
|
||||
|
||||
class IndieLoginError(AuthError):
|
||||
"""IndieLogin service error"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
# Logging helper functions
|
||||
def _redact_token(value: str, show_chars: int = 6) -> str:
|
||||
"""
|
||||
Redact sensitive token for logging
|
||||
|
||||
Shows first N and last 4 characters with asterisks in between.
|
||||
|
||||
Args:
|
||||
value: Token to redact
|
||||
show_chars: Number of characters to show at start (default: 6)
|
||||
|
||||
Returns:
|
||||
Redacted token string like "abc123...********...xyz9"
|
||||
"""
|
||||
if not value or len(value) <= (show_chars + 4):
|
||||
return "***REDACTED***"
|
||||
|
||||
return f"{value[:show_chars]}...{'*' * 8}...{value[-4:]}"
|
||||
|
||||
|
||||
def _log_http_request(method: str, url: str, data: dict, headers: dict = None) -> None:
|
||||
"""
|
||||
Log HTTP request details at DEBUG level
|
||||
|
||||
Automatically redacts sensitive parameters (code, state, authorization)
|
||||
|
||||
Args:
|
||||
method: HTTP method (GET, POST, etc.)
|
||||
url: Request URL
|
||||
data: Request data/parameters
|
||||
headers: Optional request headers
|
||||
"""
|
||||
if not current_app.logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
# Redact sensitive data
|
||||
safe_data = data.copy()
|
||||
if "code" in safe_data:
|
||||
safe_data["code"] = _redact_token(safe_data["code"])
|
||||
if "state" in safe_data:
|
||||
safe_data["state"] = _redact_token(safe_data["state"], 8)
|
||||
if "code_verifier" in safe_data:
|
||||
safe_data["code_verifier"] = _redact_token(safe_data["code_verifier"])
|
||||
|
||||
current_app.logger.debug(
|
||||
f"IndieAuth HTTP Request:\n"
|
||||
f" Method: {method}\n"
|
||||
f" URL: {url}\n"
|
||||
f" Data: {safe_data}"
|
||||
)
|
||||
|
||||
if headers:
|
||||
safe_headers = {
|
||||
k: v
|
||||
for k, v in headers.items()
|
||||
if k.lower() not in ["authorization", "cookie"]
|
||||
}
|
||||
current_app.logger.debug(f" Headers: {safe_headers}")
|
||||
|
||||
|
||||
def _log_http_response(status_code: int, headers: dict, body: str) -> None:
|
||||
"""
|
||||
Log HTTP response details at DEBUG level
|
||||
|
||||
Automatically redacts sensitive response data
|
||||
|
||||
Args:
|
||||
status_code: HTTP status code
|
||||
headers: Response headers
|
||||
body: Response body (JSON string or text)
|
||||
"""
|
||||
if not current_app.logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
# Parse and redact JSON body if present
|
||||
safe_body = body
|
||||
try:
|
||||
import json
|
||||
|
||||
data = json.loads(body)
|
||||
if "access_token" in data:
|
||||
data["access_token"] = _redact_token(data["access_token"])
|
||||
if "code" in data:
|
||||
data["code"] = _redact_token(data["code"])
|
||||
safe_body = json.dumps(data, indent=2)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
# Not JSON or parsing failed, log as-is (likely error message)
|
||||
pass
|
||||
|
||||
# Redact sensitive headers
|
||||
safe_headers = {
|
||||
k: v for k, v in headers.items() if k.lower() not in ["set-cookie", "authorization"]
|
||||
}
|
||||
|
||||
current_app.logger.debug(
|
||||
f"IndieAuth HTTP Response:\n"
|
||||
f" Status: {status_code}\n"
|
||||
f" Headers: {safe_headers}\n"
|
||||
f" Body: {safe_body}"
|
||||
)
|
||||
|
||||
|
||||
# Helper functions
|
||||
def _hash_token(token: str) -> str:
|
||||
"""
|
||||
Hash token using SHA-256
|
||||
@@ -185,323 +83,264 @@ def _hash_token(token: str) -> str:
|
||||
|
||||
|
||||
def _generate_state_token() -> str:
|
||||
"""
|
||||
Generate CSRF state token
|
||||
|
||||
Returns:
|
||||
URL-safe random token
|
||||
"""
|
||||
"""Generate a URL-safe random token"""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def _verify_state_token(state: str) -> bool:
|
||||
def _pkce_challenge(verifier: str) -> str:
|
||||
"""S256 PKCE challenge for a verifier (RFC 7636)"""
|
||||
digest = hashlib.sha256(verifier.encode("ascii")).digest()
|
||||
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def _redirect_uri() -> str:
|
||||
"""OIDC redirect URI registered with the provider"""
|
||||
return current_app.config["SITE_URL"].rstrip("/") + "/auth/callback"
|
||||
|
||||
|
||||
def _safe_next_url(next_url: Optional[str]) -> Optional[str]:
|
||||
"""Only allow redirects back to this site after login"""
|
||||
if not next_url:
|
||||
return None
|
||||
site = current_app.config["SITE_URL"].rstrip("/")
|
||||
if next_url.startswith(site + "/"):
|
||||
return next_url
|
||||
if next_url.startswith("/") and not next_url.startswith("//"):
|
||||
return next_url
|
||||
return None
|
||||
|
||||
|
||||
def _cleanup_expired_sessions() -> None:
|
||||
"""Remove expired sessions and pending login state"""
|
||||
db = get_db(current_app)
|
||||
db.execute("DELETE FROM sessions WHERE expires_at <= datetime('now')")
|
||||
db.execute("DELETE FROM oidc_login_state WHERE expires_at <= datetime('now')")
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_oidc_metadata() -> dict:
|
||||
"""
|
||||
Verify and consume CSRF state token.
|
||||
Fetch (and cache) the provider's OpenID configuration
|
||||
|
||||
Raises:
|
||||
OIDCError: Discovery failed or the issuer does not match
|
||||
"""
|
||||
issuer = current_app.config.get("OIDC_ISSUER", "").rstrip("/")
|
||||
if not issuer:
|
||||
raise OIDCError("OIDC_ISSUER is not configured")
|
||||
|
||||
cached = _METADATA_CACHE.get(issuer)
|
||||
if cached and time.time() - cached[0] < _METADATA_TTL:
|
||||
return cached[1]
|
||||
|
||||
url = f"{issuer}/.well-known/openid-configuration"
|
||||
try:
|
||||
response = httpx.get(url, timeout=10.0)
|
||||
response.raise_for_status()
|
||||
metadata = response.json()
|
||||
except (httpx.HTTPError, ValueError) as e:
|
||||
raise OIDCError(f"OIDC discovery failed: {e}")
|
||||
|
||||
if metadata.get("issuer", "").rstrip("/") != issuer:
|
||||
raise OIDCError(
|
||||
f"OIDC issuer mismatch: expected {issuer}, got {metadata.get('issuer')}"
|
||||
)
|
||||
for key in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
|
||||
if not metadata.get(key):
|
||||
raise OIDCError(f"OIDC metadata is missing {key}")
|
||||
|
||||
_METADATA_CACHE[issuer] = (time.time(), metadata)
|
||||
return metadata
|
||||
|
||||
|
||||
def _get_signing_key(metadata: dict, id_token: str):
|
||||
"""Resolve the key that signed an ID token from the provider's JWKS"""
|
||||
jwks_uri = metadata["jwks_uri"]
|
||||
client = _JWKS_CLIENTS.get(jwks_uri)
|
||||
if client is None:
|
||||
client = jwt.PyJWKClient(jwks_uri, timeout=10)
|
||||
_JWKS_CLIENTS[jwks_uri] = client
|
||||
return client.get_signing_key_from_jwt(id_token).key
|
||||
|
||||
|
||||
def _validate_id_token(metadata: dict, id_token: str, nonce: str) -> dict:
|
||||
"""
|
||||
Verify the ID token signature and standard claims (OIDC Core 3.1.3.7)
|
||||
|
||||
Raises:
|
||||
OIDCError: Token is invalid
|
||||
"""
|
||||
algorithms = metadata.get("id_token_signing_alg_values_supported") or ["RS256"]
|
||||
algorithms = [alg for alg in algorithms if alg != "none"]
|
||||
try:
|
||||
key = _get_signing_key(metadata, id_token)
|
||||
claims = jwt.decode(
|
||||
id_token,
|
||||
key,
|
||||
algorithms=algorithms,
|
||||
audience=current_app.config["OIDC_CLIENT_ID"],
|
||||
issuer=metadata["issuer"],
|
||||
options={"require": ["exp", "iat", "sub", "iss", "aud"]},
|
||||
leeway=60,
|
||||
)
|
||||
except jwt.PyJWTError as e:
|
||||
raise OIDCError(f"Invalid ID token: {e}")
|
||||
|
||||
if not nonce or not secrets.compare_digest(str(claims.get("nonce", "")), nonce):
|
||||
raise OIDCError("ID token nonce does not match login request")
|
||||
|
||||
return claims
|
||||
|
||||
|
||||
# Core authentication functions
|
||||
def initiate_login(next_url: Optional[str] = None) -> str:
|
||||
"""
|
||||
Start the OIDC authorization code flow
|
||||
|
||||
Args:
|
||||
state: State token to verify
|
||||
next_url: Where to send the admin after login (same site only)
|
||||
|
||||
Returns:
|
||||
True if valid, False if invalid or expired
|
||||
"""
|
||||
db = get_db(current_app)
|
||||
Redirect URL to the provider's authorization endpoint
|
||||
|
||||
# Check if state exists and not expired
|
||||
result = db.execute(
|
||||
Raises:
|
||||
OIDCError: Provider discovery failed
|
||||
"""
|
||||
metadata = get_oidc_metadata()
|
||||
|
||||
state = _generate_state_token()
|
||||
nonce = secrets.token_urlsafe(32)
|
||||
code_verifier = secrets.token_urlsafe(64)
|
||||
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"""
|
||||
SELECT 1 FROM auth_state
|
||||
INSERT INTO oidc_login_state (state, nonce, code_verifier, next_url, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
state,
|
||||
nonce,
|
||||
code_verifier,
|
||||
_safe_next_url(next_url),
|
||||
datetime.utcnow() + timedelta(minutes=LOGIN_STATE_MINUTES),
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
params = {
|
||||
"response_type": "code",
|
||||
"client_id": current_app.config["OIDC_CLIENT_ID"],
|
||||
"redirect_uri": _redirect_uri(),
|
||||
"scope": "openid",
|
||||
"state": state,
|
||||
"nonce": nonce,
|
||||
"code_challenge": _pkce_challenge(code_verifier),
|
||||
"code_challenge_method": "S256",
|
||||
}
|
||||
|
||||
current_app.logger.info("Auth: OIDC login initiated")
|
||||
return f"{metadata['authorization_endpoint']}?{urlencode(params)}"
|
||||
|
||||
|
||||
def _consume_login_state(state: str) -> Optional[dict]:
|
||||
"""Fetch and delete a pending login (single use)"""
|
||||
db = get_db(current_app)
|
||||
row = db.execute(
|
||||
"""
|
||||
SELECT nonce, code_verifier, next_url FROM oidc_login_state
|
||||
WHERE state = ? AND expires_at > datetime('now')
|
||||
""",
|
||||
(state,),
|
||||
).fetchone()
|
||||
|
||||
if not result:
|
||||
return False
|
||||
|
||||
# Delete state (single-use)
|
||||
db.execute("DELETE FROM auth_state WHERE state = ?", (state,))
|
||||
db.execute("DELETE FROM oidc_login_state WHERE state = ?", (state,))
|
||||
db.commit()
|
||||
|
||||
return True
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def _cleanup_expired_sessions() -> None:
|
||||
"""Remove expired sessions and state tokens"""
|
||||
db = get_db(current_app)
|
||||
|
||||
# Delete expired sessions
|
||||
db.execute(
|
||||
"""
|
||||
DELETE FROM sessions
|
||||
WHERE expires_at <= datetime('now')
|
||||
def handle_callback(
|
||||
code: str, state: str, iss: Optional[str] = None
|
||||
) -> Tuple[str, Optional[str]]:
|
||||
"""
|
||||
)
|
||||
|
||||
# Delete expired state tokens
|
||||
db.execute(
|
||||
"""
|
||||
DELETE FROM auth_state
|
||||
WHERE expires_at <= datetime('now')
|
||||
"""
|
||||
)
|
||||
|
||||
db.commit()
|
||||
|
||||
|
||||
# Core authentication functions
|
||||
def initiate_login(me_url: str) -> str:
|
||||
"""
|
||||
Initiate IndieAuth authentication flow with endpoint discovery.
|
||||
|
||||
Per W3C IndieAuth spec, discovers authorization_endpoint from user's
|
||||
profile URL rather than using a hardcoded service.
|
||||
Finish the OIDC flow: exchange the code, verify the ID token, check
|
||||
the subject is the configured admin, and create a session.
|
||||
|
||||
Args:
|
||||
me_url: User's IndieWeb identity URL
|
||||
|
||||
Returns:
|
||||
Redirect URL to discovered authorization endpoint
|
||||
|
||||
Raises:
|
||||
ValueError: Invalid me_url format
|
||||
DiscoveryError: Failed to discover endpoints from profile
|
||||
"""
|
||||
# Validate URL format
|
||||
if not is_valid_url(me_url):
|
||||
raise ValueError(f"Invalid URL format: {me_url}")
|
||||
|
||||
current_app.logger.debug(f"Auth: Validating me URL: {me_url}")
|
||||
|
||||
# Discover authorization endpoint from user's profile URL
|
||||
# Per IndieAuth spec: clients MUST discover endpoints, not hardcode them
|
||||
try:
|
||||
endpoints = discover_endpoints(me_url)
|
||||
except DiscoveryError as e:
|
||||
current_app.logger.error(f"Auth: Endpoint discovery failed for {me_url}: {e}")
|
||||
raise
|
||||
|
||||
auth_endpoint = endpoints.get('authorization_endpoint')
|
||||
if not auth_endpoint:
|
||||
raise DiscoveryError(
|
||||
f"No authorization_endpoint found at {me_url}. "
|
||||
"Ensure your profile has IndieAuth link elements or headers."
|
||||
)
|
||||
|
||||
current_app.logger.info(f"Auth: Discovered authorization_endpoint: {auth_endpoint}")
|
||||
|
||||
# Generate CSRF state token
|
||||
state = _generate_state_token()
|
||||
current_app.logger.debug(f"Auth: Generated state token: {_redact_token(state, 8)}")
|
||||
|
||||
# Store state in database (5-minute expiry)
|
||||
db = get_db(current_app)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
redirect_uri = f"{current_app.config['SITE_URL']}auth/callback"
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO auth_state (state, expires_at, redirect_uri)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(state, expires_at, redirect_uri),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Build authorization URL
|
||||
# Per W3C IndieAuth spec: use response_type=id for authentication-only flow
|
||||
# (identity verification without access token). This allows code redemption
|
||||
# at the authorization_endpoint rather than requiring token_endpoint.
|
||||
params = {
|
||||
"me": me_url,
|
||||
"client_id": current_app.config["SITE_URL"],
|
||||
"redirect_uri": redirect_uri,
|
||||
"state": state,
|
||||
"response_type": "id",
|
||||
}
|
||||
|
||||
current_app.logger.debug(
|
||||
f"Auth: Building authorization URL with params:\n"
|
||||
f" me: {me_url}\n"
|
||||
f" client_id: {current_app.config['SITE_URL']}\n"
|
||||
f" redirect_uri: {redirect_uri}\n"
|
||||
f" state: {_redact_token(state, 8)}\n"
|
||||
f" response_type: id (authentication-only flow)"
|
||||
)
|
||||
|
||||
auth_url = f"{auth_endpoint}?{urlencode(params)}"
|
||||
|
||||
current_app.logger.debug(f"Auth: Complete authorization URL: {auth_url}")
|
||||
current_app.logger.info(f"Auth: Authentication initiated for {me_url}")
|
||||
|
||||
return auth_url
|
||||
|
||||
|
||||
def handle_callback(code: str, state: str, iss: Optional[str] = None) -> Optional[str]:
|
||||
"""
|
||||
Handle IndieAuth callback with endpoint discovery.
|
||||
|
||||
Discovers authorization_endpoint from ADMIN_ME profile and exchanges
|
||||
authorization code for identity verification.
|
||||
|
||||
Per IndieAuth spec: Authentication-only flows POST to the authorization
|
||||
endpoint (not token endpoint) and do not include grant_type.
|
||||
|
||||
Args:
|
||||
code: Authorization code from authorization server
|
||||
code: Authorization code from the provider
|
||||
state: CSRF state token
|
||||
iss: Issuer identifier (optional, for security validation)
|
||||
iss: Issuer from the redirect (RFC 9207), checked when present
|
||||
|
||||
Returns:
|
||||
Session token if successful, None otherwise
|
||||
(session_token, next_url)
|
||||
|
||||
Raises:
|
||||
InvalidStateError: State token validation failed
|
||||
UnauthorizedError: User not authorized as admin
|
||||
IndieLoginError: Code exchange failed
|
||||
UnauthorizedError: Subject is not the configured admin
|
||||
OIDCError: Provider or token error
|
||||
"""
|
||||
current_app.logger.debug(f"Auth: Verifying state token: {_redact_token(state, 8)}")
|
||||
|
||||
# Verify state token (CSRF protection)
|
||||
if not _verify_state_token(state):
|
||||
current_app.logger.warning(
|
||||
"Auth: Invalid state token received (possible CSRF or expired token)"
|
||||
)
|
||||
pending = _consume_login_state(state)
|
||||
if not pending:
|
||||
current_app.logger.warning("Auth: Invalid or expired OIDC state")
|
||||
raise InvalidStateError("Invalid or expired state token")
|
||||
|
||||
current_app.logger.debug("Auth: State token valid")
|
||||
metadata = get_oidc_metadata()
|
||||
|
||||
# Discover authorization endpoint from ADMIN_ME profile
|
||||
admin_me = current_app.config.get("ADMIN_ME")
|
||||
if not admin_me:
|
||||
current_app.logger.error("Auth: ADMIN_ME not configured")
|
||||
raise IndieLoginError("ADMIN_ME not configured")
|
||||
if iss and iss.rstrip("/") != metadata["issuer"].rstrip("/"):
|
||||
raise OIDCError(f"Unexpected issuer in callback: {iss}")
|
||||
|
||||
try:
|
||||
endpoints = discover_endpoints(admin_me)
|
||||
except DiscoveryError as e:
|
||||
current_app.logger.error(f"Auth: Endpoint discovery failed: {e}")
|
||||
raise IndieLoginError(f"Failed to discover endpoints: {e}")
|
||||
|
||||
# Use authorization_endpoint for authentication-only flow (identity verification)
|
||||
# Per IndieAuth spec: auth-only flows POST to authorization_endpoint, not token_endpoint
|
||||
auth_endpoint = endpoints.get('authorization_endpoint')
|
||||
if not auth_endpoint:
|
||||
raise IndieLoginError(
|
||||
f"No authorization_endpoint found at {admin_me}. "
|
||||
"Ensure your profile has IndieAuth endpoints configured."
|
||||
)
|
||||
|
||||
current_app.logger.debug(f"Auth: Using authorization_endpoint: {auth_endpoint}")
|
||||
|
||||
# Verify issuer if provided (security check - optional)
|
||||
if iss:
|
||||
current_app.logger.debug(f"Auth: Issuer provided: {iss}")
|
||||
|
||||
# Prepare code verification request
|
||||
# Note: grant_type is NOT included for authentication-only flows per IndieAuth spec
|
||||
token_exchange_data = {
|
||||
"code": code,
|
||||
"client_id": current_app.config["SITE_URL"],
|
||||
"redirect_uri": f"{current_app.config['SITE_URL']}auth/callback",
|
||||
}
|
||||
|
||||
# Log the request
|
||||
_log_http_request(
|
||||
method="POST",
|
||||
url=auth_endpoint,
|
||||
data=token_exchange_data,
|
||||
)
|
||||
|
||||
current_app.logger.debug(
|
||||
"Auth: Sending code verification request to authorization endpoint:\n"
|
||||
" Method: POST\n"
|
||||
" URL: %s\n"
|
||||
" Data: code=%s, client_id=%s, redirect_uri=%s",
|
||||
auth_endpoint,
|
||||
_redact_token(code),
|
||||
token_exchange_data["client_id"],
|
||||
token_exchange_data["redirect_uri"],
|
||||
)
|
||||
|
||||
# Exchange code for identity at authorization endpoint (authentication-only flow)
|
||||
try:
|
||||
response = httpx.post(
|
||||
auth_endpoint,
|
||||
data=token_exchange_data,
|
||||
metadata["token_endpoint"],
|
||||
data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": _redirect_uri(),
|
||||
"code_verifier": pending["code_verifier"],
|
||||
},
|
||||
auth=(
|
||||
current_app.config["OIDC_CLIENT_ID"],
|
||||
current_app.config["OIDC_CLIENT_SECRET"],
|
||||
),
|
||||
timeout=10.0,
|
||||
)
|
||||
|
||||
current_app.logger.debug(
|
||||
"Auth: Received code verification response:\n"
|
||||
" Status: %d\n"
|
||||
" Headers: %s\n"
|
||||
" Body: %s",
|
||||
response.status_code,
|
||||
{k: v for k, v in dict(response.headers).items()
|
||||
if k.lower() not in ["set-cookie", "authorization"]},
|
||||
_redact_token(response.text) if response.text else "(empty)",
|
||||
)
|
||||
|
||||
_log_http_response(
|
||||
status_code=response.status_code,
|
||||
headers=dict(response.headers),
|
||||
body=response.text,
|
||||
)
|
||||
|
||||
response.raise_for_status()
|
||||
except httpx.RequestError as e:
|
||||
current_app.logger.error(f"Auth: Authorization endpoint request failed: {e}")
|
||||
raise IndieLoginError(f"Failed to verify code: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise OIDCError(f"Token request failed: {e}")
|
||||
|
||||
if response.status_code != 200:
|
||||
current_app.logger.error(
|
||||
f"Auth: Authorization endpoint returned error: {e.response.status_code} - {e.response.text}"
|
||||
)
|
||||
raise IndieLoginError(
|
||||
f"Authorization endpoint returned error: {e.response.status_code}"
|
||||
f"Auth: OIDC token endpoint returned {response.status_code}: {response.text[:200]}"
|
||||
)
|
||||
raise OIDCError(f"Token endpoint returned {response.status_code}")
|
||||
|
||||
# Parse response
|
||||
try:
|
||||
data = response.json()
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Auth: Failed to parse authorization endpoint response: {e}")
|
||||
raise IndieLoginError("Invalid JSON response from authorization endpoint")
|
||||
id_token = response.json().get("id_token")
|
||||
except ValueError:
|
||||
raise OIDCError("Token endpoint returned invalid JSON")
|
||||
if not id_token:
|
||||
raise OIDCError("Token endpoint returned no id_token")
|
||||
|
||||
me = data.get("me")
|
||||
claims = _validate_id_token(metadata, id_token, pending["nonce"])
|
||||
|
||||
admin_sub = current_app.config.get("OIDC_ADMIN_SUB", "")
|
||||
if not admin_sub or not secrets.compare_digest(claims["sub"], admin_sub):
|
||||
current_app.logger.warning(f"Auth: Unauthorized OIDC subject {claims['sub']}")
|
||||
raise UnauthorizedError("This account is not the site admin")
|
||||
|
||||
me = current_app.config.get("ADMIN_ME")
|
||||
if not me:
|
||||
current_app.logger.error("Auth: No identity returned from authorization endpoint")
|
||||
raise IndieLoginError("No identity returned from authorization endpoint")
|
||||
raise OIDCError("ADMIN_ME not configured")
|
||||
|
||||
current_app.logger.debug(f"Auth: Received identity: {me}")
|
||||
|
||||
# Verify this is the admin user
|
||||
current_app.logger.info(f"Auth: Verifying admin authorization for me={me}")
|
||||
|
||||
# Normalize URLs for comparison (handles trailing slashes and case differences)
|
||||
# This is correct per IndieAuth spec - the returned 'me' is the canonical form
|
||||
if normalize_url(me) != normalize_url(admin_me):
|
||||
current_app.logger.warning(
|
||||
f"Auth: Unauthorized login attempt: {me} (expected {admin_me})"
|
||||
)
|
||||
raise UnauthorizedError(f"User {me} is not authorized")
|
||||
|
||||
current_app.logger.debug("Auth: Admin verification passed")
|
||||
|
||||
# Create session
|
||||
session_token = create_session(me)
|
||||
|
||||
# Trigger author profile discovery (v1.2.0 Phase 2)
|
||||
# Per Q14: Never block login, always allow fallback
|
||||
# Refresh the author h-card; never block login on it
|
||||
try:
|
||||
from starpunk.author_discovery import get_author_profile
|
||||
author_profile = get_author_profile(me, refresh=True)
|
||||
current_app.logger.info(f"Author profile refreshed for {me}")
|
||||
|
||||
get_author_profile(me, refresh=True)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Author discovery failed: {e}")
|
||||
# Continue login anyway - never block per Q14
|
||||
|
||||
return session_token
|
||||
return session_token, pending["next_url"]
|
||||
|
||||
|
||||
def create_session(me: str) -> str:
|
||||
@@ -567,7 +406,6 @@ def verify_session(token: str) -> Optional[Dict[str, Any]]:
|
||||
current_app.logger.debug("Auth: No session token provided")
|
||||
return None
|
||||
|
||||
current_app.logger.debug(f"Auth: Verifying session token: {_redact_token(token)}")
|
||||
|
||||
token_hash = _hash_token(token)
|
||||
|
||||
|
||||
@@ -1,614 +0,0 @@
|
||||
"""
|
||||
External IndieAuth Token Verification with Endpoint Discovery
|
||||
|
||||
This module handles verification of bearer tokens issued by external
|
||||
IndieAuth providers. Following the IndieAuth specification, endpoints
|
||||
are discovered dynamically from the user's profile URL, not hardcoded.
|
||||
|
||||
For StarPunk V1 (single-user CMS), we always discover endpoints from
|
||||
ADMIN_ME since only the site owner can post content.
|
||||
|
||||
Key Components:
|
||||
EndpointCache: Simple in-memory cache for discovered endpoints and tokens
|
||||
verify_external_token: Main entry point for token verification
|
||||
discover_endpoints: Discovers IndieAuth endpoints from profile URL
|
||||
|
||||
Configuration (via Flask app.config):
|
||||
ADMIN_ME: Site owner's profile URL (required)
|
||||
DEBUG: Allow HTTP endpoints in debug mode
|
||||
|
||||
ADR: ADR-031 IndieAuth Endpoint Discovery Implementation
|
||||
Date: 2025-11-24
|
||||
Version: v1.0.0-rc.5
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Dict, Optional, Any
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from flask import current_app
|
||||
|
||||
|
||||
# Timeouts
|
||||
DISCOVERY_TIMEOUT = 5.0 # Profile fetch (cached, so can be slower)
|
||||
VERIFICATION_TIMEOUT = 3.0 # Token verification (every request)
|
||||
|
||||
# Cache TTLs
|
||||
ENDPOINT_CACHE_TTL = 3600 # 1 hour for endpoints
|
||||
TOKEN_CACHE_TTL = 300 # 5 minutes for token verifications
|
||||
|
||||
|
||||
class EndpointCache:
|
||||
"""
|
||||
Simple in-memory cache for endpoint discovery and token verification
|
||||
|
||||
V1 single-user implementation: We only cache one user's endpoints
|
||||
since StarPunk V1 is explicitly single-user (only ADMIN_ME can post).
|
||||
|
||||
When V2 adds multi-user support, this will need refactoring to
|
||||
cache endpoints per profile URL.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Endpoint cache (single-user V1)
|
||||
self.endpoints: Optional[Dict[str, str]] = None
|
||||
self.endpoints_expire: float = 0
|
||||
|
||||
# Token verification cache (token_hash -> (info, expiry))
|
||||
self.token_cache: Dict[str, tuple[Dict[str, Any], float]] = {}
|
||||
|
||||
def get_endpoints(self, ignore_expiry: bool = False) -> Optional[Dict[str, str]]:
|
||||
"""
|
||||
Get cached endpoints if still valid
|
||||
|
||||
Args:
|
||||
ignore_expiry: Return cached endpoints even if expired (grace period)
|
||||
|
||||
Returns:
|
||||
Cached endpoints dict or None if not cached or expired
|
||||
"""
|
||||
if self.endpoints is None:
|
||||
return None
|
||||
|
||||
if ignore_expiry or time.time() < self.endpoints_expire:
|
||||
return self.endpoints
|
||||
|
||||
return None
|
||||
|
||||
def set_endpoints(self, endpoints: Dict[str, str], ttl: int = ENDPOINT_CACHE_TTL):
|
||||
"""Cache discovered endpoints"""
|
||||
self.endpoints = endpoints
|
||||
self.endpoints_expire = time.time() + ttl
|
||||
|
||||
def get_token_info(self, token_hash: str) -> Optional[Dict[str, Any]]:
|
||||
"""Get cached token verification if still valid"""
|
||||
if token_hash in self.token_cache:
|
||||
info, expiry = self.token_cache[token_hash]
|
||||
if time.time() < expiry:
|
||||
return info
|
||||
else:
|
||||
# Expired, remove from cache
|
||||
del self.token_cache[token_hash]
|
||||
return None
|
||||
|
||||
def set_token_info(self, token_hash: str, info: Dict[str, Any], ttl: int = TOKEN_CACHE_TTL):
|
||||
"""Cache token verification result"""
|
||||
expiry = time.time() + ttl
|
||||
self.token_cache[token_hash] = (info, expiry)
|
||||
|
||||
|
||||
# Global cache instance (singleton for V1)
|
||||
_cache = EndpointCache()
|
||||
|
||||
|
||||
class DiscoveryError(Exception):
|
||||
"""Raised when endpoint discovery fails"""
|
||||
pass
|
||||
|
||||
|
||||
class TokenVerificationError(Exception):
|
||||
"""Raised when token verification fails"""
|
||||
pass
|
||||
|
||||
|
||||
def verify_external_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Verify bearer token with external IndieAuth provider
|
||||
|
||||
This is the main entry point for token verification. For StarPunk V1
|
||||
(single-user), we always discover endpoints from ADMIN_ME since only
|
||||
the site owner can post content.
|
||||
|
||||
Process:
|
||||
1. Check token verification cache
|
||||
2. Discover endpoints from ADMIN_ME (with caching)
|
||||
3. Verify token with discovered endpoint
|
||||
4. Validate token belongs to ADMIN_ME
|
||||
5. Cache successful verification
|
||||
|
||||
Args:
|
||||
token: Bearer token to verify
|
||||
|
||||
Returns:
|
||||
Dict with token info (me, client_id, scope) if valid
|
||||
None if token is invalid or verification fails
|
||||
|
||||
Token info dict contains:
|
||||
me: User's profile URL
|
||||
client_id: Client application URL
|
||||
scope: Space-separated list of scopes
|
||||
"""
|
||||
admin_me = current_app.config.get("ADMIN_ME")
|
||||
|
||||
if not admin_me:
|
||||
current_app.logger.error(
|
||||
"ADMIN_ME not configured. Cannot verify token ownership."
|
||||
)
|
||||
return None
|
||||
|
||||
# Check token cache first
|
||||
token_hash = _hash_token(token)
|
||||
cached_info = _cache.get_token_info(token_hash)
|
||||
if cached_info:
|
||||
current_app.logger.debug("Token verification cache hit")
|
||||
return cached_info
|
||||
|
||||
# Discover endpoints from ADMIN_ME (V1 single-user assumption)
|
||||
try:
|
||||
endpoints = discover_endpoints(admin_me)
|
||||
except DiscoveryError as e:
|
||||
current_app.logger.error(f"Endpoint discovery failed: {e}")
|
||||
return None
|
||||
|
||||
token_endpoint = endpoints.get('token_endpoint')
|
||||
if not token_endpoint:
|
||||
current_app.logger.error("No token endpoint found in discovery")
|
||||
return None
|
||||
|
||||
# Verify token with discovered endpoint
|
||||
try:
|
||||
token_info = _verify_with_endpoint(token_endpoint, token)
|
||||
except TokenVerificationError as e:
|
||||
current_app.logger.warning(f"Token verification failed: {e}")
|
||||
return None
|
||||
|
||||
# Validate token belongs to admin (single-user security check)
|
||||
token_me = token_info.get('me', '')
|
||||
if normalize_url(token_me) != normalize_url(admin_me):
|
||||
current_app.logger.warning(
|
||||
f"Token 'me' mismatch: {token_me} != {admin_me}"
|
||||
)
|
||||
return None
|
||||
|
||||
# Cache successful verification
|
||||
_cache.set_token_info(token_hash, token_info)
|
||||
|
||||
current_app.logger.debug(f"Token verified successfully for {token_me}")
|
||||
return token_info
|
||||
|
||||
|
||||
def discover_endpoints(profile_url: str) -> Dict[str, str]:
|
||||
"""
|
||||
Discover IndieAuth endpoints from a profile URL
|
||||
|
||||
Implements IndieAuth endpoint discovery per W3C spec:
|
||||
https://www.w3.org/TR/indieauth/#discovery-by-clients
|
||||
|
||||
Discovery priority:
|
||||
1. HTTP Link headers (highest priority)
|
||||
2. HTML link elements
|
||||
|
||||
Args:
|
||||
profile_url: User's profile URL (their IndieWeb identity)
|
||||
|
||||
Returns:
|
||||
Dict with discovered endpoints:
|
||||
{
|
||||
'authorization_endpoint': 'https://...',
|
||||
'token_endpoint': 'https://...'
|
||||
}
|
||||
|
||||
Raises:
|
||||
DiscoveryError: If discovery fails or no endpoints found
|
||||
"""
|
||||
# Check cache first
|
||||
cached_endpoints = _cache.get_endpoints()
|
||||
if cached_endpoints:
|
||||
current_app.logger.debug("Endpoint discovery cache hit")
|
||||
return cached_endpoints
|
||||
|
||||
# Validate profile URL
|
||||
_validate_profile_url(profile_url)
|
||||
|
||||
try:
|
||||
# Fetch profile with discovery
|
||||
endpoints = _fetch_and_parse(profile_url)
|
||||
|
||||
# Cache successful discovery
|
||||
_cache.set_endpoints(endpoints)
|
||||
|
||||
return endpoints
|
||||
|
||||
except Exception as e:
|
||||
# Check cache even if expired (grace period for network failures)
|
||||
cached = _cache.get_endpoints(ignore_expiry=True)
|
||||
if cached:
|
||||
current_app.logger.warning(
|
||||
f"Using expired cache due to discovery failure: {e}"
|
||||
)
|
||||
return cached
|
||||
|
||||
# No cache available, must fail
|
||||
raise DiscoveryError(f"Endpoint discovery failed: {e}")
|
||||
|
||||
|
||||
def _fetch_and_parse(profile_url: str) -> Dict[str, str]:
|
||||
"""
|
||||
Fetch profile URL and parse endpoints from headers and HTML
|
||||
|
||||
Args:
|
||||
profile_url: User's profile URL
|
||||
|
||||
Returns:
|
||||
Dict with discovered endpoints
|
||||
|
||||
Raises:
|
||||
DiscoveryError: If fetch fails or no endpoints found
|
||||
"""
|
||||
try:
|
||||
response = httpx.get(
|
||||
profile_url,
|
||||
timeout=DISCOVERY_TIMEOUT,
|
||||
follow_redirects=True,
|
||||
headers={
|
||||
'Accept': 'text/html,application/xhtml+xml',
|
||||
'User-Agent': f'StarPunk/{current_app.config.get("VERSION", "1.0")}'
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
except httpx.TimeoutException:
|
||||
raise DiscoveryError(f"Timeout fetching profile: {profile_url}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise DiscoveryError(f"HTTP {e.response.status_code} fetching profile")
|
||||
except httpx.RequestError as e:
|
||||
raise DiscoveryError(f"Network error fetching profile: {e}")
|
||||
|
||||
endpoints = {}
|
||||
|
||||
# 1. Parse HTTP Link headers (highest priority)
|
||||
link_header = response.headers.get('Link', '')
|
||||
if link_header:
|
||||
link_endpoints = _parse_link_header(link_header, profile_url)
|
||||
endpoints.update(link_endpoints)
|
||||
|
||||
# 2. Parse HTML link elements
|
||||
content_type = response.headers.get('Content-Type', '')
|
||||
if 'text/html' in content_type or 'application/xhtml+xml' in content_type:
|
||||
try:
|
||||
html_endpoints = _parse_html_links(response.text, profile_url)
|
||||
# Merge: Link headers take priority (so update HTML first)
|
||||
html_endpoints.update(endpoints)
|
||||
endpoints = html_endpoints
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"HTML parsing failed: {e}")
|
||||
# Continue with Link header endpoints if HTML parsing fails
|
||||
|
||||
# Validate we found at least one endpoint
|
||||
# - authorization_endpoint: Required for authentication-only flows (admin login)
|
||||
# - token_endpoint: Required for Micropub token verification
|
||||
# Having at least one allows the appropriate flow to work
|
||||
if 'token_endpoint' not in endpoints and 'authorization_endpoint' not in endpoints:
|
||||
raise DiscoveryError(
|
||||
f"No IndieAuth endpoints found at {profile_url}. "
|
||||
"Ensure your profile has authorization_endpoint or token_endpoint configured."
|
||||
)
|
||||
|
||||
# Validate endpoint URLs
|
||||
for rel, url in endpoints.items():
|
||||
_validate_endpoint_url(url, rel)
|
||||
|
||||
current_app.logger.info(
|
||||
f"Discovered endpoints from {profile_url}: "
|
||||
f"token={endpoints.get('token_endpoint')}, "
|
||||
f"auth={endpoints.get('authorization_endpoint')}"
|
||||
)
|
||||
|
||||
return endpoints
|
||||
|
||||
|
||||
def _parse_link_header(header: str, base_url: str) -> Dict[str, str]:
|
||||
"""
|
||||
Parse HTTP Link header for IndieAuth endpoints
|
||||
|
||||
Basic RFC 8288 support - handles simple Link headers.
|
||||
Limitations: Only supports quoted rel values, single Link headers.
|
||||
|
||||
Example:
|
||||
Link: <https://auth.example.com/token>; rel="token_endpoint"
|
||||
|
||||
Args:
|
||||
header: Link header value
|
||||
base_url: Base URL for resolving relative URLs
|
||||
|
||||
Returns:
|
||||
Dict with discovered endpoints
|
||||
"""
|
||||
endpoints = {}
|
||||
|
||||
# Pattern: <url>; rel="relation"
|
||||
# Note: Simplified - doesn't handle all RFC 8288 edge cases
|
||||
pattern = r'<([^>]+)>;\s*rel="([^"]+)"'
|
||||
matches = re.findall(pattern, header)
|
||||
|
||||
for url, rel in matches:
|
||||
if rel == 'authorization_endpoint':
|
||||
endpoints['authorization_endpoint'] = urljoin(base_url, url)
|
||||
elif rel == 'token_endpoint':
|
||||
endpoints['token_endpoint'] = urljoin(base_url, url)
|
||||
|
||||
return endpoints
|
||||
|
||||
|
||||
def _parse_html_links(html: str, base_url: str) -> Dict[str, str]:
|
||||
"""
|
||||
Extract IndieAuth endpoints from HTML link elements
|
||||
|
||||
Looks for:
|
||||
<link rel="authorization_endpoint" href="...">
|
||||
<link rel="token_endpoint" href="...">
|
||||
|
||||
Args:
|
||||
html: HTML content
|
||||
base_url: Base URL for resolving relative URLs
|
||||
|
||||
Returns:
|
||||
Dict with discovered endpoints
|
||||
"""
|
||||
endpoints = {}
|
||||
|
||||
try:
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
|
||||
# Find all link elements (check both head and body - be liberal)
|
||||
for link in soup.find_all('link', rel=True):
|
||||
rel = link.get('rel')
|
||||
href = link.get('href')
|
||||
|
||||
if not href:
|
||||
continue
|
||||
|
||||
# rel can be a list or string
|
||||
if isinstance(rel, list):
|
||||
rel = ' '.join(rel)
|
||||
|
||||
# Check for IndieAuth endpoints
|
||||
if 'authorization_endpoint' in rel:
|
||||
endpoints['authorization_endpoint'] = urljoin(base_url, href)
|
||||
elif 'token_endpoint' in rel:
|
||||
endpoints['token_endpoint'] = urljoin(base_url, href)
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"HTML parsing error: {e}")
|
||||
# Return what we found so far
|
||||
|
||||
return endpoints
|
||||
|
||||
|
||||
def _verify_with_endpoint(endpoint: str, token: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Verify token with the discovered token endpoint
|
||||
|
||||
Makes GET request to endpoint with Authorization header.
|
||||
Implements retry logic for network errors only.
|
||||
|
||||
Args:
|
||||
endpoint: Token endpoint URL
|
||||
token: Bearer token to verify
|
||||
|
||||
Returns:
|
||||
Token info dict from endpoint
|
||||
|
||||
Raises:
|
||||
TokenVerificationError: If verification fails
|
||||
"""
|
||||
headers = {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Accept': 'application/json',
|
||||
}
|
||||
|
||||
max_retries = 3
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
response = httpx.get(
|
||||
endpoint,
|
||||
headers=headers,
|
||||
timeout=VERIFICATION_TIMEOUT,
|
||||
follow_redirects=True,
|
||||
)
|
||||
|
||||
# Handle HTTP status codes
|
||||
if response.status_code == 200:
|
||||
token_info = response.json()
|
||||
|
||||
# Validate required fields
|
||||
if 'me' not in token_info:
|
||||
raise TokenVerificationError("Token response missing 'me' field")
|
||||
|
||||
return token_info
|
||||
|
||||
# Client errors - don't retry
|
||||
elif response.status_code in [400, 401, 403, 404]:
|
||||
raise TokenVerificationError(
|
||||
f"Token verification failed: HTTP {response.status_code}"
|
||||
)
|
||||
|
||||
# Server errors - retry
|
||||
elif response.status_code in [500, 502, 503, 504]:
|
||||
if attempt < max_retries - 1:
|
||||
wait_time = 2 ** attempt # Exponential backoff
|
||||
current_app.logger.debug(
|
||||
f"Server error {response.status_code}, retrying in {wait_time}s..."
|
||||
)
|
||||
time.sleep(wait_time)
|
||||
continue
|
||||
else:
|
||||
raise TokenVerificationError(
|
||||
f"Token endpoint error: HTTP {response.status_code}"
|
||||
)
|
||||
|
||||
# Other status codes
|
||||
else:
|
||||
raise TokenVerificationError(
|
||||
f"Unexpected response: HTTP {response.status_code}"
|
||||
)
|
||||
|
||||
except httpx.TimeoutException:
|
||||
if attempt < max_retries - 1:
|
||||
wait_time = 2 ** attempt
|
||||
current_app.logger.debug(f"Timeout, retrying in {wait_time}s...")
|
||||
time.sleep(wait_time)
|
||||
continue
|
||||
else:
|
||||
raise TokenVerificationError("Token verification timeout")
|
||||
|
||||
except httpx.NetworkError as e:
|
||||
if attempt < max_retries - 1:
|
||||
wait_time = 2 ** attempt
|
||||
current_app.logger.debug(f"Network error, retrying in {wait_time}s...")
|
||||
time.sleep(wait_time)
|
||||
continue
|
||||
else:
|
||||
raise TokenVerificationError(f"Network error: {e}")
|
||||
|
||||
except Exception as e:
|
||||
# Don't retry for unexpected errors
|
||||
raise TokenVerificationError(f"Verification failed: {e}")
|
||||
|
||||
# Should never reach here, but just in case
|
||||
raise TokenVerificationError("Maximum retries exceeded")
|
||||
|
||||
|
||||
def _validate_profile_url(url: str) -> None:
|
||||
"""
|
||||
Validate profile URL format and security requirements
|
||||
|
||||
Args:
|
||||
url: Profile URL to validate
|
||||
|
||||
Raises:
|
||||
DiscoveryError: If URL is invalid or insecure
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
|
||||
# Must be absolute
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise DiscoveryError(f"Invalid profile URL format: {url}")
|
||||
|
||||
# HTTPS required in production
|
||||
if not current_app.debug and parsed.scheme != 'https':
|
||||
raise DiscoveryError(
|
||||
f"HTTPS required for profile URLs in production. Got: {url}"
|
||||
)
|
||||
|
||||
# Allow localhost only in debug mode
|
||||
if not current_app.debug and parsed.hostname in ['localhost', '127.0.0.1', '::1']:
|
||||
raise DiscoveryError(
|
||||
"Localhost URLs not allowed in production"
|
||||
)
|
||||
|
||||
|
||||
def _validate_endpoint_url(url: str, rel: str) -> None:
|
||||
"""
|
||||
Validate discovered endpoint URL
|
||||
|
||||
Args:
|
||||
url: Endpoint URL to validate
|
||||
rel: Endpoint relation (for error messages)
|
||||
|
||||
Raises:
|
||||
DiscoveryError: If URL is invalid or insecure
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
|
||||
# Must be absolute
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise DiscoveryError(f"Invalid {rel} URL format: {url}")
|
||||
|
||||
# HTTPS required in production
|
||||
if not current_app.debug and parsed.scheme != 'https':
|
||||
raise DiscoveryError(
|
||||
f"HTTPS required for {rel} in production. Got: {url}"
|
||||
)
|
||||
|
||||
# Allow localhost only in debug mode
|
||||
if not current_app.debug and parsed.hostname in ['localhost', '127.0.0.1', '::1']:
|
||||
raise DiscoveryError(
|
||||
f"Localhost not allowed for {rel} in production"
|
||||
)
|
||||
|
||||
|
||||
def normalize_url(url: str) -> str:
|
||||
"""
|
||||
Normalize URL for comparison
|
||||
|
||||
Removes trailing slash and converts to lowercase.
|
||||
Used only for comparison, not for storage.
|
||||
|
||||
Args:
|
||||
url: URL to normalize
|
||||
|
||||
Returns:
|
||||
Normalized URL
|
||||
"""
|
||||
return url.rstrip('/').lower()
|
||||
|
||||
|
||||
def _hash_token(token: str) -> str:
|
||||
"""
|
||||
Hash token for secure caching
|
||||
|
||||
Uses SHA-256 to prevent tokens from appearing in logs
|
||||
and to create fixed-length cache keys.
|
||||
|
||||
Args:
|
||||
token: Bearer token
|
||||
|
||||
Returns:
|
||||
SHA-256 hash of token (hex)
|
||||
"""
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def check_scope(required_scope: str, token_scope: str) -> bool:
|
||||
"""
|
||||
Check if token has required scope
|
||||
|
||||
Scopes are space-separated in token_scope string.
|
||||
Any scope in the list satisfies the requirement.
|
||||
|
||||
Args:
|
||||
required_scope: Scope needed (e.g., "create")
|
||||
token_scope: Space-separated scope string from token
|
||||
|
||||
Returns:
|
||||
True if token has required scope, False otherwise
|
||||
|
||||
Examples:
|
||||
>>> check_scope("create", "create update")
|
||||
True
|
||||
>>> check_scope("create", "read")
|
||||
False
|
||||
>>> check_scope("create", "")
|
||||
False
|
||||
"""
|
||||
if not token_scope:
|
||||
return False
|
||||
|
||||
scopes = token_scope.split()
|
||||
return required_scope in scopes
|
||||
+38
-17
@@ -35,24 +35,23 @@ def load_config(app, config_override=None):
|
||||
app.config["SESSION_SECRET"] = os.getenv("SESSION_SECRET")
|
||||
app.config["SESSION_LIFETIME"] = int(os.getenv("SESSION_LIFETIME", "30"))
|
||||
|
||||
# DEPRECATED: TOKEN_ENDPOINT no longer used (v1.0.0-rc.5+)
|
||||
# Endpoints are now discovered from ADMIN_ME profile (ADR-031)
|
||||
if 'TOKEN_ENDPOINT' in os.environ:
|
||||
app.logger.warning(
|
||||
"TOKEN_ENDPOINT is deprecated and will be ignored. "
|
||||
"Remove it from your configuration. "
|
||||
"Endpoints are now discovered automatically from your ADMIN_ME profile. "
|
||||
"See docs/migration/fix-hardcoded-endpoints.md for details."
|
||||
)
|
||||
# Admin login via OpenID Connect (v2.0.0, ADR-064)
|
||||
# ADMIN_ME stays the site owner's identity URL (h-card, Micropub "me");
|
||||
# OIDC decides who may log in as that owner.
|
||||
app.config["OIDC_ISSUER"] = os.getenv("OIDC_ISSUER", "").rstrip("/")
|
||||
app.config["OIDC_CLIENT_ID"] = os.getenv("OIDC_CLIENT_ID", "")
|
||||
app.config["OIDC_CLIENT_SECRET"] = os.getenv("OIDC_CLIENT_SECRET", "")
|
||||
app.config["OIDC_ADMIN_SUB"] = os.getenv("OIDC_ADMIN_SUB", "")
|
||||
app.config["OIDC_PROVIDER_NAME"] = os.getenv("OIDC_PROVIDER_NAME", "single sign-on")
|
||||
|
||||
# DEPRECATED: INDIELOGIN_URL no longer used (hotfix 2025-12-17)
|
||||
# Authorization endpoint is now discovered from ADMIN_ME profile per IndieAuth spec
|
||||
if 'INDIELOGIN_URL' in os.environ:
|
||||
app.logger.warning(
|
||||
"INDIELOGIN_URL is deprecated and will be ignored. "
|
||||
"Remove it from your configuration. "
|
||||
"The authorization endpoint is now discovered automatically from your ADMIN_ME profile."
|
||||
)
|
||||
# Micropub access tokens issued by StarPunk's IndieAuth server (v2.0.0)
|
||||
app.config["INDIEAUTH_TOKEN_LIFETIME_DAYS"] = int(
|
||||
os.getenv("INDIEAUTH_TOKEN_LIFETIME_DAYS", "90")
|
||||
)
|
||||
|
||||
for legacy in ("TOKEN_ENDPOINT", "INDIELOGIN_URL"):
|
||||
if legacy in os.environ:
|
||||
app.logger.warning(f"{legacy} is no longer used and will be ignored.")
|
||||
|
||||
# Validate required configuration
|
||||
if not app.config["SESSION_SECRET"]:
|
||||
@@ -125,6 +124,21 @@ def load_config(app, config_override=None):
|
||||
app.config["WEBMENTION_RATE_LIMIT_WINDOW"] = int(os.getenv("WEBMENTION_RATE_LIMIT_WINDOW", "60"))
|
||||
app.config["TRUSTED_PROXY"] = os.getenv("TRUSTED_PROXY", "false").lower() == "true"
|
||||
|
||||
# Crossposting to GoToSocial / Mastodon-API (v2.1.0, ADR-065)
|
||||
# Enabled when both URL and token are set
|
||||
app.config["GOTOSOCIAL_URL"] = os.getenv("GOTOSOCIAL_URL", "")
|
||||
app.config["GOTOSOCIAL_ACCESS_TOKEN"] = os.getenv("GOTOSOCIAL_ACCESS_TOKEN", "")
|
||||
app.config["GOTOSOCIAL_NAME"] = os.getenv("GOTOSOCIAL_NAME", "GoToSocial")
|
||||
app.config["GOTOSOCIAL_VISIBILITY"] = os.getenv("GOTOSOCIAL_VISIBILITY", "public")
|
||||
app.config["GOTOSOCIAL_MAX_CHARS"] = int(os.getenv("GOTOSOCIAL_MAX_CHARS", "5000"))
|
||||
app.config["GOTOSOCIAL_MAX_MEDIA"] = int(os.getenv("GOTOSOCIAL_MAX_MEDIA", "4"))
|
||||
app.config["BLUESKY_HANDLE"] = os.getenv("BLUESKY_HANDLE", "")
|
||||
app.config["BLUESKY_APP_PASSWORD"] = os.getenv("BLUESKY_APP_PASSWORD", "")
|
||||
app.config["BLUESKY_SERVICE"] = os.getenv("BLUESKY_SERVICE", "https://bsky.social")
|
||||
app.config["BLUESKY_NAME"] = os.getenv("BLUESKY_NAME", "Bluesky")
|
||||
app.config["BLUESKY_MAX_CHARS"] = int(os.getenv("BLUESKY_MAX_CHARS", "300"))
|
||||
app.config["SYNDICATION_POLL_INTERVAL"] = int(os.getenv("SYNDICATION_POLL_INTERVAL", "10"))
|
||||
|
||||
# Apply overrides if provided
|
||||
if config_override:
|
||||
app.config.update(config_override)
|
||||
@@ -246,6 +260,13 @@ def validate_config(app):
|
||||
"Set ADMIN_ME=https://your-site.com in .env"
|
||||
)
|
||||
|
||||
# Production mode: OIDC admin login must be configured
|
||||
# (tests configure OIDC per test, so skip the check there)
|
||||
if not app.config.get("TESTING"):
|
||||
for field in ("OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET", "OIDC_ADMIN_SUB"):
|
||||
if not app.config.get(field):
|
||||
errors.append(f"Production mode requires {field} to be set (see .env.example)")
|
||||
|
||||
# If there are validation errors, fail fast with clear message
|
||||
if errors:
|
||||
error_msg = "\n".join([
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
"""
|
||||
Built-in IndieAuth authorization server for StarPunk (v2.0.0, ADR-064)
|
||||
|
||||
Micropub clients (Quill, Indigenous, ...) obtain tokens through IndieAuth.
|
||||
StarPunk issues them itself: the site owner approves a client after logging
|
||||
in with OIDC, and StarPunk hands out an authorization code and then an
|
||||
access token. Tokens are stored hashed and checked locally by /micropub.
|
||||
|
||||
Only the authorization code flow with PKCE (S256) is supported, per the
|
||||
current IndieAuth spec: https://indieauth.spec.indieweb.org/
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from flask import current_app
|
||||
|
||||
from starpunk.database import get_db
|
||||
from starpunk.utils import absolute_url_for
|
||||
|
||||
CODE_LIFETIME_MINUTES = 10
|
||||
SUPPORTED_SCOPES = ["create", "update", "delete", "media", "profile"]
|
||||
|
||||
|
||||
class AuthorizationRequestError(Exception):
|
||||
"""
|
||||
Invalid authorization request
|
||||
|
||||
redirectable=False means the client_id or redirect_uri cannot be trusted,
|
||||
so the error must be shown to the user instead of sent to the client.
|
||||
"""
|
||||
|
||||
def __init__(self, error: str, description: str, redirectable: bool = True):
|
||||
super().__init__(description)
|
||||
self.error = error
|
||||
self.description = description
|
||||
self.redirectable = redirectable
|
||||
|
||||
|
||||
class InvalidGrantError(Exception):
|
||||
"""Authorization code is invalid, expired, used, or does not match"""
|
||||
|
||||
|
||||
def _hash(value: str) -> str:
|
||||
return hashlib.sha256(value.encode()).hexdigest()
|
||||
|
||||
|
||||
def issuer() -> str:
|
||||
"""Issuer identifier (RFC 9207): the site URL with trailing slash"""
|
||||
return current_app.config["SITE_URL"].rstrip("/") + "/"
|
||||
|
||||
|
||||
def admin_me() -> str:
|
||||
"""The single identity StarPunk issues tokens for"""
|
||||
return current_app.config["ADMIN_ME"]
|
||||
|
||||
|
||||
def check_scope(required_scope: str, token_scope: str) -> bool:
|
||||
"""True if required_scope is one of the space-separated token scopes"""
|
||||
return bool(token_scope) and required_scope in token_scope.split()
|
||||
|
||||
|
||||
def _is_http_url(url: str) -> bool:
|
||||
parsed = urlparse(url or "")
|
||||
return parsed.scheme in ("http", "https") and bool(parsed.netloc) and not parsed.fragment
|
||||
|
||||
|
||||
def _same_origin(a: str, b: str) -> bool:
|
||||
pa, pb = urlparse(a), urlparse(b)
|
||||
return (pa.scheme, pa.hostname, pa.port) == (pb.scheme, pb.hostname, pb.port)
|
||||
|
||||
|
||||
def fetch_client_redirect_uris(client_id: str) -> List[str]:
|
||||
"""
|
||||
Fetch the redirect URIs a client publishes at its client_id URL
|
||||
|
||||
Supports a JSON client metadata document ("redirect_uris") and the older
|
||||
HTML/Link header form (rel="redirect_uri"). Returns [] on any failure.
|
||||
"""
|
||||
from starpunk.webmention_ssrf import SSRFBlockedError, validate_url_for_fetch
|
||||
|
||||
try:
|
||||
if not current_app.config.get("DEV_MODE"):
|
||||
validate_url_for_fetch(client_id)
|
||||
response = httpx.get(
|
||||
client_id,
|
||||
timeout=5.0,
|
||||
follow_redirects=True,
|
||||
headers={"Accept": "application/json, text/html;q=0.9"},
|
||||
)
|
||||
except (httpx.HTTPError, SSRFBlockedError, ValueError) as e:
|
||||
current_app.logger.info(f"IndieAuth: could not fetch client {client_id}: {e}")
|
||||
return []
|
||||
|
||||
if response.status_code != 200:
|
||||
return []
|
||||
|
||||
base = str(response.url)
|
||||
uris: List[str] = []
|
||||
|
||||
if "json" in response.headers.get("Content-Type", ""):
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
return []
|
||||
if isinstance(data, dict) and isinstance(data.get("redirect_uris"), list):
|
||||
uris.extend(u for u in data["redirect_uris"] if isinstance(u, str))
|
||||
return uris
|
||||
|
||||
link = response.links.get("redirect_uri")
|
||||
if link and link.get("url"):
|
||||
uris.append(urljoin(base, link["url"]))
|
||||
|
||||
soup = BeautifulSoup(response.text[:500_000], "html.parser")
|
||||
for tag in soup.find_all(["link", "a"], href=True):
|
||||
if "redirect_uri" in (tag.get("rel") or []):
|
||||
uris.append(urljoin(base, tag["href"]))
|
||||
return uris
|
||||
|
||||
|
||||
def validate_authorization_request(params: Dict[str, str]) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate an IndieAuth authorization request
|
||||
|
||||
Args:
|
||||
params: Query (or form) parameters from the client
|
||||
|
||||
Returns:
|
||||
Normalized request: client_id, redirect_uri, state, scopes,
|
||||
code_challenge
|
||||
|
||||
Raises:
|
||||
AuthorizationRequestError
|
||||
"""
|
||||
client_id = (params.get("client_id") or "").strip()
|
||||
redirect_uri = (params.get("redirect_uri") or "").strip()
|
||||
|
||||
# client_id / redirect_uri problems are never redirected to the client
|
||||
if not _is_http_url(client_id):
|
||||
raise AuthorizationRequestError(
|
||||
"invalid_request", "client_id must be an http(s) URL", redirectable=False
|
||||
)
|
||||
if not redirect_uri or urlparse(redirect_uri).fragment:
|
||||
raise AuthorizationRequestError(
|
||||
"invalid_request", "redirect_uri is missing or invalid", redirectable=False
|
||||
)
|
||||
if not _same_origin(client_id, redirect_uri):
|
||||
if redirect_uri not in fetch_client_redirect_uris(client_id):
|
||||
raise AuthorizationRequestError(
|
||||
"invalid_request",
|
||||
"redirect_uri is not registered by this client",
|
||||
redirectable=False,
|
||||
)
|
||||
|
||||
if params.get("response_type", "code") != "code":
|
||||
raise AuthorizationRequestError(
|
||||
"unsupported_response_type", "Only response_type=code is supported"
|
||||
)
|
||||
if not params.get("state"):
|
||||
raise AuthorizationRequestError("invalid_request", "state is required")
|
||||
|
||||
code_challenge = params.get("code_challenge") or ""
|
||||
if not code_challenge:
|
||||
raise AuthorizationRequestError("invalid_request", "PKCE code_challenge is required")
|
||||
if params.get("code_challenge_method", "S256") != "S256":
|
||||
raise AuthorizationRequestError(
|
||||
"invalid_request", "Only code_challenge_method=S256 is supported"
|
||||
)
|
||||
|
||||
scopes = [s for s in (params.get("scope") or "").split() if s]
|
||||
|
||||
return {
|
||||
"client_id": client_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"state": params["state"],
|
||||
"scopes": scopes,
|
||||
"code_challenge": code_challenge,
|
||||
}
|
||||
|
||||
|
||||
def create_authorization_code(
|
||||
client_id: str, redirect_uri: str, scope: str, code_challenge: str
|
||||
) -> str:
|
||||
"""Issue a single-use authorization code (stored hashed)"""
|
||||
code = secrets.token_urlsafe(32)
|
||||
db = get_db(current_app)
|
||||
db.execute("DELETE FROM indieauth_codes WHERE expires_at <= datetime('now')")
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO indieauth_codes
|
||||
(code_hash, client_id, redirect_uri, scope, code_challenge, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
_hash(code),
|
||||
client_id,
|
||||
redirect_uri,
|
||||
scope,
|
||||
code_challenge,
|
||||
datetime.utcnow() + timedelta(minutes=CODE_LIFETIME_MINUTES),
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
return code
|
||||
|
||||
|
||||
def redeem_authorization_code(
|
||||
code: str, client_id: str, redirect_uri: str, code_verifier: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Redeem an authorization code exactly once
|
||||
|
||||
Returns:
|
||||
{"me": ..., "scope": ..., "client_id": ...}
|
||||
|
||||
Raises:
|
||||
InvalidGrantError
|
||||
"""
|
||||
if not code or not code_verifier:
|
||||
raise InvalidGrantError("code and code_verifier are required")
|
||||
|
||||
db = get_db(current_app)
|
||||
# Atomic single use: only the first redemption flips used_at
|
||||
cursor = db.execute(
|
||||
"""
|
||||
UPDATE indieauth_codes SET used_at = datetime('now')
|
||||
WHERE code_hash = ? AND used_at IS NULL AND expires_at > datetime('now')
|
||||
""",
|
||||
(_hash(code),),
|
||||
)
|
||||
db.commit()
|
||||
if cursor.rowcount != 1:
|
||||
raise InvalidGrantError("Authorization code is invalid, expired or already used")
|
||||
|
||||
row = db.execute(
|
||||
"SELECT client_id, redirect_uri, scope, code_challenge FROM indieauth_codes WHERE code_hash = ?",
|
||||
(_hash(code),),
|
||||
).fetchone()
|
||||
|
||||
if row["client_id"] != client_id or row["redirect_uri"] != redirect_uri:
|
||||
raise InvalidGrantError("client_id or redirect_uri does not match the code")
|
||||
|
||||
digest = hashlib.sha256(code_verifier.encode("ascii", "ignore")).digest()
|
||||
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
||||
if not secrets.compare_digest(challenge, row["code_challenge"]):
|
||||
raise InvalidGrantError("PKCE verification failed")
|
||||
|
||||
return {"me": admin_me(), "scope": row["scope"], "client_id": row["client_id"]}
|
||||
|
||||
|
||||
def create_access_token(client_id: str, scope: str) -> Dict[str, Any]:
|
||||
"""Issue an access token (stored hashed); returns the token response"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
lifetime_days = current_app.config.get("INDIEAUTH_TOKEN_LIFETIME_DAYS", 90)
|
||||
expires_at = datetime.utcnow() + timedelta(days=lifetime_days)
|
||||
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO indieauth_tokens (token_hash, client_id, scope, expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(_hash(token), client_id, scope, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
current_app.logger.info(f"IndieAuth: token issued to {client_id} (scope: {scope})")
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "Bearer",
|
||||
"scope": scope,
|
||||
"me": admin_me(),
|
||||
"expires_in": lifetime_days * 86400,
|
||||
}
|
||||
|
||||
|
||||
def verify_access_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Check a bearer token issued by StarPunk
|
||||
|
||||
Returns:
|
||||
{"me", "client_id", "scope"} if active, otherwise None
|
||||
"""
|
||||
if not token:
|
||||
return None
|
||||
db = get_db(current_app)
|
||||
row = db.execute(
|
||||
"""
|
||||
SELECT id, client_id, scope FROM indieauth_tokens
|
||||
WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > datetime('now')
|
||||
""",
|
||||
(_hash(token),),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
db.execute(
|
||||
"UPDATE indieauth_tokens SET last_used_at = datetime('now') WHERE id = ?",
|
||||
(row["id"],),
|
||||
)
|
||||
db.commit()
|
||||
return {"me": admin_me(), "client_id": row["client_id"], "scope": row["scope"]}
|
||||
|
||||
|
||||
def revoke_access_token(token: str) -> None:
|
||||
"""Revoke a token by value (unknown tokens are ignored, per RFC 7009)"""
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"UPDATE indieauth_tokens SET revoked_at = datetime('now') WHERE token_hash = ? AND revoked_at IS NULL",
|
||||
(_hash(token or ""),),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def revoke_token_by_id(token_id: int) -> None:
|
||||
"""Revoke a token from the admin UI"""
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"UPDATE indieauth_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL",
|
||||
(token_id,),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def list_active_tokens() -> List[Dict[str, Any]]:
|
||||
"""Tokens that can still be used, newest first"""
|
||||
db = get_db(current_app)
|
||||
rows = db.execute(
|
||||
"""
|
||||
SELECT id, client_id, scope, created_at, expires_at, last_used_at
|
||||
FROM indieauth_tokens
|
||||
WHERE revoked_at IS NULL AND expires_at > datetime('now')
|
||||
ORDER BY created_at DESC
|
||||
"""
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
+32
-10
@@ -29,7 +29,8 @@ from typing import Optional
|
||||
from flask import Request, current_app, jsonify
|
||||
|
||||
from starpunk.notes import create_note, get_note, InvalidNoteDataError, NoteNotFoundError
|
||||
from starpunk.auth_external import check_scope
|
||||
from starpunk.indieauth import check_scope
|
||||
from starpunk.utils import absolute_url_for
|
||||
|
||||
|
||||
# Custom Exceptions
|
||||
@@ -398,6 +399,17 @@ def handle_create(data: dict, token_info: dict):
|
||||
elif isinstance(slug_value, str):
|
||||
custom_slug = slug_value
|
||||
|
||||
# mp-syndicate-to is also a server command, not a property (v2.1.0).
|
||||
# Absent means "all targets"; present means exactly those.
|
||||
requested_targets = None
|
||||
if isinstance(data, dict):
|
||||
for key in ("mp-syndicate-to", "mp-syndicate-to[]"):
|
||||
if key in data:
|
||||
value = data[key]
|
||||
requested_targets = (requested_targets or []) + (
|
||||
value if isinstance(value, list) else [value]
|
||||
)
|
||||
|
||||
# Normalize and extract properties
|
||||
try:
|
||||
properties = normalize_properties(data)
|
||||
@@ -427,10 +439,14 @@ def handle_create(data: dict, token_info: dict):
|
||||
if photos:
|
||||
_attach_photos_to_note(note.id, photos)
|
||||
|
||||
# Build permalink URL
|
||||
# Note: SITE_URL is normalized to include trailing slash (for IndieAuth spec compliance)
|
||||
site_url = current_app.config.get("SITE_URL", "http://localhost:5000")
|
||||
permalink = f"{site_url}notes/{note.slug}"
|
||||
# Crosspost after photos are attached (v2.1.0)
|
||||
from starpunk.syndication import get_targets, resolve_targets, select_targets
|
||||
if requested_targets is None:
|
||||
select_targets(note.id, list(get_targets()))
|
||||
else:
|
||||
select_targets(note.id, resolve_targets(requested_targets))
|
||||
|
||||
permalink = absolute_url_for("public.note", slug=note.slug)
|
||||
|
||||
# Return 201 Created with Location header
|
||||
return "", 201, {"Location": permalink}
|
||||
@@ -444,6 +460,13 @@ def handle_create(data: dict, token_info: dict):
|
||||
)
|
||||
|
||||
|
||||
def _syndicate_to() -> list:
|
||||
"""Configured crosspost targets in Micropub syndicate-to form"""
|
||||
from starpunk.syndication import get_targets
|
||||
|
||||
return [{"uid": t.uid, "name": t.name} for t in get_targets().values()]
|
||||
|
||||
|
||||
def handle_query(args: dict, token_info: dict):
|
||||
"""
|
||||
Handle Micropub query endpoints
|
||||
@@ -451,7 +474,7 @@ def handle_query(args: dict, token_info: dict):
|
||||
Supports:
|
||||
- q=config: Return server configuration
|
||||
- q=source: Return post source in Microformats2 JSON
|
||||
- q=syndicate-to: Return syndication targets (empty for V1)
|
||||
- q=syndicate-to: Return syndication targets
|
||||
|
||||
Args:
|
||||
args: Query string arguments
|
||||
@@ -467,7 +490,7 @@ def handle_query(args: dict, token_info: dict):
|
||||
site_url = current_app.config.get("SITE_URL", "http://localhost:5000").rstrip('/')
|
||||
config = {
|
||||
"media-endpoint": f"{site_url}/micropub/media",
|
||||
"syndicate-to": [], # No syndication targets in V1
|
||||
"syndicate-to": _syndicate_to(),
|
||||
"post-types": [
|
||||
{"type": "note", "name": "Note", "properties": ["content"]},
|
||||
{"type": "photo", "name": "Photo", "properties": ["photo"]}
|
||||
@@ -483,7 +506,7 @@ def handle_query(args: dict, token_info: dict):
|
||||
|
||||
# Extract slug from URL
|
||||
try:
|
||||
# URL format: https://example.com/notes/{slug}
|
||||
# URL format: https://example.com/note/{slug}
|
||||
slug = url.rstrip("/").split("/")[-1]
|
||||
note = get_note(slug)
|
||||
|
||||
@@ -520,8 +543,7 @@ def handle_query(args: dict, token_info: dict):
|
||||
return jsonify(mf2), 200
|
||||
|
||||
elif q == "syndicate-to":
|
||||
# Return syndication targets (none for V1)
|
||||
return jsonify({"syndicate-to": []}), 200
|
||||
return jsonify({"syndicate-to": _syndicate_to()}), 200
|
||||
|
||||
else:
|
||||
return error_response("invalid_request", f"Unknown query: {q}")
|
||||
@@ -851,6 +851,13 @@ def update_note(
|
||||
# Reply context fetch failure should not prevent note update
|
||||
current_app.logger.warning(f"Failed to fetch reply context for {in_reply_to}: {e}")
|
||||
|
||||
# Crossposts follow the note (v2.1.0, best-effort)
|
||||
try:
|
||||
from starpunk.syndication import note_changed
|
||||
note_changed(updated_note.id)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Failed to queue syndication update: {e}")
|
||||
|
||||
# 10. RETURN UPDATED NOTE
|
||||
return updated_note
|
||||
|
||||
@@ -1018,5 +1025,12 @@ def delete_note(
|
||||
)
|
||||
# Don't fail - database record already deleted
|
||||
|
||||
# Delete crossposts too (v2.1.0, best-effort)
|
||||
try:
|
||||
from starpunk.syndication import note_changed
|
||||
note_changed(existing_note.id)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Failed to queue syndication delete: {e}")
|
||||
|
||||
# 6. RETURN (no value)
|
||||
return None
|
||||
@@ -7,7 +7,7 @@ admin, auth, and (conditionally) dev auth routes.
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from starpunk.routes import admin, auth, micropub, public, search, webmention
|
||||
from starpunk.routes import admin, auth, indieauth, micropub, public, search, webmention
|
||||
|
||||
|
||||
def register_routes(app: Flask) -> None:
|
||||
@@ -29,6 +29,7 @@ def register_routes(app: Flask) -> None:
|
||||
|
||||
# Register auth routes
|
||||
app.register_blueprint(auth.bp)
|
||||
app.register_blueprint(indieauth.bp)
|
||||
|
||||
# Register Micropub routes
|
||||
app.register_blueprint(micropub.bp)
|
||||
|
||||
@@ -97,7 +97,9 @@ def new_note_form():
|
||||
Decorator: @require_auth
|
||||
Template: templates/admin/new.html
|
||||
"""
|
||||
return render_template("admin/new.html")
|
||||
from starpunk.syndication import get_targets
|
||||
|
||||
return render_template("admin/new.html", syndication_targets=get_targets().values())
|
||||
|
||||
|
||||
@bp.route("/new", methods=["POST"])
|
||||
@@ -182,6 +184,11 @@ def create_note_submit():
|
||||
if errors:
|
||||
flash(f"Note created, but some images failed: {'; '.join(errors)}", "warning")
|
||||
|
||||
# Crosspost after media is attached so images go out too (v2.1.0)
|
||||
if "syndication_form" in request.form:
|
||||
from starpunk.syndication import select_targets
|
||||
select_targets(note.id, request.form.getlist("syndicate_to"))
|
||||
|
||||
flash(f"Note created: {note.slug}", "success")
|
||||
return redirect(url_for("admin.dashboard"))
|
||||
|
||||
@@ -223,7 +230,17 @@ def edit_note_form(note_id: int):
|
||||
tags = get_note_tags(note.id)
|
||||
object.__setattr__(note, '_cached_tags', tags)
|
||||
|
||||
return render_template("admin/edit.html", note=note)
|
||||
from starpunk.syndication import get_note_syndications, get_targets
|
||||
|
||||
syndications = get_note_syndications(note.id)
|
||||
enabled = {s["target"] for s in syndications if s["enabled"]}
|
||||
return render_template(
|
||||
"admin/edit.html",
|
||||
note=note,
|
||||
syndication_targets=get_targets().values(),
|
||||
syndications=syndications,
|
||||
syndication_enabled=enabled,
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/edit/<int:note_id>", methods=["POST"])
|
||||
@@ -274,6 +291,9 @@ def update_note_submit(note_id: int):
|
||||
published=published,
|
||||
tags=tags if tags else None
|
||||
)
|
||||
if "syndication_form" in request.form:
|
||||
from starpunk.syndication import select_targets
|
||||
select_targets(note.id, request.form.getlist("syndicate_to"))
|
||||
flash(f"Note updated: {note.slug}", "success")
|
||||
return redirect(url_for("admin.dashboard"))
|
||||
except ValueError as e:
|
||||
@@ -816,3 +836,36 @@ def webmention_bulk_action():
|
||||
logger.error(f"Error performing bulk action: {e}")
|
||||
flash(f"Error: {e}", "error")
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
|
||||
|
||||
# Connected Micropub apps (v2.0.0)
|
||||
|
||||
@bp.route("/tokens")
|
||||
@require_auth
|
||||
def tokens():
|
||||
"""List active IndieAuth tokens. Template: templates/admin/tokens.html"""
|
||||
from starpunk.indieauth import list_active_tokens
|
||||
|
||||
return render_template("admin/tokens.html", tokens=list_active_tokens(), user_me=g.me)
|
||||
|
||||
|
||||
@bp.route("/tokens/<int:token_id>/revoke", methods=["POST"])
|
||||
@require_auth
|
||||
def revoke_token(token_id):
|
||||
"""Revoke one IndieAuth token"""
|
||||
from starpunk.indieauth import revoke_token_by_id
|
||||
|
||||
revoke_token_by_id(token_id)
|
||||
flash("App access revoked", "success")
|
||||
return redirect(url_for("admin.tokens"))
|
||||
|
||||
|
||||
@bp.route("/syndication/<int:syndication_id>/retry", methods=["POST"])
|
||||
@require_auth
|
||||
def retry_syndication(syndication_id):
|
||||
"""Retry a crosspost now"""
|
||||
from starpunk.syndication import retry
|
||||
|
||||
retry(syndication_id)
|
||||
flash("Crosspost queued", "success")
|
||||
return redirect(request.referrer or url_for("admin.dashboard"))
|
||||
+49
-112
@@ -1,15 +1,14 @@
|
||||
"""
|
||||
Authentication routes for StarPunk
|
||||
|
||||
Handles IndieLogin authentication flow including login form, OAuth callback,
|
||||
logout functionality, and IndieAuth endpoints for Micropub clients.
|
||||
Admin login form, OIDC start/callback, and logout.
|
||||
The IndieAuth server endpoints for Micropub clients live in routes/indieauth.py.
|
||||
"""
|
||||
|
||||
from flask import (
|
||||
Blueprint,
|
||||
current_app,
|
||||
flash,
|
||||
jsonify,
|
||||
redirect,
|
||||
render_template,
|
||||
request,
|
||||
@@ -18,8 +17,9 @@ from flask import (
|
||||
)
|
||||
|
||||
from starpunk.auth import (
|
||||
IndieLoginError,
|
||||
AuthError,
|
||||
InvalidStateError,
|
||||
OIDCError,
|
||||
UnauthorizedError,
|
||||
destroy_session,
|
||||
handle_callback,
|
||||
@@ -27,167 +27,104 @@ from starpunk.auth import (
|
||||
require_auth,
|
||||
verify_session,
|
||||
)
|
||||
from starpunk.auth_external import DiscoveryError
|
||||
|
||||
# Create blueprint
|
||||
bp = Blueprint("auth", __name__, url_prefix="/auth")
|
||||
|
||||
SESSION_COOKIE = "starpunk_session"
|
||||
|
||||
|
||||
@bp.route("/login", methods=["GET"])
|
||||
def login_form():
|
||||
"""
|
||||
Display login form
|
||||
|
||||
If user is already authenticated, redirects to admin dashboard.
|
||||
Otherwise shows login form for IndieLogin authentication.
|
||||
|
||||
Returns:
|
||||
Redirect to dashboard if authenticated, otherwise login template
|
||||
Show the login page, or go to the dashboard if already logged in
|
||||
|
||||
Template: templates/admin/login.html
|
||||
"""
|
||||
# Check if already logged in
|
||||
session_token = request.cookies.get("starpunk_session")
|
||||
session_token = request.cookies.get(SESSION_COOKIE)
|
||||
if session_token and verify_session(session_token):
|
||||
return redirect(url_for("admin.dashboard"))
|
||||
return redirect(session.pop("next", None) or url_for("admin.dashboard"))
|
||||
|
||||
return render_template("admin/login.html")
|
||||
|
||||
|
||||
@bp.route("/login", methods=["POST"])
|
||||
def login_initiate():
|
||||
"""
|
||||
Initiate IndieLogin authentication flow
|
||||
|
||||
Validates the submitted 'me' URL and redirects to IndieLogin.com
|
||||
for authentication.
|
||||
|
||||
Form data:
|
||||
me: User's personal website URL
|
||||
|
||||
Returns:
|
||||
Redirect to IndieLogin.com or back to login form on error
|
||||
|
||||
Raises:
|
||||
Flashes error message and redirects on validation failure
|
||||
"""
|
||||
me_url = request.form.get("me", "").strip()
|
||||
|
||||
if not me_url:
|
||||
flash("Please enter your website URL", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
"""Start OIDC login and redirect to the identity provider"""
|
||||
try:
|
||||
# Initiate IndieAuth flow
|
||||
auth_url = initiate_login(me_url)
|
||||
return redirect(auth_url)
|
||||
except ValueError as e:
|
||||
flash(str(e), "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
except DiscoveryError as e:
|
||||
current_app.logger.error(f"Endpoint discovery failed for {me_url}: {e}")
|
||||
flash("Unable to verify your profile URL. Please check that it's correct and try again.", "error")
|
||||
return redirect(initiate_login(session.pop("next", None)))
|
||||
except OIDCError as e:
|
||||
current_app.logger.error(f"OIDC login could not start: {e}")
|
||||
flash("The identity provider is unavailable. Please try again later.", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
|
||||
@bp.route("/callback")
|
||||
def callback():
|
||||
"""
|
||||
Handle IndieLogin callback
|
||||
|
||||
Processes the OAuth callback from IndieLogin.com, validates the
|
||||
authorization code, state token, and issuer, then creates an
|
||||
authenticated session using PKCE verification.
|
||||
Handle the identity provider's redirect
|
||||
|
||||
Query parameters:
|
||||
code: Authorization code from IndieLogin
|
||||
state: CSRF state token
|
||||
iss: Issuer identifier (should be https://indielogin.com/)
|
||||
|
||||
Returns:
|
||||
Redirect to admin dashboard on success, login form on failure
|
||||
code, state: Authorization response
|
||||
iss: Issuer identifier (RFC 9207)
|
||||
error, error_description: Provider-reported failure
|
||||
|
||||
Sets:
|
||||
session cookie (HttpOnly, Secure, SameSite=Lax, 30 day expiry)
|
||||
session cookie (HttpOnly, Secure, SameSite=Lax)
|
||||
"""
|
||||
if request.args.get("error"):
|
||||
current_app.logger.warning(
|
||||
f"OIDC provider returned error: {request.args.get('error')} "
|
||||
f"{request.args.get('error_description', '')}"
|
||||
)
|
||||
flash("Login was cancelled or refused by the identity provider", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
code = request.args.get("code")
|
||||
state = request.args.get("state")
|
||||
iss = request.args.get("iss") # Extract issuer parameter
|
||||
|
||||
if not code or not state:
|
||||
flash("Missing authentication parameters", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
try:
|
||||
# Handle callback and create session with PKCE verification
|
||||
session_token = handle_callback(code, state, iss) # Pass issuer
|
||||
|
||||
# Create response with redirect
|
||||
response = redirect(url_for("admin.dashboard"))
|
||||
|
||||
# Set secure session cookie
|
||||
secure = current_app.config.get("SITE_URL", "").startswith("https://")
|
||||
response.set_cookie(
|
||||
"starpunk_session",
|
||||
session_token,
|
||||
httponly=True,
|
||||
secure=secure,
|
||||
samesite="Lax",
|
||||
max_age=30 * 24 * 60 * 60, # 30 days
|
||||
)
|
||||
|
||||
flash("Login successful!", "success")
|
||||
return response
|
||||
|
||||
except InvalidStateError as e:
|
||||
current_app.logger.error(f"Invalid state error: {e}")
|
||||
flash("Authentication failed: Invalid state token (possible CSRF)", "error")
|
||||
session_token, next_url = handle_callback(code, state, request.args.get("iss"))
|
||||
except InvalidStateError:
|
||||
flash("Login expired or was already used. Please try again.", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
except UnauthorizedError as e:
|
||||
current_app.logger.error(f"Unauthorized: {e}")
|
||||
except UnauthorizedError:
|
||||
flash("Authentication failed: Not authorized as admin", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
except IndieLoginError as e:
|
||||
current_app.logger.error(f"IndieLogin error: {e}")
|
||||
flash(f"Authentication failed: {e}", "error")
|
||||
except AuthError as e:
|
||||
current_app.logger.error(f"OIDC login failed: {e}")
|
||||
flash("Authentication failed. Please try again.", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Unexpected auth error: {e}")
|
||||
flash("Authentication failed: An unexpected error occurred", "error")
|
||||
return redirect(url_for("auth.login_form"))
|
||||
response = redirect(next_url or url_for("admin.dashboard"))
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE,
|
||||
session_token,
|
||||
httponly=True,
|
||||
secure=current_app.config.get("SITE_URL", "").startswith("https://"),
|
||||
samesite="Lax",
|
||||
max_age=current_app.config.get("SESSION_LIFETIME", 30) * 24 * 60 * 60,
|
||||
)
|
||||
if not next_url:
|
||||
flash("Login successful!", "success")
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/logout", methods=["POST"])
|
||||
@require_auth
|
||||
def logout():
|
||||
"""
|
||||
Logout and destroy session
|
||||
|
||||
Destroys the user's session and clears the session cookie.
|
||||
Requires authentication (user must be logged in to logout).
|
||||
|
||||
Returns:
|
||||
Redirect to homepage with session cookie cleared
|
||||
|
||||
Decorator: @require_auth
|
||||
"""
|
||||
session_token = request.cookies.get("starpunk_session")
|
||||
|
||||
# Destroy session in database
|
||||
"""Destroy the session and clear the cookie"""
|
||||
session_token = request.cookies.get(SESSION_COOKIE)
|
||||
if session_token:
|
||||
try:
|
||||
destroy_session(session_token)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Error destroying session: {e}")
|
||||
|
||||
# Clear cookie and redirect
|
||||
response = redirect(url_for("public.index"))
|
||||
response.delete_cookie("starpunk_session")
|
||||
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
flash("Logged out successfully", "success")
|
||||
return response
|
||||
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""
|
||||
IndieAuth server routes for StarPunk (v2.0.0, ADR-064)
|
||||
|
||||
Endpoints:
|
||||
GET /.well-known/oauth-authorization-server Server metadata
|
||||
GET /auth/authorize Consent screen (admin login required)
|
||||
POST /auth/authorize Profile-only code redemption
|
||||
POST /auth/authorize/approve Consent decision
|
||||
POST /auth/token Code -> access token (and legacy revoke)
|
||||
GET /auth/token Legacy token verification
|
||||
POST /auth/revoke Token revocation (RFC 7009)
|
||||
"""
|
||||
|
||||
from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl
|
||||
|
||||
from flask import (
|
||||
Blueprint,
|
||||
current_app,
|
||||
jsonify,
|
||||
redirect,
|
||||
render_template,
|
||||
request,
|
||||
session,
|
||||
url_for,
|
||||
)
|
||||
|
||||
from starpunk.auth import verify_session
|
||||
from starpunk.indieauth import (
|
||||
SUPPORTED_SCOPES,
|
||||
AuthorizationRequestError,
|
||||
InvalidGrantError,
|
||||
create_access_token,
|
||||
create_authorization_code,
|
||||
issuer,
|
||||
redeem_authorization_code,
|
||||
revoke_access_token,
|
||||
validate_authorization_request,
|
||||
verify_access_token,
|
||||
)
|
||||
from starpunk.micropub import extract_bearer_token
|
||||
from starpunk.utils import absolute_url_for
|
||||
|
||||
bp = Blueprint("indieauth", __name__)
|
||||
|
||||
# Parameters carried from the consent screen back to the approve handler
|
||||
_REQUEST_FIELDS = (
|
||||
"response_type",
|
||||
"client_id",
|
||||
"redirect_uri",
|
||||
"state",
|
||||
"code_challenge",
|
||||
"code_challenge_method",
|
||||
"scope",
|
||||
)
|
||||
|
||||
|
||||
def _json(payload: dict, status: int = 200):
|
||||
response = jsonify(payload)
|
||||
response.status_code = status
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
||||
def _oauth_error(error: str, description: str, status: int = 400):
|
||||
return _json({"error": error, "error_description": description}, status)
|
||||
|
||||
|
||||
def _redirect_with(redirect_uri: str, params: dict):
|
||||
"""Append params to redirect_uri, keeping any query it already has"""
|
||||
parts = urlparse(redirect_uri)
|
||||
query = parse_qsl(parts.query, keep_blank_values=True) + list(params.items())
|
||||
return redirect(urlunparse(parts._replace(query=urlencode(query))))
|
||||
|
||||
|
||||
def _admin_session():
|
||||
return verify_session(request.cookies.get("starpunk_session"))
|
||||
|
||||
|
||||
def _request_error_page(error: AuthorizationRequestError):
|
||||
return (
|
||||
render_template("admin/authorize.html", request_error=error.description),
|
||||
400,
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/.well-known/oauth-authorization-server")
|
||||
def metadata():
|
||||
"""IndieAuth server metadata"""
|
||||
return _json(
|
||||
{
|
||||
"issuer": issuer(),
|
||||
"authorization_endpoint": absolute_url_for("indieauth.authorize"),
|
||||
"token_endpoint": absolute_url_for("indieauth.token"),
|
||||
"revocation_endpoint": absolute_url_for("indieauth.revoke"),
|
||||
"revocation_endpoint_auth_methods_supported": ["none"],
|
||||
"scopes_supported": SUPPORTED_SCOPES,
|
||||
"response_types_supported": ["code"],
|
||||
"grant_types_supported": ["authorization_code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
"authorization_response_iss_parameter_supported": True,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/auth/authorize", methods=["GET"])
|
||||
def authorize():
|
||||
"""Show the consent screen to the logged-in admin"""
|
||||
try:
|
||||
auth_request = validate_authorization_request(request.args.to_dict())
|
||||
except AuthorizationRequestError as e:
|
||||
if not e.redirectable:
|
||||
return _request_error_page(e)
|
||||
return _redirect_with(
|
||||
request.args["redirect_uri"],
|
||||
{
|
||||
"error": e.error,
|
||||
"error_description": e.description,
|
||||
"state": request.args.get("state", ""),
|
||||
"iss": issuer(),
|
||||
},
|
||||
)
|
||||
|
||||
if not _admin_session():
|
||||
# Come back here after logging in with OIDC
|
||||
session["next"] = request.url
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
return render_template(
|
||||
"admin/authorize.html",
|
||||
auth_request=auth_request,
|
||||
fields={k: request.args.get(k, "") for k in _REQUEST_FIELDS},
|
||||
me=current_app.config["ADMIN_ME"],
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/auth/authorize/approve", methods=["POST"])
|
||||
def approve():
|
||||
"""Record the admin's consent decision and redirect to the client"""
|
||||
if not _admin_session():
|
||||
return redirect(url_for("auth.login_form"))
|
||||
|
||||
params = {k: request.form.get(k, "") for k in _REQUEST_FIELDS}
|
||||
try:
|
||||
auth_request = validate_authorization_request(params)
|
||||
except AuthorizationRequestError as e:
|
||||
return _request_error_page(e)
|
||||
|
||||
if request.form.get("decision") != "approve":
|
||||
return _redirect_with(
|
||||
auth_request["redirect_uri"],
|
||||
{"error": "access_denied", "state": auth_request["state"], "iss": issuer()},
|
||||
)
|
||||
|
||||
# Only scopes that were both requested and left checked
|
||||
granted = [s for s in auth_request["scopes"] if s in request.form.getlist("scope_granted")]
|
||||
code = create_authorization_code(
|
||||
auth_request["client_id"],
|
||||
auth_request["redirect_uri"],
|
||||
" ".join(granted),
|
||||
auth_request["code_challenge"],
|
||||
)
|
||||
current_app.logger.info(
|
||||
f"IndieAuth: approved {auth_request['client_id']} (scope: {' '.join(granted) or 'none'})"
|
||||
)
|
||||
return _redirect_with(
|
||||
auth_request["redirect_uri"],
|
||||
{"code": code, "state": auth_request["state"], "iss": issuer()},
|
||||
)
|
||||
|
||||
|
||||
def _redeem_from_form():
|
||||
return redeem_authorization_code(
|
||||
request.form.get("code", ""),
|
||||
request.form.get("client_id", ""),
|
||||
request.form.get("redirect_uri", ""),
|
||||
request.form.get("code_verifier", ""),
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/auth/authorize", methods=["POST"])
|
||||
def authorize_redeem():
|
||||
"""Profile-only flow: redeem a code for the user's identity"""
|
||||
if request.form.get("grant_type", "authorization_code") != "authorization_code":
|
||||
return _oauth_error("unsupported_grant_type", "Only authorization_code is supported")
|
||||
try:
|
||||
result = _redeem_from_form()
|
||||
except InvalidGrantError as e:
|
||||
return _oauth_error("invalid_grant", str(e))
|
||||
return _json({"me": result["me"]})
|
||||
|
||||
|
||||
@bp.route("/auth/token", methods=["POST"])
|
||||
def token():
|
||||
"""Exchange an authorization code for an access token"""
|
||||
if request.form.get("action") == "revoke":
|
||||
# Legacy IndieAuth revocation
|
||||
revoke_access_token(request.form.get("token", ""))
|
||||
return _json({})
|
||||
|
||||
if request.form.get("grant_type") != "authorization_code":
|
||||
return _oauth_error("unsupported_grant_type", "Only authorization_code is supported")
|
||||
|
||||
try:
|
||||
result = _redeem_from_form()
|
||||
except InvalidGrantError as e:
|
||||
return _oauth_error("invalid_grant", str(e))
|
||||
|
||||
if not result["scope"]:
|
||||
# Spec: a code issued without scope cannot be used for an access token
|
||||
return _oauth_error("invalid_grant", "No scope was granted; use the authorization endpoint")
|
||||
|
||||
return _json(create_access_token(result["client_id"], result["scope"]))
|
||||
|
||||
|
||||
@bp.route("/auth/token", methods=["GET"])
|
||||
def token_verify():
|
||||
"""Legacy token verification for clients that still call it"""
|
||||
info = verify_access_token(extract_bearer_token(request))
|
||||
if not info:
|
||||
return _oauth_error("unauthorized", "Invalid or expired access token", 401)
|
||||
return _json(info)
|
||||
|
||||
|
||||
@bp.route("/auth/revoke", methods=["POST"])
|
||||
def revoke():
|
||||
"""RFC 7009 token revocation (always 200)"""
|
||||
revoke_access_token(request.form.get("token", ""))
|
||||
return _json({})
|
||||
@@ -17,6 +17,7 @@ References:
|
||||
- W3C Micropub Specification: https://www.w3.org/TR/micropub/
|
||||
- ADR-028: Micropub Implementation Strategy
|
||||
- ADR-029: Micropub IndieAuth Integration Strategy
|
||||
- ADR-064: Tokens are issued and verified by StarPunk itself
|
||||
"""
|
||||
|
||||
from flask import Blueprint, current_app, request, make_response
|
||||
@@ -28,7 +29,7 @@ from starpunk.micropub import (
|
||||
handle_create,
|
||||
handle_query,
|
||||
)
|
||||
from starpunk.auth_external import verify_external_token, check_scope
|
||||
from starpunk.indieauth import verify_access_token, check_scope
|
||||
|
||||
# Create blueprint
|
||||
bp = Blueprint("micropub", __name__)
|
||||
@@ -71,7 +72,7 @@ def micropub_endpoint():
|
||||
if not token:
|
||||
return error_response("unauthorized", "No access token provided", 401)
|
||||
|
||||
token_info = verify_external_token(token)
|
||||
token_info = verify_access_token(token)
|
||||
if not token_info:
|
||||
return error_response("unauthorized", "Invalid or expired access token", 401)
|
||||
|
||||
@@ -140,7 +141,7 @@ def media_endpoint():
|
||||
if not token:
|
||||
return error_response("unauthorized", "No access token provided", 401)
|
||||
|
||||
token_info = verify_external_token(token)
|
||||
token_info = verify_access_token(token)
|
||||
if not token_info:
|
||||
return error_response("unauthorized", "Invalid or expired access token", 401)
|
||||
|
||||
|
||||
@@ -331,9 +331,14 @@ def note(slug: str):
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.error(f"Error loading webmentions for note {slug}: {e}")
|
||||
|
||||
from starpunk.syndication import get_note_syndications
|
||||
|
||||
syndications = [s for s in get_note_syndications(note_obj.id) if s["state"] == "synced"]
|
||||
|
||||
return render_template(
|
||||
"note.html",
|
||||
note=note_obj,
|
||||
syndications=syndications,
|
||||
webmentions=webmentions,
|
||||
reply_context=reply_context,
|
||||
**grouped if webmentions else {}
|
||||
|
||||
@@ -108,7 +108,7 @@ def api_search():
|
||||
"title": r["title"] or f"Note from {r['created_at'][:10]}",
|
||||
"excerpt": r["snippet"], # Already has <mark> tags
|
||||
"published_at": r["created_at"],
|
||||
"url": f"/notes/{r['slug']}",
|
||||
"url": f"/note/{r['slug']}",
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
@@ -176,7 +176,7 @@ def search_page():
|
||||
"title": r["title"] or f"Note from {r['created_at'][:10]}",
|
||||
"excerpt": Markup(safe_snippet), # Mark as safe since we've escaped it ourselves
|
||||
"published_at": r["created_at"],
|
||||
"url": f"/notes/{r['slug']}",
|
||||
"url": f"/note/{r['slug']}",
|
||||
})
|
||||
results = formatted_results
|
||||
except Exception as e:
|
||||
|
||||
@@ -0,0 +1,716 @@
|
||||
"""
|
||||
Crossposting (POSSE) for StarPunk (v2.1.0 ADR-065, v2.2.0 ADR-066)
|
||||
|
||||
Published notes are copied to syndication targets, and later edits and
|
||||
deletes follow them. Two target kinds exist: a GoToSocial (or any
|
||||
Mastodon-API) account, and a Bluesky account. Bluesky posts can't be edited,
|
||||
so there only deletes follow.
|
||||
|
||||
Each (note, target) pair has a row in `syndications`. Changing a note marks
|
||||
its rows pending; a background worker then reconciles the remote post with
|
||||
the note:
|
||||
|
||||
note published + target enabled, no remote post -> create
|
||||
note published + target enabled, remote post -> update
|
||||
otherwise, remote post exists -> delete
|
||||
|
||||
Rows carry a version so an edit made while a send is in flight is not lost.
|
||||
"""
|
||||
|
||||
import io
|
||||
import re
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
from flask import current_app
|
||||
|
||||
from starpunk.database import get_db
|
||||
|
||||
MAX_ATTEMPTS = 8
|
||||
CLAIM_MINUTES = 5
|
||||
|
||||
|
||||
class SyndicationError(Exception):
|
||||
"""A send failed. permanent=True means retrying won't help."""
|
||||
|
||||
def __init__(self, message: str, permanent: bool = False):
|
||||
super().__init__(message)
|
||||
self.permanent = permanent
|
||||
|
||||
|
||||
class RemoteGone(SyndicationError):
|
||||
"""The remote post no longer exists"""
|
||||
|
||||
|
||||
class MastodonClient:
|
||||
"""Minimal Mastodon-API client (works with GoToSocial)"""
|
||||
|
||||
def __init__(self, base_url: str, token: str, visibility: str = "public",
|
||||
http: Optional[httpx.Client] = None):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.visibility = visibility
|
||||
self.http = http or httpx.Client(timeout=30.0)
|
||||
self.headers = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
def _call(self, method: str, path: str, **kwargs) -> httpx.Response:
|
||||
headers = {**self.headers, **kwargs.pop("headers", {})}
|
||||
try:
|
||||
response = self.http.request(method, self.base_url + path, headers=headers, **kwargs)
|
||||
except httpx.HTTPError as e:
|
||||
raise SyndicationError(f"{method} {path}: {e}")
|
||||
if response.status_code == 404:
|
||||
raise RemoteGone(f"{method} {path}: not found", permanent=True)
|
||||
if response.status_code >= 400:
|
||||
# 4xx other than rate limiting won't fix itself
|
||||
permanent = 400 <= response.status_code < 500 and response.status_code != 429
|
||||
raise SyndicationError(
|
||||
f"{method} {path}: HTTP {response.status_code} {response.text[:200]}",
|
||||
permanent=permanent,
|
||||
)
|
||||
return response
|
||||
|
||||
def upload_media(self, path: Path, mime_type: str, description: str) -> str:
|
||||
with open(path, "rb") as f:
|
||||
response = self._call(
|
||||
"POST", "/api/v2/media",
|
||||
files={"file": (path.name, f, mime_type)},
|
||||
data={"description": description or ""},
|
||||
)
|
||||
return response.json()["id"]
|
||||
|
||||
def _status_body(self, text: str, media_ids: List[str]) -> dict:
|
||||
return {
|
||||
"status": text,
|
||||
"media_ids": media_ids,
|
||||
"visibility": self.visibility,
|
||||
"content_type": "text/markdown",
|
||||
}
|
||||
|
||||
def create_status(self, text: str, media_ids: List[str], idempotency_key: str) -> dict:
|
||||
response = self._call(
|
||||
"POST", "/api/v1/statuses",
|
||||
json=self._status_body(text, media_ids),
|
||||
headers={"Idempotency-Key": idempotency_key},
|
||||
)
|
||||
data = response.json()
|
||||
return {"id": data["id"], "url": data.get("url") or data.get("uri")}
|
||||
|
||||
def update_status(self, remote_id: str, text: str, media_ids: List[str]) -> dict:
|
||||
response = self._call("PUT", f"/api/v1/statuses/{remote_id}",
|
||||
json=self._status_body(text, media_ids))
|
||||
data = response.json()
|
||||
return {"id": data["id"], "url": data.get("url") or data.get("uri")}
|
||||
|
||||
def delete_status(self, remote_id: str) -> None:
|
||||
try:
|
||||
self._call("DELETE", f"/api/v1/statuses/{remote_id}")
|
||||
except RemoteGone:
|
||||
pass # already gone
|
||||
|
||||
# Interface used by the reconcile loop
|
||||
can_edit = True
|
||||
|
||||
def _prepare(self, post: "Post") -> tuple:
|
||||
text = compose_text(post.note, post.permalink, post.tags, post.max_chars)
|
||||
media_ids = [self.upload_media(f["path"], f["mime_type"], f["description"]) for f in post.media]
|
||||
return text, media_ids
|
||||
|
||||
def create(self, post: "Post", key: str, retrying: bool = False) -> dict:
|
||||
text, media_ids = self._prepare(post)
|
||||
return self.create_status(text, media_ids, idempotency_key=key)
|
||||
|
||||
def update(self, remote_id: str, post: "Post") -> dict:
|
||||
text, media_ids = self._prepare(post)
|
||||
return self.update_status(remote_id, text, media_ids)
|
||||
|
||||
def delete(self, remote_id: str) -> None:
|
||||
self.delete_status(remote_id)
|
||||
|
||||
|
||||
BLUESKY_BLOB_LIMIT = 1_000_000 # app.bsky.embed.images maxSize
|
||||
_TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
|
||||
class BlueskyClient:
|
||||
"""
|
||||
Minimal AT Protocol client for posting to Bluesky with an app password
|
||||
|
||||
Posts are plain text with link and hashtag facets. Images go in an
|
||||
images embed; a note without images gets a link card instead.
|
||||
"""
|
||||
|
||||
can_edit = False # Bluesky has no edits; only deletes follow the note
|
||||
POST = "app.bsky.feed.post"
|
||||
|
||||
def __init__(self, service: str, identifier: str, password: str,
|
||||
http: Optional[httpx.Client] = None):
|
||||
self.service = service.rstrip("/")
|
||||
self.identifier = identifier
|
||||
self.password = password
|
||||
self.http = http or httpx.Client(timeout=30.0)
|
||||
self.pds = self.service
|
||||
self.did: Optional[str] = None
|
||||
self.handle = identifier
|
||||
self._access: Optional[str] = None
|
||||
self._refresh: Optional[str] = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# --- XRPC plumbing ---
|
||||
|
||||
def _raw(self, method: str, nsid: str, base: str, token: Optional[str], **kwargs) -> httpx.Response:
|
||||
headers = kwargs.pop("headers", {})
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
try:
|
||||
return self.http.request(method, f"{base}/xrpc/{nsid}", headers=headers, **kwargs)
|
||||
except httpx.HTTPError as e:
|
||||
raise SyndicationError(f"{nsid}: {e}")
|
||||
|
||||
@staticmethod
|
||||
def _error_name(response: httpx.Response) -> str:
|
||||
try:
|
||||
return response.json().get("error") or ""
|
||||
except ValueError:
|
||||
return ""
|
||||
|
||||
def _raise_for(self, nsid: str, response: httpx.Response) -> None:
|
||||
if response.status_code < 400:
|
||||
return
|
||||
permanent = 400 <= response.status_code < 500 and response.status_code != 429
|
||||
raise SyndicationError(
|
||||
f"{nsid}: HTTP {response.status_code} {response.text[:200]}", permanent=permanent
|
||||
)
|
||||
|
||||
def _login(self) -> None:
|
||||
response = None
|
||||
if self._refresh:
|
||||
response = self._raw("POST", "com.atproto.server.refreshSession", self.service, self._refresh)
|
||||
if response.status_code >= 400:
|
||||
response = None
|
||||
if response is None:
|
||||
response = self._raw("POST", "com.atproto.server.createSession", self.service, None,
|
||||
json={"identifier": self.identifier, "password": self.password})
|
||||
self._raise_for("com.atproto.server.createSession", response)
|
||||
data = response.json()
|
||||
self._access, self._refresh = data["accessJwt"], data["refreshJwt"]
|
||||
self.did = data["did"]
|
||||
self.handle = data.get("handle") or self.handle
|
||||
for service in (data.get("didDoc") or {}).get("service", []):
|
||||
if service.get("id", "").endswith("#atproto_pds") and service.get("serviceEndpoint"):
|
||||
self.pds = service["serviceEndpoint"].rstrip("/")
|
||||
|
||||
def _call(self, method: str, nsid: str, **kwargs) -> httpx.Response:
|
||||
with self._lock:
|
||||
if not self._access:
|
||||
self._login()
|
||||
response = self._raw(method, nsid, self.pds, self._access, **kwargs)
|
||||
if response.status_code == 401 or self._error_name(response) == "ExpiredToken":
|
||||
self._access = None
|
||||
self._login()
|
||||
response = self._raw(method, nsid, self.pds, self._access, **kwargs)
|
||||
self._raise_for(nsid, response)
|
||||
return response
|
||||
|
||||
# --- Posts ---
|
||||
|
||||
def upload_blob(self, data: bytes, mime_type: str) -> dict:
|
||||
response = self._call("POST", "com.atproto.repo.uploadBlob", content=data,
|
||||
headers={"Content-Type": mime_type})
|
||||
return response.json()["blob"]
|
||||
|
||||
def _image(self, media: dict) -> dict:
|
||||
data, mime_type, width, height = _fit_image(media["path"], media["mime_type"], BLUESKY_BLOB_LIMIT)
|
||||
image = {"image": self.upload_blob(data, mime_type), "alt": media["description"] or ""}
|
||||
if width and height:
|
||||
image["aspectRatio"] = {"width": width, "height": height}
|
||||
return image
|
||||
|
||||
def _record(self, post: "Post") -> dict:
|
||||
text = compose_text(post.note, post.permalink, post.tags, post.max_chars,
|
||||
body=plain_text(post.note.content))
|
||||
record = {
|
||||
"$type": self.POST,
|
||||
"text": text,
|
||||
"createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
|
||||
}
|
||||
facets = bluesky_facets(text)
|
||||
if facets:
|
||||
record["facets"] = facets
|
||||
if post.media:
|
||||
record["embed"] = {"$type": "app.bsky.embed.images",
|
||||
"images": [self._image(m) for m in post.media]}
|
||||
else:
|
||||
record["embed"] = {"$type": "app.bsky.embed.external", "external": {
|
||||
"uri": post.permalink,
|
||||
"title": post.note.title[:300],
|
||||
"description": plain_text(post.note.content)[:300],
|
||||
}}
|
||||
return record
|
||||
|
||||
def _web_url(self, uri: str) -> str:
|
||||
rkey = uri.rsplit("/", 1)[1]
|
||||
return f"https://bsky.app/profile/{self.handle or self.did}/post/{rkey}"
|
||||
|
||||
def _find_existing(self, permalink: str) -> Optional[dict]:
|
||||
"""A recent post that already links to this note (an earlier send whose reply was lost)"""
|
||||
response = self._call("GET", "com.atproto.repo.listRecords",
|
||||
params={"repo": self.did, "collection": self.POST, "limit": 25})
|
||||
for item in response.json().get("records", []):
|
||||
if permalink in (item.get("value") or {}).get("text", ""):
|
||||
return {"id": item["uri"], "url": self._web_url(item["uri"])}
|
||||
return None
|
||||
|
||||
def create(self, post: "Post", key: str, retrying: bool = False) -> dict:
|
||||
if retrying:
|
||||
if not self.did:
|
||||
with self._lock:
|
||||
self._login()
|
||||
existing = self._find_existing(post.permalink)
|
||||
if existing:
|
||||
return existing
|
||||
record = self._record(post)
|
||||
response = self._call("POST", "com.atproto.repo.createRecord",
|
||||
json={"repo": self.did or self.identifier, "collection": self.POST,
|
||||
"record": record})
|
||||
uri = response.json()["uri"]
|
||||
return {"id": uri, "url": self._web_url(uri)}
|
||||
|
||||
def update(self, remote_id: str, post: "Post") -> dict:
|
||||
raise NotImplementedError("Bluesky posts can't be edited")
|
||||
|
||||
def delete(self, remote_id: str) -> None:
|
||||
# at://<did>/app.bsky.feed.post/<rkey>; deleting a missing record succeeds
|
||||
repo, collection, rkey = remote_id[len("at://"):].split("/", 2)
|
||||
self._call("POST", "com.atproto.repo.deleteRecord",
|
||||
json={"repo": repo, "collection": collection, "rkey": rkey})
|
||||
|
||||
|
||||
def _fit_image(path: Path, mime_type: str, limit: int) -> tuple:
|
||||
"""Image bytes no bigger than `limit`, re-encoded as JPEG if needed. Returns (data, mime, w, h)."""
|
||||
from PIL import Image
|
||||
|
||||
data = Path(path).read_bytes()
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
width, height = img.size
|
||||
if len(data) <= limit:
|
||||
return data, mime_type, width, height
|
||||
img = img.convert("RGB")
|
||||
for max_side, quality in ((2000, 85), (2000, 75), (1600, 70), (1200, 65), (1000, 60)):
|
||||
copy = img.copy()
|
||||
copy.thumbnail((max_side, max_side))
|
||||
buf = io.BytesIO()
|
||||
copy.save(buf, format="JPEG", quality=quality, optimize=True)
|
||||
if buf.tell() <= limit:
|
||||
return buf.getvalue(), "image/jpeg", copy.size[0], copy.size[1]
|
||||
raise SyndicationError(f"{Path(path).name}: image too large for Bluesky", permanent=True)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Target:
|
||||
id: str # stored in syndications.target
|
||||
uid: str # Micropub syndicate-to uid
|
||||
name: str # shown in the editor and Micropub clients
|
||||
client: object # MastodonClient or BlueskyClient
|
||||
max_chars: int = 5000
|
||||
max_media: int = 4
|
||||
|
||||
|
||||
@dataclass
|
||||
class Post:
|
||||
"""What a client needs to publish a note"""
|
||||
note: object
|
||||
permalink: str
|
||||
tags: List[str]
|
||||
max_chars: int
|
||||
media: List[dict] = field(default_factory=list)
|
||||
|
||||
|
||||
_client_cache: Dict[str, object] = {}
|
||||
|
||||
|
||||
def targets_configured(config) -> bool:
|
||||
"""Whether any crossposting target has credentials (used to start the worker)"""
|
||||
return bool(
|
||||
(config.get("GOTOSOCIAL_URL") and config.get("GOTOSOCIAL_ACCESS_TOKEN"))
|
||||
or (config.get("BLUESKY_HANDLE") and config.get("BLUESKY_APP_PASSWORD"))
|
||||
)
|
||||
|
||||
|
||||
def get_targets() -> Dict[str, Target]:
|
||||
"""Configured syndication targets, by id"""
|
||||
config = current_app.config
|
||||
targets: Dict[str, Target] = {}
|
||||
|
||||
url = (config.get("GOTOSOCIAL_URL") or "").rstrip("/")
|
||||
token = config.get("GOTOSOCIAL_ACCESS_TOKEN") or ""
|
||||
if url and token:
|
||||
client = _client_cache.get(url)
|
||||
if client is None:
|
||||
client = MastodonClient(url, token, config.get("GOTOSOCIAL_VISIBILITY", "public"))
|
||||
_client_cache[url] = client
|
||||
targets["gotosocial"] = Target(
|
||||
id="gotosocial",
|
||||
uid=url + "/",
|
||||
name=config.get("GOTOSOCIAL_NAME", "GoToSocial"),
|
||||
client=client,
|
||||
max_chars=int(config.get("GOTOSOCIAL_MAX_CHARS", 5000)),
|
||||
max_media=int(config.get("GOTOSOCIAL_MAX_MEDIA", 4)),
|
||||
)
|
||||
|
||||
handle = (config.get("BLUESKY_HANDLE") or "").lstrip("@")
|
||||
password = config.get("BLUESKY_APP_PASSWORD") or ""
|
||||
if handle and password:
|
||||
service = (config.get("BLUESKY_SERVICE") or "https://bsky.social").rstrip("/")
|
||||
key = f"bluesky:{service}:{handle}"
|
||||
client = _client_cache.get(key)
|
||||
if client is None:
|
||||
client = BlueskyClient(service, handle, password)
|
||||
_client_cache[key] = client
|
||||
targets["bluesky"] = Target(
|
||||
id="bluesky",
|
||||
uid=f"https://bsky.app/profile/{handle}",
|
||||
name=config.get("BLUESKY_NAME", "Bluesky"),
|
||||
client=client,
|
||||
max_chars=int(config.get("BLUESKY_MAX_CHARS", 300)),
|
||||
max_media=4,
|
||||
)
|
||||
return targets
|
||||
|
||||
|
||||
def resolve_targets(requested: List[str]) -> List[str]:
|
||||
"""Map Micropub uids or target ids to configured target ids"""
|
||||
targets = get_targets()
|
||||
by_uid = {t.uid.rstrip("/"): t.id for t in targets.values()}
|
||||
chosen = []
|
||||
for value in requested:
|
||||
value = (value or "").strip()
|
||||
target_id = value if value in targets else by_uid.get(value.rstrip("/"))
|
||||
if target_id and target_id not in chosen:
|
||||
chosen.append(target_id)
|
||||
return chosen
|
||||
|
||||
|
||||
# --- Queue -----------------------------------------------------------------
|
||||
|
||||
def select_targets(note_id: int, target_ids: List[str]) -> None:
|
||||
"""
|
||||
Set which targets a note goes to, and queue the reconcile
|
||||
|
||||
Targets not listed are disabled (their remote post, if any, is deleted).
|
||||
Nothing is recorded for unlisted targets the note never went to.
|
||||
"""
|
||||
db = get_db(current_app)
|
||||
for target_id in get_targets():
|
||||
enabled = 1 if target_id in target_ids else 0
|
||||
existing = db.execute(
|
||||
"SELECT id FROM syndications WHERE note_id = ? AND target = ?",
|
||||
(note_id, target_id),
|
||||
).fetchone()
|
||||
if existing:
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE syndications
|
||||
SET enabled = ?, state = 'pending', version = version + 1, attempts = 0,
|
||||
last_error = NULL, next_attempt_at = datetime('now'), updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(enabled, existing["id"]),
|
||||
)
|
||||
elif enabled:
|
||||
db.execute(
|
||||
"INSERT INTO syndications (note_id, target, enabled) VALUES (?, ?, 1)",
|
||||
(note_id, target_id),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def note_changed(note_id: int) -> None:
|
||||
"""Queue a reconcile for every target the note was sent to"""
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE syndications
|
||||
SET state = 'pending', version = version + 1, attempts = 0, last_error = NULL,
|
||||
next_attempt_at = datetime('now'), updated_at = datetime('now')
|
||||
WHERE note_id = ?
|
||||
""",
|
||||
(note_id,),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def retry(syndication_id: int) -> None:
|
||||
"""Retry a failed or pending row now"""
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE syndications
|
||||
SET state = 'pending', attempts = 0, last_error = NULL, next_attempt_at = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(syndication_id,),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_note_syndications(note_id: int) -> List[dict]:
|
||||
"""Rows for a note, with the target's display name"""
|
||||
targets = get_targets()
|
||||
rows = get_db(current_app).execute(
|
||||
"SELECT * FROM syndications WHERE note_id = ? ORDER BY target", (note_id,)
|
||||
).fetchall()
|
||||
result = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
item["name"] = targets[row["target"]].name if row["target"] in targets else row["target"]
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
# --- Composing --------------------------------------------------------------
|
||||
|
||||
def _hashtag(display_name: str) -> str:
|
||||
word = re.sub(r"[^\w]", "", display_name)
|
||||
return f"#{word}" if word else ""
|
||||
|
||||
|
||||
def compose_text(note, permalink: str, tags: List[str], max_chars: int,
|
||||
body: Optional[str] = None) -> str:
|
||||
"""
|
||||
Full note (Markdown unless `body` is given), then the permalink and
|
||||
hashtags; shortened at a word boundary if too long. On short targets the
|
||||
hashtags may use at most a third of the space.
|
||||
"""
|
||||
hashtags = ""
|
||||
for h in (_hashtag(t) for t in tags):
|
||||
if h and len(hashtags) + len(h) + 1 <= max(max_chars // 3, 1):
|
||||
hashtags = f"{hashtags} {h}".strip()
|
||||
tail = f"\n\n{permalink}" + (f"\n\n{hashtags}" if hashtags else "")
|
||||
body = (note.content if body is None else body).strip()
|
||||
if len(body) + len(tail) > max_chars:
|
||||
room = max_chars - len(tail) - 1
|
||||
body = body[:room].rsplit(" ", 1)[0].rstrip() + "…"
|
||||
return body + tail
|
||||
|
||||
|
||||
_BLOCKS = ["p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "blockquote", "ul", "ol", "hr", "table"]
|
||||
|
||||
|
||||
def plain_text(markdown_text: str) -> str:
|
||||
"""Markdown as readable plain text (for targets without Markdown)"""
|
||||
import markdown
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
soup = BeautifulSoup(markdown.markdown(markdown_text, extensions=["fenced_code"]), "html.parser")
|
||||
for img in soup.find_all("img"):
|
||||
img.decompose()
|
||||
for node in soup.find_all(string=True):
|
||||
if not node.strip() and "\n" in node and node.parent.name != "pre":
|
||||
node.extract() # layout newlines between tags; we add our own
|
||||
for br in soup.find_all("br"):
|
||||
br.replace_with("\n")
|
||||
for li in soup.find_all("li"):
|
||||
li.insert(0, "• ")
|
||||
li.append("\n")
|
||||
for block in soup.find_all(_BLOCKS):
|
||||
block.append("\n\n")
|
||||
text = soup.get_text()
|
||||
text = re.sub(r"[ \t]+\n", "\n", text)
|
||||
return re.sub(r"\n{3,}", "\n\n", text).strip()
|
||||
|
||||
|
||||
_URL_RE = re.compile(r"https?://[^\s<>\"]+")
|
||||
_TAG_RE = re.compile(r"(?<![\w#])#(\w*[^\W\d]\w*)")
|
||||
|
||||
|
||||
def bluesky_facets(text: str) -> List[dict]:
|
||||
"""Link and hashtag facets (UTF-8 byte ranges) for a Bluesky post"""
|
||||
def span(start: int, end: int) -> dict:
|
||||
return {"byteStart": len(text[:start].encode()), "byteEnd": len(text[:end].encode())}
|
||||
|
||||
facets = []
|
||||
for m in _URL_RE.finditer(text):
|
||||
url = m.group(0).rstrip(".,;:!?)\"'…")
|
||||
facets.append({"index": span(m.start(), m.start() + len(url)),
|
||||
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}]})
|
||||
urls = [(f["index"]["byteStart"], f["index"]["byteEnd"]) for f in facets]
|
||||
for m in _TAG_RE.finditer(text):
|
||||
index = span(m.start(), m.end())
|
||||
if any(a <= index["byteStart"] < b for a, b in urls):
|
||||
continue # a #fragment inside a URL
|
||||
facets.append({"index": index,
|
||||
"features": [{"$type": "app.bsky.richtext.facet#tag", "tag": m.group(1)}]})
|
||||
return facets
|
||||
|
||||
|
||||
def _media_files(note_id: int, limit: int) -> List[dict]:
|
||||
"""Image files for a note: the 'large' variant when there is one"""
|
||||
from starpunk.media import get_note_media
|
||||
|
||||
media_dir = Path(current_app.config["DATA_PATH"]) / "media"
|
||||
files = []
|
||||
for media in get_note_media(note_id)[:limit]:
|
||||
variant = (media.get("variants") or {}).get("large")
|
||||
rel = variant["path"] if variant else media["path"]
|
||||
files.append({
|
||||
"path": media_dir / rel,
|
||||
"mime_type": media.get("mime_type") or "image/jpeg",
|
||||
"description": media.get("caption") or "",
|
||||
})
|
||||
return files
|
||||
|
||||
|
||||
# --- Worker -----------------------------------------------------------------
|
||||
|
||||
def _claim(db, row_id: int) -> bool:
|
||||
cursor = db.execute(
|
||||
f"""
|
||||
UPDATE syndications SET claimed_until = datetime('now', '+{CLAIM_MINUTES} minutes')
|
||||
WHERE id = ? AND state = 'pending'
|
||||
AND (claimed_until IS NULL OR claimed_until < datetime('now'))
|
||||
""",
|
||||
(row_id,),
|
||||
)
|
||||
db.commit()
|
||||
return cursor.rowcount == 1
|
||||
|
||||
|
||||
def _finish(db, row, remote_id: Optional[str], remote_url: Optional[str]) -> None:
|
||||
# Only mark synced if nothing changed while we were sending
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE syndications
|
||||
SET remote_id = ?, remote_url = ?, claimed_until = NULL, attempts = 0, last_error = NULL,
|
||||
state = CASE WHEN version = ? THEN 'synced' ELSE 'pending' END,
|
||||
updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(remote_id, remote_url, row["version"], row["id"]),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _fail(db, row, error: SyndicationError) -> None:
|
||||
attempts = row["attempts"] + 1
|
||||
failed = error.permanent or attempts >= MAX_ATTEMPTS
|
||||
delay = min(30 * (2 ** attempts), 6 * 3600)
|
||||
db.execute(
|
||||
f"""
|
||||
UPDATE syndications
|
||||
SET attempts = ?, last_error = ?, claimed_until = NULL,
|
||||
state = CASE WHEN version = ? THEN ? ELSE 'pending' END,
|
||||
next_attempt_at = datetime('now', '+{delay} seconds'), updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(attempts, str(error)[:500], row["version"], "failed" if failed else "pending", row["id"]),
|
||||
)
|
||||
db.commit()
|
||||
current_app.logger.warning(
|
||||
f"Syndication {row['target']} for note {row['note_id']} failed "
|
||||
f"(attempt {attempts}{', giving up' if failed else ''}): {error}"
|
||||
)
|
||||
|
||||
|
||||
def _reconcile(row, target: Target) -> tuple:
|
||||
"""Bring the remote post in line with the note. Returns (remote_id, remote_url)."""
|
||||
from starpunk.notes import get_note
|
||||
from starpunk.tags import get_note_tags
|
||||
|
||||
note = get_note(id=row["note_id"], load_content=True)
|
||||
wanted = bool(row["enabled"]) and note is not None and note.published
|
||||
|
||||
if not wanted:
|
||||
if row["remote_id"]:
|
||||
target.client.delete(row["remote_id"])
|
||||
return None, None
|
||||
|
||||
if row["remote_id"] and not target.client.can_edit:
|
||||
return row["remote_id"], row["remote_url"] # posted already; edits don't follow
|
||||
|
||||
site = current_app.config["SITE_URL"].rstrip("/")
|
||||
post = Post(
|
||||
note=note,
|
||||
permalink=f"{site}/note/{note.slug}",
|
||||
tags=[t["display_name"] for t in get_note_tags(note.id)],
|
||||
max_chars=target.max_chars,
|
||||
media=_media_files(note.id, target.max_media),
|
||||
)
|
||||
|
||||
if row["remote_id"]:
|
||||
try:
|
||||
result = target.client.update(row["remote_id"], post)
|
||||
return result["id"], result["url"]
|
||||
except RemoteGone:
|
||||
pass # deleted on the remote side; post it again
|
||||
|
||||
result = target.client.create(
|
||||
post, key=f"starpunk-{row['id']}-{row['version']}", retrying=row["attempts"] > 0
|
||||
)
|
||||
return result["id"], result["url"]
|
||||
|
||||
|
||||
def process_due(limit: int = 5) -> int:
|
||||
"""Reconcile up to `limit` pending rows. Returns how many were handled."""
|
||||
targets = get_targets()
|
||||
if not targets:
|
||||
return 0
|
||||
db = get_db(current_app)
|
||||
rows = db.execute(
|
||||
"""
|
||||
SELECT * FROM syndications
|
||||
WHERE state = 'pending' AND next_attempt_at <= datetime('now')
|
||||
AND (claimed_until IS NULL OR claimed_until < datetime('now'))
|
||||
ORDER BY next_attempt_at LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
|
||||
handled = 0
|
||||
for row in rows:
|
||||
if not _claim(db, row["id"]):
|
||||
continue # another worker took it
|
||||
handled += 1
|
||||
target = targets.get(row["target"])
|
||||
if target is None:
|
||||
_fail(db, row, SyndicationError(f"target {row['target']} is not configured", permanent=True))
|
||||
continue
|
||||
try:
|
||||
remote_id, remote_url = _reconcile(row, target)
|
||||
except SyndicationError as e:
|
||||
_fail(db, row, e)
|
||||
continue
|
||||
except Exception as e: # never let one bad note stop the worker
|
||||
_fail(db, row, SyndicationError(f"unexpected error: {e}"))
|
||||
continue
|
||||
_finish(db, row, remote_id, remote_url)
|
||||
if remote_id:
|
||||
current_app.logger.info(f"Syndicated note {row['note_id']} to {row['target']}: {remote_url}")
|
||||
return handled
|
||||
|
||||
|
||||
class SyndicationWorker(threading.Thread):
|
||||
"""Daemon thread that drains the syndication queue"""
|
||||
|
||||
def __init__(self, app, poll_interval: int = 10):
|
||||
super().__init__(daemon=True, name="syndication-worker")
|
||||
self.app = app
|
||||
self.poll_interval = poll_interval
|
||||
self._stop_event = threading.Event()
|
||||
|
||||
def run(self):
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
with self.app.app_context():
|
||||
handled = process_due()
|
||||
except Exception as e:
|
||||
self.app.logger.error(f"Syndication worker error: {e}", exc_info=True)
|
||||
handled = 0
|
||||
if handled == 0:
|
||||
self._stop_event.wait(self.poll_interval)
|
||||
|
||||
def stop(self):
|
||||
self._stop_event.set()
|
||||
@@ -681,3 +681,15 @@ def parse_iso8601(date_string: str) -> datetime:
|
||||
|
||||
# Parse using fromisoformat
|
||||
return datetime.fromisoformat(date_string)
|
||||
|
||||
|
||||
def absolute_url_for(endpoint: str, **values) -> str:
|
||||
"""
|
||||
Absolute URL for an endpoint, built from SITE_URL
|
||||
|
||||
Use instead of url_for(..., _external=True): behind a reverse proxy the
|
||||
request arrives over plain HTTP, so _external URLs would say http://.
|
||||
"""
|
||||
from flask import current_app, url_for
|
||||
|
||||
return current_app.config["SITE_URL"].rstrip("/") + url_for(endpoint, **values)
|
||||
@@ -0,0 +1,43 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Authorize App - StarPunk{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="login-container authorize">
|
||||
{% if request_error %}
|
||||
<h2>Cannot authorize this app</h2>
|
||||
<p>{{ request_error }}</p>
|
||||
<p><a href="/">Return to homepage</a></p>
|
||||
{% else %}
|
||||
<h2>Authorize app</h2>
|
||||
<p>
|
||||
<strong>{{ auth_request.client_id }}</strong> wants to sign in as
|
||||
<strong>{{ me }}</strong>.
|
||||
</p>
|
||||
<p><small>After approval you will be sent to {{ auth_request.redirect_uri }}</small></p>
|
||||
|
||||
<form action="{{ url_for('indieauth.approve') }}" method="POST" class="login-form">
|
||||
{% for name, value in fields.items() %}
|
||||
<input type="hidden" name="{{ name }}" value="{{ value }}">
|
||||
{% endfor %}
|
||||
|
||||
{% if auth_request.scopes %}
|
||||
<fieldset>
|
||||
<legend>Permissions requested</legend>
|
||||
{% for scope in auth_request.scopes %}
|
||||
<label>
|
||||
<input type="checkbox" name="scope_granted" value="{{ scope }}" checked>
|
||||
{{ scope }}
|
||||
</label><br>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
{% else %}
|
||||
<p>This app only wants to confirm your identity. It cannot post.</p>
|
||||
{% endif %}
|
||||
|
||||
<button type="submit" name="decision" value="approve" class="button button-primary">Approve</button>
|
||||
<button type="submit" name="decision" value="deny" class="button button-secondary">Deny</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -6,6 +6,7 @@
|
||||
<a href="{{ url_for('admin.dashboard') }}">Dashboard</a>
|
||||
<a href="{{ url_for('admin.new_note_form') }}">New Note</a>
|
||||
<a href="{{ url_for('admin.metrics_dashboard') }}">Metrics</a>
|
||||
<a href="{{ url_for('admin.tokens') }}">Connected Apps</a>
|
||||
<form action="{{ url_for('auth.logout') }}" method="POST" class="logout-form">
|
||||
<button type="submit" class="button button-secondary">Logout</button>
|
||||
</form>
|
||||
|
||||
@@ -52,15 +52,58 @@
|
||||
<label for="published">Published</label>
|
||||
</div>
|
||||
|
||||
{% if syndication_targets %}
|
||||
<input type="hidden" name="syndication_form" value="1">
|
||||
<fieldset class="form-group">
|
||||
<legend>Crosspost</legend>
|
||||
{% for target in syndication_targets %}
|
||||
<div class="form-checkbox">
|
||||
<input type="checkbox" id="syndicate-{{ target.id }}" name="syndicate_to" value="{{ target.id }}"{% if target.id in syndication_enabled %} checked{% endif %}>
|
||||
<label for="syndicate-{{ target.id }}">{{ target.name }}</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
{% endif %}
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="button button-primary">Update Note</button>
|
||||
<a href="{{ url_for('admin.dashboard') }}" class="button button-secondary">Cancel</a>
|
||||
<form action="{{ url_for('admin.delete_note_submit', note_id=note.id) }}" method="POST" class="delete-form" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this note? This cannot be undone.');">
|
||||
<input type="hidden" name="confirm" value="yes">
|
||||
<button type="submit" class="button button-danger">Delete Note</button>
|
||||
</form>
|
||||
<button type="submit" form="delete-note-form" class="button button-danger">Delete Note</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{# Outside the edit form: nested forms are not allowed in HTML #}
|
||||
<form id="delete-note-form" action="{{ url_for('admin.delete_note_submit', note_id=note.id) }}" method="POST" class="delete-form" onsubmit="return confirm('Are you sure you want to delete this note? This cannot be undone.');">
|
||||
<input type="hidden" name="confirm" value="yes">
|
||||
</form>
|
||||
|
||||
{% if syndications %}
|
||||
<section class="syndication-status">
|
||||
<h3>Crossposts</h3>
|
||||
<ul>
|
||||
{% for s in syndications %}
|
||||
<li>
|
||||
<strong>{{ s.name }}</strong>:
|
||||
{% if s.state == 'synced' and s.remote_url %}
|
||||
<a href="{{ s.remote_url }}" rel="noopener">posted</a>
|
||||
{% elif s.state == 'synced' %}
|
||||
removed
|
||||
{% elif s.state == 'pending' %}
|
||||
pending{% if s.attempts %} (retry {{ s.attempts }}){% endif %}
|
||||
{% else %}
|
||||
failed
|
||||
{% endif %}
|
||||
{% if s.last_error %}<br><small>{{ s.last_error }}</small>{% endif %}
|
||||
{% if s.state != 'synced' %}
|
||||
<form action="{{ url_for('admin.retry_syndication', syndication_id=s.id) }}" method="POST" style="display: inline;">
|
||||
<button type="submit" class="button button-secondary">Retry now</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
@@ -5,23 +5,10 @@
|
||||
{% block content %}
|
||||
<div class="login-container">
|
||||
<h2>Admin Login</h2>
|
||||
<p>Sign in with your personal website using IndieLogin</p>
|
||||
<p>Sign in with {{ config.OIDC_PROVIDER_NAME }} to manage this site.</p>
|
||||
|
||||
<form action="{{ url_for('auth.login_initiate') }}" method="POST" class="login-form">
|
||||
<div class="form-group">
|
||||
<label for="me">Your Website URL</label>
|
||||
<input
|
||||
type="url"
|
||||
id="me"
|
||||
name="me"
|
||||
placeholder="https://example.com"
|
||||
required
|
||||
autofocus
|
||||
>
|
||||
<small>Enter your website URL (must match admin configuration)</small>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="button button-primary">Sign in with IndieLogin</button>
|
||||
<button type="submit" class="button button-primary">Sign in with {{ config.OIDC_PROVIDER_NAME }}</button>
|
||||
</form>
|
||||
|
||||
{% if config.DEV_MODE %}
|
||||
@@ -33,16 +20,5 @@
|
||||
</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="login-help">
|
||||
<h3>What is IndieLogin?</h3>
|
||||
<p>
|
||||
IndieLogin allows you to sign in using your own website.
|
||||
No password required - just authenticate with your domain.
|
||||
</p>
|
||||
<a href="https://indielogin.com/api" target="_blank" rel="noopener">
|
||||
Learn more about IndieLogin
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -65,6 +65,19 @@
|
||||
<label for="published">Publish immediately</label>
|
||||
</div>
|
||||
|
||||
{% if syndication_targets %}
|
||||
<input type="hidden" name="syndication_form" value="1">
|
||||
<fieldset class="form-group">
|
||||
<legend>Crosspost</legend>
|
||||
{% for target in syndication_targets %}
|
||||
<div class="form-checkbox">
|
||||
<input type="checkbox" id="syndicate-{{ target.id }}" name="syndicate_to" value="{{ target.id }}" checked>
|
||||
<label for="syndicate-{{ target.id }}">{{ target.name }}</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
{% endif %}
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="button button-primary">Create Note</button>
|
||||
<a href="{{ url_for('admin.dashboard') }}" class="button button-secondary">Cancel</a>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
{% extends "admin/base.html" %}
|
||||
|
||||
{% block title %}Connected Apps - StarPunk Admin{% endblock %}
|
||||
|
||||
{% block admin_content %}
|
||||
<div class="tokens-admin">
|
||||
<h2>Connected Apps</h2>
|
||||
<p>Micropub apps you have approved. Revoke any you no longer use.</p>
|
||||
|
||||
{% if tokens %}
|
||||
<table class="note-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>App</th>
|
||||
<th>Scope</th>
|
||||
<th>Approved</th>
|
||||
<th>Last used</th>
|
||||
<th>Expires</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for t in tokens %}
|
||||
<tr>
|
||||
<td>{{ t.client_id }}</td>
|
||||
<td>{{ t.scope }}</td>
|
||||
<td>{{ t.created_at }}</td>
|
||||
<td>{{ t.last_used_at or "never" }}</td>
|
||||
<td>{{ t.expires_at }}</td>
|
||||
<td>
|
||||
<form method="POST" action="{{ url_for('admin.revoke_token', token_id=t.id) }}">
|
||||
<button type="submit" class="button button-danger"
|
||||
onclick="return confirm('Revoke this app\'s access?')">Revoke</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p>No apps connected.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
+6
-2
@@ -5,12 +5,16 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}StarPunk{% endblock %}</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
|
||||
<link rel="alternate" type="application/rss+xml" title="{{ config.SITE_NAME }} RSS Feed" href="{{ url_for('public.feed', _external=True) }}">
|
||||
<link rel="alternate" type="application/xml+opml" title="{{ config.SITE_NAME }} Feed Subscription List" href="{{ url_for('public.opml', _external=True) }}">
|
||||
<link rel="alternate" type="application/rss+xml" title="{{ config.SITE_NAME }} RSS Feed" href="{{ absolute_url_for('public.feed') }}">
|
||||
<link rel="alternate" type="application/xml+opml" title="{{ config.SITE_NAME }} Feed Subscription List" href="{{ absolute_url_for('public.opml') }}">
|
||||
|
||||
{# Webmention endpoint (v1.6.0) #}
|
||||
{% if config.WEBMENTION_ENABLED %}
|
||||
<link rel="webmention" href="/webmention">
|
||||
<link rel="micropub" href="{{ absolute_url_for('micropub.micropub_endpoint') }}">
|
||||
<link rel="indieauth-metadata" href="{{ absolute_url_for('indieauth.metadata') }}">
|
||||
<link rel="authorization_endpoint" href="{{ absolute_url_for('indieauth.authorize') }}">
|
||||
<link rel="token_endpoint" href="{{ absolute_url_for('indieauth.token') }}">
|
||||
{% endif %}
|
||||
|
||||
{# rel-me links from discovered author profile (v1.2.0 Phase 2) #}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<h2 class="p-name">{{ config.SITE_NAME or 'Recent Notes' }}</h2>
|
||||
|
||||
{# u-url for feed (self-reference) #}
|
||||
<a class="u-url" href="{{ url_for('public.index', _external=True) }}" style="display: none;">Feed URL</a>
|
||||
<a class="u-url" href="{{ absolute_url_for('public.index') }}" style="display: none;">Feed URL</a>
|
||||
|
||||
{# Feed-level author h-card with all properties #}
|
||||
{# Hidden because it's semantic-only markup for parsers, not visual content #}
|
||||
@@ -53,7 +53,7 @@
|
||||
|
||||
<footer class="note-meta">
|
||||
{# u-url for permalink #}
|
||||
<a class="u-url" href="{{ url_for('public.note', slug=note.slug, _external=True) }}">
|
||||
<a class="u-url" href="{{ absolute_url_for('public.note', slug=note.slug) }}">
|
||||
<time class="dt-published" datetime="{{ note.created_at.isoformat() }}">
|
||||
{{ note.created_at.strftime('%B %d, %Y') }}
|
||||
</time>
|
||||
|
||||
+4
-1
@@ -49,7 +49,10 @@
|
||||
|
||||
<footer class="note-meta">
|
||||
{# u-url and u-uid same for notes (per Q23) #}
|
||||
<a class="u-url u-uid" href="{{ url_for('public.note', slug=note.slug, _external=True) }}">
|
||||
{% for s in syndications if s.remote_url %}
|
||||
<a class="u-syndication" href="{{ s.remote_url }}" rel="syndication">Also on {{ s.name }}</a>
|
||||
{% endfor %}
|
||||
<a class="u-url u-uid" href="{{ absolute_url_for('public.note', slug=note.slug) }}">
|
||||
<time class="dt-published" datetime="{{ note.created_at.isoformat() }}">
|
||||
{{ note.created_at.strftime('%B %d, %Y at %I:%M %p') }}
|
||||
</time>
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@
|
||||
|
||||
<footer class="note-meta">
|
||||
{# u-url for permalink #}
|
||||
<a class="u-url" href="{{ url_for('public.note', slug=note.slug, _external=True) }}">
|
||||
<a class="u-url" href="{{ absolute_url_for('public.note', slug=note.slug) }}">
|
||||
<time class="dt-published" datetime="{{ note.created_at.isoformat() }}">
|
||||
{{ note.created_at.strftime('%B %d, %Y') }}
|
||||
</time>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
Absolute URLs come from SITE_URL, not the request (v2.0.1)
|
||||
|
||||
Behind a reverse proxy the app is reached over plain HTTP, so URLs built
|
||||
from the request said http:// on an https site.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from starpunk import create_app
|
||||
from starpunk.notes import create_note
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path):
|
||||
data = tmp_path / "data"
|
||||
return create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"SITE_URL": "https://blog.example.com",
|
||||
"ADMIN_ME": "https://example.com",
|
||||
"SESSION_SECRET": "test-secret",
|
||||
"DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "starpunk.db",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_pages_use_site_url_behind_http_proxy(app):
|
||||
with app.app_context():
|
||||
note = create_note(content="Hello over the proxy", published=True, tags=["proxy"])
|
||||
client = app.test_client()
|
||||
|
||||
pages = ["/", f"/note/{note.slug}", "/tag/proxy"]
|
||||
for path in pages:
|
||||
# The test client makes plain http://localhost requests, like Caddy does
|
||||
response = client.get(path)
|
||||
assert response.status_code == 200, path
|
||||
html = response.data.decode()
|
||||
assert "http://localhost" not in html, path
|
||||
|
||||
home = client.get("/").data.decode()
|
||||
assert 'href="https://blog.example.com/feed"' in home
|
||||
assert 'href="https://blog.example.com/opml.xml"' in home
|
||||
|
||||
note_html = client.get(f"/note/{note.slug}").data.decode()
|
||||
assert f'href="https://blog.example.com/note/{note.slug}"' in note_html
|
||||
@@ -12,21 +12,11 @@ import pytest
|
||||
from flask import g
|
||||
|
||||
from starpunk.auth import (
|
||||
AuthError,
|
||||
IndieLoginError,
|
||||
InvalidStateError,
|
||||
UnauthorizedError,
|
||||
_cleanup_expired_sessions,
|
||||
_generate_state_token,
|
||||
_hash_token,
|
||||
_log_http_request,
|
||||
_log_http_response,
|
||||
_redact_token,
|
||||
_verify_state_token,
|
||||
create_session,
|
||||
destroy_session,
|
||||
handle_callback,
|
||||
initiate_login,
|
||||
require_auth,
|
||||
verify_session,
|
||||
)
|
||||
@@ -104,45 +94,6 @@ class TestHelpers:
|
||||
assert len(set(tokens)) == 10
|
||||
|
||||
|
||||
class TestStateTokenVerification:
|
||||
def test_verify_valid_state_token(self, app, db):
|
||||
"""Test verifying a valid state token"""
|
||||
with app.app_context():
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
assert _verify_state_token(state) is True
|
||||
|
||||
# Token should be deleted after verification
|
||||
result = db.execute(
|
||||
"SELECT 1 FROM auth_state WHERE state = ?", (state,)
|
||||
).fetchone()
|
||||
assert result is None
|
||||
|
||||
def test_verify_invalid_state_token(self, app):
|
||||
"""Test verifying an invalid state token"""
|
||||
with app.app_context():
|
||||
assert _verify_state_token("invalid-token") is False
|
||||
|
||||
def test_verify_expired_state_token(self, app, db):
|
||||
"""Test verifying an expired state token"""
|
||||
with app.app_context():
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() - timedelta(minutes=5)
|
||||
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
assert _verify_state_token(state) is False
|
||||
|
||||
|
||||
class TestCleanup:
|
||||
@@ -170,25 +121,6 @@ class TestCleanup:
|
||||
).fetchone()
|
||||
assert result is None
|
||||
|
||||
def test_cleanup_expired_auth_state(self, app, db):
|
||||
"""Test cleanup of expired auth state"""
|
||||
with app.app_context():
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() - timedelta(minutes=10)
|
||||
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
_cleanup_expired_sessions()
|
||||
|
||||
# Expired state should be deleted
|
||||
result = db.execute(
|
||||
"SELECT 1 FROM auth_state WHERE state = ?", (state,)
|
||||
).fetchone()
|
||||
assert result is None
|
||||
|
||||
def test_cleanup_keeps_valid_sessions(self, app, db):
|
||||
"""Test that cleanup keeps valid sessions"""
|
||||
@@ -214,185 +146,8 @@ class TestCleanup:
|
||||
assert result is not None
|
||||
|
||||
|
||||
class TestInitiateLogin:
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
def test_initiate_login_success(self, mock_discover, app, db):
|
||||
"""Test successful login initiation"""
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
me_url = "https://example.com"
|
||||
auth_url = initiate_login(me_url)
|
||||
|
||||
# Changed: Check for discovered endpoint instead of indielogin.com
|
||||
assert "auth.example.com/authorize" in auth_url
|
||||
assert "me=https%3A%2F%2Fexample.com" in auth_url
|
||||
assert "client_id=" in auth_url
|
||||
assert "redirect_uri=" in auth_url
|
||||
assert "state=" in auth_url
|
||||
# Per W3C IndieAuth: response_type=id for authentication-only (identity verification)
|
||||
assert "response_type=id" in auth_url
|
||||
|
||||
# State should be stored in database
|
||||
result = db.execute("SELECT COUNT(*) as count FROM auth_state").fetchone()
|
||||
assert result["count"] > 0
|
||||
|
||||
def test_initiate_login_invalid_url(self, app):
|
||||
"""Test login initiation with invalid URL"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValueError, match="Invalid URL format"):
|
||||
initiate_login("not-a-url")
|
||||
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
def test_initiate_login_stores_state(self, mock_discover, app, db):
|
||||
"""Test that state token is stored"""
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
me_url = "https://example.com"
|
||||
auth_url = initiate_login(me_url)
|
||||
|
||||
# Extract state from URL
|
||||
state_param = [p for p in auth_url.split("&") if p.startswith("state=")][0]
|
||||
state = state_param.split("=")[1]
|
||||
|
||||
# State should exist in database
|
||||
result = db.execute(
|
||||
"SELECT expires_at FROM auth_state WHERE state = ?", (state,)
|
||||
).fetchone()
|
||||
assert result is not None
|
||||
|
||||
|
||||
class TestHandleCallback:
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
@patch("starpunk.auth.httpx.post")
|
||||
def test_handle_callback_success(self, mock_post, mock_discover, app, db, client):
|
||||
"""Test successful callback handling"""
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.test_request_context():
|
||||
# Setup state token
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Mock authorization endpoint response
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = {"me": "https://example.com"}
|
||||
mock_post.return_value = mock_response
|
||||
|
||||
# Handle callback
|
||||
code = "test-code"
|
||||
session_token = handle_callback(code, state)
|
||||
|
||||
assert session_token is not None
|
||||
assert isinstance(session_token, str)
|
||||
|
||||
# Session should be created
|
||||
token_hash = _hash_token(session_token)
|
||||
result = db.execute(
|
||||
"SELECT me FROM sessions WHERE session_token_hash = ?", (token_hash,)
|
||||
).fetchone()
|
||||
assert result is not None
|
||||
assert result["me"] == "https://example.com"
|
||||
|
||||
def test_handle_callback_invalid_state(self, app):
|
||||
"""Test callback with invalid state"""
|
||||
with app.app_context():
|
||||
with pytest.raises(InvalidStateError):
|
||||
handle_callback("code", "invalid-state")
|
||||
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
@patch("starpunk.auth.httpx.post")
|
||||
def test_handle_callback_unauthorized_user(self, mock_post, mock_discover, app, db):
|
||||
"""Test callback with unauthorized user"""
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
# Setup state token
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Mock authorization endpoint response with different user
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = {"me": "https://attacker.com"}
|
||||
mock_post.return_value = mock_response
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
handle_callback("code", state)
|
||||
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
@patch("starpunk.auth.httpx.post")
|
||||
def test_handle_callback_indielogin_error(self, mock_post, mock_discover, app, db):
|
||||
"""Test callback with authorization endpoint error"""
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
# Setup state token
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Mock authorization endpoint error
|
||||
mock_post.side_effect = httpx.RequestError("Connection failed")
|
||||
|
||||
with pytest.raises(IndieLoginError):
|
||||
handle_callback("code", state)
|
||||
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
@patch("starpunk.auth.httpx.post")
|
||||
def test_handle_callback_no_identity(self, mock_post, mock_discover, app, db):
|
||||
"""Test callback with no identity in response"""
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
# Setup state token
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Mock authorization endpoint response without 'me' field
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = {}
|
||||
mock_post.return_value = mock_response
|
||||
|
||||
with pytest.raises(IndieLoginError, match="No identity returned"):
|
||||
handle_callback("code", state)
|
||||
|
||||
|
||||
class TestCreateSession:
|
||||
@@ -625,23 +380,6 @@ class TestSecurityFeatures:
|
||||
assert result["session_token_hash"] != session_token
|
||||
assert len(result["session_token_hash"]) == 64 # SHA-256 hex length
|
||||
|
||||
def test_state_tokens_are_single_use(self, app, db):
|
||||
"""Test that state tokens can only be used once"""
|
||||
with app.app_context():
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# First verification should succeed
|
||||
assert _verify_state_token(state) is True
|
||||
|
||||
# Second verification should fail (token deleted)
|
||||
assert _verify_state_token(state) is False
|
||||
|
||||
def test_session_expiry(self, app, db, client):
|
||||
"""Test that sessions expire correctly"""
|
||||
@@ -668,273 +406,13 @@ class TestSecurityFeatures:
|
||||
assert delta.total_seconds() <= 86401 # At most 1 day + 1 second
|
||||
|
||||
|
||||
class TestExceptionHierarchy:
|
||||
def test_exception_inheritance(self):
|
||||
"""Test that custom exceptions inherit correctly"""
|
||||
assert issubclass(InvalidStateError, AuthError)
|
||||
assert issubclass(UnauthorizedError, AuthError)
|
||||
assert issubclass(IndieLoginError, AuthError)
|
||||
assert issubclass(AuthError, Exception)
|
||||
|
||||
def test_exception_messages(self):
|
||||
"""Test that exceptions can carry messages"""
|
||||
error = InvalidStateError("Test message")
|
||||
assert str(error) == "Test message"
|
||||
|
||||
error = UnauthorizedError("Unauthorized")
|
||||
assert str(error) == "Unauthorized"
|
||||
|
||||
error = IndieLoginError("Service error")
|
||||
assert str(error) == "Service error"
|
||||
|
||||
|
||||
class TestLoggingHelpers:
|
||||
def test_redact_token_normal(self):
|
||||
"""Test token redaction for normal-length tokens"""
|
||||
token = "abcdefghijklmnopqrstuvwxyz"
|
||||
result = _redact_token(token, 6)
|
||||
assert result == "abcdef...********...wxyz"
|
||||
|
||||
def test_redact_token_short(self):
|
||||
"""Test token redaction for short tokens"""
|
||||
token = "short"
|
||||
result = _redact_token(token, 6)
|
||||
assert result == "***REDACTED***"
|
||||
|
||||
def test_redact_token_empty(self):
|
||||
"""Test token redaction for empty tokens"""
|
||||
result = _redact_token("", 6)
|
||||
assert result == "***REDACTED***"
|
||||
|
||||
result = _redact_token(None, 6)
|
||||
assert result == "***REDACTED***"
|
||||
|
||||
def test_redact_token_custom_length(self):
|
||||
"""Test token redaction with custom show_chars"""
|
||||
token = "abcdefghijklmnopqrstuvwxyz"
|
||||
result = _redact_token(token, 8)
|
||||
assert result == "abcdefgh...********...wxyz"
|
||||
|
||||
def test_log_http_request_redacts_code(self, app, caplog):
|
||||
"""Test that code parameter is redacted in request logs"""
|
||||
import logging
|
||||
|
||||
with app.app_context():
|
||||
# Set DEBUG level for logging
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
_log_http_request(
|
||||
method="POST",
|
||||
url="https://indielogin.com/auth",
|
||||
data={"code": "sensitive_code_12345"},
|
||||
)
|
||||
|
||||
# Should log but with redacted code
|
||||
assert "sensitive_code_12345" not in caplog.text
|
||||
assert "sensit...********...2345" in caplog.text
|
||||
|
||||
def test_log_http_request_redacts_state(self, app, caplog):
|
||||
"""Test that state parameter is redacted in request logs"""
|
||||
import logging
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
_log_http_request(
|
||||
method="POST",
|
||||
url="https://indielogin.com/auth",
|
||||
data={"state": "state_token_123456789"},
|
||||
)
|
||||
|
||||
# Should log but with redacted state (8 chars shown at start)
|
||||
assert "state_token_123456789" not in caplog.text
|
||||
assert "state_to...********...6789" in caplog.text
|
||||
|
||||
def test_log_http_request_not_logged_at_info(self, app, caplog):
|
||||
"""Test that HTTP requests are not logged at INFO level"""
|
||||
import logging
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.INFO)
|
||||
|
||||
with caplog.at_level(logging.INFO):
|
||||
_log_http_request(
|
||||
method="POST",
|
||||
url="https://indielogin.com/auth",
|
||||
data={"code": "test_code"},
|
||||
)
|
||||
|
||||
# Should not log anything
|
||||
assert "IndieAuth HTTP Request" not in caplog.text
|
||||
|
||||
def test_log_http_response_redacts_tokens(self, app, caplog):
|
||||
"""Test that response tokens are redacted"""
|
||||
import logging
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
_log_http_response(
|
||||
status_code=200,
|
||||
headers={"content-type": "application/json"},
|
||||
body='{"access_token": "secret_token_xyz789"}',
|
||||
)
|
||||
|
||||
# Should log but with redacted token
|
||||
assert "secret_token_xyz789" not in caplog.text
|
||||
assert "secret...********...z789" in caplog.text
|
||||
|
||||
def test_log_http_response_handles_non_json(self, app, caplog):
|
||||
"""Test that non-JSON responses are logged as-is"""
|
||||
import logging
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
_log_http_response(
|
||||
status_code=500, headers={}, body="Internal Server Error"
|
||||
)
|
||||
|
||||
# Should log the plain text body
|
||||
assert "Internal Server Error" in caplog.text
|
||||
|
||||
def test_log_http_response_redacts_sensitive_headers(self, app, caplog):
|
||||
"""Test that sensitive headers are redacted"""
|
||||
import logging
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
_log_http_response(
|
||||
status_code=200,
|
||||
headers={
|
||||
"content-type": "application/json",
|
||||
"set-cookie": "sensitive_cookie",
|
||||
"authorization": "Bearer token",
|
||||
},
|
||||
body='{"me": "https://example.com"}',
|
||||
)
|
||||
|
||||
# Should log content-type but not sensitive headers
|
||||
assert "content-type" in caplog.text
|
||||
assert "set-cookie" not in caplog.text
|
||||
assert "authorization" not in caplog.text
|
||||
assert "sensitive_cookie" not in caplog.text
|
||||
|
||||
|
||||
class TestLoggingIntegration:
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
def test_initiate_login_logs_at_debug(self, mock_discover, app, db, caplog):
|
||||
"""Test that initiate_login logs at DEBUG level"""
|
||||
import logging
|
||||
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
me_url = "https://example.com"
|
||||
initiate_login(me_url)
|
||||
|
||||
# Should see DEBUG logs
|
||||
assert "Validating me URL" in caplog.text
|
||||
assert "Generated state token" in caplog.text
|
||||
assert "Building authorization URL" in caplog.text
|
||||
|
||||
# Should see INFO log
|
||||
assert "Authentication initiated" in caplog.text
|
||||
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
def test_initiate_login_info_level(self, mock_discover, app, db, caplog):
|
||||
"""Test that initiate_login only shows milestones at INFO level"""
|
||||
import logging
|
||||
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
app.logger.setLevel(logging.INFO)
|
||||
|
||||
with caplog.at_level(logging.INFO):
|
||||
me_url = "https://example.com"
|
||||
initiate_login(me_url)
|
||||
|
||||
# Should see INFO milestone
|
||||
assert "Authentication initiated" in caplog.text
|
||||
|
||||
# Should NOT see DEBUG details
|
||||
assert "Validating me URL" not in caplog.text
|
||||
assert "Generated state token" not in caplog.text
|
||||
|
||||
@patch("starpunk.auth.discover_endpoints")
|
||||
@patch("starpunk.auth.httpx.post")
|
||||
def test_handle_callback_logs_http_details(self, mock_post, mock_discover, app, db, client, caplog):
|
||||
"""Test that handle_callback logs HTTP request/response at DEBUG"""
|
||||
import logging
|
||||
|
||||
mock_discover.return_value = {
|
||||
'authorization_endpoint': 'https://auth.example.com/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
with app.test_request_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Setup state token
|
||||
state = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=5)
|
||||
db.execute(
|
||||
"INSERT INTO auth_state (state, expires_at) VALUES (?, ?)",
|
||||
(state, expires_at),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Mock authorization endpoint response
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {"content-type": "application/json"}
|
||||
mock_response.text = '{"me": "https://example.com"}'
|
||||
mock_response.json.return_value = {"me": "https://example.com"}
|
||||
mock_post.return_value = mock_response
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
code = "test_authorization_code"
|
||||
handle_callback(code, state)
|
||||
|
||||
# Should see HTTP request/response logs
|
||||
assert "IndieAuth HTTP Request" in caplog.text
|
||||
assert "IndieAuth HTTP Response" in caplog.text
|
||||
|
||||
# Code should be redacted
|
||||
assert "test_authorization_code" not in caplog.text
|
||||
assert "test_a...********...code" in caplog.text
|
||||
|
||||
def test_create_session_logs_details(self, app, db, client, caplog):
|
||||
"""Test that create_session logs session details at DEBUG"""
|
||||
import logging
|
||||
|
||||
with app.test_request_context():
|
||||
app.logger.setLevel(logging.DEBUG)
|
||||
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
me = "https://example.com"
|
||||
create_session(me)
|
||||
|
||||
# Should see DEBUG logs
|
||||
assert "Session token generated" in caplog.text
|
||||
assert "Session expiry" in caplog.text
|
||||
assert "Request metadata" in caplog.text
|
||||
|
||||
# Should see INFO log
|
||||
assert "Session created" in caplog.text
|
||||
@@ -1,637 +0,0 @@
|
||||
"""
|
||||
Tests for external IndieAuth token verification with endpoint discovery
|
||||
|
||||
Tests cover:
|
||||
- Endpoint discovery from HTTP Link headers
|
||||
- Endpoint discovery from HTML link elements
|
||||
- Token verification with discovered endpoints
|
||||
- Caching behavior for endpoints and tokens
|
||||
- Error handling and edge cases
|
||||
- HTTPS validation
|
||||
- URL normalization
|
||||
|
||||
ADR: ADR-031 IndieAuth Endpoint Discovery Implementation
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import time
|
||||
from unittest.mock import Mock, patch
|
||||
import pytest
|
||||
import httpx
|
||||
|
||||
from starpunk.auth_external import (
|
||||
verify_external_token,
|
||||
discover_endpoints,
|
||||
check_scope,
|
||||
normalize_url,
|
||||
_parse_link_header,
|
||||
_parse_html_links,
|
||||
_cache,
|
||||
DiscoveryError,
|
||||
TokenVerificationError,
|
||||
ENDPOINT_CACHE_TTL,
|
||||
TOKEN_CACHE_TTL,
|
||||
)
|
||||
|
||||
|
||||
# Test Fixtures
|
||||
# -------------
|
||||
|
||||
@pytest.fixture
|
||||
def mock_profile_html():
|
||||
"""HTML profile with IndieAuth link elements"""
|
||||
return """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="authorization_endpoint" href="https://auth.example.com/authorize">
|
||||
<link rel="token_endpoint" href="https://auth.example.com/token">
|
||||
<title>Test Profile</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello World</h1>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_profile_html_relative():
|
||||
"""HTML profile with relative URLs"""
|
||||
return """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="authorization_endpoint" href="/auth/authorize">
|
||||
<link rel="token_endpoint" href="/auth/token">
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_link_headers():
|
||||
"""HTTP Link headers with IndieAuth endpoints"""
|
||||
return (
|
||||
'<https://auth.example.com/authorize>; rel="authorization_endpoint", '
|
||||
'<https://auth.example.com/token>; rel="token_endpoint"'
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_token_response():
|
||||
"""Valid token verification response"""
|
||||
return {
|
||||
'me': 'https://alice.example.com/',
|
||||
'client_id': 'https://app.example.com/',
|
||||
'scope': 'create update',
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cache():
|
||||
"""Clear cache before each test"""
|
||||
_cache.endpoints = None
|
||||
_cache.endpoints_expire = 0
|
||||
_cache.token_cache.clear()
|
||||
yield
|
||||
# Clear after test too
|
||||
_cache.endpoints = None
|
||||
_cache.endpoints_expire = 0
|
||||
_cache.token_cache.clear()
|
||||
|
||||
|
||||
# Endpoint Discovery Tests
|
||||
# -------------------------
|
||||
|
||||
def test_parse_link_header_both_endpoints(mock_link_headers):
|
||||
"""Parse Link header with both authorization and token endpoints"""
|
||||
endpoints = _parse_link_header(mock_link_headers, 'https://alice.example.com/')
|
||||
|
||||
assert endpoints['authorization_endpoint'] == 'https://auth.example.com/authorize'
|
||||
assert endpoints['token_endpoint'] == 'https://auth.example.com/token'
|
||||
|
||||
|
||||
def test_parse_link_header_single_endpoint():
|
||||
"""Parse Link header with only token endpoint"""
|
||||
header = '<https://auth.example.com/token>; rel="token_endpoint"'
|
||||
endpoints = _parse_link_header(header, 'https://alice.example.com/')
|
||||
|
||||
assert endpoints['token_endpoint'] == 'https://auth.example.com/token'
|
||||
assert 'authorization_endpoint' not in endpoints
|
||||
|
||||
|
||||
def test_parse_link_header_relative_url():
|
||||
"""Parse Link header with relative URL"""
|
||||
header = '</auth/token>; rel="token_endpoint"'
|
||||
endpoints = _parse_link_header(header, 'https://alice.example.com/')
|
||||
|
||||
assert endpoints['token_endpoint'] == 'https://alice.example.com/auth/token'
|
||||
|
||||
|
||||
def test_parse_html_links_both_endpoints(mock_profile_html):
|
||||
"""Parse HTML with both authorization and token endpoints"""
|
||||
endpoints = _parse_html_links(mock_profile_html, 'https://alice.example.com/')
|
||||
|
||||
assert endpoints['authorization_endpoint'] == 'https://auth.example.com/authorize'
|
||||
assert endpoints['token_endpoint'] == 'https://auth.example.com/token'
|
||||
|
||||
|
||||
def test_parse_html_links_relative_urls(mock_profile_html_relative):
|
||||
"""Parse HTML with relative endpoint URLs"""
|
||||
endpoints = _parse_html_links(
|
||||
mock_profile_html_relative,
|
||||
'https://alice.example.com/'
|
||||
)
|
||||
|
||||
assert endpoints['authorization_endpoint'] == 'https://alice.example.com/auth/authorize'
|
||||
assert endpoints['token_endpoint'] == 'https://alice.example.com/auth/token'
|
||||
|
||||
|
||||
def test_parse_html_links_empty():
|
||||
"""Parse HTML with no IndieAuth links"""
|
||||
html = '<html><head></head><body></body></html>'
|
||||
endpoints = _parse_html_links(html, 'https://alice.example.com/')
|
||||
|
||||
assert endpoints == {}
|
||||
|
||||
|
||||
def test_parse_html_links_malformed():
|
||||
"""Parse malformed HTML gracefully"""
|
||||
html = '<html><head><link rel="token_endpoint"' # Missing closing tags
|
||||
endpoints = _parse_html_links(html, 'https://alice.example.com/')
|
||||
|
||||
# Should return empty dict, not crash
|
||||
assert isinstance(endpoints, dict)
|
||||
|
||||
|
||||
def test_parse_html_links_rel_as_list():
|
||||
"""Parse HTML where rel attribute is a list"""
|
||||
html = '''
|
||||
<html><head>
|
||||
<link rel="authorization_endpoint me" href="https://auth.example.com/authorize">
|
||||
</head></html>
|
||||
'''
|
||||
endpoints = _parse_html_links(html, 'https://alice.example.com/')
|
||||
|
||||
assert endpoints['authorization_endpoint'] == 'https://auth.example.com/authorize'
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_from_html(mock_get, app_with_admin_me, mock_profile_html):
|
||||
"""Discover endpoints from HTML link elements"""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {'Content-Type': 'text/html'}
|
||||
mock_response.text = mock_profile_html
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
endpoints = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert endpoints['token_endpoint'] == 'https://auth.example.com/token'
|
||||
assert endpoints['authorization_endpoint'] == 'https://auth.example.com/authorize'
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_from_link_header(mock_get, app_with_admin_me, mock_link_headers):
|
||||
"""Discover endpoints from HTTP Link headers"""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {
|
||||
'Content-Type': 'text/html',
|
||||
'Link': mock_link_headers
|
||||
}
|
||||
mock_response.text = '<html></html>'
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
endpoints = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert endpoints['token_endpoint'] == 'https://auth.example.com/token'
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_link_header_priority(mock_get, app_with_admin_me, mock_profile_html, mock_link_headers):
|
||||
"""Link headers take priority over HTML link elements"""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {
|
||||
'Content-Type': 'text/html',
|
||||
'Link': '<https://different.example.com/token>; rel="token_endpoint"'
|
||||
}
|
||||
# HTML has different endpoint
|
||||
mock_response.text = mock_profile_html
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
endpoints = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
# Link header should win
|
||||
assert endpoints['token_endpoint'] == 'https://different.example.com/token'
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_no_token_endpoint(mock_get, app_with_admin_me):
|
||||
"""Raise error if no IndieAuth endpoints found"""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {'Content-Type': 'text/html'}
|
||||
mock_response.text = '<html><head></head><body></body></html>'
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert 'No IndieAuth endpoints found' in str(exc_info.value)
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_http_error(mock_get, app_with_admin_me):
|
||||
"""Handle HTTP errors during discovery"""
|
||||
mock_get.side_effect = httpx.HTTPStatusError(
|
||||
"404 Not Found",
|
||||
request=Mock(),
|
||||
response=Mock(status_code=404)
|
||||
)
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert 'HTTP 404' in str(exc_info.value)
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_timeout(mock_get, app_with_admin_me):
|
||||
"""Handle timeout during discovery"""
|
||||
mock_get.side_effect = httpx.TimeoutException("Timeout")
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert 'Timeout' in str(exc_info.value)
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_network_error(mock_get, app_with_admin_me):
|
||||
"""Handle network errors during discovery"""
|
||||
mock_get.side_effect = httpx.NetworkError("Connection failed")
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert 'Network error' in str(exc_info.value)
|
||||
|
||||
|
||||
# HTTPS Validation Tests
|
||||
# -----------------------
|
||||
|
||||
def test_discover_endpoints_http_not_allowed_production(app_with_admin_me):
|
||||
"""HTTP profile URLs not allowed in production"""
|
||||
with app_with_admin_me.app_context():
|
||||
app_with_admin_me.config['DEBUG'] = False
|
||||
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
discover_endpoints('http://alice.example.com/')
|
||||
|
||||
assert 'HTTPS required' in str(exc_info.value)
|
||||
|
||||
|
||||
def test_discover_endpoints_http_allowed_debug(app_with_admin_me):
|
||||
"""HTTP profile URLs allowed in debug mode"""
|
||||
with app_with_admin_me.app_context():
|
||||
app_with_admin_me.config['DEBUG'] = True
|
||||
|
||||
# Should validate without raising (mock would be needed for full test)
|
||||
# Just test validation doesn't raise
|
||||
from starpunk.auth_external import _validate_profile_url
|
||||
_validate_profile_url('http://localhost:5000/')
|
||||
|
||||
|
||||
def test_discover_endpoints_localhost_not_allowed_production(app_with_admin_me):
|
||||
"""Localhost URLs not allowed in production"""
|
||||
with app_with_admin_me.app_context():
|
||||
app_with_admin_me.config['DEBUG'] = False
|
||||
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
discover_endpoints('https://localhost/')
|
||||
|
||||
assert 'Localhost' in str(exc_info.value)
|
||||
|
||||
|
||||
# Caching Tests
|
||||
# -------------
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_caching(mock_get, app_with_admin_me, mock_profile_html):
|
||||
"""Discovered endpoints are cached"""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {'Content-Type': 'text/html'}
|
||||
mock_response.text = mock_profile_html
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
# First call - should fetch
|
||||
endpoints1 = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
# Second call - should use cache
|
||||
endpoints2 = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
# Should only call httpx.get once
|
||||
assert mock_get.call_count == 1
|
||||
assert endpoints1 == endpoints2
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_cache_expiry(mock_get, app_with_admin_me, mock_profile_html):
|
||||
"""Endpoint cache expires after TTL"""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {'Content-Type': 'text/html'}
|
||||
mock_response.text = mock_profile_html
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
# First call
|
||||
discover_endpoints('https://alice.example.com/')
|
||||
|
||||
# Expire cache manually
|
||||
_cache.endpoints_expire = time.time() - 1
|
||||
|
||||
# Second call should fetch again
|
||||
discover_endpoints('https://alice.example.com/')
|
||||
|
||||
assert mock_get.call_count == 2
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_discover_endpoints_grace_period(mock_get, app_with_admin_me, mock_profile_html):
|
||||
"""Use expired cache on network failure (grace period)"""
|
||||
# First call succeeds
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.headers = {'Content-Type': 'text/html'}
|
||||
mock_response.text = mock_profile_html
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
endpoints1 = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
# Expire cache
|
||||
_cache.endpoints_expire = time.time() - 1
|
||||
|
||||
# Second call fails, but should use expired cache
|
||||
mock_get.side_effect = httpx.NetworkError("Connection failed")
|
||||
|
||||
endpoints2 = discover_endpoints('https://alice.example.com/')
|
||||
|
||||
# Should return cached endpoints despite network failure
|
||||
assert endpoints1 == endpoints2
|
||||
|
||||
|
||||
# Token Verification Tests
|
||||
# -------------------------
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_success(mock_get, mock_discover, app_with_admin_me, mock_token_response):
|
||||
"""Successfully verify token with discovered endpoint"""
|
||||
# Mock discovery
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
# Mock token verification
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = mock_token_response
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
token_info = verify_external_token('test-token-123')
|
||||
|
||||
assert token_info is not None
|
||||
assert token_info['me'] == 'https://alice.example.com/'
|
||||
assert token_info['scope'] == 'create update'
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_wrong_me(mock_get, mock_discover, app_with_admin_me):
|
||||
"""Reject token for different user"""
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
# Token for wrong user
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {
|
||||
'me': 'https://bob.example.com/', # Not ADMIN_ME
|
||||
'scope': 'create',
|
||||
}
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
token_info = verify_external_token('test-token-123')
|
||||
|
||||
# Should reject
|
||||
assert token_info is None
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_401(mock_get, mock_discover, app_with_admin_me):
|
||||
"""Handle 401 Unauthorized from token endpoint"""
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 401
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
token_info = verify_external_token('invalid-token')
|
||||
|
||||
assert token_info is None
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_missing_me(mock_get, mock_discover, app_with_admin_me):
|
||||
"""Reject token response missing 'me' field"""
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {
|
||||
'scope': 'create',
|
||||
# Missing 'me' field
|
||||
}
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
token_info = verify_external_token('test-token')
|
||||
|
||||
assert token_info is None
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_retry_on_500(mock_get, mock_discover, app_with_admin_me, mock_token_response):
|
||||
"""Retry token verification on 500 server error"""
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
# First call: 500 error
|
||||
error_response = Mock()
|
||||
error_response.status_code = 500
|
||||
|
||||
# Second call: success
|
||||
success_response = Mock()
|
||||
success_response.status_code = 200
|
||||
success_response.json.return_value = mock_token_response
|
||||
|
||||
mock_get.side_effect = [error_response, success_response]
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
with patch('time.sleep'): # Skip sleep delay
|
||||
token_info = verify_external_token('test-token')
|
||||
|
||||
assert token_info is not None
|
||||
assert mock_get.call_count == 2
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_no_retry_on_403(mock_get, mock_discover, app_with_admin_me):
|
||||
"""Don't retry on 403 Forbidden (client error)"""
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 403
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
token_info = verify_external_token('test-token')
|
||||
|
||||
assert token_info is None
|
||||
# Should only call once (no retries)
|
||||
assert mock_get.call_count == 1
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
@patch('starpunk.auth_external.httpx.get')
|
||||
def test_verify_external_token_caching(mock_get, mock_discover, app_with_admin_me, mock_token_response):
|
||||
"""Token verifications are cached"""
|
||||
mock_discover.return_value = {
|
||||
'token_endpoint': 'https://auth.example.com/token'
|
||||
}
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = mock_token_response
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
with app_with_admin_me.app_context():
|
||||
# First call
|
||||
token_info1 = verify_external_token('test-token')
|
||||
|
||||
# Second call should use cache
|
||||
token_info2 = verify_external_token('test-token')
|
||||
|
||||
assert token_info1 == token_info2
|
||||
# Should only verify once
|
||||
assert mock_get.call_count == 1
|
||||
|
||||
|
||||
@patch('starpunk.auth_external.discover_endpoints')
|
||||
def test_verify_external_token_no_admin_me(mock_discover, app):
|
||||
"""Fail if ADMIN_ME not configured"""
|
||||
with app.app_context():
|
||||
# app fixture has no ADMIN_ME
|
||||
token_info = verify_external_token('test-token')
|
||||
|
||||
assert token_info is None
|
||||
# Should not even attempt discovery
|
||||
mock_discover.assert_not_called()
|
||||
|
||||
|
||||
# URL Normalization Tests
|
||||
# ------------------------
|
||||
|
||||
def test_normalize_url_removes_trailing_slash():
|
||||
"""Normalize URL removes trailing slash"""
|
||||
assert normalize_url('https://example.com/') == 'https://example.com'
|
||||
assert normalize_url('https://example.com') == 'https://example.com'
|
||||
|
||||
|
||||
def test_normalize_url_lowercase():
|
||||
"""Normalize URL converts to lowercase"""
|
||||
assert normalize_url('https://Example.COM/') == 'https://example.com'
|
||||
assert normalize_url('HTTPS://EXAMPLE.COM') == 'https://example.com'
|
||||
|
||||
|
||||
def test_normalize_url_path_preserved():
|
||||
"""Normalize URL preserves path"""
|
||||
assert normalize_url('https://example.com/path/') == 'https://example.com/path'
|
||||
assert normalize_url('https://Example.com/Path') == 'https://example.com/path'
|
||||
|
||||
|
||||
# Scope Checking Tests
|
||||
# ---------------------
|
||||
|
||||
def test_check_scope_present():
|
||||
"""Check scope returns True when scope is present"""
|
||||
assert check_scope('create', 'create update delete') is True
|
||||
assert check_scope('create', 'create') is True
|
||||
|
||||
|
||||
def test_check_scope_missing():
|
||||
"""Check scope returns False when scope is missing"""
|
||||
assert check_scope('create', 'update delete') is False
|
||||
assert check_scope('create', '') is False
|
||||
assert check_scope('create', 'created') is False # Partial match
|
||||
|
||||
|
||||
def test_check_scope_empty():
|
||||
"""Check scope handles empty scope string"""
|
||||
assert check_scope('create', '') is False
|
||||
assert check_scope('create', None) is False
|
||||
|
||||
|
||||
# Fixtures
|
||||
# --------
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
"""Create test Flask app without ADMIN_ME"""
|
||||
from flask import Flask
|
||||
app = Flask(__name__)
|
||||
app.config['TESTING'] = True
|
||||
app.config['DEBUG'] = False
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_with_admin_me():
|
||||
"""Create test Flask app with ADMIN_ME configured"""
|
||||
from flask import Flask
|
||||
app = Flask(__name__)
|
||||
app.config['TESTING'] = True
|
||||
app.config['DEBUG'] = False
|
||||
app.config['ADMIN_ME'] = 'https://alice.example.com/'
|
||||
app.config['VERSION'] = '1.0.0-test'
|
||||
return app
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
Tests for OIDC admin login (starpunk/auth.py, v2.0.0)
|
||||
"""
|
||||
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from starpunk import auth
|
||||
from starpunk.auth import (
|
||||
InvalidStateError,
|
||||
OIDCError,
|
||||
UnauthorizedError,
|
||||
_pkce_challenge,
|
||||
handle_callback,
|
||||
initiate_login,
|
||||
verify_session,
|
||||
)
|
||||
|
||||
ISSUER = "https://id.example.com"
|
||||
CLIENT_ID = "starpunk-client"
|
||||
ADMIN_SUB = "admin-sub-123"
|
||||
|
||||
METADATA = {
|
||||
"issuer": ISSUER,
|
||||
"authorization_endpoint": f"{ISSUER}/authorize",
|
||||
"token_endpoint": f"{ISSUER}/api/oidc/token",
|
||||
"jwks_uri": f"{ISSUER}/.well-known/jwks.json",
|
||||
"id_token_signing_alg_values_supported": ["RS256"],
|
||||
}
|
||||
|
||||
PRIVATE_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
OTHER_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path):
|
||||
from starpunk import create_app
|
||||
|
||||
data = tmp_path / "data"
|
||||
return create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"SITE_URL": "https://blog.example.com",
|
||||
"ADMIN_ME": "https://example.com",
|
||||
"SESSION_SECRET": "test-secret",
|
||||
"DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "starpunk.db",
|
||||
"OIDC_ISSUER": ISSUER,
|
||||
"OIDC_CLIENT_ID": CLIENT_ID,
|
||||
"OIDC_CLIENT_SECRET": "secret",
|
||||
"OIDC_ADMIN_SUB": ADMIN_SUB,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def provider():
|
||||
"""Fake identity provider: discovery, JWKS key and token endpoint"""
|
||||
auth._METADATA_CACHE.clear()
|
||||
metadata_response = MagicMock(status_code=200)
|
||||
metadata_response.json.return_value = METADATA
|
||||
metadata_response.raise_for_status.return_value = None
|
||||
with patch("starpunk.auth.httpx.get", return_value=metadata_response) as get, patch(
|
||||
"starpunk.auth._get_signing_key", return_value=PRIVATE_KEY.public_key()
|
||||
), patch("starpunk.auth.httpx.post") as post, patch(
|
||||
"starpunk.author_discovery.get_author_profile"
|
||||
):
|
||||
yield {"get": get, "post": post}
|
||||
|
||||
|
||||
def make_id_token(nonce, sub=ADMIN_SUB, aud=CLIENT_ID, iss=ISSUER, key=PRIVATE_KEY, exp_in=300):
|
||||
now = int(time.time())
|
||||
claims = {"iss": iss, "aud": aud, "sub": sub, "iat": now, "exp": now + exp_in, "nonce": nonce}
|
||||
return jwt.encode(claims, key, algorithm="RS256")
|
||||
|
||||
|
||||
def start_login(app, next_url=None):
|
||||
"""Run initiate_login and return (state, nonce) from the stored row"""
|
||||
with app.test_request_context():
|
||||
url = initiate_login(next_url)
|
||||
query = parse_qs(urlparse(url).query)
|
||||
return query["state"][0], query["nonce"][0], query
|
||||
|
||||
|
||||
def token_response(provider, id_token, status=200):
|
||||
response = MagicMock(status_code=status, text="")
|
||||
response.json.return_value = {"id_token": id_token, "access_token": "x"}
|
||||
provider["post"].return_value = response
|
||||
|
||||
|
||||
class TestInitiateLogin:
|
||||
def test_redirects_to_provider_with_pkce(self, app):
|
||||
with app.test_request_context():
|
||||
url = initiate_login()
|
||||
parsed = urlparse(url)
|
||||
query = parse_qs(parsed.query)
|
||||
assert f"{parsed.scheme}://{parsed.netloc}{parsed.path}" == METADATA["authorization_endpoint"]
|
||||
assert query["client_id"] == [CLIENT_ID]
|
||||
assert query["redirect_uri"] == ["https://blog.example.com/auth/callback"]
|
||||
assert query["response_type"] == ["code"]
|
||||
assert query["scope"] == ["openid"]
|
||||
assert query["code_challenge_method"] == ["S256"]
|
||||
assert query["state"][0] and query["nonce"][0]
|
||||
|
||||
def test_stores_verifier_matching_challenge(self, app):
|
||||
state, _, query = start_login(app)
|
||||
from starpunk.database import get_db
|
||||
|
||||
with app.app_context():
|
||||
row = get_db(app).execute(
|
||||
"SELECT code_verifier FROM oidc_login_state WHERE state = ?", (state,)
|
||||
).fetchone()
|
||||
assert _pkce_challenge(row["code_verifier"]) == query["code_challenge"][0]
|
||||
|
||||
def test_rejects_offsite_next_url(self, app):
|
||||
state, _, _ = start_login(app, "https://evil.example/steal")
|
||||
from starpunk.database import get_db
|
||||
|
||||
with app.app_context():
|
||||
row = get_db(app).execute(
|
||||
"SELECT next_url FROM oidc_login_state WHERE state = ?", (state,)
|
||||
).fetchone()
|
||||
assert row["next_url"] is None
|
||||
|
||||
def test_issuer_mismatch_fails(self, app, provider):
|
||||
provider["get"].return_value.json.return_value = {**METADATA, "issuer": "https://other"}
|
||||
with app.test_request_context(), pytest.raises(OIDCError):
|
||||
initiate_login()
|
||||
|
||||
|
||||
class TestHandleCallback:
|
||||
def test_success_creates_admin_session(self, app, provider):
|
||||
state, nonce, _ = start_login(app, "/admin/new")
|
||||
token_response(provider, make_id_token(nonce))
|
||||
|
||||
with app.test_request_context():
|
||||
session_token, next_url = handle_callback("code", state, ISSUER)
|
||||
assert verify_session(session_token)["me"] == "https://example.com"
|
||||
assert next_url == "/admin/new"
|
||||
|
||||
sent = provider["post"].call_args
|
||||
assert sent.kwargs["data"]["grant_type"] == "authorization_code"
|
||||
assert sent.kwargs["data"]["code_verifier"]
|
||||
assert sent.kwargs["auth"] == (CLIENT_ID, "secret")
|
||||
|
||||
def test_state_is_single_use(self, app, provider):
|
||||
state, nonce, _ = start_login(app)
|
||||
token_response(provider, make_id_token(nonce))
|
||||
with app.test_request_context():
|
||||
handle_callback("code", state)
|
||||
with pytest.raises(InvalidStateError):
|
||||
handle_callback("code", state)
|
||||
|
||||
def test_unknown_state(self, app):
|
||||
with app.test_request_context(), pytest.raises(InvalidStateError):
|
||||
handle_callback("code", "nope")
|
||||
|
||||
def test_wrong_subject_is_unauthorized(self, app, provider):
|
||||
state, nonce, _ = start_login(app)
|
||||
token_response(provider, make_id_token(nonce, sub="someone-else"))
|
||||
with app.test_request_context(), pytest.raises(UnauthorizedError):
|
||||
handle_callback("code", state)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs",
|
||||
[
|
||||
{"aud": "another-client"},
|
||||
{"iss": "https://evil.example"},
|
||||
{"key": OTHER_KEY},
|
||||
{"exp_in": -3600},
|
||||
],
|
||||
)
|
||||
def test_invalid_id_token_rejected(self, app, provider, kwargs):
|
||||
state, nonce, _ = start_login(app)
|
||||
token_response(provider, make_id_token(nonce, **kwargs))
|
||||
with app.test_request_context(), pytest.raises(OIDCError):
|
||||
handle_callback("code", state)
|
||||
|
||||
def test_nonce_mismatch_rejected(self, app, provider):
|
||||
state, _, _ = start_login(app)
|
||||
token_response(provider, make_id_token("wrong-nonce"))
|
||||
with app.test_request_context(), pytest.raises(OIDCError):
|
||||
handle_callback("code", state)
|
||||
|
||||
def test_callback_issuer_mismatch_rejected(self, app, provider):
|
||||
state, nonce, _ = start_login(app)
|
||||
token_response(provider, make_id_token(nonce))
|
||||
with app.test_request_context(), pytest.raises(OIDCError):
|
||||
handle_callback("code", state, "https://evil.example")
|
||||
|
||||
def test_token_endpoint_error(self, app, provider):
|
||||
state, _, _ = start_login(app)
|
||||
token_response(provider, None, status=400)
|
||||
with app.test_request_context(), pytest.raises(OIDCError):
|
||||
handle_callback("code", state)
|
||||
|
||||
|
||||
class TestRoutes:
|
||||
def test_login_page_shows_sso_button(self, app):
|
||||
response = app.test_client().get("/auth/login")
|
||||
assert response.status_code == 200
|
||||
assert b"Sign in with" in response.data
|
||||
assert b'name="me"' not in response.data
|
||||
|
||||
def test_login_post_redirects_to_provider(self, app):
|
||||
response = app.test_client().post("/auth/login")
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"].startswith(METADATA["authorization_endpoint"])
|
||||
|
||||
def test_callback_sets_cookie_and_returns_to_next(self, app, provider):
|
||||
client = app.test_client()
|
||||
with client.session_transaction() as s:
|
||||
s["next"] = "https://blog.example.com/admin/tokens"
|
||||
login = client.post("/auth/login")
|
||||
query = parse_qs(urlparse(login.headers["Location"]).query)
|
||||
token_response(provider, make_id_token(query["nonce"][0]))
|
||||
|
||||
response = client.get(f"/auth/callback?code=abc&state={query['state'][0]}&iss={ISSUER}")
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"] == "https://blog.example.com/admin/tokens"
|
||||
cookie = response.headers["Set-Cookie"]
|
||||
assert "starpunk_session=" in cookie and "HttpOnly" in cookie and "Secure" in cookie
|
||||
|
||||
def test_callback_wrong_user_gets_no_cookie(self, app, provider):
|
||||
client = app.test_client()
|
||||
login = client.post("/auth/login")
|
||||
query = parse_qs(urlparse(login.headers["Location"]).query)
|
||||
token_response(provider, make_id_token(query["nonce"][0], sub="intruder"))
|
||||
|
||||
response = client.get(f"/auth/callback?code=abc&state={query['state'][0]}")
|
||||
assert response.headers["Location"].endswith("/auth/login")
|
||||
assert "starpunk_session" not in response.headers.get("Set-Cookie", "")
|
||||
|
||||
def test_callback_provider_error(self, app):
|
||||
response = app.test_client().get("/auth/callback?error=access_denied")
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"].endswith("/auth/login")
|
||||
@@ -0,0 +1,329 @@
|
||||
"""
|
||||
Tests for the built-in IndieAuth server (starpunk/indieauth.py, v2.0.0)
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.parse import parse_qs, urlencode, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from starpunk.auth import create_session
|
||||
from starpunk.indieauth import (
|
||||
AuthorizationRequestError,
|
||||
InvalidGrantError,
|
||||
check_scope,
|
||||
create_access_token,
|
||||
create_authorization_code,
|
||||
fetch_client_redirect_uris,
|
||||
redeem_authorization_code,
|
||||
validate_authorization_request,
|
||||
verify_access_token,
|
||||
)
|
||||
|
||||
CLIENT_ID = "https://quill.example/"
|
||||
REDIRECT_URI = "https://quill.example/auth/callback"
|
||||
|
||||
|
||||
def challenge_for(verifier):
|
||||
digest = hashlib.sha256(verifier.encode()).digest()
|
||||
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path):
|
||||
from starpunk import create_app
|
||||
|
||||
data = tmp_path / "data"
|
||||
return create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"SITE_URL": "https://blog.example.com",
|
||||
"ADMIN_ME": "https://example.com",
|
||||
"SESSION_SECRET": "test-secret",
|
||||
"DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "starpunk.db",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
return app.test_client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_client(app):
|
||||
"""Test client with a valid admin session cookie"""
|
||||
client = app.test_client()
|
||||
with app.test_request_context():
|
||||
token = create_session("https://example.com")
|
||||
client.set_cookie("starpunk_session", token)
|
||||
return client
|
||||
|
||||
|
||||
def auth_params(verifier="v" * 50, **overrides):
|
||||
params = {
|
||||
"response_type": "code",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"state": "client-state",
|
||||
"code_challenge": challenge_for(verifier),
|
||||
"code_challenge_method": "S256",
|
||||
"scope": "create media",
|
||||
}
|
||||
params.update(overrides)
|
||||
return params
|
||||
|
||||
|
||||
def approve(admin_client, granted=("create", "media"), **overrides):
|
||||
form = auth_params(**overrides)
|
||||
form["decision"] = "approve"
|
||||
form["scope_granted"] = list(granted)
|
||||
response = admin_client.post("/auth/authorize/approve", data=form)
|
||||
assert response.status_code == 302
|
||||
return parse_qs(urlparse(response.headers["Location"]).query)
|
||||
|
||||
|
||||
class TestValidation:
|
||||
def test_valid_request(self, app):
|
||||
with app.test_request_context():
|
||||
result = validate_authorization_request(auth_params())
|
||||
assert result["scopes"] == ["create", "media"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"overrides",
|
||||
[{"client_id": "not-a-url"}, {"redirect_uri": ""}, {"client_id": "ftp://x.example/"}],
|
||||
)
|
||||
def test_untrusted_client_errors_are_not_redirected(self, app, overrides):
|
||||
with app.test_request_context(), pytest.raises(AuthorizationRequestError) as e:
|
||||
validate_authorization_request(auth_params(**overrides))
|
||||
assert e.value.redirectable is False
|
||||
|
||||
def test_missing_pkce_is_redirectable_error(self, app):
|
||||
with app.test_request_context(), pytest.raises(AuthorizationRequestError) as e:
|
||||
validate_authorization_request(auth_params(code_challenge=""))
|
||||
assert e.value.redirectable is True
|
||||
|
||||
def test_plain_pkce_rejected(self, app):
|
||||
with app.test_request_context(), pytest.raises(AuthorizationRequestError):
|
||||
validate_authorization_request(auth_params(code_challenge_method="plain"))
|
||||
|
||||
def test_cross_origin_redirect_needs_client_registration(self, app):
|
||||
params = auth_params(redirect_uri="https://evil.example/cb")
|
||||
with app.test_request_context(), patch(
|
||||
"starpunk.indieauth.fetch_client_redirect_uris", return_value=[]
|
||||
), pytest.raises(AuthorizationRequestError) as e:
|
||||
validate_authorization_request(params)
|
||||
assert e.value.redirectable is False
|
||||
|
||||
def test_cross_origin_redirect_allowed_when_published(self, app):
|
||||
params = auth_params(redirect_uri="app://callback")
|
||||
with app.test_request_context(), patch(
|
||||
"starpunk.indieauth.fetch_client_redirect_uris", return_value=["app://callback"]
|
||||
):
|
||||
assert validate_authorization_request(params)["redirect_uri"] == "app://callback"
|
||||
|
||||
|
||||
class TestClientMetadata:
|
||||
def _response(self, content_type, body, links=None):
|
||||
response = MagicMock(status_code=200, text=body, url="https://quill.example/")
|
||||
response.headers = {"Content-Type": content_type}
|
||||
response.links = links or {}
|
||||
response.json.return_value = __import__("json").loads(body) if "json" in content_type else None
|
||||
return response
|
||||
|
||||
def test_json_metadata(self, app):
|
||||
body = '{"client_id": "https://quill.example/", "redirect_uris": ["app://cb"]}'
|
||||
with app.test_request_context(), patch(
|
||||
"starpunk.webmention_ssrf.validate_url_for_fetch"
|
||||
), patch("starpunk.indieauth.httpx.get", return_value=self._response("application/json", body)):
|
||||
assert fetch_client_redirect_uris(CLIENT_ID) == ["app://cb"]
|
||||
|
||||
def test_html_link(self, app):
|
||||
body = '<html><head><link rel="redirect_uri" href="/cb"></head></html>'
|
||||
with app.test_request_context(), patch(
|
||||
"starpunk.webmention_ssrf.validate_url_for_fetch"
|
||||
), patch("starpunk.indieauth.httpx.get", return_value=self._response("text/html", body)):
|
||||
assert fetch_client_redirect_uris(CLIENT_ID) == ["https://quill.example/cb"]
|
||||
|
||||
|
||||
class TestCodesAndTokens:
|
||||
def test_full_exchange(self, app):
|
||||
verifier = secrets.token_urlsafe(50)
|
||||
with app.test_request_context():
|
||||
code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for(verifier))
|
||||
result = redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier)
|
||||
assert result == {"me": "https://example.com", "scope": "create", "client_id": CLIENT_ID}
|
||||
|
||||
token = create_access_token(CLIENT_ID, "create")
|
||||
info = verify_access_token(token["access_token"])
|
||||
assert info["me"] == "https://example.com"
|
||||
assert info["scope"] == "create"
|
||||
|
||||
def test_code_single_use(self, app):
|
||||
verifier = "v" * 50
|
||||
with app.test_request_context():
|
||||
code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for(verifier))
|
||||
redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier)
|
||||
with pytest.raises(InvalidGrantError):
|
||||
redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"client_id,redirect_uri,verifier",
|
||||
[
|
||||
("https://other.example/", REDIRECT_URI, "v" * 50),
|
||||
(CLIENT_ID, "https://quill.example/other", "v" * 50),
|
||||
(CLIENT_ID, REDIRECT_URI, "wrong-verifier"),
|
||||
],
|
||||
)
|
||||
def test_code_mismatch_rejected(self, app, client_id, redirect_uri, verifier):
|
||||
with app.test_request_context():
|
||||
code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for("v" * 50))
|
||||
with pytest.raises(InvalidGrantError):
|
||||
redeem_authorization_code(code, client_id, redirect_uri, verifier)
|
||||
|
||||
def test_token_stored_hashed(self, app):
|
||||
from starpunk.database import get_db
|
||||
|
||||
with app.test_request_context():
|
||||
token = create_access_token(CLIENT_ID, "create")["access_token"]
|
||||
rows = get_db(app).execute("SELECT token_hash FROM indieauth_tokens").fetchall()
|
||||
assert token not in [r["token_hash"] for r in rows]
|
||||
|
||||
def test_unknown_token(self, app):
|
||||
with app.test_request_context():
|
||||
assert verify_access_token("nope") is None
|
||||
assert verify_access_token("") is None
|
||||
|
||||
def test_check_scope(self):
|
||||
assert check_scope("create", "create media")
|
||||
assert not check_scope("create", "media")
|
||||
assert not check_scope("create", "")
|
||||
|
||||
|
||||
class TestEndpoints:
|
||||
def test_metadata(self, client):
|
||||
data = client.get("/.well-known/oauth-authorization-server").get_json()
|
||||
assert data["issuer"] == "https://blog.example.com/"
|
||||
assert data["authorization_endpoint"] == "https://blog.example.com/auth/authorize"
|
||||
assert data["token_endpoint"] == "https://blog.example.com/auth/token"
|
||||
assert data["code_challenge_methods_supported"] == ["S256"]
|
||||
|
||||
def test_discovery_links_on_homepage(self, client):
|
||||
html = client.get("/").data.decode()
|
||||
assert 'rel="indieauth-metadata"' in html
|
||||
assert 'rel="micropub"' in html
|
||||
|
||||
def test_authorize_requires_login(self, client):
|
||||
response = client.get("/auth/authorize?" + urlencode(auth_params()))
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"].endswith("/auth/login")
|
||||
with client.session_transaction() as s:
|
||||
assert "/auth/authorize?" in s["next"]
|
||||
|
||||
def test_authorize_shows_consent(self, admin_client):
|
||||
response = admin_client.get("/auth/authorize?" + urlencode(auth_params()))
|
||||
assert response.status_code == 200
|
||||
assert b"quill.example" in response.data
|
||||
assert b'value="create"' in response.data
|
||||
|
||||
def test_authorize_bad_client_shows_error_page(self, admin_client):
|
||||
response = admin_client.get("/auth/authorize?" + urlencode(auth_params(client_id="nope")))
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_approve_requires_login(self, client):
|
||||
response = client.post("/auth/authorize/approve", data={**auth_params(), "decision": "approve"})
|
||||
assert response.headers["Location"].endswith("/auth/login")
|
||||
|
||||
def test_deny(self, admin_client):
|
||||
form = {**auth_params(), "decision": "deny"}
|
||||
query = parse_qs(urlparse(admin_client.post("/auth/authorize/approve", data=form).headers["Location"]).query)
|
||||
assert query["error"] == ["access_denied"]
|
||||
assert query["state"] == ["client-state"]
|
||||
|
||||
def test_full_micropub_flow(self, admin_client, client):
|
||||
verifier = "v" * 50
|
||||
query = approve(admin_client, granted=["create"])
|
||||
assert query["state"] == ["client-state"]
|
||||
assert query["iss"] == ["https://blog.example.com/"]
|
||||
|
||||
response = client.post(
|
||||
"/auth/token",
|
||||
data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": query["code"][0],
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"code_verifier": verifier,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
body = response.get_json()
|
||||
assert body["me"] == "https://example.com"
|
||||
assert body["scope"] == "create" # media was unchecked
|
||||
|
||||
token = body["access_token"]
|
||||
micropub = client.post(
|
||||
"/micropub",
|
||||
data={"h": "entry", "content": "Posted through the built-in IndieAuth server"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert micropub.status_code == 201
|
||||
|
||||
verify = client.get("/auth/token", headers={"Authorization": f"Bearer {token}"})
|
||||
assert verify.get_json()["client_id"] == CLIENT_ID
|
||||
|
||||
client.post("/auth/revoke", data={"token": token})
|
||||
again = client.post(
|
||||
"/micropub",
|
||||
data={"h": "entry", "content": "should fail"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert again.status_code == 401
|
||||
|
||||
def test_profile_only_code_cannot_get_token(self, admin_client, client):
|
||||
query = approve(admin_client, granted=[], scope="")
|
||||
form = {
|
||||
"grant_type": "authorization_code",
|
||||
"code": query["code"][0],
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"code_verifier": "v" * 50,
|
||||
}
|
||||
assert client.post("/auth/token", data=form).get_json()["error"] == "invalid_grant"
|
||||
|
||||
def test_profile_only_redemption(self, admin_client, client):
|
||||
query = approve(admin_client, granted=[], scope="")
|
||||
response = client.post(
|
||||
"/auth/authorize",
|
||||
data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": query["code"][0],
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"code_verifier": "v" * 50,
|
||||
},
|
||||
)
|
||||
assert response.get_json() == {"me": "https://example.com"}
|
||||
|
||||
def test_unsupported_grant(self, client):
|
||||
assert client.post("/auth/token", data={"grant_type": "password"}).status_code == 400
|
||||
|
||||
def test_admin_can_list_and_revoke(self, app, admin_client):
|
||||
with app.test_request_context():
|
||||
token = create_access_token(CLIENT_ID, "create")["access_token"]
|
||||
page = admin_client.get("/admin/tokens")
|
||||
assert page.status_code == 200 and b"quill.example" in page.data
|
||||
|
||||
from starpunk.database import get_db
|
||||
|
||||
with app.app_context():
|
||||
token_id = get_db(app).execute("SELECT id FROM indieauth_tokens").fetchone()["id"]
|
||||
admin_client.post(f"/admin/tokens/{token_id}/revoke")
|
||||
with app.test_request_context():
|
||||
assert verify_access_token(token) is None
|
||||
+14
-14
@@ -69,7 +69,7 @@ def test_micropub_no_token(client):
|
||||
|
||||
def test_micropub_invalid_token(client, mock_invalid_token):
|
||||
"""Test Micropub endpoint rejects invalid tokens"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_invalid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_invalid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
data={'h': 'entry', 'content': 'Test post'},
|
||||
@@ -84,7 +84,7 @@ def test_micropub_invalid_token(client, mock_invalid_token):
|
||||
|
||||
def test_micropub_insufficient_scope(client, mock_read_only_token):
|
||||
"""Test Micropub endpoint rejects token without create scope"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_read_only_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_read_only_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
data={'h': 'entry', 'content': 'Test post'},
|
||||
@@ -101,7 +101,7 @@ def test_micropub_insufficient_scope(client, mock_read_only_token):
|
||||
|
||||
def test_micropub_create_note_form(client, app, mock_valid_token):
|
||||
"""Test creating a note via form-encoded request"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
data={
|
||||
@@ -126,7 +126,7 @@ def test_micropub_create_note_form(client, app, mock_valid_token):
|
||||
|
||||
def test_micropub_create_note_json(client, app, mock_valid_token):
|
||||
"""Test creating a note via JSON request"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
json={
|
||||
@@ -150,7 +150,7 @@ def test_micropub_create_note_json(client, app, mock_valid_token):
|
||||
|
||||
def test_micropub_create_with_name(client, app, mock_valid_token):
|
||||
"""Test creating a note with a title (name property)"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
json={
|
||||
@@ -170,7 +170,7 @@ def test_micropub_create_with_name(client, app, mock_valid_token):
|
||||
|
||||
def test_micropub_create_with_categories(client, app, mock_valid_token):
|
||||
"""Test creating a note with tags (category property)"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
json={
|
||||
@@ -190,7 +190,7 @@ def test_micropub_create_with_categories(client, app, mock_valid_token):
|
||||
|
||||
def test_micropub_create_with_custom_slug_form(client, app, mock_valid_token):
|
||||
"""Test creating a note with custom slug via form-encoded request"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
data={
|
||||
@@ -206,7 +206,7 @@ def test_micropub_create_with_custom_slug_form(client, app, mock_valid_token):
|
||||
|
||||
# Verify the custom slug was used
|
||||
location = response.headers['Location']
|
||||
assert location.endswith('/notes/my-custom-slug')
|
||||
assert location.endswith('/note/my-custom-slug')
|
||||
|
||||
# Verify note exists with the custom slug
|
||||
with app.app_context():
|
||||
@@ -218,7 +218,7 @@ def test_micropub_create_with_custom_slug_form(client, app, mock_valid_token):
|
||||
|
||||
def test_micropub_create_with_custom_slug_json(client, app, mock_valid_token):
|
||||
"""Test creating a note with custom slug via JSON request"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
json={
|
||||
@@ -236,7 +236,7 @@ def test_micropub_create_with_custom_slug_json(client, app, mock_valid_token):
|
||||
|
||||
# Verify the custom slug was used
|
||||
location = response.headers['Location']
|
||||
assert location.endswith('/notes/json-custom-slug')
|
||||
assert location.endswith('/note/json-custom-slug')
|
||||
|
||||
# Verify note exists with the custom slug
|
||||
with app.app_context():
|
||||
@@ -251,7 +251,7 @@ def test_micropub_create_with_custom_slug_json(client, app, mock_valid_token):
|
||||
|
||||
def test_micropub_query_config(client, mock_valid_token):
|
||||
"""Test q=config endpoint"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.get(
|
||||
'/micropub?q=config',
|
||||
headers={'Authorization': 'Bearer valid_token'}
|
||||
@@ -266,7 +266,7 @@ def test_micropub_query_config(client, mock_valid_token):
|
||||
|
||||
def test_micropub_query_source(client, mock_valid_token):
|
||||
"""Test q=source endpoint"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
# First create a note
|
||||
create_response = client.post(
|
||||
'/micropub',
|
||||
@@ -297,7 +297,7 @@ def test_micropub_query_source(client, mock_valid_token):
|
||||
|
||||
def test_micropub_missing_content(client, mock_valid_token):
|
||||
"""Test creating note without content fails"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
json={
|
||||
@@ -314,7 +314,7 @@ def test_micropub_missing_content(client, mock_valid_token):
|
||||
|
||||
def test_micropub_unsupported_action(client, mock_valid_token):
|
||||
"""Test unsupported actions (update, delete) return error"""
|
||||
with patch('starpunk.routes.micropub.verify_external_token', mock_valid_token):
|
||||
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
|
||||
# Test update
|
||||
response = client.post(
|
||||
'/micropub',
|
||||
|
||||
@@ -220,8 +220,8 @@ def test_search_api_generates_correct_urls(client, test_notes):
|
||||
|
||||
if data["count"] > 0:
|
||||
result = data["results"][0]
|
||||
assert result["url"].startswith("/notes/")
|
||||
assert result["url"] == f"/notes/{result['slug']}"
|
||||
assert result["url"].startswith("/note/")
|
||||
assert result["url"] == f"/note/{result['slug']}"
|
||||
|
||||
|
||||
def test_search_api_provides_fallback_title(client, app):
|
||||
|
||||
@@ -185,8 +185,8 @@ def test_search_page_links_to_notes(client, test_notes):
|
||||
response = client.get("/search?q=test")
|
||||
assert response.status_code == 200
|
||||
|
||||
# Should contain links to /notes/
|
||||
assert b'href="/notes/' in response.data
|
||||
# Should contain links to /note/
|
||||
assert b'href="/note/' in response.data
|
||||
|
||||
|
||||
def test_search_form_validation(client):
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
"""
|
||||
Tests for crossposting to GoToSocial (starpunk/syndication.py, v2.1.0)
|
||||
|
||||
A fake Mastodon-API server (httpx.MockTransport) records what StarPunk sends.
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from starpunk import create_app, syndication
|
||||
from starpunk.auth import create_session
|
||||
from starpunk.indieauth import create_access_token
|
||||
from starpunk.notes import create_note, delete_note, update_note
|
||||
from starpunk.syndication import (
|
||||
MastodonClient,
|
||||
compose_text,
|
||||
get_note_syndications,
|
||||
note_changed,
|
||||
process_due,
|
||||
select_targets,
|
||||
)
|
||||
|
||||
GTS = "https://social.example.com"
|
||||
|
||||
|
||||
class FakeServer:
|
||||
def __init__(self):
|
||||
self.statuses = {}
|
||||
self.calls = []
|
||||
self.media = 0
|
||||
self.fail_next = None # status code to return once
|
||||
|
||||
def __call__(self, request: httpx.Request) -> httpx.Response:
|
||||
self.calls.append((request.method, request.url.path))
|
||||
assert request.headers["Authorization"] == "Bearer secret-token"
|
||||
if self.fail_next:
|
||||
code, self.fail_next = self.fail_next, None
|
||||
return httpx.Response(code, json={"error": "nope"})
|
||||
path = request.url.path
|
||||
if path == "/api/v2/media":
|
||||
self.media += 1
|
||||
return httpx.Response(200, json={"id": f"m{self.media}"})
|
||||
if path == "/api/v1/statuses" and request.method == "POST":
|
||||
body = json.loads(request.content)
|
||||
sid = str(len(self.statuses) + 1)
|
||||
self.statuses[sid] = body
|
||||
return httpx.Response(200, json={"id": sid, "url": f"{GTS}/@phil/statuses/{sid}"})
|
||||
if path.startswith("/api/v1/statuses/"):
|
||||
sid = path.rsplit("/", 1)[1]
|
||||
if sid not in self.statuses:
|
||||
return httpx.Response(404, json={"error": "not found"})
|
||||
if request.method == "PUT":
|
||||
self.statuses[sid] = json.loads(request.content)
|
||||
return httpx.Response(200, json={"id": sid, "url": f"{GTS}/@phil/statuses/{sid}"})
|
||||
if request.method == "DELETE":
|
||||
del self.statuses[sid]
|
||||
return httpx.Response(200, json={"id": sid})
|
||||
return httpx.Response(500)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server():
|
||||
return FakeServer()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path, server):
|
||||
data = tmp_path / "data"
|
||||
app = create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"SITE_URL": "https://blog.example.com",
|
||||
"ADMIN_ME": "https://example.com",
|
||||
"SESSION_SECRET": "test-secret",
|
||||
"DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "starpunk.db",
|
||||
"GOTOSOCIAL_URL": GTS,
|
||||
"GOTOSOCIAL_ACCESS_TOKEN": "secret-token",
|
||||
}
|
||||
)
|
||||
syndication._client_cache[GTS] = MastodonClient(
|
||||
GTS, "secret-token", http=httpx.Client(transport=httpx.MockTransport(server))
|
||||
)
|
||||
yield app
|
||||
syndication._client_cache.clear()
|
||||
|
||||
|
||||
def rows(app, note_id):
|
||||
with app.app_context():
|
||||
return get_note_syndications(note_id)
|
||||
|
||||
|
||||
def publish(app, content="Hello fediverse", tags=None, targets=("gotosocial",)):
|
||||
with app.test_request_context():
|
||||
note = create_note(content=content, published=True, tags=tags)
|
||||
select_targets(note.id, list(targets))
|
||||
process_due()
|
||||
return note
|
||||
|
||||
|
||||
class TestCompose:
|
||||
def test_full_note_with_link_and_hashtags(self, app):
|
||||
with app.app_context():
|
||||
note = create_note(content="# Title\n\nSome *markdown*", published=True)
|
||||
text = compose_text(note, "https://blog.example.com/note/x", ["IndieWeb", "Self Hosting"], 5000)
|
||||
assert text == "# Title\n\nSome *markdown*\n\nhttps://blog.example.com/note/x\n\n#IndieWeb #SelfHosting"
|
||||
|
||||
def test_long_note_is_shortened_but_keeps_link(self, app):
|
||||
with app.app_context():
|
||||
note = create_note(content="word " * 2000, published=True)
|
||||
text = compose_text(note, "https://blog.example.com/note/x", [], 500)
|
||||
assert len(text) <= 500
|
||||
assert text.endswith("https://blog.example.com/note/x")
|
||||
assert "…" in text
|
||||
|
||||
|
||||
class TestLifecycle:
|
||||
def test_publish_creates_status(self, app, server):
|
||||
note = publish(app, tags=["Test"])
|
||||
(row,) = rows(app, note.id)
|
||||
assert row["state"] == "synced"
|
||||
assert row["remote_url"] == f"{GTS}/@phil/statuses/1"
|
||||
body = server.statuses["1"]
|
||||
assert body["content_type"] == "text/markdown"
|
||||
assert body["visibility"] == "public"
|
||||
assert f"https://blog.example.com/note/{note.slug}" in body["status"]
|
||||
assert "#Test" in body["status"]
|
||||
|
||||
def test_edit_updates_status(self, app, server):
|
||||
note = publish(app)
|
||||
with app.test_request_context():
|
||||
update_note(id=note.id, content="Edited text")
|
||||
process_due()
|
||||
assert server.statuses["1"]["status"].startswith("Edited text")
|
||||
assert ("PUT", "/api/v1/statuses/1") in server.calls
|
||||
|
||||
def test_delete_deletes_status(self, app, server):
|
||||
note = publish(app)
|
||||
with app.test_request_context():
|
||||
delete_note(id=note.id)
|
||||
process_due()
|
||||
assert server.statuses == {}
|
||||
(row,) = rows(app, note.id)
|
||||
assert row["remote_id"] is None and row["state"] == "synced"
|
||||
|
||||
def test_hard_delete_deletes_status(self, app, server):
|
||||
note = publish(app)
|
||||
with app.test_request_context():
|
||||
delete_note(id=note.id, soft=False)
|
||||
process_due()
|
||||
assert server.statuses == {}
|
||||
|
||||
def test_unpublish_then_republish(self, app, server):
|
||||
note = publish(app)
|
||||
with app.test_request_context():
|
||||
update_note(id=note.id, published=False)
|
||||
process_due()
|
||||
assert server.statuses == {}
|
||||
update_note(id=note.id, published=True)
|
||||
process_due()
|
||||
assert len(server.statuses) == 1
|
||||
|
||||
def test_opt_out_sends_nothing(self, app, server):
|
||||
note = publish(app, targets=())
|
||||
assert server.calls == []
|
||||
assert rows(app, note.id) == []
|
||||
|
||||
def test_unticking_later_deletes_status(self, app, server):
|
||||
note = publish(app)
|
||||
with app.test_request_context():
|
||||
select_targets(note.id, [])
|
||||
process_due()
|
||||
assert server.statuses == {}
|
||||
|
||||
def test_drafts_are_not_sent(self, app, server):
|
||||
with app.test_request_context():
|
||||
note = create_note(content="draft", published=False)
|
||||
select_targets(note.id, ["gotosocial"])
|
||||
process_due()
|
||||
assert server.statuses == {}
|
||||
|
||||
def test_remote_deleted_by_hand_is_reposted_on_edit(self, app, server):
|
||||
note = publish(app)
|
||||
server.statuses.clear()
|
||||
with app.test_request_context():
|
||||
note_changed(note.id)
|
||||
process_due()
|
||||
assert len(server.statuses) == 1
|
||||
|
||||
def test_edit_during_send_is_not_lost(self, app, server):
|
||||
with app.test_request_context():
|
||||
note = create_note(content="v1", published=True)
|
||||
select_targets(note.id, ["gotosocial"])
|
||||
# Simulate an edit arriving while the first send is in flight
|
||||
original = syndication._reconcile
|
||||
|
||||
def edit_mid_send(row, target):
|
||||
result = original(row, target)
|
||||
update_note(id=note.id, content="v2")
|
||||
return result
|
||||
|
||||
syndication._reconcile = edit_mid_send
|
||||
try:
|
||||
process_due()
|
||||
finally:
|
||||
syndication._reconcile = original
|
||||
assert rows(app, note.id)[0]["state"] == "pending"
|
||||
process_due()
|
||||
assert server.statuses["1"]["status"].startswith("v2")
|
||||
|
||||
|
||||
class TestFailures:
|
||||
def test_server_error_retries_later(self, app, server):
|
||||
server.fail_next = 503
|
||||
note = publish(app)
|
||||
(row,) = rows(app, note.id)
|
||||
assert row["state"] == "pending"
|
||||
assert row["attempts"] == 1
|
||||
assert "503" in row["last_error"]
|
||||
|
||||
def test_client_error_fails_permanently(self, app, server):
|
||||
server.fail_next = 422
|
||||
note = publish(app)
|
||||
(row,) = rows(app, note.id)
|
||||
assert row["state"] == "failed"
|
||||
|
||||
def test_retry_button(self, app, server):
|
||||
server.fail_next = 422
|
||||
note = publish(app)
|
||||
(row,) = rows(app, note.id)
|
||||
client = app.test_client()
|
||||
with app.test_request_context():
|
||||
client.set_cookie("starpunk_session", create_session("https://example.com"))
|
||||
client.post(f"/admin/syndication/{row['id']}/retry")
|
||||
with app.test_request_context():
|
||||
process_due()
|
||||
assert rows(app, note.id)[0]["state"] == "synced"
|
||||
|
||||
def test_no_targets_configured_does_nothing(self, tmp_path):
|
||||
data = tmp_path / "d"
|
||||
app = create_app({
|
||||
"TESTING": True, "SITE_URL": "https://b.example", "ADMIN_ME": "https://e.example",
|
||||
"SESSION_SECRET": "x", "DATA_PATH": data, "NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "s.db",
|
||||
})
|
||||
with app.test_request_context():
|
||||
note = create_note(content="x", published=True)
|
||||
select_targets(note.id, ["gotosocial"])
|
||||
assert process_due() == 0
|
||||
assert get_note_syndications(note.id) == []
|
||||
|
||||
|
||||
class TestMedia:
|
||||
def test_images_are_uploaded_with_alt_text(self, app, server):
|
||||
from starpunk.media import attach_media_to_note, save_media
|
||||
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (800, 600), "red").save(buf, format="JPEG")
|
||||
with app.test_request_context():
|
||||
note = create_note(content="With a picture", published=True)
|
||||
media = save_media(buf.getvalue(), "red.jpg")
|
||||
attach_media_to_note(note.id, [media["id"]], ["A red square"])
|
||||
select_targets(note.id, ["gotosocial"])
|
||||
process_due()
|
||||
assert ("POST", "/api/v2/media") in server.calls
|
||||
assert server.statuses["1"]["media_ids"] == ["m1"]
|
||||
|
||||
|
||||
class TestEntryPoints:
|
||||
@pytest.fixture
|
||||
def admin(self, app):
|
||||
client = app.test_client()
|
||||
with app.test_request_context():
|
||||
client.set_cookie("starpunk_session", create_session("https://example.com"))
|
||||
return client
|
||||
|
||||
def test_new_note_form_ticks_target_by_default(self, admin):
|
||||
html = admin.get("/admin/new").data.decode()
|
||||
assert 'name="syndicate_to" value="gotosocial" checked' in html
|
||||
|
||||
def test_admin_create_queues(self, app, admin):
|
||||
admin.post("/admin/new", data={
|
||||
"content": "From the editor", "published": "on",
|
||||
"syndication_form": "1", "syndicate_to": "gotosocial",
|
||||
})
|
||||
with app.app_context():
|
||||
from starpunk.database import get_db
|
||||
assert get_db(app).execute("SELECT COUNT(*) FROM syndications").fetchone()[0] == 1
|
||||
|
||||
def test_admin_create_opt_out(self, app, admin):
|
||||
admin.post("/admin/new", data={"content": "Not this one", "published": "on", "syndication_form": "1"})
|
||||
with app.app_context():
|
||||
from starpunk.database import get_db
|
||||
assert get_db(app).execute("SELECT COUNT(*) FROM syndications").fetchone()[0] == 0
|
||||
|
||||
def _token(self, app):
|
||||
with app.test_request_context():
|
||||
return create_access_token("https://quill.example/", "create")["access_token"]
|
||||
|
||||
def test_micropub_lists_target(self, app):
|
||||
token = self._token(app)
|
||||
data = app.test_client().get(
|
||||
"/micropub?q=syndicate-to", headers={"Authorization": f"Bearer {token}"}
|
||||
).get_json()
|
||||
assert data["syndicate-to"] == [{"uid": f"{GTS}/", "name": "GoToSocial"}]
|
||||
|
||||
def test_micropub_default_is_all_targets(self, app):
|
||||
token = self._token(app)
|
||||
response = app.test_client().post(
|
||||
"/micropub", data={"h": "entry", "content": "via quill"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
assert "/note/" in response.headers["Location"]
|
||||
assert response.headers["Location"].startswith("https://blog.example.com/note/")
|
||||
with app.app_context():
|
||||
from starpunk.database import get_db
|
||||
assert get_db(app).execute("SELECT COUNT(*) FROM syndications").fetchone()[0] == 1
|
||||
|
||||
def test_micropub_explicit_empty_choice(self, app):
|
||||
token = self._token(app)
|
||||
app.test_client().post(
|
||||
"/micropub", json={"type": ["h-entry"], "properties": {"content": ["no crosspost"]},
|
||||
"mp-syndicate-to": []},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
with app.app_context():
|
||||
from starpunk.database import get_db
|
||||
assert get_db(app).execute("SELECT COUNT(*) FROM syndications").fetchone()[0] == 0
|
||||
|
||||
def test_note_page_links_to_crosspost(self, app, server):
|
||||
note = publish(app)
|
||||
html = app.test_client().get(f"/note/{note.slug}").data.decode()
|
||||
assert f'class="u-syndication" href="{GTS}/@phil/statuses/1"' in html
|
||||
|
||||
def test_edit_page_shows_status_and_separate_delete_form(self, app, admin, server):
|
||||
note = publish(app)
|
||||
html = admin.get(f"/admin/edit/{note.id}").data.decode()
|
||||
assert 'value="gotosocial" checked' in html
|
||||
assert f"{GTS}/@phil/statuses/1" in html
|
||||
# Delete button belongs to its own form, not the edit form
|
||||
assert 'form="delete-note-form"' in html
|
||||
edit_form = html.split('class="note-form"', 1)[1].split("</form>", 1)[0]
|
||||
assert "<form" not in edit_form
|
||||
@@ -0,0 +1,274 @@
|
||||
"""
|
||||
Tests for crossposting to Bluesky (starpunk/syndication.py, v2.2.0)
|
||||
|
||||
A fake PDS (httpx.MockTransport) records what StarPunk sends.
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from starpunk import create_app, syndication
|
||||
from starpunk.notes import create_note, delete_note, update_note
|
||||
from starpunk.syndication import (
|
||||
BlueskyClient,
|
||||
bluesky_facets,
|
||||
get_note_syndications,
|
||||
plain_text,
|
||||
process_due,
|
||||
select_targets,
|
||||
)
|
||||
|
||||
SERVICE = "https://bsky.example"
|
||||
PDS = "https://pds.example"
|
||||
DID = "did:plc:abc123"
|
||||
|
||||
|
||||
class FakePDS:
|
||||
def __init__(self):
|
||||
self.records = {}
|
||||
self.blobs = []
|
||||
self.calls = []
|
||||
self.logins = 0
|
||||
self.expire_next = False
|
||||
self.lose_next_reply = False
|
||||
self.fail_next = None
|
||||
|
||||
def _json(self, code, body):
|
||||
return httpx.Response(code, json=body)
|
||||
|
||||
def __call__(self, request: httpx.Request) -> httpx.Response:
|
||||
nsid = request.url.path.removeprefix("/xrpc/")
|
||||
self.calls.append((request.url.host, nsid))
|
||||
if nsid == "com.atproto.server.createSession":
|
||||
body = json.loads(request.content)
|
||||
if body["password"] != "app-pass":
|
||||
return self._json(401, {"error": "AuthenticationRequired"})
|
||||
self.logins += 1
|
||||
return self._json(200, {
|
||||
"did": DID, "handle": "phil.example", "accessJwt": f"access{self.logins}",
|
||||
"refreshJwt": "refresh",
|
||||
"didDoc": {"service": [{"id": "#atproto_pds", "serviceEndpoint": PDS}]},
|
||||
})
|
||||
if nsid == "com.atproto.server.refreshSession":
|
||||
self.logins += 1
|
||||
return self._json(200, {"did": DID, "handle": "phil.example",
|
||||
"accessJwt": f"access{self.logins}", "refreshJwt": "refresh"})
|
||||
assert request.url.host == "pds.example"
|
||||
if request.headers.get("Authorization") != f"Bearer access{self.logins}" or self.expire_next:
|
||||
self.expire_next = False
|
||||
return self._json(400, {"error": "ExpiredToken"})
|
||||
if self.fail_next:
|
||||
code, self.fail_next = self.fail_next, None
|
||||
return self._json(code, {"error": "Nope"})
|
||||
if nsid == "com.atproto.repo.uploadBlob":
|
||||
self.blobs.append(len(request.content))
|
||||
assert len(request.content) <= 1_000_000
|
||||
return self._json(200, {"blob": {"$type": "blob", "ref": {"$link": f"b{len(self.blobs)}"},
|
||||
"mimeType": request.headers["Content-Type"],
|
||||
"size": len(request.content)}})
|
||||
if nsid == "com.atproto.repo.createRecord":
|
||||
body = json.loads(request.content)
|
||||
uri = f"at://{DID}/app.bsky.feed.post/r{len(self.records) + 1}"
|
||||
self.records[uri] = body["record"]
|
||||
if self.lose_next_reply:
|
||||
self.lose_next_reply = False
|
||||
raise httpx.ReadTimeout("lost reply")
|
||||
return self._json(200, {"uri": uri, "cid": "c"})
|
||||
if nsid == "com.atproto.repo.listRecords":
|
||||
return self._json(200, {"records": [{"uri": u, "value": v} for u, v in self.records.items()]})
|
||||
if nsid == "com.atproto.repo.deleteRecord":
|
||||
body = json.loads(request.content)
|
||||
self.records.pop(f"at://{body['repo']}/{body['collection']}/{body['rkey']}", None)
|
||||
return self._json(200, {})
|
||||
return self._json(500, {"error": "unknown"})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pds():
|
||||
return FakePDS()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path, pds):
|
||||
data = tmp_path / "data"
|
||||
app = create_app({
|
||||
"TESTING": True,
|
||||
"SITE_URL": "https://blog.example.com",
|
||||
"ADMIN_ME": "https://example.com",
|
||||
"SESSION_SECRET": "test-secret",
|
||||
"DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "starpunk.db",
|
||||
"BLUESKY_HANDLE": "phil.example",
|
||||
"BLUESKY_APP_PASSWORD": "app-pass",
|
||||
"BLUESKY_SERVICE": SERVICE,
|
||||
})
|
||||
syndication._client_cache[f"bluesky:{SERVICE}:phil.example"] = BlueskyClient(
|
||||
SERVICE, "phil.example", "app-pass", http=httpx.Client(transport=httpx.MockTransport(pds))
|
||||
)
|
||||
yield app
|
||||
syndication._client_cache.clear()
|
||||
|
||||
|
||||
def publish(app, content="Hello Bluesky", tags=None):
|
||||
with app.test_request_context():
|
||||
note = create_note(content=content, published=True, tags=tags)
|
||||
select_targets(note.id, ["bluesky"])
|
||||
process_due()
|
||||
return note
|
||||
|
||||
|
||||
def only_record(pds):
|
||||
(record,) = pds.records.values()
|
||||
return record
|
||||
|
||||
|
||||
def row(app, note):
|
||||
with app.app_context():
|
||||
(r,) = get_note_syndications(note.id)
|
||||
return r
|
||||
|
||||
|
||||
class TestText:
|
||||
def test_markdown_becomes_plain_text(self):
|
||||
md = "# Title\n\nSome *emphasis* and a [link](https://x.example).\n\n- one\n- two\n\n"
|
||||
assert plain_text(md) == "Title\n\nSome emphasis and a link.\n\n• one\n• two"
|
||||
|
||||
def test_facets_use_utf8_byte_offsets(self):
|
||||
text = "Café ☕ https://blog.example.com/note/x #IndieWeb"
|
||||
link, tag = bluesky_facets(text)
|
||||
raw = text.encode()
|
||||
assert raw[link["index"]["byteStart"]:link["index"]["byteEnd"]] == b"https://blog.example.com/note/x"
|
||||
assert raw[tag["index"]["byteStart"]:tag["index"]["byteEnd"]] == b"#IndieWeb"
|
||||
assert tag["features"][0]["tag"] == "IndieWeb"
|
||||
|
||||
def test_fragment_in_url_is_not_a_tag(self):
|
||||
facets = bluesky_facets("see https://x.example/page#section and #42 too")
|
||||
assert [f["features"][0]["$type"] for f in facets] == ["app.bsky.richtext.facet#link"]
|
||||
|
||||
|
||||
class TestLifecycle:
|
||||
def test_publish_posts_with_link_card(self, app, pds):
|
||||
note = publish(app, content="Hello **Bluesky**", tags=["IndieWeb"])
|
||||
record = only_record(pds)
|
||||
permalink = f"https://blog.example.com/note/{note.slug}"
|
||||
assert record["text"] == f"Hello Bluesky\n\n{permalink}\n\n#IndieWeb"
|
||||
assert record["embed"]["external"]["uri"] == permalink
|
||||
kinds = {f["features"][0]["$type"] for f in record["facets"]}
|
||||
assert kinds == {"app.bsky.richtext.facet#link", "app.bsky.richtext.facet#tag"}
|
||||
r = row(app, note)
|
||||
assert r["state"] == "synced"
|
||||
assert r["remote_id"] == f"at://{DID}/app.bsky.feed.post/r1"
|
||||
assert r["remote_url"] == "https://bsky.app/profile/phil.example/post/r1"
|
||||
|
||||
def test_long_note_fits_300(self, app, pds):
|
||||
note = publish(app, content="word " * 500)
|
||||
text = only_record(pds)["text"]
|
||||
assert len(text) <= 300
|
||||
assert text.endswith(f"https://blog.example.com/note/{note.slug}")
|
||||
|
||||
def test_edit_leaves_post_alone(self, app, pds):
|
||||
note = publish(app, content="first")
|
||||
with app.test_request_context():
|
||||
update_note(id=note.id, content="second")
|
||||
process_due()
|
||||
assert only_record(pds)["text"].startswith("first")
|
||||
assert row(app, note)["state"] == "synced"
|
||||
|
||||
def test_delete_and_unpublish_remove_post(self, app, pds):
|
||||
note = publish(app)
|
||||
with app.test_request_context():
|
||||
update_note(id=note.id, published=False)
|
||||
process_due()
|
||||
assert pds.records == {}
|
||||
update_note(id=note.id, published=True)
|
||||
process_due()
|
||||
assert len(pds.records) == 1
|
||||
delete_note(id=note.id)
|
||||
process_due()
|
||||
assert pds.records == {}
|
||||
|
||||
|
||||
class TestSession:
|
||||
def test_logs_in_once_and_uses_pds(self, app, pds):
|
||||
publish(app, content="one")
|
||||
publish(app, content="two")
|
||||
assert pds.logins == 1
|
||||
assert ("bsky.example", "com.atproto.server.createSession") in pds.calls
|
||||
assert ("pds.example", "com.atproto.repo.createRecord") in pds.calls
|
||||
|
||||
def test_expired_token_is_refreshed(self, app, pds):
|
||||
publish(app, content="one")
|
||||
pds.expire_next = True
|
||||
publish(app, content="two")
|
||||
assert len(pds.records) == 2
|
||||
assert ("bsky.example", "com.atproto.server.refreshSession") in pds.calls
|
||||
|
||||
def test_bad_password_fails_permanently(self, app, pds):
|
||||
syndication._client_cache[f"bluesky:{SERVICE}:phil.example"].password = "wrong"
|
||||
note = publish(app)
|
||||
r = row(app, note)
|
||||
assert r["state"] == "failed" and "401" in r["last_error"]
|
||||
|
||||
def test_lost_reply_does_not_double_post(self, app, pds):
|
||||
pds.lose_next_reply = True
|
||||
note = publish(app)
|
||||
assert row(app, note)["state"] == "pending"
|
||||
with app.test_request_context():
|
||||
from starpunk.syndication import retry
|
||||
retry(row(app, note)["id"])
|
||||
# retry() resets attempts; simulate the scheduled retry instead
|
||||
from starpunk.database import get_db
|
||||
get_db(app).execute("UPDATE syndications SET attempts = 1")
|
||||
get_db(app).commit()
|
||||
process_due()
|
||||
assert len(pds.records) == 1
|
||||
assert row(app, note)["state"] == "synced"
|
||||
|
||||
def test_server_error_retries(self, app, pds):
|
||||
publish(app, content="warm up") # log in first
|
||||
pds.fail_next = 502
|
||||
note = publish(app, content="later")
|
||||
assert row(app, note)["state"] == "pending"
|
||||
|
||||
|
||||
class TestMedia:
|
||||
def test_large_image_is_shrunk_with_alt_and_aspect_ratio(self, app, pds):
|
||||
from starpunk.media import attach_media_to_note, save_media
|
||||
import os
|
||||
|
||||
img = Image.frombytes("RGB", (2400, 1800), os.urandom(2400 * 1800 * 3))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
assert buf.tell() > 1_000_000
|
||||
with app.test_request_context():
|
||||
note = create_note(content="noisy", published=True)
|
||||
media = save_media(buf.getvalue(), "noise.png")
|
||||
attach_media_to_note(note.id, [media["id"]], ["Static"])
|
||||
select_targets(note.id, ["bluesky"])
|
||||
process_due()
|
||||
record = only_record(pds)
|
||||
(image,) = record["embed"]["images"]
|
||||
assert record["embed"]["$type"] == "app.bsky.embed.images"
|
||||
assert image["alt"] == "Static"
|
||||
assert image["aspectRatio"]["width"] > 0
|
||||
|
||||
|
||||
def test_both_targets_listed_for_micropub(tmp_path):
|
||||
data = tmp_path / "d"
|
||||
app = create_app({
|
||||
"TESTING": True, "SITE_URL": "https://b.example", "ADMIN_ME": "https://e.example",
|
||||
"SESSION_SECRET": "x", "DATA_PATH": data, "NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "s.db",
|
||||
"GOTOSOCIAL_URL": "https://social.example", "GOTOSOCIAL_ACCESS_TOKEN": "t",
|
||||
"BLUESKY_HANDLE": "phil.example", "BLUESKY_APP_PASSWORD": "p",
|
||||
})
|
||||
with app.app_context():
|
||||
from starpunk.syndication import get_targets, resolve_targets
|
||||
assert set(get_targets()) == {"gotosocial", "bluesky"}
|
||||
assert resolve_targets(["https://bsky.app/profile/phil.example"]) == ["bluesky"]
|
||||
syndication._client_cache.clear()
|
||||
@@ -212,11 +212,12 @@ class TestAdminTemplates:
|
||||
assert response.status_code == 200
|
||||
assert b"<form" in response.data
|
||||
|
||||
def test_login_has_me_input(self, client):
|
||||
"""Test login form has 'me' URL input"""
|
||||
def test_login_has_sso_button(self, client):
|
||||
"""Test login form offers OIDC sign-in, not a URL field (v2.0.0)"""
|
||||
response = client.get("/auth/login")
|
||||
assert response.status_code == 200
|
||||
assert b'name="me"' in response.data or b'id="me"' in response.data
|
||||
assert b"Sign in with" in response.data
|
||||
assert b'name="me"' not in response.data
|
||||
|
||||
def test_login_has_submit_button(self, client):
|
||||
"""Test login form has submit button"""
|
||||
|
||||
Reference in new issue
Block a user