* feat: replace provider config with credential-based system (#477) Introduce a new credential management system replacing the old ProviderConfig singleton and standalone Models page. Each credential stores encrypted API keys and provider-specific configuration with full CRUD support via a unified settings UI. Backend: - Add Credential domain model with encrypted API key storage - Add credentials API router (CRUD, discovery, registration, testing) - Add encryption utilities for secure key storage - Add key_provider for DB-first env-var fallback provisioning - Add connection tester and model discovery services - Integrate ModelManager with credential-based config - Add provider name normalization for Esperanto compatibility - Add database migrations 11-12 for credential schema Frontend: - Rewrite settings/api-keys page with credential management UI - Add model discovery dialog with search and custom model support - Add compact default model assignments (primary/advanced layout) - Add inline model testing and credential connection testing - Add env-var migration banner - Update navigation to unified settings page - Remove standalone models page and old settings components i18n: - Update all 7 locale files with credential and model management keys Closes #477 Co-Authored-By: JFMD <git@jfmd.us> Co-Authored-By: OraCatQAQ <570768706@qq.com> * fix: address PR #540 review comments - Fix docs referencing removed Models page - Fix error-handler returning raw messages instead of i18n keys - Fix auth.py misleading docstring and missing no-password guard - Fix connection_tester using wrong env var for openai_compatible - Add provision_provider_keys before model discovery/sync - Update CLAUDE.md to reflect credential-based system - Fix missing closing brace in api-keys page useEffect * fix: add logging to credential migration and surface errors in UI - Add comprehensive logging to migrate-from-env and migrate-from-provider-config endpoints (start, per-provider progress, success/failure with stack traces, final summary) - Fix frontend migration hooks ignoring errors array from response - Show error toast when migration fails instead of "nothing to migrate" - Invalidate status/envStatus queries after migration so banner updates * docs: update CLAUDE.md files for credential system Replace stale ProviderConfig and /api-keys/ references across 8 CLAUDE.md files to reflect the new Credential-based system from PR #540. * docs: update user documentation for credential-based system Replace env var API key instructions with Settings UI credential workflow across all user-facing documentation. The new flow is: set OPEN_NOTEBOOK_ENCRYPTION_KEY → start services → add credential in Settings UI → test → discover models → register. - Rewrite ai-providers.md, api-configuration.md, environment-reference.md - Update all quick-start guides and installation docs - Update ollama.md, openai-compatible.md, local-tts/stt networking sections - Update reverse-proxy.md, development-setup.md, security.md - Fix broken links to non-existent docs/deployment/ paths - Add credentials endpoints to api-reference.md - Move all API key env vars to deprecated/legacy sections * chore: bump version to 1.7.0-rc1 Release candidate for credential-based provider management system. * fix: initialize provider before try block in test_credential Prevents UnboundLocalError when Credential.get() throws (e.g., invalid credential_id) before provider is assigned. * fix: reorder down migration to drop index before table Removes duplicate REMOVE FIELD statement and reorders so the index is dropped before the table, preventing rollback failures. * refactor: simplify encryption key to always derive via SHA-256 Remove the dual code path in _ensure_fernet_key() that detected native Fernet keys. Since the credential system is new, always deriving via SHA-256 removes unnecessary complexity. Also removes the generate_key() function and Fernet.generate_key() references from docs. * fix: correct mock patch targets in embedding tests and URL validation Fix embedding tests patching wrong module path for model_manager (was targeting open_notebook.utils.embedding.model_manager but it's imported locally from open_notebook.ai.models). Also fix URL validation to allow unresolvable hostnames since they may be valid in the deployment environment (e.g., Azure endpoints, internal DNS). * feat: add global setup banner for encryption and migration status Show a persistent banner in AppShell when encryption key is missing (red) or env var API keys can be migrated (amber), so users see these prompts on every page instead of only on Settings > API Keys. Includes a docs link for the encryption banner and i18n support across all 7 locales. * docs: several improvements to docker-compose e env examples * Update README.md Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * docs: fix env var format in README and update model setup instructions Align the encryption key snippet in README Step 2 with the list format used in the compose file. Replace deprecated "Settings → Models" instructions with credential-based Discover Models flow. * fix: address credential system review issues - Fix SSRF bypass via IPv4-mapped IPv6 addresses (::ffff:169.254.x.x) - Fix TTS connection test missing config parameter - Add Azure-specific model discovery using api-key auth header - Add Vertex static model list for credential-based discovery - Fix PROVIDER_DISCOVERY_FUNCTIONS incorrect azure/vertex mapping - Extract business logic to api/credentials_service.py (service layer) - Move credential Pydantic schemas to api/models.py - Update tests to use new service imports and ValueError assertions * fix: sanitize error responses and migrate key_provider to Credential - Replace raw exception messages in all credential router 500 responses with generic error strings (internal details logged server-side only) - Refactor key_provider.py to use Credential.get_by_provider() instead of deprecated ProviderConfig.get_instance() - Remove unused functions (get_provider_configs, get_default_api_key, get_provider_config) that were dead code --------- Co-authored-by: JFMD <git@jfmd.us> Co-authored-by: OraCatQAQ <570768706@qq.com>
12 KiB
API Module
FastAPI-based REST backend exposing services for notebooks, sources, notes, chat, podcasts, and AI model management.
Purpose
FastAPI application serving three architectural layers: routes (HTTP endpoints), services (business logic), and models (request/response schemas). Integrates LangGraph workflows (chat, ask, source_chat), SurrealDB persistence, and AI providers via Esperanto.
Architecture Overview
Three layers:
- Routes (
routers/*): HTTP endpoints mapping to services - Services (
*_service.py): Business logic orchestrating domain models, database, graphs, AI providers - Models (
models.py): Pydantic request/response schemas with validation
Startup flow:
- Load .env environment variables
- Initialize CORS middleware + password auth middleware
- Run database migrations via AsyncMigrationManager on lifespan startup
- Register all routers
Key services:
chat_service.py: Invokes chat graph with messages, contextpodcast_service.py: Orchestrates outline + transcript generationsources_service.py: Content ingestion, vectorization, metadatanotes_service.py: Note creation, linking to sources/insightstransformations_service.py: Applies transformations to contentmodels_service.py: Manages AI provider/model configurationepisode_profiles_service.py: Manages podcast speaker/episode profiles
Component Catalog
Main Application
- main.py: FastAPI app initialization, CORS setup, auth middleware, lifespan event, router registration
- Lifespan handler: Runs AsyncMigrationManager on startup (database schema migration)
- Auth middleware: PasswordAuthMiddleware protects endpoints (password-based access control)
Services (Business Logic)
- chat_service.py: Invokes chat.py graph; handles message history via SqliteSaver
- podcast_service.py: Generates outline (outline.jinja), then transcript (transcript.jinja) for episodes
- sources_service.py: Ingests files/URLs (content_core), extracts text, vectorizes, saves to SurrealDB
- transformations_service.py: Applies transformations via transformation.py graph
- models_service.py: Manages ModelManager config (AI provider overrides)
- episode_profiles_service.py: CRUD for EpisodeProfile and SpeakerProfile models
- insights_service.py: Generates and retrieves source insights
- notes_service.py: Creates notes linked to sources/insights
Models (Schemas)
- models.py: Pydantic schemas for request/response validation
- Request bodies: ChatRequest, CreateNoteRequest, PodcastGenerationRequest, etc.
- Response bodies: ChatResponse, NoteResponse, PodcastResponse, etc.
- Custom validators for enum fields, file paths, model references
Routers
- routers/chat.py: POST /chat
- routers/source_chat.py: POST /source/{source_id}/chat
- routers/podcasts.py: POST /podcasts, GET /podcasts/{id}, etc.
- routers/notes.py: POST /notes, GET /notes/{id}
- routers/sources.py: POST /sources, GET /sources/{id}, DELETE /sources/{id}
- routers/models.py: GET /models, POST /models/config
- routers/credentials.py: CRUD + test + discover + migrate for credential management
- routers/transformations.py: POST /transformations
- routers/insights.py: GET /sources/{source_id}/insights
- routers/auth.py: POST /auth/password (password-based auth)
- routers/commands.py: GET /commands/{command_id} (job status tracking)
Common Patterns
- Service injection via FastAPI: Routers import services directly; no DI framework
- Async/await throughout: All DB queries, graph invocations, AI calls are async
- SurrealDB transactions: Services use repo_query, repo_create, repo_upsert from database layer
- Config override pattern: Models/config override via models_service passed to graph.ainvoke(config=...)
- Error handling: Services catch exceptions and return HTTP status codes (400 Bad Request, 404 Not Found, 500 Internal Server Error)
- Logging: loguru logger in main.py; services expected to log key operations
- Response normalization: All responses follow standard schema (data + metadata structure)
Key Dependencies
fastapi: FastAPI app, routers, HTTPExceptionpydantic: Validation models with Field, field_validatoropen_notebook.graphs: chat, ask, source_chat, source, transformation graphsopen_notebook.database: SurrealDB repository functions (repo_query, repo_create, repo_upsert)open_notebook.domain: Notebook, Source, Note, SourceInsight modelsopen_notebook.ai.provision: provision_langchain_model() factoryai_prompter: Prompter for template renderingcontent_core: extract_content() for file/URL processingesperanto: AI provider client library (LLM, embeddings, TTS)surreal_commands: Job queue for async operations (podcast generation)loguru: Structured logging
Important Quirks & Gotchas
- Migration auto-run: Database schema migrations run on every API startup (via lifespan); no manual migration steps
- PasswordAuthMiddleware is basic: Uses simple password check; production deployments should replace with OAuth/JWT
- No request rate limiting: No built-in rate limiting; deployment must add via proxy/middleware
- Service state is stateless: Services don't cache results; each request re-queries database/AI models
- Graph invocation is blocking: chat/podcast workflows may take minutes; no timeout handling in services
- Command job fire-and-forget: podcast_service.py submits jobs but doesn't wait (async job queue pattern)
- Model override scoping: Model config override via RunnableConfig is per-request only (not persistent)
- CORS open by default: main.py CORS settings allow all origins (restrict before production)
- No OpenAPI security scheme: API docs available without auth (disable before production)
- Services don't validate user permission: All endpoints trust authentication layer; no per-notebook permission checks
How to Add New Endpoint
- Create router file in
routers/(e.g.,routers/new_feature.py) - Import router into
main.pyand register:app.include_router(new_feature.router, tags=["new_feature"]) - Create service in
new_feature_service.pywith business logic - Define request/response schemas in
models.py(or createnew_feature_models.py) - Implement router functions calling service methods
- Test with
uv run uvicorn api.main:app --host 0.0.0.0 --port 5055
Testing Patterns
- Interactive docs: http://localhost:5055/docs (Swagger UI)
- Direct service tests: Import service, call methods directly with test data
- Mock graphs: Replace graph.ainvoke() with mock for testing service logic
- Database: Use test database (separate SurrealDB instance or mock repo_query)
Credential Management (API Configuration UI)
The Credential Management system enables users to configure AI provider credentials through the UI instead of environment variables. Keys are stored securely in SurrealDB (encrypted via Fernet) with database-first fallback to environment variables.
Router: routers/credentials.py
Endpoints:
| Method | Endpoint | Description |
|---|---|---|
| GET | /credentials |
List all credentials (optional ?provider= filter) |
| GET | /credentials/by-provider/{provider} |
List credentials for a provider |
| POST | /credentials |
Create a new credential |
| GET | /credentials/{credential_id} |
Get a specific credential |
| PUT | /credentials/{credential_id} |
Update a credential |
| DELETE | /credentials/{credential_id} |
Delete a credential |
| POST | /credentials/{credential_id}/test |
Test connection using credential |
| POST | /credentials/{credential_id}/discover |
Discover available models |
| POST | /credentials/{credential_id}/register-models |
Register discovered models |
| POST | /credentials/migrate-from-provider-config |
Migrate from legacy ProviderConfig |
Supported Providers (13 total):
- Simple API key:
openai,anthropic,google,groq,mistral,deepseek,xai,openrouter,voyage,elevenlabs - URL-based:
ollama - Multi-field:
azure,vertex,openai_compatible
Security Features:
- NEVER returns actual API key values (only metadata)
- URL validation (SSRF protection) on all URL fields via
_validate_url() - Allows private IPs and localhost for self-hosted services (Ollama, LM Studio)
- Requires
OPEN_NOTEBOOK_ENCRYPTION_KEYto be set for storing credentials
Domain Model: Credential (open_notebook/domain/credential.py)
Individual credential records replacing the old ProviderConfig singleton. Each credential stores:
- Provider name, display name, modalities
- Encrypted API key (via Fernet)
- Provider-specific config (base_url, endpoint, api_version, etc.)
Integration with Key Provider (open_notebook/ai/key_provider.py)
The key_provider module provisions DB-stored credentials into environment variables for Esperanto compatibility:
Database-first Pattern:
- API endpoint saves keys to
Credentialrecords (encrypted in SurrealDB) - Before model provisioning,
provision_provider_keys(provider)checks DB, then env vars - Keys from DB are set as environment variables for Esperanto compatibility
- Existing env vars remain unchanged if no DB config exists
Key Functions:
get_api_key(provider): Get API key (DB first, env fallback)provision_provider_keys(provider): Set env vars from DB for a providerprovision_all_keys(): Load all provider keys from DB into env vars
Authentication
No changes to authentication. The credentials router uses the same PasswordAuthMiddleware as all other endpoints. Keys are protected by the same password-based auth.
Auth Flow (unchanged from api/auth.py):
PasswordAuthMiddleware: Global middleware checkingAuthorization: Bearer {password}header- Default password:
open-notebook-change-me(setOPEN_NOTEBOOK_PASSWORDin production) - Docker secrets support via
OPEN_NOTEBOOK_PASSWORD_FILE
Connection Testing (open_notebook/ai/connection_tester.py)
The /credentials/{credential_id}/test endpoint uses minimal API calls to verify credentials:
- Loads Credential via
Credential.get(config_id), usescredential.to_esperanto_config() - Uses cheapest/smallest models per provider (TEST_MODELS map)
- Returns success status and descriptive message
- Special handlers for ollama, openai_compatible, and azure providers
Migration Workflows
Two migration endpoints help users transition to the credential system:
From environment variables (POST /credentials/migrate-from-env):
- Checks each provider for env var presence
- Creates Credential records from env var values
- Returns summary: migrated, skipped, errors
From legacy ProviderConfig (POST /credentials/migrate-from-provider-config):
- Reads old ProviderConfig records from database
- Converts each to individual Credential records
- Returns summary: migrated, skipped, errors
Example Usage
# Check status
GET /credentials/status
# Response: {"configured": {"openai": true, "anthropic": false}, "source": {"openai": "database", "anthropic": "none"}, "encryption_configured": true}
# Create credential
POST /credentials
{"name": "My OpenAI Key", "provider": "openai", "modalities": ["language", "embedding"], "api_key": "sk-proj-..."}
# Test connection
POST /credentials/{credential_id}/test
# Response: {"provider": "openai", "success": true, "message": "Connection successful"}
# Discover models
POST /credentials/{credential_id}/discover
# Response: {"provider": "openai", "models": [{"model_id": "gpt-4", "name": "gpt-4", ...}], "credential_id": "..."}
# Migrate from env
POST /credentials/migrate-from-env
# Response: {"message": "Migration complete. Migrated 3 providers.", "migrated": ["openai", "anthropic", "groq"], "skipped": [], "errors": []}