feat!: OIDC admin login and built-in IndieAuth server (v2.0.0)
Admin login now uses OpenID Connect (PKCE, nonce, ID token verified against the provider JWKS) and only OIDC_ADMIN_SUB may log in. Micropub tokens are issued and verified by StarPunk itself, with a consent screen behind the OIDC session and a Connected Apps page to revoke them, so an external IndieAuth server (Gondulf) is no longer needed. Existing notes, media, tags, webmentions, author profile and sessions are unchanged. Migration 011 adds new tables only. BREAKING CHANGE: production requires OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET and OIDC_ADMIN_SUB. The ADMIN_ME page must point Micropub apps at StarPunk's IndieAuth endpoints. See ADR-064. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d3fa5b7a2a
commit
b84cf23e1a
29 files changed
+1824
-2354
No files matched your search
@@ -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
|
||||
+12
-12
@@ -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={
|
||||
@@ -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={
|
||||
@@ -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',
|
||||
|
||||
@@ -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