Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(credentials): check the credential a node actually uses
trohitg144023a00435
diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxindex c0cd6ec3..891c403a 100644--- a/client/src/components/SquareNode.tsx+++ b/client/src/components/SquareNode.tsx@@ -9,6 +9,7 @@ import { useWebSocket, useWhatsAppStatus, useNodeStatus } from '../contexts/WebSimport { isNodeInBackendGroup, resolveNodeDescription, useNodeSpec } from '../lib/nodeSpec';import { NodeIcon } from '../assets/icons';import { AI_MODEL_PROVIDER_MAP } from '../lib/aiModelProviders';+import { credentialProviderId } from '../lib/credentialProviderId';import { useProviderStored } from '../hooks/useCatalogueQuery';import type { NodeSpecHandle } from '../adapters/nodeSpecToDescription';@@ -24,13 +25,6 @@ const hasToolGroup = (definition: any): boolean => {// The map of node types itself comes from the backend NodeSpec registry.const AI_MODEL_NODE_TYPES = AI_MODEL_PROVIDER_MAP;-const CREDENTIAL_TO_PROVIDER: Record<string, string> = {- googleMapsApi: 'google_maps',- openaiApi: 'openai',- anthropicApi: 'anthropic',- googleAiApi: 'gemini',-};-const REACT_POSITION: Record<NodeSpecHandle['position'], Position> = {top: Position.Top,bottom: Position.Bottom,@@ -188,15 +182,14 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab[id, setRenamingNodeId]);- // Provider id for legacy credentialed nodes (non-AI, non-maps). AI- // model nodes route through `aiProviderId` above, Google Maps through- // `googleMapsKeyStatus` — both read from WS-context apiKeyStatuses.- const providerId = useMemo<string>(() => {- const credName = definition?.credentials?.[0]?.name;- if (credName && CREDENTIAL_TO_PROVIDER[credName]) return CREDENTIAL_TO_PROVIDER[credName];- if (type?.includes('map') || type?.includes('location')) return 'google_maps';- return '';- }, [definition?.credentials, type]);+ // Catalogue provider of the node's first declared credential: the+ // plugin credential id itself, or a mapped legacy name. Its `stored`+ // flag is `hasApiKey` below; AI model nodes add the validation state+ // from `aiProviderId`, Google Maps from `googleMapsKeyStatus`.+ const providerId = useMemo<string>(+ () => credentialProviderId(definition?.credentials?.[0]?.name, type),+ [definition?.credentials, type],+ );// "Is a credential configured for this provider?" reads from the// server-driven catalogue (single source of truth — the `stored`diff --git a/client/src/lib/__tests__/credentialProviderId.test.ts b/client/src/lib/__tests__/credentialProviderId.test.tsnew file mode 100644index 00000000..5e6667fe--- /dev/null+++ b/client/src/lib/__tests__/credentialProviderId.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { credentialProviderId } from '../credentialProviderId';++describe('credentialProviderId', () => {+ it('uses a plugin credential id as the catalogue provider id', () => {+ expect(credentialProviderId('openai', 'openaiChatModel')).toBe('openai');+ expect(credentialProviderId('openai_compatible', 'openaiCompatibleChatModel')).toBe('openai_compatible');+ expect(credentialProviderId('telegram', 'telegramSend')).toBe('telegram');+ });++ it('maps the legacy credential names', () => {+ expect(credentialProviderId('openaiApi', undefined)).toBe('openai');+ expect(credentialProviderId('googleMapsApi', undefined)).toBe('google_maps');+ });++ it('falls back to Google Maps for location nodes that declare no credential', () => {+ expect(credentialProviderId(undefined, 'gmaps_locations')).toBe('google_maps');+ expect(credentialProviderId(undefined, 'calculatorTool')).toBe('');+ });+});diff --git a/client/src/lib/credentialProviderId.ts b/client/src/lib/credentialProviderId.tsnew file mode 100644index 00000000..2dcc01a2--- /dev/null+++ b/client/src/lib/credentialProviderId.ts@@ -0,0 +1,20 @@+/**+ * Which credential-catalogue provider a canvas node's status dot reads its+ * "stored" flag from.+ *+ * A NodeSpec lists its credentials by plugin credential id (`openai`,+ * `telegram`, `openai_compatible`, ...), and those ids are catalogue provider+ * ids themselves. Only a few legacy names predate that and need mapping.+ */+const LEGACY_CREDENTIAL_NAMES: Record<string, string> = {+ googleMapsApi: 'google_maps',+ openaiApi: 'openai',+ anthropicApi: 'anthropic',+ googleAiApi: 'gemini',+};++export function credentialProviderId(credentialName: string | undefined, nodeType: string | undefined): string {+ if (credentialName) return LEGACY_CREDENTIAL_NAMES[credentialName] ?? credentialName;+ if (nodeType?.includes('map') || nodeType?.includes('location')) return 'google_maps';+ return '';+}diff --git a/server/nodes/model/_credentials.py b/server/nodes/model/_credentials.pyindex 1bed4bcf..f16c57aa 100644--- a/server/nodes/model/_credentials.py+++ b/server/nodes/model/_credentials.py@@ -309,3 +309,9 @@ class OpenAICompatibleCredential(_LLMApiKey):for e in await list_endpoints(get_auth_service())]return {"stored": bool(endpoints), "endpoints": endpoints}++ @classmethod+ async def is_configured(cls, auth_service: Any, parameters: Dict[str, Any]) -> bool:+ """The endpoint the node names is saved. Nothing is stored under the bare id."""+ ref = str(parameters.get("endpoint") or "")+ return bool(ref) and bool(await auth_service.has_valid_key(ref))diff --git a/server/services/plugin/credential.py b/server/services/plugin/credential.pyindex 36c6e232..60ffea63 100644--- a/server/services/plugin/credential.py+++ b/server/services/plugin/credential.py@@ -353,6 +353,17 @@ class Credential:"""return None+ @classmethod+ async def is_configured(cls, auth_service: Any, parameters: Dict[str, Any]) -> bool:+ """Whether a node with these ``parameters`` has what this credential needs.++ Read by the workflow validator's MISSING_CREDENTIAL check. The+ default asks whether anything is stored under ``cls.id``. A+ credential holding several named rows overrides it to check the+ row the node's parameters name.+ """+ return bool(await auth_service.has_valid_key(cls.id))+class OAuth2Credential(Credential):"""OAuth 2.0 with refresh-token support.diff --git a/server/services/workflow_validator.py b/server/services/workflow_validator.pyindex ce13c551..84e05880 100644--- a/server/services/workflow_validator.py+++ b/server/services/workflow_validator.py@@ -342,7 +342,10 @@ async def validate_workflow()# Credential presence — for each Credential subclass declared on- # the plugin, ask AuthService whether a key/token is stored.+ # the plugin, ask whether what this node needs is stored. A+ # Credential answers through ``is_configured`` (a named endpoint+ # checks the row the node names); anything else declared on a+ # plugin is checked by its id.for cred_cls in getattr(cls, "credentials", ()) or ():if auth_service is None:# Lazy import to avoid a hard dependency on the container at@@ -353,7 +356,11 @@ async def validate_workflow(auth_service = container.auth_service()try:- stored = await auth_service.has_valid_key(cred_cls.id)+ is_configured = getattr(cred_cls, "is_configured", None)+ if is_configured is not None:+ stored = await is_configured(auth_service, params)+ else:+ stored = await auth_service.has_valid_key(cred_cls.id)except Exception:logger.debug("[workflow_validator] has_valid_key failed for %s",diff --git a/server/tests/credentials/test_openai_compatible_credential.py b/server/tests/credentials/test_openai_compatible_credential.pyindex 99d8b5ab..7f74bcc9 100644--- a/server/tests/credentials/test_openai_compatible_credential.py+++ b/server/tests/credentials/test_openai_compatible_credential.py@@ -161,6 +161,34 @@ class TestDelete:broadcaster.broadcast_credential_event.assert_awaited_once()+class TestLint:+ """MISSING_CREDENTIAL asks about the endpoint the node names, not the bare id."""++ async def test_a_node_is_configured_when_its_endpoint_is_saved(self, auth):+ await _store_endpoint(auth, REF, "http://host:8000/v1", "sk-1", "Home vLLM")++ assert await OpenAICompatibleCredential.is_configured(auth, {"endpoint": REF}) is True+ assert await OpenAICompatibleCredential.is_configured(auth, {"endpoint": "openai_compatible:gone"}) is False+ assert await OpenAICompatibleCredential.is_configured(auth, {}) is False++ async def test_the_validator_warns_only_for_an_unsaved_endpoint(self, auth):+ from services.workflow_validator import validate_workflow++ await _store_endpoint(auth, REF, "http://host:8000/v1", "sk-1", "Home vLLM")++ async def missing(endpoint: str) -> list:+ report = await validate_workflow(+ nodes=[{"id": "n1", "type": "openaiCompatibleChatModel", "data": {}}],+ edges=[],+ parameters_by_id={"n1": {"endpoint": endpoint, "prompt": "hi"}},+ auth_service=auth,+ )+ return [w for w in report["warnings"] if w["code"] == "MISSING_CREDENTIAL"]++ assert await missing(REF) == []+ assert [w["provider_id"] for w in await missing("openai_compatible:gone")] == ["openai_compatible"]++def test_the_credential_is_registered_for_dispatch():from services.plugin.credential import CREDENTIAL_REGISTRYdiff --git a/server/tests/test_workflow_validator.py b/server/tests/test_workflow_validator.pyindex 3c4a205e..e07039bc 100644--- a/server/tests/test_workflow_validator.py+++ b/server/tests/test_workflow_validator.py@@ -165,6 +165,44 @@ async def test_missing_credential_is_warning(monkeypatch):assert issue["node_id"] == "n1"+class _NamedRowsCredential:+ """A credential holding several named rows: it checks the one the node names."""++ id = "fake_rows"+ auth = "api_key"++ @classmethod+ async def is_configured(cls, auth_service, parameters):+ return parameters.get("row") == "fake_rows:saved"+++class _NamedRowsNodeClass:+ type = "fakeRowsNode"++ class Params(BaseModel):+ row: str = ""++ credentials = (_NamedRowsCredential,)+++async def test_a_credential_can_check_the_row_the_node_names(monkeypatch):+ from services.workflow_validator import validate_workflow++ _patch_registry(monkeypatch, {"fakeRowsNode": _NamedRowsNodeClass})+ _patch_auth(monkeypatch, False) # nothing stored under the bare id++ report = await validate_workflow(+ nodes=[+ {"id": "saved", "type": "fakeRowsNode", "data": {"parameters": {"row": "fake_rows:saved"}}},+ {"id": "gone", "type": "fakeRowsNode", "data": {"parameters": {"row": "fake_rows:gone"}}},+ ],+ edges=[],+ )++ missing = [iss["node_id"] for iss in report["warnings"] if iss["code"] == "MISSING_CREDENTIAL"]+ assert missing == ["gone"]++async def test_cycle_is_error(monkeypatch):from services.workflow_validator import validate_workflow