@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""JWT verification shared by every JWT-based provider, and the own-secret (HS256) verifier.
|
|
2
|
+
|
|
3
|
+
JwtVerifier decode (subclass: `_decode`) -> TokenClaims -> CurrentUser (`_to_user`, overridable)
|
|
4
|
+
HmacJwtVerifier tokens this backend issued with `JWT_SECRET` (see `issue_token`)
|
|
5
|
+
|
|
6
|
+
All PyJWT errors become `InvalidToken`: the reason goes to the log, never to the client.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from abc import abstractmethod
|
|
11
|
+
from datetime import UTC, datetime, timedelta
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import jwt
|
|
15
|
+
|
|
16
|
+
from api.auth import CurrentUser, InvalidToken, TokenVerifier
|
|
17
|
+
|
|
18
|
+
from .models import TokenClaims
|
|
19
|
+
from .settings import AuthSettings
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class JwtVerifier(TokenVerifier):
|
|
25
|
+
def __init__(self, settings: AuthSettings) -> None:
|
|
26
|
+
self._settings = settings
|
|
27
|
+
|
|
28
|
+
async def verify(self, token: str) -> CurrentUser:
|
|
29
|
+
try:
|
|
30
|
+
payload = await self._decode(token)
|
|
31
|
+
except jwt.PyJWTError as exc:
|
|
32
|
+
logger.info("Token refused: %s", exc)
|
|
33
|
+
raise InvalidToken(str(exc)) from None
|
|
34
|
+
claims = self._claims(payload)
|
|
35
|
+
return await self._to_user(claims, payload)
|
|
36
|
+
|
|
37
|
+
@abstractmethod
|
|
38
|
+
async def _decode(self, token: str) -> dict[str, Any]:
|
|
39
|
+
"""Verify signature, expiry, issuer/audience and required claims. Raise `jwt.PyJWTError`."""
|
|
40
|
+
|
|
41
|
+
def _claims(self, payload: dict[str, Any]) -> TokenClaims:
|
|
42
|
+
"""Which payload fields matter. Override when your provider stores them elsewhere."""
|
|
43
|
+
return TokenClaims(**payload)
|
|
44
|
+
|
|
45
|
+
async def _to_user(self, claims: TokenClaims, payload: dict[str, Any]) -> CurrentUser:
|
|
46
|
+
"""Claims -> caller. Async so a subclass can look the profile up in the DB (then raise
|
|
47
|
+
`InvalidToken` for an account without profile). Default: tenant from the claim or
|
|
48
|
+
`AUTH_DEFAULT_TENANT_ID`; no tenant at all -> refused."""
|
|
49
|
+
tenant_id = claims.tenant_id or self._settings.auth_default_tenant_id
|
|
50
|
+
if not tenant_id:
|
|
51
|
+
raise InvalidToken("token without tenant and no AUTH_DEFAULT_TENANT_ID")
|
|
52
|
+
return CurrentUser(
|
|
53
|
+
id=claims.sub,
|
|
54
|
+
tenant_id=tenant_id,
|
|
55
|
+
email=claims.email,
|
|
56
|
+
role=claims.role,
|
|
57
|
+
**({"language": claims.language} if claims.language else {}),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class HmacJwtVerifier(JwtVerifier):
|
|
62
|
+
"""Tokens signed by this backend with the shared `JWT_SECRET` (HS256)."""
|
|
63
|
+
|
|
64
|
+
ALGORITHMS = ["HS256"]
|
|
65
|
+
|
|
66
|
+
async def _decode(self, token: str) -> dict[str, Any]:
|
|
67
|
+
s = self._settings
|
|
68
|
+
assert s.jwt_secret is not None # AuthSettings validated it
|
|
69
|
+
return jwt.decode(
|
|
70
|
+
token,
|
|
71
|
+
s.jwt_secret.get_secret_value(),
|
|
72
|
+
algorithms=self.ALGORITHMS,
|
|
73
|
+
issuer=s.jwt_issuer,
|
|
74
|
+
audience=s.jwt_audience,
|
|
75
|
+
leeway=s.auth_leeway_seconds,
|
|
76
|
+
options={"require": ["exp", "sub"], "verify_aud": s.jwt_audience is not None},
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def issue_token(settings: AuthSettings, user: CurrentUser, *, ttl_seconds: int | None = None, now: datetime | None = None) -> str:
|
|
81
|
+
"""A token `HmacJwtVerifier` accepts, for your login endpoint or a dev script.
|
|
82
|
+
Only the JWT provider issues tokens: with Supabase the frontend gets them from Supabase."""
|
|
83
|
+
if settings.jwt_secret is None:
|
|
84
|
+
raise ValueError("issue_token needs JWT_SECRET")
|
|
85
|
+
now = now or datetime.now(UTC)
|
|
86
|
+
payload: dict[str, Any] = {
|
|
87
|
+
"sub": user.id,
|
|
88
|
+
"tenant_id": user.tenant_id,
|
|
89
|
+
"language": user.language,
|
|
90
|
+
"iat": int(now.timestamp()),
|
|
91
|
+
"exp": int((now + timedelta(seconds=ttl_seconds or settings.jwt_ttl_seconds)).timestamp()),
|
|
92
|
+
}
|
|
93
|
+
if user.email:
|
|
94
|
+
payload["email"] = user.email
|
|
95
|
+
if user.role:
|
|
96
|
+
payload["role"] = user.role
|
|
97
|
+
if settings.jwt_issuer:
|
|
98
|
+
payload["iss"] = settings.jwt_issuer
|
|
99
|
+
if settings.jwt_audience:
|
|
100
|
+
payload["aud"] = settings.jwt_audience
|
|
101
|
+
return jwt.encode(payload, settings.jwt_secret.get_secret_value(), algorithm="HS256")
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AuthProvider(StrEnum):
|
|
7
|
+
"""Who signs the tokens. Chosen in the settings (`AUTH_PROVIDER`), built by `AuthFactory`.
|
|
8
|
+
|
|
9
|
+
STATIC: a fixed token -> user table given in code (tests, local dev). Never in production.
|
|
10
|
+
JWT: tokens the backend issues itself with a shared secret (HS256). Own login endpoint.
|
|
11
|
+
SUPABASE: tokens issued by Supabase Auth, verified with its public keys (JWKS).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
STATIC = "static"
|
|
15
|
+
JWT = "jwt"
|
|
16
|
+
SUPABASE = "supabase"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TokenClaims(BaseModel):
|
|
20
|
+
"""The claims a verifier cares about, already validated. `tenant_id` may still be missing
|
|
21
|
+
here: `JwtVerifier._to_user` decides what to do with that."""
|
|
22
|
+
|
|
23
|
+
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
24
|
+
|
|
25
|
+
sub: str = Field(min_length=1)
|
|
26
|
+
tenant_id: str | None = None
|
|
27
|
+
email: str | None = None
|
|
28
|
+
role: str | None = None
|
|
29
|
+
language: str | None = None
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Auth settings BLOCK, meant to be mixed into the project settings (`project-settings` recipe):
|
|
2
|
+
|
|
3
|
+
class Settings(AuthSettings, BaseAppSettings): ...
|
|
4
|
+
|
|
5
|
+
Env vars: AUTH_PROVIDER (required: static | jwt | supabase), AUTH_DEFAULT_TENANT_ID (tokens without a
|
|
6
|
+
tenant claim get it; empty = such tokens are refused), AUTH_LEEWAY_SECONDS (30).
|
|
7
|
+
JWT: JWT_SECRET (required), JWT_ISSUER, JWT_AUDIENCE, JWT_TTL_SECONDS (for `issue_token`, 7 days).
|
|
8
|
+
SUPABASE: SUPABASE_URL (required), SUPABASE_AUDIENCE (authenticated), SUPABASE_JWT_SECRET (only for
|
|
9
|
+
projects still on the legacy HS256 secret; empty = asymmetric keys only).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from pydantic import Field, SecretStr, model_validator
|
|
13
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
14
|
+
|
|
15
|
+
from .models import AuthProvider
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AuthSettings(BaseSettings):
|
|
19
|
+
model_config = SettingsConfigDict(extra="ignore")
|
|
20
|
+
|
|
21
|
+
# No default on purpose: falling back to the static double would ship an open door.
|
|
22
|
+
auth_provider: AuthProvider
|
|
23
|
+
auth_default_tenant_id: str | None = Field(default=None, min_length=1)
|
|
24
|
+
auth_leeway_seconds: int = Field(default=30, ge=0, description="Clock skew tolerated on exp/nbf/iat.")
|
|
25
|
+
|
|
26
|
+
jwt_secret: SecretStr | None = None
|
|
27
|
+
jwt_issuer: str | None = None
|
|
28
|
+
jwt_audience: str | None = None
|
|
29
|
+
jwt_ttl_seconds: int = Field(default=7 * 24 * 3600, ge=1)
|
|
30
|
+
|
|
31
|
+
supabase_url: str | None = None
|
|
32
|
+
supabase_audience: str = "authenticated"
|
|
33
|
+
supabase_jwt_secret: SecretStr | None = None
|
|
34
|
+
|
|
35
|
+
@model_validator(mode="after")
|
|
36
|
+
def _provider_has_what_it_needs(self) -> "AuthSettings":
|
|
37
|
+
if self.auth_provider == AuthProvider.JWT and self.jwt_secret is None:
|
|
38
|
+
raise ValueError("AUTH_PROVIDER=jwt needs JWT_SECRET")
|
|
39
|
+
if self.auth_provider == AuthProvider.SUPABASE and not self.supabase_url:
|
|
40
|
+
raise ValueError("AUTH_PROVIDER=supabase needs SUPABASE_URL")
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def supabase_issuer(self) -> str:
|
|
45
|
+
return f"{(self.supabase_url or '').rstrip('/')}/auth/v1"
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Tokens issued by Supabase Auth.
|
|
2
|
+
|
|
3
|
+
Verified with the project's public keys (`<SUPABASE_URL>/auth/v1/.well-known/jwks.json`, ES256 or
|
|
4
|
+
RS256), fetched once and kept by `PyJWKClient`. Projects still on the legacy shared secret can set
|
|
5
|
+
`SUPABASE_JWT_SECRET` and HS256 tokens are accepted too; without it, a symmetric algorithm is
|
|
6
|
+
refused outright (accepting one would let a public key be used as the secret).
|
|
7
|
+
|
|
8
|
+
Tenant: Supabase has none. The default `_claims` reads `tenant_id` from `app_metadata` (set by you,
|
|
9
|
+
server-side) or `user_metadata` (set by the user: only if you trust it), then `AUTH_DEFAULT_TENANT_ID`.
|
|
10
|
+
Projects with a profiles table override `_to_user` and look the account up there.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
from typing import Any, Protocol
|
|
15
|
+
|
|
16
|
+
import jwt
|
|
17
|
+
|
|
18
|
+
from api.auth import AuthUnavailable
|
|
19
|
+
|
|
20
|
+
from .jwt_verifier import JwtVerifier
|
|
21
|
+
from .models import TokenClaims
|
|
22
|
+
from .settings import AuthSettings
|
|
23
|
+
|
|
24
|
+
KEYS_LIFESPAN_SECONDS = 600
|
|
25
|
+
KEYS_TIMEOUT_SECONDS = 5
|
|
26
|
+
ASYMMETRIC = ["ES256", "RS256"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SigningKeys(Protocol):
|
|
30
|
+
def key_for(self, token: str) -> Any:
|
|
31
|
+
"""The public key that signed this token. Raises `jwt.PyJWTError` if there is none. May block."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SupabaseKeys:
|
|
35
|
+
"""The keys Supabase publishes, cached by `PyJWKClient` and refreshed when they expire."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, supabase_url: str) -> None:
|
|
38
|
+
self._client = jwt.PyJWKClient(
|
|
39
|
+
f"{supabase_url.rstrip('/')}/auth/v1/.well-known/jwks.json",
|
|
40
|
+
lifespan=KEYS_LIFESPAN_SECONDS,
|
|
41
|
+
timeout=KEYS_TIMEOUT_SECONDS,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def key_for(self, token: str) -> Any:
|
|
45
|
+
return self._client.get_signing_key_from_jwt(token).key
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SupabaseJwtVerifier(JwtVerifier):
|
|
49
|
+
def __init__(self, settings: AuthSettings, keys: SigningKeys | None = None) -> None:
|
|
50
|
+
super().__init__(settings)
|
|
51
|
+
assert settings.supabase_url # AuthSettings validated it
|
|
52
|
+
self._keys = keys or SupabaseKeys(settings.supabase_url)
|
|
53
|
+
|
|
54
|
+
async def _decode(self, token: str) -> dict[str, Any]:
|
|
55
|
+
s = self._settings
|
|
56
|
+
common: dict[str, Any] = dict(
|
|
57
|
+
audience=s.supabase_audience,
|
|
58
|
+
issuer=s.supabase_issuer,
|
|
59
|
+
leeway=s.auth_leeway_seconds,
|
|
60
|
+
options={"require": ["exp", "sub", "iss"]},
|
|
61
|
+
)
|
|
62
|
+
algorithm = jwt.get_unverified_header(token).get("alg")
|
|
63
|
+
if algorithm == "HS256" and s.supabase_jwt_secret is not None:
|
|
64
|
+
return jwt.decode(token, s.supabase_jwt_secret.get_secret_value(), algorithms=["HS256"], **common)
|
|
65
|
+
try:
|
|
66
|
+
key = await asyncio.to_thread(self._keys.key_for, token) # first time it goes to the network
|
|
67
|
+
except jwt.PyJWKClientConnectionError:
|
|
68
|
+
raise AuthUnavailable("Supabase keys unreachable") from None
|
|
69
|
+
return jwt.decode(token, key, algorithms=ASYMMETRIC, **common)
|
|
70
|
+
|
|
71
|
+
def _claims(self, payload: dict[str, Any]) -> TokenClaims:
|
|
72
|
+
app_meta = payload.get("app_metadata") or {}
|
|
73
|
+
user_meta = payload.get("user_metadata") or {}
|
|
74
|
+
return TokenClaims(
|
|
75
|
+
sub=payload["sub"],
|
|
76
|
+
tenant_id=app_meta.get("tenant_id") or user_meta.get("tenant_id"),
|
|
77
|
+
email=payload.get("email"),
|
|
78
|
+
role=app_meta.get("role"), # `payload["role"]` is "authenticated" for everyone: not a business role
|
|
79
|
+
language=user_meta.get("language"),
|
|
80
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Verifiers without network: own HS256 tokens, Supabase ES256 tokens signed with a key generated
|
|
2
|
+
here (the `SigningKeys` seam replaces the JWKS fetch), and the FastAPI dependency."""
|
|
3
|
+
|
|
4
|
+
from datetime import UTC, datetime, timedelta
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
import jwt
|
|
8
|
+
import pytest
|
|
9
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
10
|
+
from fastapi import Depends, FastAPI
|
|
11
|
+
from pydantic import ValidationError
|
|
12
|
+
|
|
13
|
+
from api.auth import AuthUnavailable, CurrentUser, InvalidToken, StaticTokenVerifier, get_current_user
|
|
14
|
+
from auth import AuthFactory, AuthSettings, HmacJwtVerifier, SupabaseJwtVerifier, issue_token
|
|
15
|
+
|
|
16
|
+
ALICE = CurrentUser(id="user-1", tenant_id="tenant-1", language="en", email="a@example.com", role="admin")
|
|
17
|
+
|
|
18
|
+
SECRET = "s3cret-" * 6 # HS256 wants >= 32 bytes
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def jwt_settings(**overrides) -> AuthSettings:
|
|
22
|
+
return AuthSettings(**{"auth_provider": "jwt", "jwt_secret": SECRET, "jwt_issuer": "{{app_name}}", **overrides})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
JWT_SETTINGS = jwt_settings()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def hs256(payload: dict, secret: str = SECRET) -> str:
|
|
29
|
+
return jwt.encode(payload, secret, algorithm="HS256")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# --- Own JWT (HS256) -------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def test_issued_token_round_trips_to_the_same_user():
|
|
36
|
+
token = issue_token(JWT_SETTINGS, ALICE, ttl_seconds=60)
|
|
37
|
+
assert await HmacJwtVerifier(JWT_SETTINGS).verify(token) == ALICE
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def test_expired_forged_or_wrong_issuer_tokens_are_invalid():
|
|
41
|
+
verifier = HmacJwtVerifier(JWT_SETTINGS)
|
|
42
|
+
past = datetime.now(UTC) - timedelta(hours=1)
|
|
43
|
+
cases = {
|
|
44
|
+
"expired": issue_token(JWT_SETTINGS, ALICE, now=past, ttl_seconds=60),
|
|
45
|
+
"forged": issue_token(jwt_settings(jwt_secret="other-" * 6), ALICE),
|
|
46
|
+
"issuer": hs256({"sub": "u", "tenant_id": "t", "iss": "someone-else", "exp": 4102444800}),
|
|
47
|
+
"no sub": hs256({"tenant_id": "t", "iss": "{{app_name}}", "exp": 4102444800}),
|
|
48
|
+
"no exp": hs256({"sub": "u", "tenant_id": "t", "iss": "{{app_name}}"}),
|
|
49
|
+
"garbage": "not.a.token",
|
|
50
|
+
}
|
|
51
|
+
for name, token in cases.items():
|
|
52
|
+
with pytest.raises(InvalidToken):
|
|
53
|
+
await verifier.verify(token)
|
|
54
|
+
print("refused:", name)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def test_tenant_comes_from_the_claim_then_the_default_then_refused():
|
|
58
|
+
settings = jwt_settings(jwt_issuer=None)
|
|
59
|
+
token = hs256({"sub": "u", "exp": 4102444800})
|
|
60
|
+
|
|
61
|
+
with pytest.raises(InvalidToken, match="tenant"):
|
|
62
|
+
await HmacJwtVerifier(settings).verify(token)
|
|
63
|
+
with_default = jwt_settings(jwt_issuer=None, auth_default_tenant_id="default")
|
|
64
|
+
assert (await HmacJwtVerifier(with_default).verify(token)).tenant_id == "default"
|
|
65
|
+
user = await HmacJwtVerifier(with_default).verify(hs256({"sub": "u", "tenant_id": "mine", "exp": 4102444800}))
|
|
66
|
+
assert (user.tenant_id, user.language) == ("mine", "es")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def test_audience_is_checked_only_when_configured():
|
|
70
|
+
settings = jwt_settings(jwt_audience="api")
|
|
71
|
+
assert (await HmacJwtVerifier(settings).verify(issue_token(settings, ALICE))).id == "user-1"
|
|
72
|
+
with pytest.raises(InvalidToken):
|
|
73
|
+
await HmacJwtVerifier(settings).verify(issue_token(JWT_SETTINGS, ALICE)) # no aud claim
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# --- Supabase (ES256 via JWKS, HS256 legacy) --------------------------------------------------
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class FakeKeys:
|
|
80
|
+
"""Stands in for the JWKS endpoint: always the same public key, or a connection error."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, public_key=None, *, down: bool = False) -> None:
|
|
83
|
+
self.public_key, self.down = public_key, down
|
|
84
|
+
|
|
85
|
+
def key_for(self, token: str):
|
|
86
|
+
if self.down:
|
|
87
|
+
raise jwt.PyJWKClientConnectionError("boom")
|
|
88
|
+
return self.public_key
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@pytest.fixture
|
|
92
|
+
def supabase():
|
|
93
|
+
private = ec.generate_private_key(ec.SECP256R1())
|
|
94
|
+
settings = AuthSettings(auth_provider="supabase", supabase_url="https://xyz.supabase.co/")
|
|
95
|
+
return settings, SupabaseJwtVerifier(settings, keys=FakeKeys(private.public_key())), private
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def supabase_payload(**extra) -> dict:
|
|
99
|
+
return {
|
|
100
|
+
"sub": "uuid-1",
|
|
101
|
+
"aud": "authenticated",
|
|
102
|
+
"iss": "https://xyz.supabase.co/auth/v1",
|
|
103
|
+
"role": "authenticated",
|
|
104
|
+
"email": "a@example.com",
|
|
105
|
+
"exp": 4102444800,
|
|
106
|
+
**extra,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def test_supabase_token_maps_tenant_and_role_from_app_metadata(supabase):
|
|
111
|
+
settings, verifier, private = supabase
|
|
112
|
+
token = jwt.encode(
|
|
113
|
+
supabase_payload(app_metadata={"tenant_id": "acme", "role": "manager"}, user_metadata={"language": "fr"}),
|
|
114
|
+
private,
|
|
115
|
+
algorithm="ES256",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
user = await verifier.verify(token)
|
|
119
|
+
|
|
120
|
+
assert user == CurrentUser(id="uuid-1", tenant_id="acme", language="fr", email="a@example.com", role="manager")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
async def test_supabase_refuses_other_audience_issuer_or_key(supabase):
|
|
124
|
+
settings, verifier, private = supabase
|
|
125
|
+
other = ec.generate_private_key(ec.SECP256R1())
|
|
126
|
+
cases = {
|
|
127
|
+
"audience": jwt.encode(supabase_payload(aud="anon"), private, algorithm="ES256"),
|
|
128
|
+
"issuer": jwt.encode(supabase_payload(iss="https://evil.example/auth/v1"), private, algorithm="ES256"),
|
|
129
|
+
"other key": jwt.encode(supabase_payload(), other, algorithm="ES256"),
|
|
130
|
+
"hs256 without legacy secret": hs256(supabase_payload(app_metadata={"tenant_id": "t"})),
|
|
131
|
+
"no tenant anywhere": jwt.encode(supabase_payload(), private, algorithm="ES256"),
|
|
132
|
+
}
|
|
133
|
+
for name, token in cases.items():
|
|
134
|
+
with pytest.raises(InvalidToken):
|
|
135
|
+
await verifier.verify(token)
|
|
136
|
+
print("refused:", name)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def test_supabase_legacy_hs256_secret_is_accepted_when_configured():
|
|
140
|
+
settings = AuthSettings(
|
|
141
|
+
auth_provider="supabase", supabase_url="https://xyz.supabase.co", supabase_jwt_secret="legacy-" * 6, auth_default_tenant_id="t"
|
|
142
|
+
)
|
|
143
|
+
verifier = SupabaseJwtVerifier(settings, keys=FakeKeys(down=True)) # never consulted for HS256
|
|
144
|
+
|
|
145
|
+
user = await verifier.verify(hs256(supabase_payload(), "legacy-" * 6))
|
|
146
|
+
|
|
147
|
+
assert (user.id, user.tenant_id) == ("uuid-1", "t")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def test_supabase_keys_unreachable_is_unavailable_not_invalid(supabase):
|
|
151
|
+
settings, _, private = supabase
|
|
152
|
+
verifier = SupabaseJwtVerifier(settings, keys=FakeKeys(down=True))
|
|
153
|
+
with pytest.raises(AuthUnavailable):
|
|
154
|
+
await verifier.verify(jwt.encode(supabase_payload(), private, algorithm="ES256"))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
async def test_profile_lookup_is_one_method():
|
|
158
|
+
class WithProfiles(HmacJwtVerifier):
|
|
159
|
+
profiles = {"user-1": ("tenant-9", "editor")}
|
|
160
|
+
|
|
161
|
+
async def _to_user(self, claims, payload): # e.g. a DB query
|
|
162
|
+
try:
|
|
163
|
+
tenant_id, role = self.profiles[claims.sub]
|
|
164
|
+
except KeyError:
|
|
165
|
+
raise InvalidToken("no profile") from None
|
|
166
|
+
return CurrentUser(id=claims.sub, tenant_id=tenant_id, role=role)
|
|
167
|
+
|
|
168
|
+
verifier = WithProfiles(JWT_SETTINGS)
|
|
169
|
+
assert (await verifier.verify(issue_token(JWT_SETTINGS, ALICE))).tenant_id == "tenant-9"
|
|
170
|
+
with pytest.raises(InvalidToken):
|
|
171
|
+
await verifier.verify(issue_token(JWT_SETTINGS, ALICE.model_copy(update={"id": "nobody"})))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# --- Settings + factory: the provider is chosen in .env, not in code -------------------------
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_provider_comes_from_env_and_each_one_needs_its_keys(monkeypatch):
|
|
178
|
+
monkeypatch.setenv("AUTH_PROVIDER", "jwt")
|
|
179
|
+
monkeypatch.setenv("JWT_SECRET", SECRET)
|
|
180
|
+
assert isinstance(AuthFactory.create(AuthSettings()), HmacJwtVerifier)
|
|
181
|
+
|
|
182
|
+
monkeypatch.delenv("JWT_SECRET")
|
|
183
|
+
with pytest.raises(ValidationError, match="JWT_SECRET"):
|
|
184
|
+
AuthSettings()
|
|
185
|
+
with pytest.raises(ValidationError, match="SUPABASE_URL"):
|
|
186
|
+
AuthSettings(auth_provider="supabase")
|
|
187
|
+
monkeypatch.delenv("AUTH_PROVIDER")
|
|
188
|
+
with pytest.raises(ValidationError):
|
|
189
|
+
AuthSettings()
|
|
190
|
+
with pytest.raises(ValidationError):
|
|
191
|
+
AuthSettings(auth_provider="ldap")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def test_static_provider_needs_users_given_in_code():
|
|
195
|
+
settings = AuthSettings(auth_provider="static")
|
|
196
|
+
with pytest.raises(ValueError, match="static_users"):
|
|
197
|
+
AuthFactory.create(settings)
|
|
198
|
+
assert isinstance(AuthFactory.create(settings, static_users={"tok": ALICE}), StaticTokenVerifier)
|
|
199
|
+
assert isinstance(
|
|
200
|
+
AuthFactory.create(AuthSettings(auth_provider="supabase", supabase_url="https://x.supabase.co")), SupabaseJwtVerifier
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_secrets_never_show_in_repr():
|
|
205
|
+
assert SECRET not in repr(JWT_SETTINGS) and SECRET not in str(JWT_SETTINGS)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# --- The dependency: 401 vs 503 ---------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
async def test_dependency_maps_invalid_to_401_and_unavailable_to_503():
|
|
212
|
+
app = FastAPI()
|
|
213
|
+
|
|
214
|
+
@app.get("/me")
|
|
215
|
+
async def me(user: CurrentUser = Depends(get_current_user)) -> dict:
|
|
216
|
+
return {"id": user.id}
|
|
217
|
+
|
|
218
|
+
token = issue_token(JWT_SETTINGS, ALICE)
|
|
219
|
+
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
|
|
220
|
+
app.state.token_verifier = HmacJwtVerifier(JWT_SETTINGS)
|
|
221
|
+
assert (await c.get("/me", headers={"Authorization": f"Bearer {token}"})).json() == {"id": "user-1"}
|
|
222
|
+
refused = await c.get("/me", headers={"Authorization": "Bearer nope"})
|
|
223
|
+
assert refused.status_code == 401 and refused.headers["www-authenticate"] == "Bearer"
|
|
224
|
+
assert (await c.get("/me")).status_code == 401
|
|
225
|
+
|
|
226
|
+
down = AuthSettings(auth_provider="supabase", supabase_url="https://x.supabase.co")
|
|
227
|
+
app.state.token_verifier = SupabaseJwtVerifier(down, keys=FakeKeys(down=True))
|
|
228
|
+
es_token = jwt.encode(supabase_payload(), ec.generate_private_key(ec.SECP256R1()), algorithm="ES256")
|
|
229
|
+
assert (await c.get("/me", headers={"Authorization": f"Bearer {es_token}"})).status_code == 503
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# conversation-history
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para que el chat tenga **barra lateral e historial**: listar las conversaciones del usuario (título, fechas, número de mensajes, paginado), cargar los mensajes de una y borrarla. Lee la misma memoria que escribe el chat: no hay segundo almacén ni sincronización.
|
|
6
|
+
|
|
7
|
+
**Requiere `agent-chat-api`** (y con ella `agent-memory`, que aporta `get_history` y `list_conversations`): usa su `get_current_user`, su `get_memory` y su `create_app`.
|
|
8
|
+
|
|
9
|
+
## Qué incluye
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
api/conversations/
|
|
13
|
+
router.py GET /conversations?limit&offset · GET /conversations/{id}/messages · DELETE /conversations/{id}
|
|
14
|
+
schemas.py ConversationOut · ConversationsResponse · MessageOut (user | assistant) · ConversationMessagesResponse
|
|
15
|
+
tests/test_conversations_api.py 5 tests: 401, orden y títulos y paginación, solo texto visible, 404 ajeno/desconocido, borrar
|
|
16
|
+
pytest.ini
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Decisiones
|
|
20
|
+
|
|
21
|
+
- **La memoria es la fuente.** `Memory.list_conversations` y `Memory.get_history` (receta `agent-memory`) hacen el trabajo; el router solo adapta. Una tabla aparte de conversaciones obligaría a mantenerla en cada turno.
|
|
22
|
+
- **Lo ajeno es un 404, no un 403.** Todas las rutas construyen la `MemoryKey` con tenant y usuario del token, así que el id de otro no existe en tu espacio. No se revela si existe.
|
|
23
|
+
- **Solo texto visible.** `MessageOut` mapea `human → user` y `ai → assistant` y descarta tool calls, resultados de tools y mensajes vacíos. En la base de datos sigue todo (el LLM lo necesita). Cada mensaje lleva su `id` almacenado: es el `message_id` que `agent-feedback` vota.
|
|
24
|
+
- **Título = primer mensaje humano recortado.** Se calcula en la memoria (`title_from`), no en el router, para que SQL lo haga en una consulta.
|
|
25
|
+
- **Orden por última actividad**, con `limit` (máx. 200) y `offset`. Sin total: en producción no hizo falta y la barra lateral no lo necesita.
|
|
26
|
+
- **Borrar es `Memory.clear`.** Es nuevo; se añade porque el contrato de memoria ya lo tenía ("el usuario pide olvidar"). 204, y 404 si no era tuya. Renombrar queda fuera: requeriría guardar el título.
|
|
27
|
+
- **Mismo patrón de montaje** que `rate-limit-quota`: `app.include_router(conversations_router)` tras `create_app`. Sin el kill switch del agente: el historial se puede leer aunque el chat esté apagado.
|
|
28
|
+
|
|
29
|
+
## Cómo adaptarla
|
|
30
|
+
|
|
31
|
+
1. Copia `files/` en la raíz del backend, encima de `agent-chat-api`.
|
|
32
|
+
2. **`main.py`:**
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from api.conversations.router import router as conversations_router
|
|
36
|
+
app = create_app(...)
|
|
37
|
+
app.include_router(conversations_router)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
3. **Frontend:** `GET /conversations` al cargar la barra lateral; al pulsar una, `GET /conversations/{id}/messages` y seguir el hilo mandando ese `conversation_id` a `POST /agent/chat` o `/stream`. Tras un `done`, refrescar la lista (el título aparece con el primer turno).
|
|
41
|
+
4. **Fechas:** ISO 8601 en UTC (`2026-03-30T10:00:00Z`). Si el negocio quiere otra zona, se convierte en el cliente.
|
|
42
|
+
5. Para comprobarla: `pytest` con las recetas backend copiadas (114 tests con las siete).
|
|
43
|
+
|
|
44
|
+
**Dependencias:** las de `agent-chat-api`.
|
|
45
|
+
|
|
46
|
+
## Origen
|
|
47
|
+
|
|
48
|
+
- Probado en producción: `GET /conversations` paginado con `limit` y `offset` (resumen con id, título y fechas) y `GET /conversations/{id}/messages` con 404 si no existe o es de otro usuario, leyendo de la memoria.
|
|
49
|
+
- Nuevo en esta receta: `DELETE`, `message_count`, filtrado de tools en la respuesta y los ids de mensaje en el historial.
|
|
File without changes
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""GET /conversations (sidebar), GET /conversations/{id}/messages (history), DELETE /conversations/{id}.
|
|
2
|
+
|
|
3
|
+
Reads the same `Memory` the chat writes (`app.state.memory`): no second store, no sync.
|
|
4
|
+
Every route scopes by the token's tenant and user, so a conversation that is not yours is a 404,
|
|
5
|
+
not a 403: the id exists only inside its owner's namespace.
|
|
6
|
+
Mount it next to the chat router: `app.include_router(conversations_router)` after `create_app(...)`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, Depends, HTTPException, Path, Query, Response, status
|
|
10
|
+
|
|
11
|
+
from agentic.memory import Memory, MemoryKey
|
|
12
|
+
|
|
13
|
+
from ..agent.router import get_memory
|
|
14
|
+
from ..auth import CurrentUser, get_current_user
|
|
15
|
+
from .schemas import ConversationMessagesResponse, ConversationOut, ConversationsResponse, MessageOut
|
|
16
|
+
|
|
17
|
+
router = APIRouter(prefix="/conversations", tags=["conversations"])
|
|
18
|
+
|
|
19
|
+
ConversationId = Path(pattern=r"^[A-Za-z0-9_\-]+$", max_length=100) # same rule as ChatRequest.conversation_id
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def conversation_key(
|
|
23
|
+
conversation_id: str = ConversationId, user: CurrentUser = Depends(get_current_user)
|
|
24
|
+
) -> MemoryKey:
|
|
25
|
+
return MemoryKey(tenant_id=user.tenant_id, user_id=user.id, conversation_id=conversation_id)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@router.get("", response_model=ConversationsResponse)
|
|
29
|
+
async def list_conversations(
|
|
30
|
+
user: CurrentUser = Depends(get_current_user),
|
|
31
|
+
memory: Memory = Depends(get_memory),
|
|
32
|
+
limit: int = Query(default=50, ge=1, le=200),
|
|
33
|
+
offset: int = Query(default=0, ge=0),
|
|
34
|
+
) -> ConversationsResponse:
|
|
35
|
+
summaries = await memory.list_conversations(user.tenant_id, user.id, limit=limit, offset=offset)
|
|
36
|
+
return ConversationsResponse(conversations=[ConversationOut.from_summary(s) for s in summaries])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@router.get("/{conversation_id}/messages", response_model=ConversationMessagesResponse)
|
|
40
|
+
async def conversation_messages(
|
|
41
|
+
key: MemoryKey = Depends(conversation_key), memory: Memory = Depends(get_memory)
|
|
42
|
+
) -> ConversationMessagesResponse:
|
|
43
|
+
history = await memory.get_history(key)
|
|
44
|
+
if not history:
|
|
45
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, "Conversation not found")
|
|
46
|
+
messages = [m for m in (MessageOut.from_history(item) for item in history) if m is not None]
|
|
47
|
+
return ConversationMessagesResponse(conversation_id=key.conversation_id, messages=messages)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@router.delete("/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
51
|
+
async def delete_conversation(key: MemoryKey = Depends(conversation_key), memory: Memory = Depends(get_memory)) -> Response:
|
|
52
|
+
if not await memory.get_history(key):
|
|
53
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, "Conversation not found")
|
|
54
|
+
await memory.clear(key)
|
|
55
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""What the sidebar and the history view receive. Built from `agent-memory` models, never exposed raw."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
7
|
+
|
|
8
|
+
from agentic.memory import ConversationSummary, HistoryMessage
|
|
9
|
+
|
|
10
|
+
ROLES: dict[str, str] = {"human": "user", "ai": "assistant"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConversationOut(BaseModel):
|
|
14
|
+
model_config = ConfigDict(frozen=True)
|
|
15
|
+
|
|
16
|
+
conversation_id: str
|
|
17
|
+
title: str
|
|
18
|
+
created_at: datetime
|
|
19
|
+
updated_at: datetime
|
|
20
|
+
message_count: int = Field(ge=0)
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def from_summary(cls, summary: ConversationSummary) -> "ConversationOut":
|
|
24
|
+
return cls(**summary.model_dump())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ConversationsResponse(BaseModel):
|
|
28
|
+
model_config = ConfigDict(frozen=True)
|
|
29
|
+
|
|
30
|
+
conversations: list[ConversationOut]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class MessageOut(BaseModel):
|
|
34
|
+
"""Only what a chat renders: user and assistant text. Tool calls and results stay in the DB."""
|
|
35
|
+
|
|
36
|
+
model_config = ConfigDict(frozen=True)
|
|
37
|
+
|
|
38
|
+
id: str | None = Field(default=None, description="The stored message id (what `agent-feedback` votes on).")
|
|
39
|
+
role: Literal["user", "assistant"]
|
|
40
|
+
content: str
|
|
41
|
+
created_at: datetime
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_history(cls, item: HistoryMessage) -> "MessageOut | None":
|
|
45
|
+
"""None for messages the UI does not show (tool calls, tool results, empty AI messages)."""
|
|
46
|
+
role = ROLES.get(item.message.type)
|
|
47
|
+
content = str(item.message.text).strip()
|
|
48
|
+
if role is None or not content:
|
|
49
|
+
return None
|
|
50
|
+
return cls(id=item.message.id, role=role, content=content, created_at=item.created_at)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ConversationMessagesResponse(BaseModel):
|
|
54
|
+
model_config = ConfigDict(frozen=True)
|
|
55
|
+
|
|
56
|
+
conversation_id: str
|
|
57
|
+
messages: list[MessageOut]
|