@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,48 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from enum import StrEnum
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
6
|
+
|
|
7
|
+
# +1 helpful, -1 not helpful. Integers so dashboards can SUM/AVG without converting.
|
|
8
|
+
Rating = Literal[-1, 1]
|
|
9
|
+
|
|
10
|
+
COMMENT_MAX_LENGTH = 2000
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FeedbackBackend(StrEnum):
|
|
14
|
+
"""Where votes live. Chosen in the settings (`FEEDBACK_BACKEND`), built by `FeedbackFactory`.
|
|
15
|
+
|
|
16
|
+
IN_MEMORY: a dict of the process. Lost on restart: tests and local dev.
|
|
17
|
+
SQL: the `agent_feedback` table (Postgres/Supabase in production, SQLite in tests).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
IN_MEMORY = "in_memory"
|
|
21
|
+
SQL = "sql"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class FeedbackVote(BaseModel):
|
|
25
|
+
"""What a user says about one answer. Tenant and user come from the token, never from the body."""
|
|
26
|
+
|
|
27
|
+
model_config = ConfigDict(frozen=True)
|
|
28
|
+
|
|
29
|
+
tenant_id: str = Field(min_length=1)
|
|
30
|
+
user_id: str = Field(min_length=1)
|
|
31
|
+
conversation_id: str = Field(min_length=1)
|
|
32
|
+
message_id: str = Field(min_length=1, description="The stored answer (`message_id` of `done` / `ChatResponse`).")
|
|
33
|
+
rating: Rating
|
|
34
|
+
comment: str | None = Field(default=None, max_length=COMMENT_MAX_LENGTH)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Feedback(FeedbackVote):
|
|
38
|
+
"""A stored vote. One per (tenant, user, message): voting again updates it."""
|
|
39
|
+
|
|
40
|
+
created_at: datetime
|
|
41
|
+
updated_at: datetime
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FeedbackResult(BaseModel):
|
|
45
|
+
model_config = ConfigDict(frozen=True)
|
|
46
|
+
|
|
47
|
+
feedback: Feedback
|
|
48
|
+
created: bool = Field(description="True on the first vote, False when an existing one was updated.")
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Feedback settings BLOCK, meant to be mixed into the project settings (`project-settings` recipe):
|
|
2
|
+
|
|
3
|
+
class Settings(FeedbackSettings, BaseAppSettings): ...
|
|
4
|
+
|
|
5
|
+
Env vars: FEEDBACK_BACKEND (required: in_memory | sql).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
9
|
+
|
|
10
|
+
from .models import FeedbackBackend
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FeedbackSettings(BaseSettings):
|
|
14
|
+
model_config = SettingsConfigDict(extra="ignore")
|
|
15
|
+
|
|
16
|
+
# No default on purpose: votes kept "just in case" in process memory vanish on every restart.
|
|
17
|
+
feedback_backend: FeedbackBackend
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""SQL store (Postgres/Supabase in production, SQLite in tests) with SQLAlchemy 2.
|
|
2
|
+
|
|
3
|
+
Same pattern as `agent-memory`: the app's `session_factory`, sync queries in `asyncio.to_thread`.
|
|
4
|
+
`agent_feedback` has one row per (tenant, user, message). No foreign key to `agent_messages` on
|
|
5
|
+
purpose: the recipe does not know your table names; add it in your migration if you want cascade.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import CheckConstraint, Column, DateTime, Integer, MetaData, String, Table, Text, UniqueConstraint, delete, select
|
|
13
|
+
from sqlalchemy.orm import Session
|
|
14
|
+
|
|
15
|
+
from .base import FeedbackStore
|
|
16
|
+
from .models import Feedback
|
|
17
|
+
|
|
18
|
+
metadata = MetaData()
|
|
19
|
+
|
|
20
|
+
agent_feedback = Table(
|
|
21
|
+
"agent_feedback",
|
|
22
|
+
metadata,
|
|
23
|
+
Column("id", Integer, primary_key=True, autoincrement=True),
|
|
24
|
+
Column("tenant_id", String, nullable=False, index=True),
|
|
25
|
+
Column("user_id", String, nullable=False),
|
|
26
|
+
Column("conversation_id", String, nullable=False, index=True),
|
|
27
|
+
Column("message_id", String, nullable=False),
|
|
28
|
+
Column("rating", Integer, nullable=False),
|
|
29
|
+
Column("comment", Text, nullable=True),
|
|
30
|
+
Column("created_at", DateTime(timezone=True), nullable=False),
|
|
31
|
+
Column("updated_at", DateTime(timezone=True), nullable=False),
|
|
32
|
+
UniqueConstraint("tenant_id", "user_id", "message_id", name="uq_agent_feedback_user_message"),
|
|
33
|
+
CheckConstraint("rating IN (-1, 1)", name="ck_agent_feedback_rating"),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
COLUMNS = [c.name for c in agent_feedback.c if c.name != "id"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _aware(value: datetime) -> datetime:
|
|
40
|
+
"""SQLite drops the timezone; Postgres keeps it. Always hand back UTC-aware datetimes."""
|
|
41
|
+
return value if value.tzinfo else value.replace(tzinfo=UTC)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _row_to_feedback(row) -> Feedback:
|
|
45
|
+
data = dict(row._mapping)
|
|
46
|
+
data.pop("id")
|
|
47
|
+
data["created_at"], data["updated_at"] = _aware(data["created_at"]), _aware(data["updated_at"])
|
|
48
|
+
return Feedback(**data)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SqlFeedbackStore(FeedbackStore):
|
|
52
|
+
def __init__(self, session_factory: Callable[[], Session], **kwargs) -> None:
|
|
53
|
+
super().__init__(**kwargs)
|
|
54
|
+
self._session_factory = session_factory
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def _one(tenant_id: str, user_id: str, message_id: str):
|
|
58
|
+
c = agent_feedback.c
|
|
59
|
+
return (c.tenant_id == tenant_id, c.user_id == user_id, c.message_id == message_id)
|
|
60
|
+
|
|
61
|
+
async def get(self, tenant_id: str, user_id: str, message_id: str) -> Feedback | None:
|
|
62
|
+
def run():
|
|
63
|
+
with self._session_factory() as db:
|
|
64
|
+
row = db.execute(select(agent_feedback).where(*self._one(tenant_id, user_id, message_id))).first()
|
|
65
|
+
return _row_to_feedback(row) if row else None
|
|
66
|
+
|
|
67
|
+
return await asyncio.to_thread(run)
|
|
68
|
+
|
|
69
|
+
async def list_for_conversation(self, tenant_id: str, user_id: str, conversation_id: str) -> list[Feedback]:
|
|
70
|
+
def run():
|
|
71
|
+
c = agent_feedback.c
|
|
72
|
+
with self._session_factory() as db:
|
|
73
|
+
rows = db.execute(
|
|
74
|
+
select(agent_feedback)
|
|
75
|
+
.where(c.tenant_id == tenant_id, c.user_id == user_id, c.conversation_id == conversation_id)
|
|
76
|
+
.order_by(c.created_at, c.id)
|
|
77
|
+
).all()
|
|
78
|
+
return [_row_to_feedback(r) for r in rows]
|
|
79
|
+
|
|
80
|
+
return await asyncio.to_thread(run)
|
|
81
|
+
|
|
82
|
+
async def remove(self, tenant_id: str, user_id: str, message_id: str) -> bool:
|
|
83
|
+
def run():
|
|
84
|
+
with self._session_factory() as db:
|
|
85
|
+
deleted = db.execute(delete(agent_feedback).where(*self._one(tenant_id, user_id, message_id))).rowcount
|
|
86
|
+
db.commit()
|
|
87
|
+
return deleted > 0
|
|
88
|
+
|
|
89
|
+
return await asyncio.to_thread(run)
|
|
90
|
+
|
|
91
|
+
async def _save(self, feedback: Feedback) -> None:
|
|
92
|
+
def run():
|
|
93
|
+
# Delete + insert in one transaction: portable upsert. On Postgres under load prefer
|
|
94
|
+
# `insert(...).on_conflict_do_update(...)` from sqlalchemy.dialects.postgresql.
|
|
95
|
+
with self._session_factory() as db:
|
|
96
|
+
db.execute(
|
|
97
|
+
delete(agent_feedback).where(*self._one(feedback.tenant_id, feedback.user_id, feedback.message_id))
|
|
98
|
+
)
|
|
99
|
+
db.execute(agent_feedback.insert().values(**feedback.model_dump(include=set(COLUMNS))))
|
|
100
|
+
db.commit()
|
|
101
|
+
|
|
102
|
+
await asyncio.to_thread(run)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Behaviour every `FeedbackStore` backend must have. A new backend = a subclass with a `store` fixture.
|
|
2
|
+
|
|
3
|
+
class TestRedisFeedbackStore(FeedbackConformance):
|
|
4
|
+
@pytest.fixture
|
|
5
|
+
def store(self, clock): return RedisFeedbackStore(redis, clock=clock)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from datetime import UTC, datetime, timedelta
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
from feedback import FeedbackVote
|
|
13
|
+
|
|
14
|
+
START = datetime(2026, 3, 30, 10, 0, tzinfo=UTC)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class FakeClock:
|
|
18
|
+
def __init__(self, now: datetime = START) -> None:
|
|
19
|
+
self.now = now
|
|
20
|
+
|
|
21
|
+
def __call__(self) -> datetime:
|
|
22
|
+
return self.now
|
|
23
|
+
|
|
24
|
+
def advance(self, seconds: float) -> None:
|
|
25
|
+
self.now += timedelta(seconds=seconds)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.fixture
|
|
29
|
+
def clock() -> FakeClock:
|
|
30
|
+
return FakeClock()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def vote(message_id: str = "a1", rating: int = 1, *, user_id: str = "user-1", tenant_id: str = "tenant-1", **kw) -> FeedbackVote:
|
|
34
|
+
return FeedbackVote(
|
|
35
|
+
tenant_id=tenant_id, user_id=user_id, conversation_id=kw.pop("conversation_id", "conv-1"), message_id=message_id, rating=rating, **kw
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class FeedbackConformance:
|
|
40
|
+
async def test_unknown_vote_is_none_and_remove_is_false(self, store):
|
|
41
|
+
assert await store.get("tenant-1", "user-1", "a1") is None
|
|
42
|
+
assert await store.remove("tenant-1", "user-1", "a1") is False
|
|
43
|
+
assert await store.list_for_conversation("tenant-1", "user-1", "conv-1") == []
|
|
44
|
+
|
|
45
|
+
async def test_first_vote_is_created_with_timestamps(self, store):
|
|
46
|
+
result = await store.vote(vote(rating=1, comment="útil"))
|
|
47
|
+
|
|
48
|
+
assert result.created is True
|
|
49
|
+
assert (result.feedback.rating, result.feedback.comment) == (1, "útil")
|
|
50
|
+
assert result.feedback.created_at == result.feedback.updated_at == START
|
|
51
|
+
assert await store.get("tenant-1", "user-1", "a1") == result.feedback
|
|
52
|
+
|
|
53
|
+
async def test_voting_again_updates_rating_and_comment_but_keeps_created_at(self, store, clock):
|
|
54
|
+
await store.vote(vote(rating=1, comment="útil"))
|
|
55
|
+
clock.advance(60)
|
|
56
|
+
|
|
57
|
+
result = await store.vote(vote(rating=-1))
|
|
58
|
+
|
|
59
|
+
assert result.created is False
|
|
60
|
+
assert (result.feedback.rating, result.feedback.comment) == (-1, None)
|
|
61
|
+
assert (result.feedback.created_at, result.feedback.updated_at) == (START, START + timedelta(seconds=60))
|
|
62
|
+
assert len(await store.list_for_conversation("tenant-1", "user-1", "conv-1")) == 1
|
|
63
|
+
|
|
64
|
+
async def test_votes_are_private_to_tenant_and_user(self, store):
|
|
65
|
+
await store.vote(vote(rating=1))
|
|
66
|
+
await store.vote(vote(rating=-1, user_id="user-2"))
|
|
67
|
+
await store.vote(vote(rating=-1, tenant_id="tenant-2"))
|
|
68
|
+
|
|
69
|
+
assert (await store.get("tenant-1", "user-1", "a1")).rating == 1
|
|
70
|
+
assert (await store.get("tenant-1", "user-2", "a1")).rating == -1
|
|
71
|
+
assert [f.rating for f in await store.list_for_conversation("tenant-1", "user-1", "conv-1")] == [1]
|
|
72
|
+
|
|
73
|
+
async def test_list_for_conversation_is_oldest_first_and_scoped(self, store, clock):
|
|
74
|
+
await store.vote(vote("a2", -1))
|
|
75
|
+
clock.advance(1)
|
|
76
|
+
await store.vote(vote("a1", 1))
|
|
77
|
+
await store.vote(vote("a9", 1, conversation_id="conv-2"))
|
|
78
|
+
|
|
79
|
+
votes = await store.list_for_conversation("tenant-1", "user-1", "conv-1")
|
|
80
|
+
|
|
81
|
+
assert [(f.message_id, f.rating) for f in votes] == [("a2", -1), ("a1", 1)]
|
|
82
|
+
|
|
83
|
+
async def test_remove_deletes_only_that_vote(self, store):
|
|
84
|
+
await store.vote(vote("a1"))
|
|
85
|
+
await store.vote(vote("a2"))
|
|
86
|
+
|
|
87
|
+
assert await store.remove("tenant-1", "user-1", "a1") is True
|
|
88
|
+
assert await store.get("tenant-1", "user-1", "a1") is None
|
|
89
|
+
assert await store.get("tenant-1", "user-1", "a2") is not None
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from pydantic import ValidationError
|
|
3
|
+
from sqlalchemy import create_engine
|
|
4
|
+
from sqlalchemy.orm import sessionmaker
|
|
5
|
+
from sqlalchemy.pool import StaticPool
|
|
6
|
+
|
|
7
|
+
from feedback import FeedbackBackend, FeedbackFactory, FeedbackSettings, FeedbackVote, InMemoryFeedbackStore
|
|
8
|
+
from feedback.sql import SqlFeedbackStore, metadata
|
|
9
|
+
|
|
10
|
+
from .feedback_conformance import FeedbackConformance, clock # noqa: F401 (fixture)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def sqlite_session_factory():
|
|
14
|
+
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
|
15
|
+
metadata.create_all(engine)
|
|
16
|
+
return sessionmaker(engine)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TestInMemoryFeedbackStore(FeedbackConformance):
|
|
20
|
+
@pytest.fixture
|
|
21
|
+
def store(self, clock):
|
|
22
|
+
return InMemoryFeedbackStore(clock=clock)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TestSqlFeedbackStore(FeedbackConformance):
|
|
26
|
+
@pytest.fixture
|
|
27
|
+
def store(self, clock):
|
|
28
|
+
return SqlFeedbackStore(sqlite_session_factory(), clock=clock)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# --- Models ----------------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_rating_is_plus_or_minus_one_and_comment_is_bounded():
|
|
35
|
+
base = dict(tenant_id="t", user_id="u", conversation_id="c", message_id="m")
|
|
36
|
+
with pytest.raises(ValidationError):
|
|
37
|
+
FeedbackVote(**base, rating=0)
|
|
38
|
+
with pytest.raises(ValidationError):
|
|
39
|
+
FeedbackVote(**base, rating=1, comment="x" * 2001)
|
|
40
|
+
assert FeedbackVote(**base, rating=-1).comment is None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# --- Settings + factory: the backend is chosen in .env, not in code ---------------------------
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_backend_comes_from_env(monkeypatch):
|
|
47
|
+
monkeypatch.setenv("FEEDBACK_BACKEND", "in_memory")
|
|
48
|
+
assert isinstance(FeedbackFactory.create(FeedbackSettings()), InMemoryFeedbackStore)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_switching_to_sql_is_only_a_setting():
|
|
52
|
+
store = FeedbackFactory.create(FeedbackSettings(feedback_backend="sql"), session_factory=sqlite_session_factory())
|
|
53
|
+
assert isinstance(store, SqlFeedbackStore)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_backend_is_required_and_validated(monkeypatch):
|
|
57
|
+
monkeypatch.delenv("FEEDBACK_BACKEND", raising=False)
|
|
58
|
+
with pytest.raises(ValidationError):
|
|
59
|
+
FeedbackSettings()
|
|
60
|
+
with pytest.raises(ValidationError):
|
|
61
|
+
FeedbackSettings(feedback_backend="redis")
|
|
62
|
+
with pytest.raises(ValueError, match="session_factory"):
|
|
63
|
+
FeedbackFactory.create(FeedbackSettings(feedback_backend=FeedbackBackend.SQL))
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Feedback routes over the app from agent-chat-api, with an in-memory memory and store.
|
|
2
|
+
Needs agent-chat-api (and what it requires) copied next to `feedback/`."""
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
|
6
|
+
|
|
7
|
+
from agentic.memory import InMemoryMemory, MemoryKey
|
|
8
|
+
from api.agent.settings import AgentApiSettings
|
|
9
|
+
from api.app import create_app
|
|
10
|
+
from api.auth import StaticTokenVerifier
|
|
11
|
+
from api.feedback.router import router as feedback_router
|
|
12
|
+
from feedback import InMemoryFeedbackStore
|
|
13
|
+
|
|
14
|
+
from .feedback_conformance import FakeClock
|
|
15
|
+
from .test_agent_api import TOKENS, auth
|
|
16
|
+
|
|
17
|
+
ALICE = MemoryKey(tenant_id="tenant-1", user_id="user-1", conversation_id="conv-1")
|
|
18
|
+
THREAD = [
|
|
19
|
+
HumanMessage("busca algo", id="h1"),
|
|
20
|
+
AIMessage("", id="call1", tool_calls=[{"name": "search", "args": {}, "id": "t1"}]),
|
|
21
|
+
ToolMessage("resultado", tool_call_id="t1", id="tool1"),
|
|
22
|
+
AIMessage("Encontré esto", id="a1"),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def make_app(enabled: bool = True):
|
|
27
|
+
memory = InMemoryMemory()
|
|
28
|
+
await memory.add_messages(ALICE, THREAD)
|
|
29
|
+
app = create_app(
|
|
30
|
+
settings=AgentApiSettings(agent_endpoint_enabled=enabled),
|
|
31
|
+
token_verifier=StaticTokenVerifier(TOKENS),
|
|
32
|
+
memory=memory,
|
|
33
|
+
document_search=None,
|
|
34
|
+
)
|
|
35
|
+
app.state.feedback_store = InMemoryFeedbackStore(clock=FakeClock())
|
|
36
|
+
app.include_router(feedback_router)
|
|
37
|
+
return app
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def client(app) -> httpx.AsyncClient:
|
|
41
|
+
return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
VOTE = {"conversation_id": "conv-1", "message_id": "a1", "rating": 1}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def test_guards_401_and_404_when_the_agent_is_off():
|
|
48
|
+
app = await make_app()
|
|
49
|
+
async with client(app) as c:
|
|
50
|
+
assert (await c.post("/agent/feedback", json=VOTE)).status_code == 401
|
|
51
|
+
app = await make_app(enabled=False)
|
|
52
|
+
async with client(app) as c:
|
|
53
|
+
assert (await c.post("/agent/feedback", json=VOTE, headers=auth())).status_code == 404
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def test_vote_then_revote_is_created_then_updated():
|
|
57
|
+
app = await make_app()
|
|
58
|
+
async with client(app) as c:
|
|
59
|
+
first = await c.post("/agent/feedback", json={**VOTE, "comment": "útil"}, headers=auth())
|
|
60
|
+
second = await c.post("/agent/feedback", json={**VOTE, "rating": -1}, headers=auth())
|
|
61
|
+
listed = await c.get("/agent/feedback?conversation_id=conv-1", headers=auth())
|
|
62
|
+
|
|
63
|
+
assert first.status_code == 200
|
|
64
|
+
assert first.json() == {
|
|
65
|
+
"message_id": "a1",
|
|
66
|
+
"conversation_id": "conv-1",
|
|
67
|
+
"rating": 1,
|
|
68
|
+
"comment": "útil",
|
|
69
|
+
"updated_at": "2026-03-30T10:00:00Z",
|
|
70
|
+
"created_or_updated": "created",
|
|
71
|
+
}
|
|
72
|
+
assert (second.json()["rating"], second.json()["comment"], second.json()["created_or_updated"]) == (-1, None, "updated")
|
|
73
|
+
assert [f["message_id"] for f in listed.json()["feedback"]] == ["a1"]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def test_only_answers_in_your_own_conversation_can_be_voted():
|
|
77
|
+
app = await make_app()
|
|
78
|
+
async with client(app) as c:
|
|
79
|
+
human = await c.post("/agent/feedback", json={**VOTE, "message_id": "h1"}, headers=auth())
|
|
80
|
+
tool_call = await c.post("/agent/feedback", json={**VOTE, "message_id": "call1"}, headers=auth())
|
|
81
|
+
unknown = await c.post("/agent/feedback", json={**VOTE, "message_id": "zzz"}, headers=auth())
|
|
82
|
+
other_user = await c.post("/agent/feedback", json=VOTE, headers=auth("tok-bob"))
|
|
83
|
+
bad_rating = await c.post("/agent/feedback", json={**VOTE, "rating": 0}, headers=auth())
|
|
84
|
+
|
|
85
|
+
assert [r.status_code for r in (human, tool_call, unknown, other_user)] == [404] * 4
|
|
86
|
+
assert bad_rating.status_code == 422
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
async def test_undo_removes_the_vote():
|
|
90
|
+
app = await make_app()
|
|
91
|
+
async with client(app) as c:
|
|
92
|
+
await c.post("/agent/feedback", json=VOTE, headers=auth())
|
|
93
|
+
assert (await c.delete("/agent/feedback/a1", headers=auth())).status_code == 204
|
|
94
|
+
assert (await c.delete("/agent/feedback/a1", headers=auth())).status_code == 404
|
|
95
|
+
assert (await c.get("/agent/feedback?conversation_id=conv-1", headers=auth())).json()["feedback"] == []
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# auth-verifier
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para **saber quién llama** a partir de un token Bearer sin atar la API a un proveedor: Supabase Auth (claves públicas por JWKS), JWT propio con secreto compartido, o un doble estático para tests. El proveedor se elige en `.env` y la API solo conoce `TokenVerifier.verify(token) -> CurrentUser`.
|
|
6
|
+
|
|
7
|
+
No depende de otras recetas: trae su propio `api/auth.py` (el mismo archivo que `agent-chat-api`; copiar encima no cambia nada). **Usa `project-settings`** (bloque `AuthSettings`).
|
|
8
|
+
|
|
9
|
+
## Qué incluye
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
api/auth.py CurrentUser · InvalidToken (401) · AuthUnavailable (503) · TokenVerifier (ABC) · StaticTokenVerifier · get_current_user
|
|
13
|
+
auth/
|
|
14
|
+
models.py AuthProvider (static | jwt | supabase) · TokenClaims
|
|
15
|
+
settings.py bloque AuthSettings: AUTH_PROVIDER (obligatorio), AUTH_DEFAULT_TENANT_ID, JWT_*, SUPABASE_*
|
|
16
|
+
jwt_verifier.py JwtVerifier (decodificar → claims → CurrentUser, con `_to_user` sobrescribible) · HmacJwtVerifier · issue_token
|
|
17
|
+
supabase.py SupabaseJwtVerifier (ES256/RS256 por JWKS, HS256 legado opcional) · SupabaseKeys · SigningKeys (costura)
|
|
18
|
+
factory.py AuthFactory.create(settings, static_users=...)
|
|
19
|
+
tests/test_auth.py 13 tests sin red: HS256, caducidad, emisor, audiencia, tenant, Supabase ES256 con clave generada, legado, 503, factory
|
|
20
|
+
pytest.ini
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Decisiones
|
|
24
|
+
|
|
25
|
+
- **Un contrato, tres proveedores.** `TokenVerifier` vive en `app.state.token_verifier` y `AuthFactory` construye el que diga `AUTH_PROVIDER`, sin valor por defecto: caer en el doble estático sería dejar una puerta abierta. El estático exige los usuarios en código, nunca del entorno.
|
|
26
|
+
- **Claims → usuario en un solo método.** `JwtVerifier._to_user` convierte las claims en `CurrentUser`; es async para que un proyecto con tabla de perfiles la consulte ahí y rechace cuentas sin perfil. `_claims` dice dónde están los campos: Supabase los lleva en `app_metadata` (puesto por el servidor, fiable) o `user_metadata` (lo pone el usuario: solo si te fías).
|
|
27
|
+
- **Tenant obligatorio.** Sin claim de tenant ni `AUTH_DEFAULT_TENANT_ID`, el token se rechaza: una conversación sin tenant no tiene espacio donde vivir.
|
|
28
|
+
- **Supabase solo con claves asimétricas** (ES256/RS256 por JWKS), con `aud=authenticated` e `iss=<SUPABASE_URL>/auth/v1`. Aceptar HS256 sin más permitiría usar la clave pública como secreto; se admite solo si configuras `SUPABASE_JWT_SECRET` (proyectos aún con el secreto legado).
|
|
29
|
+
- **JWKS caído no es 401.** `AuthUnavailable` se traduce a 503: el cliente no debe cerrar la sesión porque el proveedor no conteste. La primera obtención de claves va en `asyncio.to_thread`.
|
|
30
|
+
- **Los motivos solo al log.** Todo fallo de PyJWT es `InvalidToken` y el cliente ve "Invalid token"; el detalle (caducado, emisor, firma) queda en el log a nivel info.
|
|
31
|
+
- **`SigningKeys` es la costura de test:** los tests firman con una clave ES256 generada al vuelo y la inyectan en lugar del JWKS. Sin red.
|
|
32
|
+
- **`issue_token` solo para el proveedor JWT:** para tu endpoint de login o un script de desarrollo. Con Supabase los tokens los da Supabase.
|
|
33
|
+
- **Tolerancia de reloj** (`AUTH_LEEWAY_SECONDS=30`): sin ella un desfase de segundos expulsa al usuario nada más entrar.
|
|
34
|
+
|
|
35
|
+
## Cómo adaptarla
|
|
36
|
+
|
|
37
|
+
1. Copia `files/` en la raíz del backend (encima de `agent-chat-api` si la usas).
|
|
38
|
+
2. **Settings:** `class Settings(AuthSettings, BaseAppSettings)`. En el `.env`, uno de:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
AUTH_PROVIDER=supabase
|
|
42
|
+
SUPABASE_URL=https://xyz.supabase.co
|
|
43
|
+
# SUPABASE_JWT_SECRET=... solo proyectos con el secreto HS256 legado
|
|
44
|
+
AUTH_DEFAULT_TENANT_ID=default # o pon tenant_id en app_metadata
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
AUTH_PROVIDER=jwt
|
|
49
|
+
JWT_SECRET=<32 bytes o más>
|
|
50
|
+
JWT_ISSUER={{app_name}}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
3. **`main.py`:** `create_app(token_verifier=AuthFactory.create(settings), ...)`. En tests, `AuthFactory.create(settings, static_users={...})` o `StaticTokenVerifier` directamente.
|
|
54
|
+
4. **Perfiles en tu base de datos:** subclase de `HmacJwtVerifier` o `SupabaseJwtVerifier` que sobrescriba `_to_user(claims, payload)` y busque el perfil (ver `test_profile_lookup_is_one_method`). Añade la rama en `AuthFactory`.
|
|
55
|
+
5. **Roles:** `CurrentUser.role` llega de la claim (`app_metadata.role` en Supabase). Las comprobaciones (403) van en `ensure_turn_allowed` o en una dependencia `require_roles`, no aquí.
|
|
56
|
+
6. Para comprobarla: `pytest` en solitario (13 tests) o con las recetas backend (147 con las nueve).
|
|
57
|
+
|
|
58
|
+
**Dependencias:** `pyjwt[crypto]` (incluye `cryptography`, necesaria para ES256), `pydantic-settings`, `fastapi`; `httpx` en tests. Probado con PyJWT 2.15.
|
|
59
|
+
|
|
60
|
+
## Origen
|
|
61
|
+
|
|
62
|
+
- Probado en producción: proveedor elegido por settings, JWT propio HS256 con `sub`, `tenant_id` y caducidad, tenant por defecto desde settings y metadatos de usuario de Supabase; JWKS de Supabase con ES256 y HS256 legado según la cabecera del token, `leeway` de 30 s, `role=authenticated` como señal de usuario no anónimo y búsqueda del perfil tras verificar; `TokenVerifier` en `app.state`, `PyJWKClient` con caché e inyectable (`SigningKeys`), solo algoritmos asimétricos, `audience` e `issuer` verificados, error distinto cuando el proveedor no responde, factory sin valor por defecto y doble de test.
|
|
63
|
+
- Nuevo en esta receta: `_to_user` como único punto de mapeo y `TokenClaims` como modelo intermedio, para que cambiar de proveedor o añadir la tabla de perfiles no toque el resto.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Who is calling: `CurrentUser` from a Bearer token.
|
|
2
|
+
|
|
3
|
+
The router never parses tokens itself. It asks the `TokenVerifier` stored in `app.state`, so the
|
|
4
|
+
provider (Supabase, own JWT, API key...) is chosen when the app is built, and tests use
|
|
5
|
+
`StaticTokenVerifier`. The `auth-verifier` recipe provides the real verifiers and their factory
|
|
6
|
+
(and ships this same file); until then, write one subclass here.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from abc import ABC, abstractmethod
|
|
10
|
+
|
|
11
|
+
from fastapi import Depends, HTTPException, Request, status
|
|
12
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CurrentUser(BaseModel):
|
|
17
|
+
"""The authenticated caller. `tenant_id` and `id` are the namespace of every conversation,
|
|
18
|
+
so they come from the token and never from the request body. Add what your guards need."""
|
|
19
|
+
|
|
20
|
+
model_config = ConfigDict(frozen=True)
|
|
21
|
+
|
|
22
|
+
id: str = Field(min_length=1)
|
|
23
|
+
tenant_id: str = Field(min_length=1)
|
|
24
|
+
language: str = Field(default="es", description="Fallback language when the request has none.")
|
|
25
|
+
email: str | None = None
|
|
26
|
+
role: str | None = Field(default=None, description="For 403 checks in `ensure_turn_allowed`, if you have roles.")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InvalidToken(Exception):
|
|
30
|
+
"""The token is missing, expired, forged or belongs to nobody. Reason only for the logs."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AuthUnavailable(Exception):
|
|
34
|
+
"""The verifier could not decide (the identity provider did not answer). Not a 401: a 503."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class TokenVerifier(ABC):
|
|
38
|
+
@abstractmethod
|
|
39
|
+
async def verify(self, token: str) -> CurrentUser:
|
|
40
|
+
"""Return the caller, or raise `InvalidToken` (401) / `AuthUnavailable` (503)."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class StaticTokenVerifier(TokenVerifier):
|
|
44
|
+
"""A fixed `token -> user` table. For tests and local development only."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, users: dict[str, CurrentUser]) -> None:
|
|
47
|
+
self._users = users
|
|
48
|
+
|
|
49
|
+
async def verify(self, token: str) -> CurrentUser:
|
|
50
|
+
try:
|
|
51
|
+
return self._users[token]
|
|
52
|
+
except KeyError:
|
|
53
|
+
raise InvalidToken("unknown token") from None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# auto_error=False: a missing header gets the same 401 as a bad token, with our own message.
|
|
57
|
+
_bearer = HTTPBearer(auto_error=False)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def get_current_user(
|
|
61
|
+
request: Request, credentials: HTTPAuthorizationCredentials | None = Depends(_bearer)
|
|
62
|
+
) -> CurrentUser:
|
|
63
|
+
verifier: TokenVerifier | None = getattr(request.app.state, "token_verifier", None)
|
|
64
|
+
if verifier is None:
|
|
65
|
+
raise RuntimeError("app.state.token_verifier is not set: build the app with a TokenVerifier")
|
|
66
|
+
if credentials is None:
|
|
67
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Not authenticated", {"WWW-Authenticate": "Bearer"})
|
|
68
|
+
try:
|
|
69
|
+
return await verifier.verify(credentials.credentials)
|
|
70
|
+
except InvalidToken:
|
|
71
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token", {"WWW-Authenticate": "Bearer"}) from None
|
|
72
|
+
except AuthUnavailable:
|
|
73
|
+
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Authentication service unavailable") from None
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Token verifiers for `api/auth.py`: own HS256 JWT, Supabase Auth (JWKS), and the static double.
|
|
2
|
+
|
|
3
|
+
Chosen in the settings (`AUTH_PROVIDER`), built by `AuthFactory`. Claims become a `CurrentUser`
|
|
4
|
+
in one overridable method (`_to_user`), which is where a profile lookup in your DB would go.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .factory import AuthFactory
|
|
8
|
+
from .jwt_verifier import HmacJwtVerifier, JwtVerifier, issue_token
|
|
9
|
+
from .models import AuthProvider, TokenClaims
|
|
10
|
+
from .settings import AuthSettings
|
|
11
|
+
from .supabase import SupabaseJwtVerifier, SupabaseKeys
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"AuthFactory",
|
|
15
|
+
"AuthProvider",
|
|
16
|
+
"AuthSettings",
|
|
17
|
+
"HmacJwtVerifier",
|
|
18
|
+
"JwtVerifier",
|
|
19
|
+
"SupabaseJwtVerifier",
|
|
20
|
+
"SupabaseKeys",
|
|
21
|
+
"TokenClaims",
|
|
22
|
+
"issue_token",
|
|
23
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The one place that builds the verifier the settings name. There is no default."""
|
|
2
|
+
|
|
3
|
+
from api.auth import CurrentUser, StaticTokenVerifier, TokenVerifier
|
|
4
|
+
|
|
5
|
+
from .models import AuthProvider
|
|
6
|
+
from .settings import AuthSettings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AuthFactory:
|
|
10
|
+
@staticmethod
|
|
11
|
+
def create(settings: AuthSettings, *, static_users: dict[str, CurrentUser] | None = None) -> TokenVerifier:
|
|
12
|
+
"""Once at startup:
|
|
13
|
+
app = create_app(token_verifier=AuthFactory.create(get_settings()), ...)
|
|
14
|
+
`STATIC` needs `static_users` (built in code: never from the environment)."""
|
|
15
|
+
match settings.auth_provider:
|
|
16
|
+
case AuthProvider.STATIC:
|
|
17
|
+
if static_users is None:
|
|
18
|
+
raise ValueError("AUTH_PROVIDER=static needs static_users (tests and local dev only)")
|
|
19
|
+
return StaticTokenVerifier(static_users)
|
|
20
|
+
case AuthProvider.JWT:
|
|
21
|
+
from .jwt_verifier import HmacJwtVerifier
|
|
22
|
+
|
|
23
|
+
return HmacJwtVerifier(settings)
|
|
24
|
+
case AuthProvider.SUPABASE:
|
|
25
|
+
from .supabase import SupabaseJwtVerifier
|
|
26
|
+
|
|
27
|
+
return SupabaseJwtVerifier(settings)
|
|
28
|
+
raise ValueError(f"Unknown auth provider: {settings.auth_provider!r}")
|