diff --git a/AGENTS.md b/AGENTS.md index 9c859520f0..c369c24d13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -198,6 +198,8 @@ When tasks process templates (system prompts, HTTP call bodies, property instruc | `context` | `Map` | Input context variables set per turn | `{{context.language}}` | | `properties` | `Map` | Conversation properties — raw values from `ConversationProperties.toMap()` | `{properties.preferred_language}` | | `memory` | `Map` with `current`, `last`, `past` | Conversation step data from the pipeline | `{memory.current.output}`, `{memory.last.input}` | +| `snippets` | `Map` | Prompt Snippets — auto-injected from `PromptSnippetService` | `{{snippets.cautious_mode}}` | +| `vars` | `Map` | Global Variables — deployment-wide config from `GlobalVariableResolver` | `{{vars.default-model}}` | | `userInfo` | `Map` with `userId` | Authenticated user identity | `{{userInfo.userId}}` | | `conversationInfo` | `Map` with `conversationId`, `agentId`, etc. | Conversation metadata | `{{conversationInfo.agentId}}` | | `conversationLog` | `String` | Formatted conversation history | `{{conversationLog}}` | @@ -635,6 +637,8 @@ This is because `ConversationProperties.put()` stores `property.getValueString() | `{memory.current.output}` | Output text for current step | | | `{memory.last.input}` | Previous step's input | | | `{context.key}` | Context variable set by client | `{context.language}` | +| `{snippets.name}` | Prompt snippet content | `{snippets.cautious_mode}` | +| `{vars.key}` | Global variable value | `{vars.default-model}` | | `{userInfo.userId}` | Authenticated user ID | | | `{conversationInfo.agentId}` | Current agent ID | | | `{conversationInfo.conversationId}` | Current conversation ID | | @@ -740,7 +744,7 @@ Matcher: "actions" : "ask_for_model" | `step` | Cleared at end of turn | | `conversation` | Lives for the session (default for most agent-building properties) | | `longTerm` | Persisted to `usermemories` collection across conversations | -| `secret` | Auto-vaulted: plaintext stored in SecretsVault, raw input scrubbed from memory, vault reference (`${eddivault:...}`) stored as property value | +| `secret` | Auto-vaulted: plaintext stored in SecretsVault, raw input scrubbed from memory, vault reference (`${vault:...}`) stored as property value | > **Warning**: `scope: "secret"` requires the vault to be active (`EDDI_VAULT_MASTER_KEY` env var set). If vault is disabled (common in dev mode), `autoVaultSecret()` fails and falls back to storing plaintext — but logs an ERROR that may confuse users. For wizard-style agents that collect API keys and pass them to an endpoint (like the Agent Father), prefer `scope: "conversation"` and delegate vaulting to the receiving service. diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index e04e23ed3b..79d110eab8 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -59,6 +59,7 @@ - [Security](security.md) - [Secrets Vault](secrets-vault.md) +- [Global Variables](global-variables.md) - [Audit Ledger](audit-ledger.md) - [GDPR / CCPA Compliance](gdpr-compliance.md) - [HIPAA Compliance](hipaa-compliance.md) diff --git a/docs/a2a-protocol.md b/docs/a2a-protocol.md index 300a576254..310d8cfb84 100644 --- a/docs/a2a-protocol.md +++ b/docs/a2a-protocol.md @@ -84,7 +84,7 @@ Configure remote A2A agents in your LLM task configuration. They are discovered { "url": "https://remote-eddi.example.com/a2a/agents/support-agent", "name": "support-agent", - "apiKey": "${eddivault:remote-agent-key}", + "apiKey": "${vault:remote-agent-key}", "timeoutMs": 30000, "skillsFilter": ["order-tracking"] } @@ -96,11 +96,11 @@ Configure remote A2A agents in your LLM task configuration. They are discovered |---|---|---|---| | `url` | string | *required* | Base URL of the remote A2A agent | | `name` | string | from Agent Card | Display name (used in tool naming) | -| `apiKey` | string | — | **Must be a vault reference** (`${eddivault:...}`) to prevent secret leakage | +| `apiKey` | string | — | **Must be a vault reference** (`${vault:...}`) to prevent secret leakage | | `timeoutMs` | long | `30000` | Timeout for A2A operations | | `skillsFilter` | string[] | all skills | Only expose specific skills (by id or name) | -> **⚠️ Security:** Always use vault references (`${eddivault:my-key}`) for API keys. Raw keys trigger a runtime warning and risk leakage in configuration exports. See [Secrets Vault](secrets-vault.md). +> **⚠️ Security:** Always use vault references (`${vault:my-key}`) for API keys. Raw keys trigger a runtime warning and risk leakage in configuration exports. See [Secrets Vault](secrets-vault.md). ### How It Works diff --git a/docs/audit-ledger.md b/docs/audit-ledger.md index 2a3593de8a..c01eb3fc18 100644 --- a/docs/audit-ledger.md +++ b/docs/audit-ledger.md @@ -96,7 +96,7 @@ All string values in audit entries pass through the `SecretRedactionFilter` befo - Anthropic API keys (`sk-ant-...`) - Bearer tokens (JWTs and opaque tokens) - Generic API key patterns (`apikey=...`, `token=...`, etc.) -- Vault references (`${eddivault:...}`) +- Vault references (`${vault:...}`) Redaction is applied recursively to nested maps and lists. diff --git a/docs/changelog.md b/docs/changelog.md index 624df77aeb..82a26ff51d 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -13,6 +13,43 @@ Each entry follows this format: - **Decision** — Key design decisions and their reasoning - **Files** — Links to modified files +## 🔧 PR #470 Review Remediation (2026-05-05) + +**Repo:** EDDI (`feat/global-variables`) + +**What changed:** Addressed all Copilot and CodeRabbit review feedback on the Global Variables PR. + +### Code Fixes + +| File | Issue | Fix | +|------|-------|-----| +| `GlobalVariableCrudIT` | Invalid key test accepted 500 (should only accept 400) | Assert `statusCode(400)` only — `IllegalArgumentExceptionMapper` guarantees 400 | +| `DataStoreProducers` | Missing CDI producer for `IGlobalVariableStore` (ambiguous bean) | Added `globalVariableStore()` producer following established pattern | +| `RestGlobalVariableStore` | Null `variable` body → NPE → 500 | Added null guard throwing `BadRequestException` + unit test | +| `GlobalVariableResolver` | `getTemplateData(null)` didn't normalize to DEFAULT_TENANT | Added null → `"default"` fallback, matching `resolveValue()` | +| `PostgresGlobalVariableStore` | All `SQLException`s silently swallowed, returning empty results | Re-throw as `RuntimeException` — DB outage now surfaces properly | +| `A2AToolProviderManager` | `warnIfRawKey()` false-positive on `${vars:...}` references | Added `${vars:}` prefix recognition alongside vault prefixes | +| `McpSetupTools` | API key `@ToolArg` description incorrectly said "required for cloud providers" | Clarified: bedrock uses IAM, oracle-genai uses OCI auth — not all cloud providers need `apiKey` | + +### Test Updates + +| File | Change | +|------|--------| +| `PostgresGlobalVariableStoreTest` | 4 error-handling tests now assert `RuntimeException` propagation instead of silent empty returns | +| `RestGlobalVariableStoreTest` | +1 test: `upsertVariableNullBody` verifies `BadRequestException` on missing body | + +### Documentation Fixes + +| File | Fix | +|------|-----| +| `changelog.md` | Section title `eddivar` → `vars`; resolution order `eddivar/eddivault` → `vars/vault`; A2A Security typo (duplicate `${vault:}`); test count 48 → 75; composite key descriptions | +| `global-variables.md` | Added `text` language tags to 4 bare fenced code blocks (MD040) | +| `secrets-vault.md` | Added `text` language tags to 4 bare fenced code blocks (MD040) | + +**Files:** `DataStoreProducers.java`, `RestGlobalVariableStore.java`, `GlobalVariableResolver.java`, `PostgresGlobalVariableStore.java`, `A2AToolProviderManager.java`, `McpSetupTools.java`, `GlobalVariableCrudIT.java`, `PostgresGlobalVariableStoreTest.java`, `RestGlobalVariableStoreTest.java`, `changelog.md`, `global-variables.md`, `secrets-vault.md` + +--- + ## 🔒 CVE-2026-42198 — PostgreSQL JDBC DoS Fix (2026-05-02) **Repo:** EDDI (`fix/cve-2026-42198-postgresql`) @@ -63,6 +100,105 @@ The `Validate baselines` step only checked whether the required day/week baselin --- +## 🏷️ Late-Binding Prefix Rename (2026-05-01) + +**Repo:** EDDI (`feat/global-variables`) + +**What changed:** Unified late-binding reference syntax to use short, clean prefixes: +- `${eddivar:...}` → `${vars:...}` (clean rename — never shipped) +- `${eddivault:...}` → `${vault:...}` (backward-compat alias retained via dual-pattern regex) + +**Why:** The `eddi` prefix was redundant (you're already inside the EDDI platform) and inconsistent with the template layer which already uses `{{vars.x}}`. Short names improve DX for agent designers. + +### Backward Compatibility + +- `${eddivault:...}` is still accepted everywhere (regex alternation: `(?:vault|eddivault)`) +- Agent import auto-migrates: `${eddivault:...}` → `${vault:...}` on import +- `toReferenceString()` now outputs the new canonical form `${vault:...}` + +### Files Changed + +| Area | Files | Change | +|------|-------|--------| +| Vault core | `SecretReference.java` | Dual-pattern regex, new canonical output | +| Vault sanitization | `SecretScrubber.java`, `SecretRedactionFilter.java` | Dual-prefix detection | +| Variable resolver | `GlobalVariableResolver.java` | `EDDIVAR_PATTERN` → `VARS_PATTERN` | +| Callsites | `ApiCallExecutor`, `ChatModelRegistry`, `A2AToolProviderManager`, `VaultStartupBanner` | Dual-prefix checks, new log messages | +| Import | `AbstractBackupService`, `RestImportService` | Auto-migrate `eddivault` → `vault` on import | +| Javadoc | 10+ source files | Updated syntax examples | +| Tests | 18 test files | Updated string literals + 4 backward-compat tests | +| Docs | 12 markdown files + `AGENTS.md` | Updated all examples | + +--- + +## ⚙️ Global Variable Store — `vars` (2026-05-01) + +**Repo:** EDDI (`feat/global-variables`) + +**What changed:** Added a non-encrypted, deployment-wide Global Variable Store for runtime configuration parameters. Enables changing operational values (LLM models, API endpoints, temperatures, feature flags) across all agents simultaneously without redeployment. + +### New Components + +| Component | Purpose | +|-----------|---------| +| `GlobalVariable` | Record model: `key`, `value`, `description`, `exportable` | +| `IGlobalVariableStore` | Persistence interface (non-versioned, flat key-value) | +| `GlobalVariableStore` | MongoDB adapter (`globalvariables` collection, composite `_id` = `tenantId/key`) | +| `PostgresGlobalVariableStore` | PostgreSQL adapter (`global_variables` table, PK = `(tenant_id, key)`) | +| `GlobalVariableResolver` | Regex-based `${vars:}` resolution with Caffeine cache + invalidation listeners | +| `IRestGlobalVariableStore` | JAX-RS REST API (`/variablestore/variables`) | +| `RestGlobalVariableStore` | REST implementation with key validation and write-through cache invalidation | + +### Pipeline Integration (8 callsites) + +Resolution order: Jinja2/Qute templates → **vars** → vault. Integrated into: + +1. **LlmTask** — `{{vars.}}` template injection + `${vars:...}` in `type` field (provider late-binding) +2. **ChatModelRegistry** — `resolveAll` before `resolveSecrets`, registers invalidation listener +3. **ApiCallExecutor** — URL, body, headers, query params +4. **McpToolProviderManager** — API key/URL resolution +5. **A2AToolProviderManager** — API key/URL resolution +6. **EmbeddingModelFactory** — config params before model creation +7. **EmbeddingStoreFactory** — config params before store creation +8. **SlackChannelRouter** — channel config values + +### Design Decisions + +- **Two syntaxes**: `{{vars.}}` for template layer (system prompts), `${vars:}` for late-binding layer (everywhere). Same data, two access patterns for different resolution stages. +- **Non-versioned**: Unlike agent configs, global variables are operational deployment config. No version history — upsert semantics with PUT. +- **Non-encrypted**: Fully visible in UI and logs. Use the vault (`${vault:...}`) for sensitive values. +- **Invalidation listeners**: Downstream caches (ChatModelRegistry) register `Runnable` callbacks. When variables change, all cached model instances are evicted so agents pick up new config on next request. +- **`exportable` flag**: Variables marked `exportable: false` are excluded from agent exports (e.g., environment-specific URLs). + +### Bug Fixes + +- **BUG-1 (LlmTask)**: `task.getType()` was used raw (unresolved) in `tokenCounterFactory.getEstimator()` (line 288) and `chatModelRegistry.getOrCreateStreaming()` (line 411). Hoisted `resolvedType` above both branches so `${vars:default-provider}` works correctly for token-aware windowing and streaming mode. +- **BUG-2 (Resolver Null Safety)**: Added guard in `GlobalVariableResolver.resolveValue(value, tenantId)` to default a `null` tenantId to `"default"` before hitting the store, preventing potential undefined behavior. +- **BUG-3 (MongoDB Filter Parity)**: Extracted `compositeId()` helper and updated MongoDB `get()` and `delete()` methods to filter by `_id` (consistent with `upsert()`) instead of by fields. Added `Sorts.ascending` to MongoDB `getAll`/`listAll` for parity with Postgres. +- **BUG-4 (Postgres Reserved Words)**: Quoted SQL reserved words `"key"` and `"value"` across all DDL and DML in `PostgresGlobalVariableStore` and updated the corresponding test matchers. + +### Documentation + +- New: `docs/global-variables.md` — comprehensive public docs with architecture, syntax, REST API, use cases, and comparison table +- Updated: `AGENTS.md` — added `snippets` and `vars` to both template data model tables (sections 4.2 and 5.1) + +### Tests (75 total) + +| Test Class | Tests | Type | +|-----------|-------|------| +| `GlobalVariableTest` | 7 | Unit — model, defaults, JSON | +| `GlobalVariableResolverTest` | 14 | Unit — resolution, cache, invalidation | +| `RestGlobalVariableStoreTest` | 11 | Unit — CRUD, validation | +| `GlobalVariableCrudIT` | 8 | Integration — MongoDB CRUD lifecycle | +| `PostgresGlobalVariableCrudIT` | 8 | Integration — PostgreSQL CRUD lifecycle | +| `GlobalVariableStoreTest` | 10 | Unit — MongoDB adapter with mocked MongoCollection | +| `PostgresGlobalVariableStoreTest` | 15 | Unit — PostgreSQL adapter with mocked JDBC | +| 9 modified test suites | — | Constructor dependency updates | + +**Files:** `src/main/java/ai/labs/eddi/configs/variables/` (6 new files), `src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java`, `src/main/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistry.java`, `docs/global-variables.md`, `AGENTS.md` + +--- + ## 🔒 OpenSSF Scorecard: Pinned-Dependencies Remediation (2026-04-28) **Repo:** EDDI (`chore/openssf-pinned-dependencies`) @@ -1306,16 +1442,16 @@ All Slack credentials (`botToken`, `signingSecret`) moved from `application.prop **Before:** ```properties -eddi.slack.bot-token=${eddivault:slack-bot-token} # one per EDDI instance -eddi.slack.signing-secret=${eddivault:slack-signing-secret} +eddi.slack.bot-token=${vault:slack-bot-token} # one per EDDI instance +eddi.slack.signing-secret=${vault:slack-signing-secret} ``` **After:** ```json { "channels": [{ "type": "slack", "config": { "channelId": "C0123...", - "botToken": "${eddivault:slack-bot-token}", - "signingSecret": "${eddivault:slack-signing-secret}", + "botToken": "${vault:slack-bot-token}", + "signingSecret": "${vault:slack-signing-secret}", "groupId": "optional" }}]} ``` @@ -1328,7 +1464,7 @@ eddi.slack.signing-secret=${eddivault:slack-signing-secret} - New `SlackCredentials` record (agentId, botToken, signingSecret, groupId) - `resolveCredentials(channelId)` → returns full credentials for a channel - `getAllSigningSecrets()` → all unique signing secrets from all deployed agents -- `SecretResolver` integration for `${eddivault:...}` references at cache refresh time (60s) +- `SecretResolver` integration for `${vault:...}` references at cache refresh time (60s) - Removed dependency on `SlackIntegrationConfig` for credentials/defaults ### SlackSignatureVerifier — Multi-Secret Verification @@ -1805,7 +1941,7 @@ Added log category suppressions in `src/test/resources/application.properties`: ### Security Fix: Auto-Vault API Keys -`AgentSetupService.vaultApiKey()` — new method that automatically stores API keys in the Secrets Vault when available, persisting only the vault reference (`${eddivault:setup...apiKey}`) in the LLM config. Timestamp suffix prevents key collision when two agents share the same name. `ChatModelRegistry.resolveSecrets()` already resolves vault references at model-load time, so no downstream changes needed. +`AgentSetupService.vaultApiKey()` — new method that automatically stores API keys in the Secrets Vault when available, persisting only the vault reference (`${vault:setup...apiKey}`) in the LLM config. Timestamp suffix prevents key collision when two agents share the same name. `ChatModelRegistry.resolveSecrets()` already resolves vault references at model-load time, so no downstream changes needed. **Degraded mode:** When vault is disabled (no `EDDI_VAULT_MASTER_KEY`), logs a warning and falls back to plaintext storage. This ensures the Agent Father wizard works in dev mode without requiring vault setup. @@ -2013,7 +2149,7 @@ MCP tools default to unauthenticated (`authorization.enabled=false`). Added a pr - `SecretResolver` fires `Consumer` listeners (not `Runnable`) — passes the specific changed reference, or `null` for bulk rotation - `ChatModelRegistry` registers via `@PostConstruct` and receives the reference -- **Single secret change:** scans cache entries, evicts only models whose parameter values contain the matching vault reference (checks both `${eddivault:keyName}` and `${eddivault:tenantId/keyName}` forms) +- **Single secret change:** scans cache entries, evicts only models whose parameter values contain the matching vault reference (checks both `${vault:keyName}` and `${vault:tenantId/keyName}` forms) - **DEK/KEK rotation (null reference):** clears all models (every secret is affected) **Design decision:** Surgical eviction (not full clear, not TTL) because: (a) most deployments have multiple agents with different API keys — rotating one key shouldn't rebuild models for all providers; (b) `ConcurrentHashMap` iterator is safe for concurrent removal; (c) `CopyOnWriteArrayList` listeners are lock-free for reads. @@ -3363,11 +3499,11 @@ Complete re-architecture of the EDDI Secrets Vault from agent-scoped ephemeral s |---|---| | **Scope** | `tenant/agent/key` → `tenant/key` — secrets shared across all agents within a tenant | | **Persistence** | `DatabaseSecretProvider` (ephemeral) → `VaultSecretProvider` backed by `ISecretPersistence` (MongoDB + PostgreSQL) | -| **Reference Syntax** | New `${eddivault:keyName}` (short-form, defaults to "default" tenant) and `${eddivault:tenantId/keyName}` (full-form) | +| **Reference Syntax** | New `${vault:keyName}` (short-form, defaults to "default" tenant) and `${vault:tenantId/keyName}` (full-form) | | **Model** | `SecretReference` dual-format regex, `SecretMetadata` gains `description`, `lastRotatedAt`, `allowedAgents`, `@JsonFormat(STRING)` timestamps | | **REST API** | 3-segment → 2-segment paths (removed agentId), `SecretRequest` with description/allowedAgents | | **Auto-Vaulting** | `PropertySetterTask.autoVaultSecret()` namespaces keys with `agentId.keyName` to prevent cross-agent collision | -| **A2A Security** | `A2AToolProviderManager` recognizes both `${vault:}` (legacy) and `${eddivault:}` prefixes | +| **A2A Security** | `A2AToolProviderManager` recognizes both `${vault:}` (canonical) and `${eddivault:}` (legacy) prefixes | **Manager UI changes:** @@ -3382,7 +3518,7 @@ Complete re-architecture of the EDDI Secrets Vault from agent-scoped ephemeral s **Design decisions:** - Access control by configuration authorship — admins control which vault references to embed in agent configs, not runtime enforcement -- Short-form `${eddivault:keyName}` preferred for UX simplicity; full-form available for multi-tenant deployments +- Short-form `${vault:keyName}` preferred for UX simplicity; full-form available for multi-tenant deployments - Auto-vaulted property keys prefixed with `agentId.` to prevent cross-agent collisions while keeping the short-form UX - `VaultStartupBanner` Javadoc updated from deleted `DatabaseSecretProvider` to `VaultSecretProvider` @@ -4124,7 +4260,7 @@ Implemented the Agent2Agent (A2A) protocol for distributed peer-to-peer agent co | **A2A Client** | `A2AToolProviderManager.java` (mirrors `McpToolProviderManager` — discovers remote agents, wraps skills as `ToolSpecification`) | | **Config** | `AgentConfiguration` gains `a2aEnabled`, `a2aSkills`, `description` fields; `LlmConfiguration.Task` gains `a2aAgents` list with `A2AAgentConfig` | | **Integration** | `AgentOrchestrator` + `LlmTask` inject `A2AToolProviderManager`; A2A tools merge alongside built-in, MCP, and httpcall tools | -| **Security** | Vault reference enforcement for API keys (`${eddivault:...}`), runtime warning on raw key usage | +| **Security** | Vault reference enforcement for API keys (`${vault:...}`), runtime warning on raw key usage | | **Endpoints** | `GET /.well-known/agent.json`, `GET/POST /a2a/agents/{id}`, `GET /a2a/agents` | **Design decisions:** @@ -4528,7 +4664,7 @@ Agents can now connect to external MCP servers and use their tools during conver | **AgentOrchestrator** | MCP tool specs merged into tool-calling loop with budget/rate-limiting | | **McpSetupTools** | `mcpServers` param on `setup_agent` — comma-separated URLs → `McpServerConfig` list | -**Design:** StreamableHttpMcpTransport (non-deprecated), graceful degradation (MCP failures never kill pipeline), port 7070, `${eddivault:key}` support. +**Design:** StreamableHttpMcpTransport (non-deprecated), graceful degradation (MCP failures never kill pipeline), port 7070, `${vault:key}` support. **Tests:** `McpToolProviderManagerTest` (8 tests), updated `AgentOrchestratorTest` + `LangchainTaskTest` + `McpSetupToolsTest` (21 calls). @@ -5016,7 +5152,7 @@ Security audit identified 5 critical/high issues in the vault implementation. Al **Additional fixes:** -- Fixed `SecretRedactionFilter` — `$` in replacement string `${eddivault:}` was interpreted as regex group reference +- Fixed `SecretRedactionFilter` — `$` in replacement string `${vault:}` was interpreted as regex group reference - Removed dead `secretResolver` field from `PropertySetterTask` (left over from R1 fix) - Fixed 8 pre-existing Lombok ghost-method bugs in OutputItem subclasses + `OutputConfiguration` - Cleaned unused imports in `HttpCallExecutorTest` and `PropertySetterTaskTest` diff --git a/docs/developer-quickstart.md b/docs/developer-quickstart.md index 5917ba30fc..3888c1651a 100644 --- a/docs/developer-quickstart.md +++ b/docs/developer-quickstart.md @@ -79,7 +79,7 @@ cd EDDI open http://localhost:7070 ``` -> **💡 Secrets Vault:** If you plan to store API keys through the Manager UI or use `${eddivault:...}` references, set the vault master key first: +> **💡 Secrets Vault:** If you plan to store API keys through the Manager UI or use `${vault:...}` references, set the vault master key first: > > ```bash > export EDDI_VAULT_MASTER_KEY=my-dev-passphrase # Linux/macOS diff --git a/docs/global-variables.md b/docs/global-variables.md new file mode 100644 index 0000000000..415c4ed1cd --- /dev/null +++ b/docs/global-variables.md @@ -0,0 +1,331 @@ +# Global Variables + +EDDI includes a built-in global variable store for managing configuration values like default LLM model names, API base URLs, temperature settings, and feature flags. Variables are **scoped per tenant** — single-tenant deployments use `"default"` implicitly, while multi-tenant deployments can maintain separate variable sets per tenant. Unlike secrets, global variables are **not encrypted** and are **fully visible** in the UI and logs. + +## Architecture + +```text +┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐ +│ Configuration │────>│ GlobalVariable │────>│ GlobalVariable │ +│ (JSON configs) │ │ Resolver │ │ Store │ +│ ${vars:..} │ │ (regex + cache) │ │ (MongoDB/PG) │ +└─────────────────┘ └──────────────────┘ └──────────────────┘ + │ + ▼ +┌─────────────────┐ +│ Template Layer │ +│ {{vars.}} │ +│ (Jinja2/Qute) │ +└─────────────────┘ +``` + +### Core Components + +| Component | Package | Purpose | +|-----------|---------|---------| +| `GlobalVariable` | `configs.variables.model` | Record: `tenantId`, `key`, `value`, `description`, `exportable` | +| `IGlobalVariableStore` | `configs.variables` | Persistence interface (non-versioned, tenant-scoped key-value) | +| `GlobalVariableStore` | `configs.variables.mongo` | MongoDB implementation (`globalvariables` collection, composite `_id: tenantId/key`) | +| `PostgresGlobalVariableStore` | `datastore.postgres` | PostgreSQL implementation (`global_variables` table, PK: `(tenant_id, key)`) | +| `GlobalVariableResolver` | `configs.variables` | Resolves `${vars:...}` references with Caffeine cache | +| `IRestGlobalVariableStore` | `configs.variables.rest` | JAX-RS REST interface | +| `RestGlobalVariableStore` | `configs.variables.rest` | REST implementation with key validation and cache invalidation | + +## Two Access Syntaxes + +Global variables are available through two complementary syntaxes: + +### 1. Template Syntax: `{{vars.}}` + +Available in LLM task system prompts and other template contexts. Resolved by the Jinja2/Qute template engine at template processing time. + +```text +You are an AI assistant powered by {{vars.default-model}}. +Always respond at temperature {{vars.default-temperature}}. +``` + +### 2. Late-Binding Syntax: `${vars:}` / `${vars:tenantId/}` + +Available **everywhere** — in LLM task parameters, HTTP call configurations, MCP/A2A settings, embedding configs, Slack configs, and even the `type` field that selects the LLM provider. Resolved by `GlobalVariableResolver` at runtime, after template processing but before vault secret resolution. + +Supports two forms, mirroring the vault's pattern: + +| Form | Syntax | Behavior | +|------|--------|----------| +| **Short form** | `${vars:key}` | Uses the context tenant (defaults to `"default"`) | +| **Full form** | `${vars:tenantId/key}` | Uses the explicit tenant | + +```json +{ + "type": "${vars:default-provider}", + "parameters": { + "model": "${vars:default-model}", + "apiKey": "${vault:openai-api-key}", + "baseUrl": "${vars:api-base-url}" + } +} +``` + +Multi-tenant example: +```json +{ + "parameters": { + "model": "${vars:tenant-a/default-model}" + } +} +``` + +### When to Use Which + +| Syntax | Where It Works | When to Use | +|--------|---------------|-------------| +| `{{vars.}}` | System prompts, template-processed strings | Dynamic prompt content that changes per-deployment | +| `${vars:}` | Everywhere (params, URLs, headers, type) | Operational config that affects infrastructure | + +### Resolution Order + +EDDI resolves configuration values in a strict three-step order: + +```text +1. Jinja2/Qute templates → {{vars.x}}, {{snippets.x}}, {{properties.x}}, etc. +2. Global variables → ${vars:x} ← this feature +3. Vault secrets → ${vault:x} +``` + +This ordering is important: vault secrets can contain global variable references, and global variables can be composed with template expressions. + +> **⚠️ Nesting is not supported.** `${vars:${vault:x}}` and `${vault:${vars:x}}` will NOT work. Each resolution layer operates independently on the fully-resolved output of the previous layer. + +## Where References Work + +`${vars:...}` references are resolved in these pipeline callsites: + +| Configuration Type | Fields Resolved | +|-------------------|-----------------| +| **LLM Task** (`langchain.json`) | `type` (provider selection), all template parameters | +| **Chat Model Registry** | All model parameters before model creation | +| **HTTP Calls** (`httpcalls.json`) | URL, request body, headers, query parameters | +| **MCP Tool Providers** | API keys, server URLs | +| **A2A Tool Providers** | API keys, agent URLs | +| **Embedding Model Factory** | All embedding model parameters | +| **Embedding Store Factory** | All embedding store parameters | +| **Slack Channel Router** | Channel configuration values (bot tokens, etc.) | + +## REST API + +All endpoints require the `eddi-admin` or `eddi-editor` role. + +### Endpoints + +| Method | Path | Description | +|--------|------|-------------| +| `GET` | `/variablestore/variables/{tenantId}` | List all variables for a tenant | +| `GET` | `/variablestore/variables/{tenantId}/{key}` | Get a single variable by tenant and key | +| `PUT` | `/variablestore/variables/{tenantId}/{key}` | Create or update a variable | +| `DELETE` | `/variablestore/variables/{tenantId}/{key}` | Delete a variable | + +> **Single-tenant shortcut:** Use `default` as the tenantId for single-tenant deployments. + +### ID Validation + +Both `tenantId` and `key` must match the pattern `[a-zA-Z0-9_.\-]+`: + +| Valid ✅ | Invalid ❌ | +|---------|-----------| +| `default` | `has space` | +| `tenant-a` | `key=value` | +| `api.base-url` | `key/path` | +| `feature_flag_v2` | `special!char` | + +### Response Examples + +**`GET /variablestore/variables/default`**: + +```json +[ + { + "tenantId": "default", + "key": "default-model", + "value": "gpt-4.1", + "description": "The default LLM model used by all agents", + "exportable": true + }, + { + "tenantId": "default", + "key": "api.base-url", + "value": "https://api.openai.com", + "description": "OpenAI API base URL", + "exportable": false + } +] +``` + +**`PUT /variablestore/variables/default/default-model`** — request body: + +```json +{ + "key": "default-model", + "value": "gpt-4.1-mini", + "description": "The default LLM model used by all agents", + "exportable": true +} +``` + +**`GET /variablestore/variables/default/missing-key`** — returns `404 Not Found`. + +## Caching + +Global variables are cached in a Caffeine cache with a **2-minute TTL** (configurable). This means: + +- Variables load once from the database, then serve from cache +- After creating/updating/deleting a variable via the REST API, changes take effect **immediately** (the REST endpoint invalidates the cache) +- If the database is updated directly (outside the REST API), changes appear within 2 minutes + +### Configuration + +```properties +# Cache TTL for global variables (default: 2 minutes) +eddi.variables.cache-ttl-minutes=2 +``` + +### Downstream Cache Invalidation + +When global variables change, downstream caches that were built with old variable values need to be evicted. The `GlobalVariableResolver` supports an **invalidation listener** pattern: + +- **ChatModelRegistry** registers a listener that clears all cached model instances when variables change +- This ensures that if you change `${vars:default-model}` from `gpt-4.1` to `gpt-4.1-mini`, all agents pick up the new model on their next request + +## Use Cases + +### Fleet-Wide Model Switching + +Set a default model for all agents: + +```bash +# Set the variable (default tenant) +curl -X PUT http://localhost:7070/variablestore/variables/default/default-model \ + -H "Content-Type: application/json" \ + -d '{"key": "default-model", "value": "gpt-4.1", "description": "Fleet default"}' +``` + +Reference it in all agents' `langchain.json`: +```json +{ + "type": "${vars:default-provider}", + "parameters": { + "model": "${vars:default-model}" + } +} +``` + +Switch all agents at once: +```bash +curl -X PUT http://localhost:7070/variablestore/variables/default/default-model \ + -H "Content-Type: application/json" \ + -d '{"key": "default-model", "value": "gpt-4.1-mini"}' +``` + +### Multi-Tenant Model Switching + +Set a different default model per tenant: + +```bash +# Tenant A uses GPT +curl -X PUT http://localhost:7070/variablestore/variables/tenant-a/default-model \ + -H "Content-Type: application/json" \ + -d '{"key": "default-model", "value": "gpt-4.1"}' + +# Tenant B uses Claude +curl -X PUT http://localhost:7070/variablestore/variables/tenant-b/default-model \ + -H "Content-Type: application/json" \ + -d '{"key": "default-model", "value": "claude-sonnet-4-20250514"}' +``` + +Reference in agent config: +```json +{ + "parameters": { + "model": "${vars:default-model}" + } +} +``` + +### Environment-Specific API Endpoints + +```json +{ + "key": "api-gateway-url", + "value": "https://staging.api.example.com", + "description": "API gateway URL (changes between staging/production)", + "exportable": false +} +``` + +### Feature Flags + +```json +{ + "key": "enable-rag", + "value": "true", + "description": "Toggle RAG context injection" +} +``` + +### System Prompt Injection + +```text +You are an AI assistant for {{vars.company-name}}. +Your default language is {{vars.default-language}}. +Current API version: {{vars.api-version}}. +``` + +## Comparison: Global Variables vs Secrets vs Properties vs Snippets + +| Aspect | Global Variables | Secrets Vault | Properties | Snippets | +|--------|-----------------|---------------|------------|----------| +| **Purpose** | Operational config | Sensitive credentials | Per-user/conversation state | Reusable prompt text | +| **Scope** | Per-tenant (all agents) | Per-tenant | Per-user or per-conversation | Deployment-wide | +| **Encryption** | None | AES-256-GCM | None | None | +| **Visibility** | Fully visible | Write-only | Fully visible | Fully visible | +| **Template syntax** | `{{vars.}}` | — | `{{properties.}}` | `{{snippets.}}` | +| **Late-binding** | `${vars:}` or `${vars:tenantId/}` | `${vault:}` or `${vault:tenantId/}` | — | — | +| **Versioned** | No | No | No | Yes | +| **REST path** | `/variablestore/variables/{tenantId}` | `/secretstore/secrets/{tenantId}` | via PropertySetter | `/snippetstore/snippets` | +| **Caching** | 2 min (per-tenant) | 5 min | No cache | 5 min | +| **Export** | Configurable (`exportable`) | Always scrubbed | Per-user | Included | + +### Decision Guide + +- **Need to store an API key?** → Use the **Secrets Vault** (`${vault:...}`) +- **Need to change the LLM model for all agents?** → Use a **Global Variable** (`${vars:...}`) +- **Need to remember a user's name across conversations?** → Use **Properties** with `scope: longTerm` +- **Need reusable system prompt instructions?** → Use **Prompt Snippets** (`{{snippets.}}`) + +## Testing + +### Backend Tests + +| Test Class | Tests | Coverage | +|-----------|-------|---------| +| `GlobalVariableTest` | 9 | Model record, tenant defaults, JSON serialization, equality | +| `GlobalVariableResolverTest` | 16 | Short/full form resolution, tenant caching, invalidation, edge cases | +| `RestGlobalVariableStoreTest` | 11 | CRUD, tenant+key validation, cache invalidation, patterns | +| `GlobalVariableStoreTest` | 9 | MongoDB adapter CRUD with mocked MongoCollection, tenant scoping | +| `PostgresGlobalVariableStoreTest` | 14 | PostgreSQL adapter CRUD with mocked JDBC, tenant isolation, error paths | +| `GlobalVariableCrudIT` | 8 | Full CRUD lifecycle against MongoDB (Testcontainers) | +| `PostgresGlobalVariableCrudIT` | 8 | Full CRUD lifecycle against PostgreSQL (Testcontainers) | + +### Integration Tests + +The integration tests verify the complete REST API lifecycle: + +1. List variables (initially empty) +2. Create a variable via PUT +3. Read the variable by key +4. Update the variable value +5. Verify the variable appears in the list +6. Verify 404 for non-existent keys +7. Verify validation rejects invalid key patterns +8. Delete the variable and verify removal + +Tests run against both MongoDB and PostgreSQL via Quarkus DevServices (Testcontainers). diff --git a/docs/how-to....md b/docs/how-to....md index 3aed487b62..fb068aa6f4 100644 --- a/docs/how-to....md +++ b/docs/how-to....md @@ -16,7 +16,7 @@ "id": "openai_chat", "type": "openai", "parameters": { - "apiKey": "${eddivault:OPENAI_KEY}", + "apiKey": "${vault:OPENAI_KEY}", "modelName": "gpt-4o", "systemMessage": "You are a helpful assistant", "sendConversation": "true", @@ -50,7 +50,7 @@ curl -X PUT http://localhost:7070/secretstore/secrets/MY_API_KEY \ ```json { "parameters": { - "apiKey": "${eddivault:MY_API_KEY}" + "apiKey": "${vault:MY_API_KEY}" } } ``` diff --git a/docs/mcp-server.md b/docs/mcp-server.md index 995dda7efa..171575ad73 100644 --- a/docs/mcp-server.md +++ b/docs/mcp-server.md @@ -529,7 +529,7 @@ Add `mcpServers` to a LangChain task configuration: { "url": "http://localhost:7070/mcp", "name": "eddi-docs", - "apiKey": "${eddivault:mcp-api-key}", + "apiKey": "${vault:mcp-api-key}", "timeoutMs": 30000 }, { @@ -547,7 +547,7 @@ Add `mcpServers` to a LangChain task configuration: | `url` | string | **Yes** | — | MCP server URL (Streamable HTTP transport) | | `name` | string | No | URL | Human-readable name for logging | | `transport` | string | No | `"streamableHttp"` | Transport type (only `streamableHttp` supported) | -| `apiKey` | string | No | — | API key, sent as `Authorization: Bearer `. Supports `${eddivault:key}` references | +| `apiKey` | string | No | — | API key, sent as `Authorization: Bearer `. Supports `${vault:key}` references | | `timeoutMs` | long | No | `30000` | Connection and request timeout in milliseconds | ### Using `setup_agent` with MCP Servers @@ -592,5 +592,5 @@ The `mcpServers` parameter accepts a comma-separated list of URLs. - **Graceful degradation**: Failed MCP connections log warnings but never kill the pipeline - **Connection caching**: `McpToolProviderManager` reuses connections across conversation turns - **Budget/rate-limiting**: MCP tools are subject to the same `ToolExecutionService` controls as built-in tools -- **Vault references**: API keys support `${eddivault:key}` syntax via `SecretResolver` +- **Vault references**: API keys support `${vault:key}` syntax via `SecretResolver` - **Clean shutdown**: All MCP clients are closed on application shutdown via `@PreDestroy` diff --git a/docs/model-cascade.md b/docs/model-cascade.md index 998201df4b..6be00351f8 100644 --- a/docs/model-cascade.md +++ b/docs/model-cascade.md @@ -21,7 +21,7 @@ Cascading is configured per-task in a `langchain.json` resource: "actions": ["*"], "parameters": { "systemMessage": "You are a helpful assistant.", - "apiKey": "${eddivault:openai-key}", + "apiKey": "${vault:openai-key}", "logSizeLimit": "10" }, "modelCascade": { diff --git a/docs/rag.md b/docs/rag.md index 41ad369aa1..d258ecc5d2 100644 --- a/docs/rag.md +++ b/docs/rag.md @@ -42,7 +42,7 @@ A `RagConfiguration` is a versioned resource at `/ragstore/rags/`. It defines: "embeddingProvider": "openai", "embeddingParameters": { "model": "text-embedding-3-small", - "apiKey": "${eddivault:tenant/agent/openai-key}" + "apiKey": "${vault:tenant/agent/openai-key}" }, "storeType": "in-memory", "storeParameters": {}, @@ -185,7 +185,7 @@ These are visible in the conversation memory snapshot and the audit ledger. | Provider | Default Model | Required Parameters | Notes | |---|---|---|---| -| `openai` | `text-embedding-3-small` | `apiKey` | Use `${eddivault:...}` for keys | +| `openai` | `text-embedding-3-small` | `apiKey` | Use `${vault:...}` for keys | | `azure-openai` | `text-embedding-3-small` | `endpoint`, `apiKey`, `deploymentName` | Azure-hosted OpenAI models | | `ollama` | `nomic-embed-text` | — | `baseUrl` (default: `localhost:11434`) | | `mistral` | `mistral-embed` | `apiKey` | Mistral AI embedding model | diff --git a/docs/release-notes-6.0.2.md b/docs/release-notes-6.0.2.md index b99416c490..ebbd62c9c0 100644 --- a/docs/release-notes-6.0.2.md +++ b/docs/release-notes-6.0.2.md @@ -17,7 +17,7 @@ ### Vault & Encryption - **Per-deployment random KEK salt** — Each EDDI instance now generates a unique 16-byte salt for key derivation (was hardcoded). Backward-compatible: existing deployments auto-detect and use legacy salt - **KEK rotation salt migration** — `rotateKek()` now properly migrates from legacy to new salt during key rotation -- **API key auto-vaulting** — Agent setup automatically stores API keys in the Secrets Vault, persisting only vault references (`${eddivault:...}`) in MongoDB +- **API key auto-vaulting** — Agent setup automatically stores API keys in the Secrets Vault, persisting only vault references (`${vault:...}`) in MongoDB ### Authentication & Authorization - **AuthStartupGuard** — Fail-loud production auth check: EDDI refuses to start if OIDC is disabled in production (escape hatch: `eddi.security.allow-unauthenticated=true`) diff --git a/docs/secrets-vault.md b/docs/secrets-vault.md index b42c82c8a7..8c6423cd86 100644 --- a/docs/secrets-vault.md +++ b/docs/secrets-vault.md @@ -4,11 +4,11 @@ EDDI includes a built-in secrets vault for managing sensitive values like API ke ## Architecture -``` +```text ┌─────────────────┐ ┌──────────────┐ ┌───────────────────┐ │ Configuration │────>│ SecretResolver│────>│ VaultSecretProv. │ │ (JSON configs) │ │ (resolves │ │ (envelope crypto │ -│ ${eddivault:..} │ │ at runtime) │ │ + persistence) │ +│ ${vault:..} │ │ at runtime) │ │ + persistence) │ └─────────────────┘ └──────────────┘ └───────────────────┘ │ ┌────────▼────────┐ @@ -26,9 +26,9 @@ EDDI includes a built-in secrets vault for managing sensitive values like API ke | `EnvelopeCrypto` | `secrets.crypto` | AES-256-GCM encryption with envelope key wrapping | | `ISecretProvider` | `secrets` | SPI for reading/writing encrypted secrets | | `VaultSecretProvider` | `secrets.impl` | Production implementation with envelope crypto + persistence | -| `SecretResolver` | `secrets` | Resolves `${eddivault:...}` references to plaintext at runtime | +| `SecretResolver` | `secrets` | Resolves `${vault:...}` references to plaintext at runtime | | `IRestSecretStore` / `RestSecretStore` | `secrets.rest` | JAX-RS endpoints for secret CRUD and key rotation | -| `SecretScrubber` | `secrets.sanitize` | Removes `${eddivault:...}` references from export payloads | +| `SecretScrubber` | `secrets.sanitize` | Removes `${vault:...}` references from export payloads | | `SecretRedactionFilter` | `secrets.sanitize` | Regex-based log redaction for API keys, tokens, vault refs | | `ISecretPersistence` | `secrets.persist.` | DB abstraction (MongoDB default, PostgreSQL via profile) | @@ -37,13 +37,13 @@ EDDI includes a built-in secrets vault for managing sensitive values like API ke Secrets are referenced in configuration JSON using the vault URI syntax: **Short form** (uses `default` tenant): -``` -${eddivault:keyName} +```text +${vault:keyName} ``` **Full form** (explicit tenant): -``` -${eddivault:tenantId/keyName} +```text +${vault:tenantId/keyName} ``` - **tenantId** — tenant namespace (e.g., `default`, `acme-corp`) @@ -61,7 +61,7 @@ ${eddivault:tenantId/keyName} Vault references are resolved **at runtime** when the task executes, never stored as plaintext in conversation memory. The resolution flow: -1. Task reads configuration containing `${eddivault:...}` reference +1. Task reads configuration containing `${vault:...}` reference 2. `SecretResolver.resolveValue()` finds and replaces vault URIs 3. `VaultSecretProvider.resolve()` decrypts and returns the plaintext 4. Plaintext is used for the operation (e.g., HTTP call header) @@ -75,7 +75,7 @@ Vault references are resolved **at runtime** when the task executes, never store EDDI uses **envelope encryption** — each tenant gets its own random Data Encryption Key (DEK), which is itself encrypted by a Key Encryption Key (KEK) derived from the master password. -``` +```text Master Password → PBKDF2 (600,000 iterations) → KEK │ Secret → tenant DEK → AES-256-GCM encrypt → ciphertext @@ -87,7 +87,7 @@ Secret → tenant DEK → AES-256-GCM encrypt → ciphertext ### Configuration -The vault requires a master key (KEK) to encrypt/decrypt secrets. If not set, the vault is **disabled** — all `${eddivault:...}` references pass through unresolved and a prominent warning is logged at startup. +The vault requires a master key (KEK) to encrypt/decrypt secrets. If not set, the vault is **disabled** — all `${vault:...}` references pass through unresolved and a prominent warning is logged at startup. #### Installer (Recommended) @@ -148,7 +148,7 @@ When a property has `scope: secret`: 1. **PropertySetterTask** detects `scope == secret` on the property instruction 2. The raw value is immediately stored in the vault via `ISecretProvider.store()` -3. A vault reference (`${eddivault:...}`) replaces the plaintext in memory +3. A vault reference (`${vault:...}`) replaces the plaintext in memory 4. The raw `input:initial` entry is scrubbed from the conversation step When the **client flags input as secret** (via the `secretInput` context key): @@ -212,7 +212,7 @@ The default Agent Father agent demonstrates vault integration during API key set } ``` -The `scope: secret` instruction causes `PropertySetterTask` to store the API key in the vault and replace the memory value with a `${eddivault:...}` reference. +The `scope: secret` instruction causes `PropertySetterTask` to store the API key in the vault and replace the memory value with a `${vault:...}` reference. ## Auto-Vaulting (Agent Setup) @@ -222,7 +222,7 @@ When creating agents through the **Agent Father** wizard or the Setup API, API k 1. User provides an API key during agent setup 2. `AgentSetupService.vaultApiKey()` stores the key in the vault -3. A vault reference (`${eddivault:setup...apiKey}`) is written to the LLM configuration +3. A vault reference (`${vault:setup...apiKey}`) is written to the LLM configuration 4. When the vault is enabled, the plaintext key is never persisted in MongoDB — only the vault reference is stored ### Collision Prevention @@ -261,7 +261,7 @@ All endpoints are under the base path `/secretstore/secrets`. All endpoints requ ```json { - "reference": "${eddivault:apiKey}", + "reference": "${vault:apiKey}", "tenantId": "default", "keyName": "apiKey" } @@ -399,7 +399,7 @@ The EDDI Manager includes a dedicated **Secrets Admin** page at `/manage/secrets | Anthropic keys (`sk-ant-...`) | `sk-ant-` | `sk-ant-api03-...` → `sk-ant-` | | Bearer tokens | `Bearer ` | `Bearer eyJhb...` → `Bearer ` | | API key params | `apikey=` | `apikey=secret123` → `apikey=` | -| Vault references | `${eddivault:}` | `${eddivault:t/key}` → `${eddivault:}` | +| Vault references | `${vault:}` | `${vault:t/key}` → `${vault:}` | ### Export Sanitization diff --git a/docs/slack-integration.md b/docs/slack-integration.md index 4153e13e79..5ba26ff06b 100644 --- a/docs/slack-integration.md +++ b/docs/slack-integration.md @@ -64,8 +64,8 @@ Add a `ChannelConnector` to your agent configuration: "type": "slack", "config": { "channelId": "C0123ABCDEF", - "botToken": "${eddivault:slack-bot-token}", - "signingSecret": "${eddivault:slack-signing-secret}", + "botToken": "${vault:slack-bot-token}", + "signingSecret": "${vault:slack-signing-secret}", "groupId": "optional-group-id-for-discussions" } } @@ -134,8 +134,8 @@ All credentials live in the agent's `ChannelConnector.config` map: ``` Agent Config → ChannelConnector.config - ├─ botToken: "${eddivault:slack-bot-token}" - └─ signingSecret: "${eddivault:slack-signing-secret}" + ├─ botToken: "${vault:slack-bot-token}" + └─ signingSecret: "${vault:slack-signing-secret}" │ ▼ SlackChannelRouter (60s cache refresh) @@ -277,8 +277,8 @@ Configure on each agent's `channels[]` array: "type": "slack", "config": { "channelId": "C0123ABCDEF", - "botToken": "${eddivault:slack-bot-token}", - "signingSecret": "${eddivault:slack-signing-secret}", + "botToken": "${vault:slack-bot-token}", + "signingSecret": "${vault:slack-signing-secret}", "groupId": "optional-group-id" } } diff --git a/src/main/java/ai/labs/eddi/backup/impl/AbstractBackupService.java b/src/main/java/ai/labs/eddi/backup/impl/AbstractBackupService.java index 1134ee1300..352396fd44 100644 --- a/src/main/java/ai/labs/eddi/backup/impl/AbstractBackupService.java +++ b/src/main/java/ai/labs/eddi/backup/impl/AbstractBackupService.java @@ -81,4 +81,16 @@ static String normalizeLegacyUris(String jsonString) { } return result; } + + /** + * Normalize legacy vault references during import: {@code ${eddivault:...}} → + * {@code ${vault:...}}. This ensures imported configs use the canonical short + * prefix, converging all stored configs over time. + */ + static String normalizeVaultReferences(String jsonString) { + if (jsonString == null || !jsonString.contains("${eddivault:")) { + return jsonString; + } + return jsonString.replace("${eddivault:", "${vault:"); + } } diff --git a/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java b/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java index 2def8a2d9d..4580f44647 100644 --- a/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java +++ b/src/main/java/ai/labs/eddi/backup/impl/RestImportService.java @@ -409,6 +409,8 @@ private Response importAgentZipFile(InputStream zippedAgentConfigFiles, File tar // Normalize legacy eddi:// URIs from v5 ZIP exports to v6 canonical form agentFileString = normalizeLegacyUris(agentFileString); + // Normalize legacy ${eddivault:...} → ${vault:...} + agentFileString = normalizeVaultReferences(agentFileString); AgentConfiguration agentConfig = jsonSerialization.deserialize(agentFileString, AgentConfiguration.class); agentConfig.getWorkflows() @@ -472,6 +474,8 @@ private void parseWorkflow(String targetDirPath, URI workflowUri, AgentConfigura // Normalize legacy eddi:// URIs from v5 ZIP exports to v6 canonical form workflowFileString = normalizeLegacyUris(workflowFileString); + // Normalize legacy ${eddivault:...} → ${vault:...} + workflowFileString = normalizeVaultReferences(workflowFileString); // loading old resources, creating/updating them, // updating document descriptor and replacing references in workflow config @@ -1164,6 +1168,9 @@ private List readResources(List uris, Path workflowPath, String exte } } + // Normalize legacy ${eddivault:...} → ${vault:...} + resourceContent = normalizeVaultReferences(resourceContent); + // Final pass: migrate any remaining Thymeleaf template syntax to Qute resourceContent = templateSyntaxMigrator.migrate(resourceContent); diff --git a/src/main/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsConfiguration.java b/src/main/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsConfiguration.java index 086285b54a..a75f9831d5 100644 --- a/src/main/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsConfiguration.java +++ b/src/main/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsConfiguration.java @@ -36,8 +36,8 @@ public class McpCallsConfiguration { private String transport = "http"; /** - * Optional API key or vault reference (e.g., "${eddivault:my-api-key}"). - * Resolved at connection time via {@code SecretResolver}. + * Optional API key or vault reference (e.g., "${vault:my-api-key}"). Resolved + * at connection time via {@code SecretResolver}. */ private String apiKey; diff --git a/src/main/java/ai/labs/eddi/configs/rag/model/RagConfiguration.java b/src/main/java/ai/labs/eddi/configs/rag/model/RagConfiguration.java index d927a9fda4..cb763b0de8 100644 --- a/src/main/java/ai/labs/eddi/configs/rag/model/RagConfiguration.java +++ b/src/main/java/ai/labs/eddi/configs/rag/model/RagConfiguration.java @@ -48,17 +48,16 @@ public class RagConfiguration { * Provider-specific parameters. Keys vary by provider: *
    *
  • OpenAI: {"model": "text-embedding-3-small", "apiKey": - * "${eddivault:tenant/agent/openai-key}"}
  • + * "${vault:tenant/agent/openai-key}"} *
  • Azure OpenAI: {"endpoint": "https://my.openai.azure.com/", "apiKey": - * "${eddivault:...}", "deploymentName": "text-embedding-3-small"}
  • + * "${vault:...}", "deploymentName": "text-embedding-3-small"} *
  • Ollama: {"model": "nomic-embed-text", "baseUrl": * "http://localhost:11434"}
  • - *
  • Mistral: {"model": "mistral-embed", "apiKey": "${eddivault:...}"}
  • + *
  • Mistral: {"model": "mistral-embed", "apiKey": "${vault:...}"}
  • *
  • Bedrock: {"model": "amazon.titan-embed-text-v2:0", "region": * "us-east-1"}
  • - *
  • Cohere: {"model": "embed-english-v3.0", "apiKey": - * "${eddivault:...}"}
  • - *
  • Gemini: {"model": "gemini-embedding-001", "apiKey": "${eddivault:...}", + *
  • Cohere: {"model": "embed-english-v3.0", "apiKey": "${vault:...}"}
  • + *
  • Gemini: {"model": "gemini-embedding-001", "apiKey": "${vault:...}", * "taskType": "RETRIEVAL_DOCUMENT"}
  • *
  • Vertex: {"project": "my-project", "location": "us-central1", "model": * "text-embedding-005"}
  • diff --git a/src/main/java/ai/labs/eddi/configs/variables/GlobalVariableResolver.java b/src/main/java/ai/labs/eddi/configs/variables/GlobalVariableResolver.java new file mode 100644 index 0000000000..f466221c70 --- /dev/null +++ b/src/main/java/ai/labs/eddi/configs/variables/GlobalVariableResolver.java @@ -0,0 +1,246 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables; + +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import jakarta.annotation.PostConstruct; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Resolves {@code ${vars:...}} references in configuration values at runtime + * (late-binding). Supports two forms: + *
      + *
    • Short form: {@code ${vars:keyName}} — uses the provided tenant + * context (defaults to {@code "default"})
    • + *
    • Full form: {@code ${vars:tenantId/keyName}} — explicit tenant
    • + *
    + *

    + * Values are loaded from {@link IGlobalVariableStore} and cached per-tenant via + * Caffeine with a configurable TTL. Cache invalidation is triggered by + * {@link #invalidateCache()}, which also notifies downstream listeners (e.g., + * {@code ChatModelRegistry}). + * + * @author ginccc + * @since 6.0.0 + */ +@ApplicationScoped +public class GlobalVariableResolver { + + private static final Logger LOGGER = Logger.getLogger(GlobalVariableResolver.class); + + /** + * Dual-format pattern matching both variable reference forms: + *

      + *
    • {@code ${vars:keyName}} — group(1) is null, group(2) is keyName
    • + *
    • {@code ${vars:tenantId/keyName}} — group(1) is tenantId, group(2) is + * keyName
    • + *
    + */ + static final Pattern VARS_PATTERN = Pattern.compile( + "\\$\\{vars:(?:([a-zA-Z0-9_.\\-]+)/)?([a-zA-Z0-9_.\\-]+)\\}"); + + private final IGlobalVariableStore store; + private final int cacheTtlMinutes; + + /** Per-tenant variable cache: tenantId → (key → value). */ + private Cache> cache; + + /** + * Listeners notified when the variable cache is invalidated. Used by downstream + * caches (e.g., ChatModelRegistry) to evict stale model instances that were + * built with old variable values. + */ + private final List invalidationListeners = new CopyOnWriteArrayList<>(); + + @Inject + public GlobalVariableResolver(IGlobalVariableStore store, + @ConfigProperty(name = "eddi.variables.cache-ttl-minutes", defaultValue = "2") int cacheTtlMinutes) { + this.store = store; + this.cacheTtlMinutes = cacheTtlMinutes; + } + + @PostConstruct + void init() { + this.cache = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMinutes(cacheTtlMinutes)) + .maximumSize(32) + .build(); + LOGGER.infof("GlobalVariableResolver initialized (cache TTL=%dmin)", cacheTtlMinutes); + } + + /** + * Quick check whether a string contains any {@code ${vars:...}} reference. + */ + public static boolean containsReference(String value) { + return value != null && value.contains("${vars:"); + } + + /** + * Resolve all {@code ${vars:...}} references using the default tenant. + * + * @param value + * the value that may contain {@code ${vars:...}} references + * @return the value with references replaced by stored values + */ + public String resolveValue(String value) { + return resolveValue(value, GlobalVariable.DEFAULT_TENANT); + } + + /** + * Resolve all {@code ${vars:...}} references in a single string value. + *

    + * For {@code ${vars:key}} (short form), uses the provided {@code tenantId}. For + * {@code ${vars:explicitTenant/key}} (full form), uses the explicit tenant. + *

    + * Missing variables are left as-is (passthrough) so they can be reported by + * downstream validation or logged for debugging. + * + * @param value + * the value that may contain {@code ${vars:...}} references + * @param tenantId + * the tenant context for short-form references + * @return the value with references replaced by stored values + */ + public String resolveValue(String value, String tenantId) { + if (!containsReference(value)) { + return value; + } + if (tenantId == null) { + tenantId = GlobalVariable.DEFAULT_TENANT; + } + + Matcher matcher = VARS_PATTERN.matcher(value); + StringBuilder result = new StringBuilder(); + + while (matcher.find()) { + String explicitTenant = matcher.group(1); + String key = matcher.group(2); + + // Full form: ${vars:tenantId/key} → use explicit tenant + // Short form: ${vars:key} → use the provided tenantId + String effectiveTenant = explicitTenant != null ? explicitTenant : tenantId; + + Map variables = loadVariables(effectiveTenant); + String resolved = variables.get(key); + if (resolved != null) { + matcher.appendReplacement(result, Matcher.quoteReplacement(resolved)); + } else { + // Leave the original reference — variable not found + matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group(0))); + LOGGER.debugf("Global variable not found: %s/%s — passing through unchanged", + effectiveTenant, key); + } + } + matcher.appendTail(result); + return result.toString(); + } + + /** + * Resolve all {@code ${vars:...}} references in a parameter map using the + * default tenant. Values not containing references pass through unchanged. + * + * @param params + * the parameter map + * @return a new map with references replaced + */ + public Map resolveAll(Map params) { + return resolveAll(params, GlobalVariable.DEFAULT_TENANT); + } + + /** + * Resolve all {@code ${vars:...}} references in a parameter map. Values not + * containing references pass through unchanged. + * + * @param params + * the parameter map + * @param tenantId + * the tenant context for short-form references + * @return a new map with references replaced + */ + public Map resolveAll(Map params, String tenantId) { + if (params == null || params.isEmpty()) { + return params; + } + + var resolved = new HashMap<>(params); + resolved.replaceAll((key, value) -> resolveValue(value, tenantId)); + return resolved; + } + + /** + * Get all global variables for the default tenant as a map suitable for + * injection into the Jinja2 template data model (the {@code {{vars.}}} + * namespace). + * + * @return a map of key → value (cast to Object for template compatibility) + */ + public Map getTemplateData() { + return getTemplateData(GlobalVariable.DEFAULT_TENANT); + } + + /** + * Get all global variables for a specific tenant as a map suitable for + * injection into the template data model. + * + * @param tenantId + * the tenant to load variables for + * @return a map of key → value (cast to Object for template compatibility) + */ + public Map getTemplateData(String tenantId) { + if (tenantId == null) { + tenantId = GlobalVariable.DEFAULT_TENANT; + } + Map variables = loadVariables(tenantId); + return new HashMap<>(variables); + } + + /** + * Invalidate the local cache for all tenants. Called by the REST store on + * writes. Also notifies all registered invalidation listeners. + */ + public void invalidateCache() { + cache.invalidateAll(); + LOGGER.info("Global variable cache invalidated"); + fireInvalidationListeners(); + } + + /** + * Register a listener that is called whenever global variables change. Used by + * downstream caches to perform surgical eviction. + * + * @param listener + * a callback to invoke on invalidation + */ + public void registerInvalidationListener(Runnable listener) { + invalidationListeners.add(listener); + } + + private Map loadVariables(String tenantId) { + return cache.get(tenantId, store::getAll); + } + + private void fireInvalidationListeners() { + for (Runnable listener : invalidationListeners) { + try { + listener.run(); + } catch (Exception e) { + LOGGER.warnf("Global variable invalidation listener failed: %s", e.getMessage()); + } + } + } +} diff --git a/src/main/java/ai/labs/eddi/configs/variables/IGlobalVariableStore.java b/src/main/java/ai/labs/eddi/configs/variables/IGlobalVariableStore.java new file mode 100644 index 0000000000..565553b10e --- /dev/null +++ b/src/main/java/ai/labs/eddi/configs/variables/IGlobalVariableStore.java @@ -0,0 +1,51 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables; + +import ai.labs.eddi.configs.variables.model.GlobalVariable; + +import java.util.List; +import java.util.Map; + +/** + * Persistence interface for global configuration variables, scoped per tenant. + *

    + * Unlike {@code IResourceStore}, global variables are not versioned — + * they are simple key-value pairs for operational deployment configuration, not + * agent definitions. Each variable is uniquely identified by + * {@code (tenantId, key)}. + * + * @author ginccc + * @since 6.0.0 + */ +public interface IGlobalVariableStore { + + /** + * Get all variables for a tenant as a flat key→value map (used by the resolver + * cache). + */ + Map getAll(String tenantId); + + /** + * Get a single variable by tenant and key, or {@code null} if not found. + */ + GlobalVariable get(String tenantId, String key); + + /** + * Create or update a variable. If a variable with the same tenant+key exists, + * it is overwritten. The {@code tenantId} is taken from the record. + */ + void upsert(GlobalVariable variable); + + /** + * Delete a variable by tenant and key. No-op if the key does not exist. + */ + void delete(String tenantId, String key); + + /** + * List all variables for a tenant as full objects (with descriptions). + */ + List listAll(String tenantId); +} diff --git a/src/main/java/ai/labs/eddi/configs/variables/model/GlobalVariable.java b/src/main/java/ai/labs/eddi/configs/variables/model/GlobalVariable.java new file mode 100644 index 0000000000..2db9340415 --- /dev/null +++ b/src/main/java/ai/labs/eddi/configs/variables/model/GlobalVariable.java @@ -0,0 +1,72 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.model; + +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * A global configuration variable — a key-value pair scoped at the tenant + * level, available across all agents within that tenant. + *

    + * Global variables are resolved in two ways: + *

      + *
    • Template layer: {@code {{vars.}}} — in LlmTask system + * prompts
    • + *
    • Late-binding layer: {@code ${vars:}} (default tenant) or + * {@code ${vars:tenantId/}} (explicit tenant) — everywhere (LLM params, + * httpCalls, MCP, A2A, embeddings, Slack, the {@code type} field)
    • + *
    + *

    + * Unlike vault secrets, global variables are not encrypted and are + * fully visible in the UI and logs. Use the vault for sensitive values. + *

    + * Follows the same tenant scoping model as + * {@link ai.labs.eddi.secrets.model.SecretReference}: single-tenant deployments + * use {@code "default"} implicitly; multi-tenant deployments pass an explicit + * tenant ID. + * + * @author ginccc + * @since 6.0.0 + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record GlobalVariable( + String tenantId, + String key, + String value, + String description, + Boolean exportable) { + + /** Default tenant ID used when none is specified. */ + public static final String DEFAULT_TENANT = "default"; + + /** + * Compact constructor — defaults {@code tenantId} to {@code "default"} and + * {@code exportable} to {@code true} if not specified. + */ + public GlobalVariable { + if (tenantId == null) { + tenantId = DEFAULT_TENANT; + } + if (exportable == null) { + exportable = true; + } + } + + /** + * Convenience constructor for key-value only (default tenant, no description, + * exportable=true). + */ + public GlobalVariable(String key, String value) { + this(DEFAULT_TENANT, key, value, null, true); + } + + /** + * Convenience constructor with tenant + key-value (no description, + * exportable=true). + */ + public GlobalVariable(String tenantId, String key, String value) { + this(tenantId, key, value, null, true); + } +} diff --git a/src/main/java/ai/labs/eddi/configs/variables/mongo/GlobalVariableStore.java b/src/main/java/ai/labs/eddi/configs/variables/mongo/GlobalVariableStore.java new file mode 100644 index 0000000000..3a0b92a640 --- /dev/null +++ b/src/main/java/ai/labs/eddi/configs/variables/mongo/GlobalVariableStore.java @@ -0,0 +1,117 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.mongo; + +import ai.labs.eddi.configs.variables.IGlobalVariableStore; +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.ReplaceOptions; +import io.quarkus.arc.DefaultBean; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.bson.Document; +import org.jboss.logging.Logger; + +import java.util.*; + +/** + * MongoDB implementation of {@link IGlobalVariableStore}. + *

    + * Uses a dedicated {@code globalvariables} collection with a compound identity + * of {@code (tenantId, key)}. The MongoDB {@code _id} is formed as + * {@code tenantId/key} for uniqueness. + * + *

    + * { "_id": "default/default-model", "tenantId": "default", "key": "default-model",
    + *   "value": "gpt-4.1", "description": "...", "exportable": true }
    + * 
    + * + * No versioning — this is operational deployment config, not agent definitions. + * + * @author ginccc + * @since 6.0.0 + */ +@ApplicationScoped +@DefaultBean +public class GlobalVariableStore implements IGlobalVariableStore { + + private static final Logger LOGGER = Logger.getLogger(GlobalVariableStore.class); + private static final String COLLECTION_NAME = "globalvariables"; + private static final String FIELD_TENANT_ID = "tenantId"; + private static final String FIELD_KEY = "key"; + private static final String FIELD_VALUE = "value"; + private static final String FIELD_DESCRIPTION = "description"; + private static final String FIELD_EXPORTABLE = "exportable"; + + private final MongoCollection collection; + + @Inject + public GlobalVariableStore(MongoDatabase database) { + this.collection = database.getCollection(COLLECTION_NAME); + LOGGER.infof("GlobalVariableStore initialized (collection=%s)", COLLECTION_NAME); + } + + /** Composite _id used as the unique document key: {@code tenantId/key}. */ + private static String compositeId(String tenantId, String key) { + return tenantId + "/" + key; + } + + @Override + public Map getAll(String tenantId) { + Map result = new LinkedHashMap<>(); + collection.find(Filters.eq(FIELD_TENANT_ID, tenantId)) + .forEach(doc -> result.put(doc.getString(FIELD_KEY), doc.getString(FIELD_VALUE))); + return result; + } + + @Override + public GlobalVariable get(String tenantId, String key) { + Document doc = collection.find(Filters.eq("_id", compositeId(tenantId, key))).first(); + if (doc == null) { + return null; + } + return toGlobalVariable(doc); + } + + @Override + public void upsert(GlobalVariable variable) { + String id = compositeId(variable.tenantId(), variable.key()); + Document doc = new Document("_id", id) + .append(FIELD_TENANT_ID, variable.tenantId()) + .append(FIELD_KEY, variable.key()) + .append(FIELD_VALUE, variable.value()) + .append(FIELD_DESCRIPTION, variable.description()) + .append(FIELD_EXPORTABLE, variable.exportable()); + + collection.replaceOne( + new Document("_id", id), + doc, + new ReplaceOptions().upsert(true)); + } + + @Override + public void delete(String tenantId, String key) { + collection.deleteOne(Filters.eq("_id", compositeId(tenantId, key))); + } + + @Override + public List listAll(String tenantId) { + List result = new ArrayList<>(); + collection.find(Filters.eq(FIELD_TENANT_ID, tenantId)) + .forEach(doc -> result.add(toGlobalVariable(doc))); + return result; + } + + private static GlobalVariable toGlobalVariable(Document doc) { + return new GlobalVariable( + doc.getString(FIELD_TENANT_ID), + doc.getString(FIELD_KEY), + doc.getString(FIELD_VALUE), + doc.getString(FIELD_DESCRIPTION), + doc.getBoolean(FIELD_EXPORTABLE, true)); + } +} diff --git a/src/main/java/ai/labs/eddi/configs/variables/rest/IRestGlobalVariableStore.java b/src/main/java/ai/labs/eddi/configs/variables/rest/IRestGlobalVariableStore.java new file mode 100644 index 0000000000..b175fc4256 --- /dev/null +++ b/src/main/java/ai/labs/eddi/configs/variables/rest/IRestGlobalVariableStore.java @@ -0,0 +1,59 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.rest; + +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import jakarta.annotation.security.RolesAllowed; +import org.eclipse.microprofile.openapi.annotations.Operation; +import org.eclipse.microprofile.openapi.annotations.tags.Tag; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import java.util.List; + +/** + * REST API for global configuration variables, scoped per tenant. + *

    + * Global variables are key-value pairs available in agent configurations via: + *

      + *
    • {@code ${vars:}} — late-binding, default tenant (works + * everywhere)
    • + *
    • {@code ${vars:tenantId/}} — late-binding, explicit tenant
    • + *
    • {@code {{vars.}}} — template layer (LlmTask system prompts)
    • + *
    + * + * @author ginccc + * @since 6.0.0 + */ +@Path("/variablestore/variables") +@Tag(name = "Global Variables") +@RolesAllowed({"eddi-admin", "eddi-editor"}) +public interface IRestGlobalVariableStore { + + @GET + @Path("/{tenantId}") + @Produces(MediaType.APPLICATION_JSON) + @Operation(operationId = "listGlobalVariables", description = "List all global variables for a tenant.") + List listVariables(@PathParam("tenantId") String tenantId); + + @GET + @Path("/{tenantId}/{key}") + @Produces(MediaType.APPLICATION_JSON) + @Operation(operationId = "getGlobalVariable", description = "Get a single global variable by tenant and key.") + GlobalVariable getVariable(@PathParam("tenantId") String tenantId, @PathParam("key") String key); + + @PUT + @Path("/{tenantId}/{key}") + @Consumes(MediaType.APPLICATION_JSON) + @Operation(operationId = "upsertGlobalVariable", description = "Create or update a global variable.") + Response upsertVariable(@PathParam("tenantId") String tenantId, @PathParam("key") String key, + GlobalVariable variable); + + @DELETE + @Path("/{tenantId}/{key}") + @Operation(operationId = "deleteGlobalVariable", description = "Delete a global variable.") + Response deleteVariable(@PathParam("tenantId") String tenantId, @PathParam("key") String key); +} diff --git a/src/main/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStore.java b/src/main/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStore.java new file mode 100644 index 0000000000..49d5870085 --- /dev/null +++ b/src/main/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStore.java @@ -0,0 +1,98 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.rest; + +import ai.labs.eddi.configs.variables.GlobalVariableResolver; +import ai.labs.eddi.configs.variables.IGlobalVariableStore; +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.NotFoundException; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.regex.Pattern; + +import static ai.labs.eddi.utils.LogSanitizer.sanitize; + +/** + * REST implementation for global variable CRUD. + *

    + * Writes invalidate the {@link GlobalVariableResolver} cache so that subsequent + * reads pick up the new values immediately. + * + * @author ginccc + * @since 6.0.0 + */ +@ApplicationScoped +public class RestGlobalVariableStore implements IRestGlobalVariableStore { + + private static final Logger LOGGER = Logger.getLogger(RestGlobalVariableStore.class); + private static final Pattern ID_PATTERN = Pattern.compile("[a-zA-Z0-9_.\\-]+"); + + private final IGlobalVariableStore store; + private final GlobalVariableResolver resolver; + + @Inject + public RestGlobalVariableStore(IGlobalVariableStore store, GlobalVariableResolver resolver) { + this.store = store; + this.resolver = resolver; + } + + @Override + public List listVariables(String tenantId) { + validateId(tenantId, "tenantId"); + return store.listAll(tenantId); + } + + @Override + public GlobalVariable getVariable(String tenantId, String key) { + validateId(tenantId, "tenantId"); + validateId(key, "key"); + var variable = store.get(tenantId, key); + if (variable == null) { + throw new NotFoundException("Global variable not found: " + sanitize(tenantId) + "/" + sanitize(key)); + } + return variable; + } + + @Override + public Response upsertVariable(String tenantId, String key, GlobalVariable variable) { + validateId(tenantId, "tenantId"); + validateId(key, "key"); + if (variable == null) { + throw new BadRequestException("Request body must not be empty"); + } + + // Ensure the path params take precedence over anything in the body + var toStore = new GlobalVariable(tenantId, key, variable.value(), variable.description(), variable.exportable()); + store.upsert(toStore); + resolver.invalidateCache(); + + LOGGER.infof("Global variable upserted: %s/%s", sanitize(tenantId), sanitize(key)); + return Response.ok().build(); + } + + @Override + public Response deleteVariable(String tenantId, String key) { + validateId(tenantId, "tenantId"); + validateId(key, "key"); + store.delete(tenantId, key); + resolver.invalidateCache(); + + LOGGER.infof("Global variable deleted: %s/%s", sanitize(tenantId), sanitize(key)); + return Response.noContent().build(); + } + + private static void validateId(String value, String fieldName) { + if (value == null || !ID_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException( + fieldName + " must match [a-zA-Z0-9_.\\-]+ (letters, digits, dots, underscores, hyphens). Got: " + + sanitize(value)); + } + } +} diff --git a/src/main/java/ai/labs/eddi/datastore/DataStoreProducers.java b/src/main/java/ai/labs/eddi/datastore/DataStoreProducers.java index 990f8e67dd..633000ec08 100644 --- a/src/main/java/ai/labs/eddi/datastore/DataStoreProducers.java +++ b/src/main/java/ai/labs/eddi/datastore/DataStoreProducers.java @@ -10,6 +10,8 @@ import ai.labs.eddi.configs.migration.IMigrationManager; import ai.labs.eddi.configs.migration.MigrationLogStore; import ai.labs.eddi.configs.migration.MigrationManager; +import ai.labs.eddi.configs.variables.IGlobalVariableStore; +import ai.labs.eddi.configs.variables.mongo.GlobalVariableStore; import ai.labs.eddi.configs.properties.IUserMemoryStore; import ai.labs.eddi.configs.properties.mongo.MongoUserMemoryStore; import ai.labs.eddi.datastore.mongo.MongoResourceStorageFactory; @@ -17,6 +19,7 @@ import ai.labs.eddi.datastore.postgres.PostgresConversationMemoryStore; import ai.labs.eddi.datastore.postgres.PostgresDatabaseLogs; import ai.labs.eddi.datastore.postgres.PostgresDeploymentStorage; +import ai.labs.eddi.datastore.postgres.PostgresGlobalVariableStore; import ai.labs.eddi.datastore.postgres.PostgresMigrationLogStore; import ai.labs.eddi.datastore.postgres.PostgresMigrationManager; import ai.labs.eddi.datastore.postgres.PostgresResourceStorageFactory; @@ -143,4 +146,10 @@ public IMigrationLogStore migrationLogStore(Instance mongo, I public IMigrationManager migrationManager(Instance mongo, Instance postgres) { return isPostgres() ? postgres.get() : mongo.get(); } + + @Produces + @ApplicationScoped + public IGlobalVariableStore globalVariableStore(Instance mongo, Instance postgres) { + return isPostgres() ? postgres.get() : mongo.get(); + } } diff --git a/src/main/java/ai/labs/eddi/datastore/postgres/PostgresGlobalVariableStore.java b/src/main/java/ai/labs/eddi/datastore/postgres/PostgresGlobalVariableStore.java new file mode 100644 index 0000000000..f12d938ee7 --- /dev/null +++ b/src/main/java/ai/labs/eddi/datastore/postgres/PostgresGlobalVariableStore.java @@ -0,0 +1,180 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.datastore.postgres; + +import ai.labs.eddi.configs.variables.IGlobalVariableStore; +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import io.quarkus.arc.DefaultBean; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import javax.sql.DataSource; +import java.sql.*; +import java.util.*; + +/** + * PostgreSQL implementation of {@link IGlobalVariableStore}. + *

    + * Uses a dedicated {@code global_variables} table with a composite primary key + * {@code (tenant_id, key)}. Schema is auto-created on first access. + * + *

    + * CREATE TABLE IF NOT EXISTS global_variables (
    + *     tenant_id   VARCHAR(255) NOT NULL DEFAULT 'default',
    + *     "key"       VARCHAR(255) NOT NULL,
    + *     "value"     TEXT NOT NULL,
    + *     description TEXT,
    + *     exportable  BOOLEAN DEFAULT TRUE,
    + *     PRIMARY KEY (tenant_id, "key")
    + * );
    + * 
    + * + * @author ginccc + * @since 6.0.0 + */ +@ApplicationScoped +@DefaultBean +public class PostgresGlobalVariableStore implements IGlobalVariableStore { + + private static final Logger LOGGER = Logger.getLogger(PostgresGlobalVariableStore.class); + + private static final String CREATE_TABLE = """ + CREATE TABLE IF NOT EXISTS global_variables ( + tenant_id VARCHAR(255) NOT NULL DEFAULT 'default', + "key" VARCHAR(255) NOT NULL, + "value" TEXT NOT NULL, + description TEXT, + exportable BOOLEAN DEFAULT TRUE, + PRIMARY KEY (tenant_id, "key") + ) + """; + + private final Instance dataSourceInstance; + private volatile boolean schemaInitialized = false; + + @Inject + public PostgresGlobalVariableStore(Instance dataSourceInstance) { + this.dataSourceInstance = dataSourceInstance; + } + + private synchronized void ensureSchema() { + if (schemaInitialized) + return; + try (Connection conn = dataSourceInstance.get().getConnection(); + Statement stmt = conn.createStatement()) { + stmt.execute(CREATE_TABLE); + schemaInitialized = true; + LOGGER.info("PostgresGlobalVariableStore initialized (table=global_variables)"); + } catch (SQLException e) { + throw new RuntimeException("Failed to initialize global_variables table", e); + } + } + + @Override + public Map getAll(String tenantId) { + ensureSchema(); + Map result = new LinkedHashMap<>(); + String sql = "SELECT \"key\", \"value\" FROM global_variables WHERE tenant_id = ? ORDER BY \"key\""; + try (Connection conn = dataSourceInstance.get().getConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, tenantId); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + result.put(rs.getString("key"), rs.getString("value")); + } + } + } catch (SQLException e) { + throw new RuntimeException("Failed to list all global variables for tenant: " + tenantId, e); + } + return result; + } + + @Override + public GlobalVariable get(String tenantId, String key) { + ensureSchema(); + String sql = "SELECT tenant_id, \"key\", \"value\", description, exportable FROM global_variables WHERE tenant_id = ? AND \"key\" = ?"; + try (Connection conn = dataSourceInstance.get().getConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, tenantId); + ps.setString(2, key); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return toGlobalVariable(rs); + } + } + } catch (SQLException e) { + throw new RuntimeException("Failed to get global variable: " + tenantId + "/" + key, e); + } + return null; + } + + @Override + public void upsert(GlobalVariable variable) { + ensureSchema(); + String sql = """ + INSERT INTO global_variables (tenant_id, "key", "value", description, exportable) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT (tenant_id, "key") DO UPDATE + SET "value" = EXCLUDED."value", + description = EXCLUDED.description, + exportable = EXCLUDED.exportable + """; + try (Connection conn = dataSourceInstance.get().getConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, variable.tenantId()); + ps.setString(2, variable.key()); + ps.setString(3, variable.value()); + ps.setString(4, variable.description()); + ps.setBoolean(5, variable.exportable()); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RuntimeException("Failed to upsert global variable: " + variable.tenantId() + "/" + variable.key(), e); + } + } + + @Override + public void delete(String tenantId, String key) { + ensureSchema(); + String sql = "DELETE FROM global_variables WHERE tenant_id = ? AND \"key\" = ?"; + try (Connection conn = dataSourceInstance.get().getConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, tenantId); + ps.setString(2, key); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RuntimeException("Failed to delete global variable: " + tenantId + "/" + key, e); + } + } + + @Override + public List listAll(String tenantId) { + ensureSchema(); + List result = new ArrayList<>(); + String sql = "SELECT tenant_id, \"key\", \"value\", description, exportable FROM global_variables WHERE tenant_id = ? ORDER BY \"key\""; + try (Connection conn = dataSourceInstance.get().getConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setString(1, tenantId); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + result.add(toGlobalVariable(rs)); + } + } + } catch (SQLException e) { + throw new RuntimeException("Failed to list all global variables for tenant: " + tenantId, e); + } + return result; + } + + private static GlobalVariable toGlobalVariable(ResultSet rs) throws SQLException { + return new GlobalVariable( + rs.getString("tenant_id"), + rs.getString("key"), + rs.getString("value"), + rs.getString("description"), + rs.getBoolean("exportable")); + } +} diff --git a/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java b/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java index 98e7f567b8..e68fff0a37 100644 --- a/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java +++ b/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java @@ -56,9 +56,10 @@ public String setupAgent(@ToolArg(description = "Agent name (required)") String + "'azure-openai', 'bedrock', or 'oracle-genai'") String provider, @ToolArg(description = "Model name, e.g. 'claude-sonnet-4-6' (default), 'gpt-5.4', " + "'gemini-3.1-pro-preview', 'deepseek-chat', 'llama3.2:1b' (ollama)") String model, - @ToolArg(description = "API key for the LLM provider. Required for cloud providers " - + "(anthropic, openai, gemini). Optional/unused for local LLMs (ollama, jlama). " - + "Can be a vault reference like '${eddivault:openai-key}'.") String apiKey, + @ToolArg(description = "API key for the LLM provider. Required for most cloud providers " + + "(anthropic, openai, gemini, mistral). Not needed for bedrock (uses IAM), " + + "oracle-genai (uses OCI auth), or local LLMs (ollama, jlama). " + + "Can be a vault reference like '${vault:openai-key}'.") String apiKey, @ToolArg(description = "Base URL for the LLM provider (optional). " + "Useful for ollama when running in Docker (e.g. 'http://host.docker.internal:11434')") String baseUrl, @ToolArg(description = "Greeting message shown when a conversation starts (optional)") String introMessage, @@ -105,11 +106,12 @@ public String createApIAgent(@ToolArg(description = "Agent name (required)") Str @ToolArg(description = "LLM provider: 'anthropic' (default), 'openai', 'gemini', 'mistral', " + "'azure-openai', 'bedrock', 'oracle-genai', etc.") String provider, @ToolArg(description = "Model name (default: 'claude-sonnet-4-6')") String model, - @ToolArg(description = "LLM API key (required for cloud providers). " - + "Use vault reference: '${eddivault:key-name}'.") String apiKey, + @ToolArg(description = "LLM API key (required for most cloud providers: anthropic, openai, gemini, mistral). " + + "Not needed for bedrock (IAM) or oracle-genai (OCI auth). " + + "Use vault reference: '${vault:key-name}'.") String apiKey, @ToolArg(description = "Override the API base URL from the spec (optional)") String apiBaseUrl, @ToolArg(description = "Authorization header for API calls, e.g. 'Bearer token123' (optional). " - + "Use vault reference: '${eddivault:api-token}'.") String apiAuth, + + "Use vault reference: '${vault:api-token}'.") String apiAuth, @ToolArg(description = "Comma-separated endpoint filter, e.g. 'GET /users,POST /orders'. " + "If omitted, all non-deprecated endpoints are included.") String endpoints, @ToolArg(description = "Enable quick reply buttons in Agent responses? (default: false)") Boolean enableQuickReplies, diff --git a/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java b/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java index 2808b010e1..de19140ec2 100644 --- a/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java +++ b/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java @@ -475,7 +475,7 @@ public LlmConfiguration createLlmConfig(String modelType, String modelId, String /** * Auto-vault an API key if the vault is available. When the vault is active, * the plaintext key is stored encrypted and a vault reference string - * ({@code ${eddivault:keyName}}) is returned. Downstream consumers + * ({@code ${vault:keyName}}) is returned. Downstream consumers * ({@link ai.labs.eddi.modules.llm.impl.ChatModelRegistry}) resolve vault * references transparently at model-load time. * diff --git a/src/main/java/ai/labs/eddi/integrations/slack/SlackChannelRouter.java b/src/main/java/ai/labs/eddi/integrations/slack/SlackChannelRouter.java index d1b9ef47d7..aada5c0afa 100644 --- a/src/main/java/ai/labs/eddi/integrations/slack/SlackChannelRouter.java +++ b/src/main/java/ai/labs/eddi/integrations/slack/SlackChannelRouter.java @@ -7,6 +7,7 @@ import ai.labs.eddi.configs.agents.IRestAgentStore; import ai.labs.eddi.configs.agents.model.AgentConfiguration; import ai.labs.eddi.configs.agents.model.AgentConfiguration.ChannelConnector; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.engine.api.IRestAgentAdministration; import ai.labs.eddi.engine.model.AgentDeploymentStatus; import ai.labs.eddi.engine.model.Deployment; @@ -25,7 +26,7 @@ *

    * All Slack credentials (bot token, signing secret) live in the agent's * {@code ChannelConnector.config} map and are resolved via - * {@link SecretResolver} (supporting {@code ${eddivault:...}} references). + * {@link SecretResolver} (supporting {@code ${vault:...}} references). *

    * Resolution order for agent routing: *

      @@ -43,6 +44,7 @@ public class SlackChannelRouter { private final IRestAgentAdministration agentAdmin; private final IRestAgentStore agentStore; + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; /** @@ -79,9 +81,10 @@ public record SlackCredentials(String agentId, String botToken, String signingSe @Inject public SlackChannelRouter(IRestAgentAdministration agentAdmin, IRestAgentStore agentStore, - SecretResolver secretResolver) { + GlobalVariableResolver globalVariableResolver, SecretResolver secretResolver) { this.agentAdmin = agentAdmin; this.agentStore = agentStore; + this.globalVariableResolver = globalVariableResolver; this.secretResolver = secretResolver; } @@ -152,7 +155,7 @@ public boolean hasAnySlackChannels() { /** * Refresh the channel→credentials mapping by scanning deployed agents. Uses a * simple time-based cache invalidation (1 minute). Vault references - * (${eddivault:...}) are resolved during refresh via {@link SecretResolver}. + * (${vault:...}) are resolved during refresh via {@link SecretResolver}. */ private void refreshIfNeeded() { long now = System.currentTimeMillis(); @@ -259,7 +262,8 @@ private String resolveSecret(String value, String agentId, String fieldName) { return null; } try { - return secretResolver.resolveValue(value); + String resolved = globalVariableResolver.resolveValue(value); + return secretResolver.resolveValue(resolved); } catch (Exception e) { LOGGER.warnf("Failed to resolve %s for agent %s: %s", fieldName, agentId, e.getMessage()); return null; diff --git a/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java b/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java index d7902c2f63..7ce661fc88 100644 --- a/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java +++ b/src/main/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutor.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.apicalls.impl; import ai.labs.eddi.configs.apicalls.model.*; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.datastore.serialization.IJsonSerialization; import ai.labs.eddi.engine.httpclient.IHttpClient; import ai.labs.eddi.engine.httpclient.IRequest; @@ -53,15 +54,17 @@ public class ApiCallExecutor implements IApiCallExecutor { private final IJsonSerialization jsonSerialization; private final IRuntime runtime; private final PrePostUtils prePostUtils; + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; @Inject public ApiCallExecutor(IHttpClient httpClient, IJsonSerialization jsonSerialization, IRuntime runtime, PrePostUtils prePostUtils, - SecretResolver secretResolver) { + GlobalVariableResolver globalVariableResolver, SecretResolver secretResolver) { this.httpClient = httpClient; this.jsonSerialization = jsonSerialization; this.runtime = runtime; this.prePostUtils = prePostUtils; + this.globalVariableResolver = globalVariableResolver; this.secretResolver = secretResolver; } @@ -314,12 +317,13 @@ private IRequest buildRequest(String targetServerUrl, Request requestConfig, Map } var targetDestination = !path.startsWith("http") ? targetServerUrl + path : path; var targetUriStr = prePostUtils.templateValues(targetDestination, templateDataObjects); - // Resolve vault references in URL (e.g., target server with embedded - // credentials) + // Resolve global variable references, then vault references in URL + targetUriStr = globalVariableResolver.resolveValue(targetUriStr); targetUriStr = secretResolver.resolveValue(targetUriStr); var targetUri = URI.create(targetUriStr); var requestBody = prePostUtils.templateValues(requestConfig.getBody(), templateDataObjects); - // Resolve vault references in request body + // Resolve global variable references, then vault references in request body + requestBody = globalVariableResolver.resolveValue(requestBody); requestBody = secretResolver.resolveValue(requestBody); var method = IHttpClient.Method.valueOf(requestConfig.getMethod().toUpperCase()); @@ -332,8 +336,8 @@ private IRequest buildRequest(String targetServerUrl, Request requestConfig, Map Map headers = requestConfig.getHeaders(); for (String headerName : headers.keySet()) { String headerValue = prePostUtils.templateValues(headers.get(headerName), templateDataObjects); - // Resolve vault references in headers (e.g., Authorization: Bearer - // ${eddivault:...}) + // Resolve global variable references, then vault references in headers + headerValue = globalVariableResolver.resolveValue(headerValue); headerValue = secretResolver.resolveValue(headerValue); request.setHttpHeader(headerName, headerValue); } @@ -341,7 +345,8 @@ private IRequest buildRequest(String targetServerUrl, Request requestConfig, Map Map queryParams = requestConfig.getQueryParams(); for (String queryParam : queryParams.keySet()) { var qpValue = prePostUtils.templateValues(queryParams.get(queryParam), templateDataObjects); - // Resolve vault references in query params + // Resolve global variable references, then vault references in query params + qpValue = globalVariableResolver.resolveValue(qpValue); qpValue = secretResolver.resolveValue(qpValue); request.setQueryParam(queryParam, qpValue); } @@ -365,7 +370,7 @@ private static void scrubSensitiveHeaders(Map requestMap) { || headerName.contains("apikey") || headerName.contains("x-api-key") || headerName.contains("token") || headerName.contains("secret") || headerName.contains("credential")) { entry.setValue(""); - } else if (entry.getValue() instanceof String val && val.contains("${eddivault:")) { + } else if (entry.getValue() instanceof String val && (val.contains("${vault:") || val.contains("${eddivault:"))) { entry.setValue(""); } } diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java b/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java index b7c22669a7..be4e53e7f1 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManager.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.model.LlmConfiguration.A2AAgentConfig; import ai.labs.eddi.secrets.SecretResolver; import com.fasterxml.jackson.databind.ObjectMapper; @@ -38,6 +39,7 @@ public class A2AToolProviderManager { private static final Logger LOGGER = Logger.getLogger(A2AToolProviderManager.class); private static final ObjectMapper MAPPER = new ObjectMapper(); + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; private final HttpClient httpClient; @@ -61,7 +63,8 @@ record A2AToolsResult(List toolSpecs, Map fetchAgentCard(String agentUrl, A2AAgentConfig confi String apiKey = config.getApiKey(); if (!isNullOrEmpty(apiKey)) { + apiKey = globalVariableResolver.resolveValue(apiKey); apiKey = secretResolver.resolveValue(apiKey); requestBuilder.header("Authorization", "Bearer " + apiKey); } @@ -251,6 +255,7 @@ private String executeA2ATask(String agentUrl, A2AAgentConfig config, ToolExecut String apiKey = config.getApiKey(); if (!isNullOrEmpty(apiKey)) { + apiKey = globalVariableResolver.resolveValue(apiKey); apiKey = secretResolver.resolveValue(apiKey); requestBuilder.header("Authorization", "Bearer " + apiKey); } @@ -311,8 +316,8 @@ private String executeA2ATask(String agentUrl, A2AAgentConfig config, ToolExecut } private void warnIfRawKey(String apiKey, String url) { - if (!apiKey.startsWith("${vault:") && !apiKey.startsWith("${eddivault:")) { - LOGGER.warnf("A2A agent at %s uses a raw API key instead of a vault " + "reference (e.g., ${eddivault:my-key}). Raw keys risk secret " + if (!apiKey.startsWith("${vault:") && !apiKey.startsWith("${eddivault:") && !apiKey.startsWith("${vars:")) { + LOGGER.warnf("A2A agent at %s uses a raw API key instead of a vault " + "reference (e.g., ${vault:my-key}). Raw keys risk secret " + "leakage in config exports — migrate to vault references.", url); } } diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistry.java b/src/main/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistry.java index 94f566ccf3..a5c0da095e 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistry.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistry.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.impl.builder.ILanguageModelBuilder; import ai.labs.eddi.secrets.SecretResolver; import ai.labs.eddi.secrets.model.SecretReference; @@ -46,13 +47,16 @@ public class ChatModelRegistry { private static final Logger LOGGER = Logger.getLogger(ChatModelRegistry.class); private final Map> languageModelApiConnectorBuilders; + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; private final Map modelCache = new ConcurrentHashMap<>(1); private final Map streamingModelCache = new ConcurrentHashMap<>(1); @Inject - ChatModelRegistry(Map> languageModelApiConnectorBuilders, SecretResolver secretResolver) { + ChatModelRegistry(Map> languageModelApiConnectorBuilders, + GlobalVariableResolver globalVariableResolver, SecretResolver secretResolver) { this.languageModelApiConnectorBuilders = languageModelApiConnectorBuilders; + this.globalVariableResolver = globalVariableResolver; this.secretResolver = secretResolver; } @@ -65,7 +69,15 @@ public class ChatModelRegistry { @PostConstruct void registerSecretInvalidation() { secretResolver.registerInvalidationListener(this::invalidateForSecret); - LOGGER.info("ChatModelRegistry registered for secret invalidation events"); + globalVariableResolver.registerInvalidationListener(() -> { + int total = modelCache.size() + streamingModelCache.size(); + modelCache.clear(); + streamingModelCache.clear(); + if (total > 0) { + LOGGER.infof("Invalidated all %d model(s) due to global variable change", total); + } + }); + LOGGER.info("ChatModelRegistry registered for secret and global variable invalidation events"); } /** @@ -91,9 +103,10 @@ ChatModel getOrCreate(String type, Map processedParams) throws U throw new UnsupportedLlmTaskException(String.format("Type \"%s\" is not supported", type)); } - // Resolve vault references (late-binding: after Qute, before - // builder.build()) - var resolvedParams = secretResolver.resolveSecrets(filteredParams); + // Resolve global variable references, then vault secrets (late-binding: + // after Qute, before builder.build()) + var resolvedParams = globalVariableResolver.resolveAll(filteredParams); + resolvedParams = secretResolver.resolveSecrets(resolvedParams); var rawModel = languageModelApiConnectorBuilders.get(type).get().build(resolvedParams); var model = ObservableChatModel.wrapIfNeeded(rawModel, type, timeoutMs, logReq, logResp); modelCache.put(cacheKey, model); @@ -119,9 +132,10 @@ StreamingChatModel getOrCreateStreaming(String type, Map process } try { - // Resolve vault references (late-binding: after Qute, before - // builder.build()) - var resolvedParams = secretResolver.resolveSecrets(filteredParams); + // Resolve global variable references, then vault secrets (late-binding: + // after Qute, before builder.build()) + var resolvedParams = globalVariableResolver.resolveAll(filteredParams); + resolvedParams = secretResolver.resolveSecrets(resolvedParams); var model = languageModelApiConnectorBuilders.get(type).get().buildStreaming(resolvedParams); streamingModelCache.put(cacheKey, model); return model; @@ -155,8 +169,9 @@ private Map filterParams(Map processedParams) { *

      * When {@code reference} is non-null (single secret changed), scan cache * entries and evict only those whose parameter values contain a vault reference - * to the changed secret — either short form ({@code ${eddivault:keyName}}) or - * full form ({@code ${eddivault:tenantId/keyName}}). + * to the changed secret — either short form ({@code ${vault:keyName}}) or full + * form ({@code ${vault:tenantId/keyName}}). Also matches the legacy + * {@code ${eddivault:...}} prefix for backward compatibility. *

      * When {@code reference} is null (DEK/KEK rotation — all secrets affected), * clear everything. @@ -177,17 +192,22 @@ void invalidateForSecret(SecretReference reference) { } // Build the vault reference forms to search for in cached parameters. - // Full form: ${eddivault:tenantId/keyName} — always valid - String fullRef = "${eddivault:" + reference.tenantId() + "/" + reference.keyName() + "}"; - // Short form: ${eddivault:keyName} — only valid for the default tenant. + // New canonical form: ${vault:tenantId/keyName} — always valid + String fullRef = "${vault:" + reference.tenantId() + "/" + reference.keyName() + "}"; + // Legacy form: ${eddivault:tenantId/keyName} — for backward compat + String legacyFullRef = "${eddivault:" + reference.tenantId() + "/" + reference.keyName() + "}"; + // Short form: ${vault:keyName} — only valid for the default tenant. // The short form always resolves to "default", so a non-default tenant's // secret must NOT match short-form references (that would be a false positive). String shortRef = SecretReference.DEFAULT_TENANT.equals(reference.tenantId()) + ? "${vault:" + reference.keyName() + "}" + : null; + String legacyShortRef = SecretReference.DEFAULT_TENANT.equals(reference.tenantId()) ? "${eddivault:" + reference.keyName() + "}" : null; - int evicted = evictMatching(modelCache, fullRef, shortRef) - + evictMatching(streamingModelCache, fullRef, shortRef); + int evicted = evictMatching(modelCache, fullRef, legacyFullRef, shortRef, legacyShortRef) + + evictMatching(streamingModelCache, fullRef, legacyFullRef, shortRef, legacyShortRef); if (evicted > 0) { LOGGER.infof("Evicted %d model(s) using secret '%s/%s'", @@ -196,15 +216,15 @@ void invalidateForSecret(SecretReference reference) { } /** - * Scan a cache and remove entries whose parameter values contain either vault - * reference form. + * Scan a cache and remove entries whose parameter values contain any of the + * given vault reference forms (new and legacy prefixes). */ - private int evictMatching(Map cache, String ref1, String ref2) { + private int evictMatching(Map cache, String... refs) { int count = 0; Iterator it = cache.keySet().iterator(); while (it.hasNext()) { ModelCacheKey key = it.next(); - if (parametersContainRef(key.parameters(), ref1, ref2)) { + if (parametersContainRef(key.parameters(), refs)) { it.remove(); count++; } @@ -212,10 +232,14 @@ private int evictMatching(Map cache, String ref1, String r return count; } - private static boolean parametersContainRef(Map params, String ref1, String ref2) { + private static boolean parametersContainRef(Map params, String... refs) { for (String value : params.values()) { - if (value != null && (value.contains(ref1) || (ref2 != null && value.contains(ref2)))) { - return true; + if (value == null) + continue; + for (String ref : refs) { + if (ref != null && value.contains(ref)) { + return true; + } } } return false; diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java b/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java index ee3b969dd6..408dcd59f4 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactory.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.llm.impl; import ai.labs.eddi.configs.rag.model.RagConfiguration; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.secrets.SecretResolver; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; @@ -45,10 +46,12 @@ public class EmbeddingModelFactory { private static final Logger LOGGER = Logger.getLogger(EmbeddingModelFactory.class); private final Cache cache = Caffeine.newBuilder().maximumSize(50).expireAfterAccess(Duration.ofMinutes(30)).build(); + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; @Inject - public EmbeddingModelFactory(SecretResolver secretResolver) { + public EmbeddingModelFactory(GlobalVariableResolver globalVariableResolver, SecretResolver secretResolver) { + this.globalVariableResolver = globalVariableResolver; this.secretResolver = secretResolver; } @@ -64,7 +67,8 @@ public EmbeddingModel getOrCreate(RagConfiguration config) { private EmbeddingModel build(RagConfiguration config) { Map rawParams = config.getEmbeddingParameters() != null ? config.getEmbeddingParameters() : Map.of(); - Map params = secretResolver.resolveSecrets(rawParams); + Map params = globalVariableResolver.resolveAll(rawParams); + params = secretResolver.resolveSecrets(params); String provider = config.getEmbeddingProvider(); LOGGER.infof("Building embedding model for provider: %s", provider); diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java b/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java index b57f90fb02..4d8b77e6b3 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactory.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.llm.impl; import ai.labs.eddi.configs.rag.model.RagConfiguration; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.secrets.SecretResolver; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; @@ -54,10 +55,12 @@ public class EmbeddingStoreFactory { private final Cache> cache = Caffeine.newBuilder().maximumSize(50).expireAfterAccess(Duration.ofMinutes(30)) .build(); private final Map mongoClientCache = new ConcurrentHashMap<>(); + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; @Inject - public EmbeddingStoreFactory(SecretResolver secretResolver) { + public EmbeddingStoreFactory(GlobalVariableResolver globalVariableResolver, SecretResolver secretResolver) { + this.globalVariableResolver = globalVariableResolver; this.secretResolver = secretResolver; } @@ -103,7 +106,7 @@ private EmbeddingStore build(RagConfiguration config, String kbId) *

    1. {@code port} — PostgreSQL port (default: 5432)
    2. *
    3. {@code database} — database name (default: "eddi")
    4. *
    5. {@code user} — database user (default: "eddi")
    6. - *
    7. {@code password} — database password, supports {@code ${eddivault:...}} + *
    8. {@code password} — database password, supports {@code ${vault:...}} * (required)
    9. *
    10. {@code table} — table name (default: auto-generated from kbId)
    11. *
    12. {@code dimension} — embedding vector dimension (default: 1536 for OpenAI @@ -140,7 +143,7 @@ private EmbeddingStore buildPgVector(RagConfiguration config, Strin * Supported storeParameters: *
        *
      • {@code connectionString} — MongoDB connection string (required, supports - * {@code ${eddivault:...}})
      • + * {@code ${vault:...}}) *
      • {@code databaseName} — database name (default: "eddi")
      • *
      • {@code collectionName} — collection name (default: auto-generated from * kbId)
      • @@ -176,8 +179,7 @@ private EmbeddingStore buildMongoDbAtlas(RagConfiguration config, S *
          *
        • {@code serverUrl} — Elasticsearch URL (default: * "http://localhost:9200")
        • - *
        • {@code apiKey} — API key (optional, supports - * {@code ${eddivault:...}})
        • + *
        • {@code apiKey} — API key (optional, supports {@code ${vault:...}})
        • *
        • {@code indexName} — index name (default: auto-generated from kbId)
        • *
        */ @@ -218,7 +220,7 @@ private EmbeddingStore buildElasticsearch(RagConfiguration config, *
      • {@code collectionName} — collection name (default: auto-generated from * kbId)
      • *
      • {@code apiKey} — Qdrant API key (optional, supports - * {@code ${eddivault:...}})
      • + * {@code ${vault:...}}) *
      • {@code useTls} — use TLS (default: "false")
      • *
      */ @@ -285,11 +287,12 @@ private EmbeddingStore buildChroma(RagConfiguration config, String // ────────────────────────────────────────────────── /** - * Resolves vault references in store parameters. + * Resolves global variable and vault references in store parameters. */ private Map resolveParams(RagConfiguration config) { Map rawParams = config.getStoreParameters() != null ? config.getStoreParameters() : Map.of(); - return secretResolver.resolveSecrets(rawParams); + Map resolved = globalVariableResolver.resolveAll(rawParams); + return secretResolver.resolveSecrets(resolved); } private ChromaApiVersion parseChromaApiVersion(String apiVersionStr) { @@ -314,7 +317,7 @@ private ChromaApiVersion parseChromaApiVersion(String apiVersionStr) { private String requireParam(Map params, String key, String storeType) { String value = params.get(key); if (value == null || value.isBlank()) { - throw new IllegalArgumentException(storeType + " requires '" + key + "' in storeParameters (use ${eddivault:...} for secrets)"); + throw new IllegalArgumentException(storeType + " requires '" + key + "' in storeParameters (use ${vault:...} for secrets)"); } return value; } diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java b/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java index be0f164794..74a56badab 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/LlmTask.java @@ -8,6 +8,7 @@ import ai.labs.eddi.configs.properties.IUserMemoryStore; import ai.labs.eddi.configs.apicalls.model.ApiCall; import ai.labs.eddi.configs.apicalls.model.ApiCallsConfiguration; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.configs.workflows.IRestWorkflowStore; import ai.labs.eddi.configs.workflows.model.ExtensionDescriptor; import ai.labs.eddi.datastore.serialization.IJsonSerialization; @@ -92,6 +93,7 @@ public class LlmTask implements ILifecycleTask { private final TokenCounterFactory tokenCounterFactory; private final ConversationSummarizer conversationSummarizer; private final PromptSnippetService promptSnippetService; + private final GlobalVariableResolver globalVariableResolver; // Retained for httpCall RAG discovery + execution (Phase 8c-0) private final IApiCallExecutor apiCallExecutor; @@ -110,6 +112,7 @@ public LlmTask(IResourceClientLibrary resourceClientLibrary, IDataFactory dataFa RagContextProvider ragContextProvider, IUserMemoryStore userMemoryStore, TokenCounterFactory tokenCounterFactory, ConversationSummarizer conversationSummarizer, PromptSnippetService promptSnippetService, + GlobalVariableResolver globalVariableResolver, ToolResponseTruncator toolResponseTruncator, TenantQuotaService tenantQuotaService) { this.resourceClientLibrary = resourceClientLibrary; this.dataFactory = dataFactory; @@ -133,6 +136,7 @@ public LlmTask(IResourceClientLibrary resourceClientLibrary, IDataFactory dataFa this.restWorkflowStore = restWorkflowStore; this.conversationSummarizer = conversationSummarizer; this.promptSnippetService = promptSnippetService; + this.globalVariableResolver = globalVariableResolver; } @Override @@ -165,6 +169,13 @@ public void execute(IConversationMemory memory, Object component) throws Lifecyc templateDataObjects.put("snippets", snippets); } + // Inject global variables into template data — auto-available as + // {{vars.}} in system prompts and parameters + Map globalVars = globalVariableResolver.getTemplateData(); + if (!globalVars.isEmpty()) { + templateDataObjects.put("vars", globalVars); + } + var actions = latestData.getResult(); if (actions == null) { return; @@ -270,11 +281,15 @@ private void executeTask(IConversationMemory memory, Task task, IWritableConvers } } + // Resolve global variable references in task type BEFORE any model + // lookups — used by token estimator, sync model, and streaming model. + var resolvedType = globalVariableResolver.resolveValue(task.getType()); + List messages; if (maxContextTokens != null && maxContextTokens > 0) { // Resolve model name from provider-specific parameter keys String resolvedModelName = resolveModelName(processedParams); - var estimator = tokenCounterFactory.getEstimator(task.getType(), resolvedModelName); + var estimator = tokenCounterFactory.getEstimator(resolvedType, resolvedModelName); messages = conversationHistoryBuilder.buildTokenAwareMessages(memory, systemMessage, processedParams.get(KEY_PROMPT), maxContextTokens, anchorFirstSteps, includeFirstAgentMessage, estimator, summaryPrefix, skipSteps); } else { @@ -291,7 +306,7 @@ private void executeTask(IConversationMemory memory, Task task, IWritableConvers return; } - var chatModel = chatModelRegistry.getOrCreate(task.getType(), processedParams); + var chatModel = chatModelRegistry.getOrCreate(resolvedType, processedParams); prePostUtils.executePreRequestPropertyInstructions(memory, templateDataObjects, task.getPreRequest()); // Detect streaming mode — event sink is set when SSE endpoint is used @@ -394,7 +409,7 @@ private void executeTask(IConversationMemory memory, Task task, IWritableConvers } } else if (eventSink != null) { // Legacy mode with streaming — try to get a streaming model - var streamingModel = chatModelRegistry.getOrCreateStreaming(task.getType(), processedParams); + var streamingModel = chatModelRegistry.getOrCreateStreaming(resolvedType, processedParams); if (streamingModel != null) { responseContent = streamingLegacyChatExecutor.execute(streamingModel, messages, eventSink); } else { diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManager.java b/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManager.java index b4009adba6..c5bf5796f6 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManager.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManager.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.model.LlmConfiguration.McpServerConfig; import ai.labs.eddi.secrets.SecretResolver; import dev.langchain4j.agent.tool.ToolSpecification; @@ -46,6 +47,7 @@ public class McpToolProviderManager { private static final Logger LOGGER = Logger.getLogger(McpToolProviderManager.class); + private final GlobalVariableResolver globalVariableResolver; private final SecretResolver secretResolver; /** @@ -55,7 +57,8 @@ public class McpToolProviderManager { private final Map clientCache = new ConcurrentHashMap<>(); @Inject - public McpToolProviderManager(SecretResolver secretResolver) { + public McpToolProviderManager(GlobalVariableResolver globalVariableResolver, SecretResolver secretResolver) { + this.globalVariableResolver = globalVariableResolver; this.secretResolver = secretResolver; } @@ -146,9 +149,10 @@ private McpClient getOrCreateClient(McpServerConfig config) { * Create the appropriate MCP transport based on configuration. */ private McpTransport createTransport(McpServerConfig config, Duration timeout) { - // Resolve API key if it's a vault reference + // Resolve API key if it's a global variable or vault reference String apiKey = config.getApiKey(); if (!isNullOrEmpty(apiKey)) { + apiKey = globalVariableResolver.resolveValue(apiKey); apiKey = secretResolver.resolveValue(apiKey); } diff --git a/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java b/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java index f8c7ee2895..d2176115c1 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java +++ b/src/main/java/ai/labs/eddi/modules/llm/model/LlmConfiguration.java @@ -598,7 +598,7 @@ public static class McpServerConfig { /** Transport type: "http" (default) or "sse" */ private String transport = "http"; - /** Optional API key or vault reference (e.g., "${eddivault:my-api-key}") */ + /** Optional API key or vault reference (e.g., "${vault:my-api-key}") */ private String apiKey; /** Timeout for MCP operations in milliseconds (default: 30000) */ @@ -663,8 +663,8 @@ public static class A2AAgentConfig { private List skillsFilter; /** - * API key as a vault reference (e.g., {@code ${eddivault:my-a2a-key}}). Raw - * keys are strongly discouraged — always use vault references to prevent secret + * API key as a vault reference (e.g., {@code ${vault:my-a2a-key}}). Raw keys + * are strongly discouraged — always use vault references to prevent secret * leakage in configuration exports. */ private String apiKey; diff --git a/src/main/java/ai/labs/eddi/modules/properties/impl/PropertySetterTask.java b/src/main/java/ai/labs/eddi/modules/properties/impl/PropertySetterTask.java index 8073e3b613..13cdaafb49 100644 --- a/src/main/java/ai/labs/eddi/modules/properties/impl/PropertySetterTask.java +++ b/src/main/java/ai/labs/eddi/modules/properties/impl/PropertySetterTask.java @@ -391,7 +391,7 @@ private List convertToProperties(List> *

      * The keyName is namespaced with the agentId to prevent cross-agent collisions: * {@code agentId.keyName}. Since the tenant is typically "default", the - * short-form syntax is used: {@code ${eddivault:agentId.keyName}}. + * short-form syntax is used: {@code ${vault:agentId.keyName}}. * * @param memory * the conversation memory (used for agentId and input scrubbing) @@ -399,8 +399,7 @@ private List convertToProperties(List> * the property name used as the vault key * @param plaintext * the secret value to store - * @return the vault reference string, e.g. - * {@code ${eddivault:69c687.userApiKey}} + * @return the vault reference string, e.g. {@code ${vault:69c687.userApiKey}} */ private String autoVaultSecret(IConversationMemory memory, String keyName, String plaintext) { // Determine tenantId — use conversation property if set, else "default" diff --git a/src/main/java/ai/labs/eddi/secrets/ISecretProvider.java b/src/main/java/ai/labs/eddi/secrets/ISecretProvider.java index cddb61130d..c2ace0a53a 100644 --- a/src/main/java/ai/labs/eddi/secrets/ISecretProvider.java +++ b/src/main/java/ai/labs/eddi/secrets/ISecretProvider.java @@ -16,7 +16,7 @@ * Secrets are scoped at the tenant level, identified by * {@code (tenantId, keyName)}. There is no agent-level scoping — access control * is via configuration authorship: the admin who writes the agent config - * decides which vault references ({@code ${eddivault:keyName}}) to include. + * decides which vault references ({@code ${vault:keyName}}) to include. *

      * All implementations MUST ensure: *

        diff --git a/src/main/java/ai/labs/eddi/secrets/SecretResolver.java b/src/main/java/ai/labs/eddi/secrets/SecretResolver.java index 020cd07af4..f46135bf22 100644 --- a/src/main/java/ai/labs/eddi/secrets/SecretResolver.java +++ b/src/main/java/ai/labs/eddi/secrets/SecretResolver.java @@ -25,8 +25,8 @@ /** * Resolves vault references in parameter maps and strings. Supports both the - * short form ({@code ${eddivault:keyName}}) and full form - * ({@code ${eddivault:tenantId/keyName}}). + * short form ({@code ${vault:keyName}}) and full form + * ({@code ${vault:tenantId/keyName}}). *

        * This is the central integration point between the vault and the execution * workflow. It is called after Qute template processing and @@ -108,7 +108,7 @@ void init() { * compatibility with plaintext configs). * * @param params - * the parameter map (may contain ${eddivault:...} values) + * the parameter map (may contain ${vault:...} values) * @return a new map with vault references replaced by plaintext values */ public Map resolveSecrets(Map params) { @@ -127,9 +127,9 @@ public Map resolveSecrets(Map params) { /** * Resolve vault references in a single string value. Supports both the short - * form ({@code ${eddivault:keyName}}) and full form - * ({@code ${eddivault:tenantId/keyName}}), and multiple references within the - * same string. + * form ({@code ${vault:keyName}}) and full form + * ({@code ${vault:tenantId/keyName}}), and multiple references within the same + * string. *

        * If the vault is not available, the value passes through unchanged. *

        @@ -139,7 +139,7 @@ public Map resolveSecrets(Map params) { * cache expiry. * * @param value - * the value that may contain ${eddivault:...} references + * the value that may contain ${vault:...} references * @return the value with vault references replaced by plaintext */ public String resolveValue(String value) { diff --git a/src/main/java/ai/labs/eddi/secrets/VaultStartupBanner.java b/src/main/java/ai/labs/eddi/secrets/VaultStartupBanner.java index e8c0c856fa..9df52676f7 100644 --- a/src/main/java/ai/labs/eddi/secrets/VaultStartupBanner.java +++ b/src/main/java/ai/labs/eddi/secrets/VaultStartupBanner.java @@ -45,7 +45,7 @@ public static void printEnabled() { | SECRETS VAULT: ENABLED | | | | Envelope encryption is active (AES-256-GCM). | - | ${eddivault:...} references will be resolved at runtime. | + | ${vault:...} references will be resolved at runtime. | | Audit entries will be HMAC-signed for tamper detection. | +------------------------------------------------------------------+ @@ -64,7 +64,7 @@ public static void printDisabled() { +------------------------------------------------------------------+ | | | What this means: | - | * ${eddivault:...} secret references will NOT be resolved | + | * ${vault:...} secret references will NOT be resolved | | * API keys in configs are stored/transmitted as PLAINTEXT | | * Audit log entries will NOT have HMAC integrity signatures | | | diff --git a/src/main/java/ai/labs/eddi/secrets/model/SecretReference.java b/src/main/java/ai/labs/eddi/secrets/model/SecretReference.java index 35fe846802..743832186b 100644 --- a/src/main/java/ai/labs/eddi/secrets/model/SecretReference.java +++ b/src/main/java/ai/labs/eddi/secrets/model/SecretReference.java @@ -11,12 +11,15 @@ * Immutable reference to a secret stored in the vault. Supports two syntax * forms: *

          - *
        • Short form: {@code ${eddivault:keyName}} — tenant defaults to + *
        • Short form: {@code ${vault:keyName}} — tenant defaults to * {@code "default"}
        • - *
        • Full form: {@code ${eddivault:tenantId/keyName}} — explicit tenant - * for multi-tenant
        • + *
        • Full form: {@code ${vault:tenantId/keyName}} — explicit tenant for + * multi-tenant
        • *
        *

        + * Backward compatibility: The older {@code ${eddivault:...}} prefix is + * also accepted for configs stored before the v6.0.2 rename. + *

        * This follows the Docker image tag convention where {@code nginx} implicitly * means {@code docker.io/library/nginx}. Single-tenant deployments (the common * case) use the cleaner short form. @@ -39,21 +42,24 @@ public record SecretReference(String tenantId, String keyName) { public static final String DEFAULT_TENANT = "default"; /** - * Dual-format regex pattern that matches both vault reference forms: + * Dual-format regex pattern that matches both vault reference forms and both + * prefixes ({@code vault} and legacy {@code eddivault}): *

          - *
        • {@code ${eddivault:keyName}} — group(1) is null, group(2) is keyName
        • - *
        • {@code ${eddivault:tenantId/keyName}} — group(1) is tenantId, group(2) is + *
        • {@code ${vault:keyName}} — group(1) is null, group(2) is keyName
        • + *
        • {@code ${vault:tenantId/keyName}} — group(1) is tenantId, group(2) is * keyName
        • + *
        • {@code ${eddivault:keyName}} — legacy, same groups
        • *
        */ - public static final String VAULT_PATTERN = "\\$\\{eddivault:(?:([^/}]+)/)?([^}]+)\\}"; + public static final String VAULT_PATTERN = "\\$\\{(?:vault|eddivault):(?:([^/}]+)/)?([^}]+)\\}"; private static final Pattern COMPILED_PATTERN = Pattern.compile(VAULT_PATTERN); /** * Parse a vault reference string into a SecretReference. Supports both short - * form ({@code ${eddivault:openaiKey}}) and full form - * ({@code ${eddivault:myTenant/openaiKey}}). + * form ({@code ${vault:openaiKey}}) and full form + * ({@code ${vault:myTenant/openaiKey}}). Also accepts the legacy + * {@code ${eddivault:...}} prefix. * * @param reference * the full reference string @@ -65,7 +71,7 @@ public static SecretReference parse(String reference) { Matcher matcher = COMPILED_PATTERN.matcher(reference); if (!matcher.find()) { throw new IllegalArgumentException( - "Invalid vault reference: " + reference + ". Expected: ${eddivault:keyName} or ${eddivault:tenantId/keyName}"); + "Invalid vault reference: " + reference + ". Expected: ${vault:keyName} or ${vault:tenantId/keyName}"); } String tenant = matcher.group(1) != null ? matcher.group(1) : DEFAULT_TENANT; String key = matcher.group(2); @@ -75,19 +81,19 @@ public static SecretReference parse(String reference) { /** * Construct the vault reference string. Uses the shortest valid form: *
          - *
        • Default tenant → {@code ${eddivault:keyName}}
        • - *
        • Custom tenant → {@code ${eddivault:tenantId/keyName}}
        • + *
        • Default tenant → {@code ${vault:keyName}}
        • + *
        • Custom tenant → {@code ${vault:tenantId/keyName}}
        • *
        */ public String toReferenceString() { - return DEFAULT_TENANT.equals(tenantId) ? "${eddivault:" + keyName + "}" : "${eddivault:" + tenantId + "/" + keyName + "}"; + return DEFAULT_TENANT.equals(tenantId) ? "${vault:" + keyName + "}" : "${vault:" + tenantId + "/" + keyName + "}"; } /** - * Check if a string contains a vault reference. + * Check if a string contains a vault reference (either new or legacy prefix). */ public static boolean isVaultReference(String value) { - return value != null && value.contains("${eddivault:"); + return value != null && (value.contains("${vault:") || value.contains("${eddivault:")); } /** diff --git a/src/main/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilter.java b/src/main/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilter.java index 109695639c..4bdcb6efa8 100644 --- a/src/main/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilter.java +++ b/src/main/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilter.java @@ -35,8 +35,9 @@ public final class SecretRedactionFilter { "$1=" + REDACTED), // Vault references (should never appear in logs, but defense-in-depth) + // Matches both ${vault:...} and legacy ${eddivault:...} // Note: $ must be escaped in replacement strings for Matcher.replaceAll() - new RedactionRule(Pattern.compile("\\$\\{eddivault:[^}]+}"), "\\${eddivault:" + REDACTED + "}")); + new RedactionRule(Pattern.compile("\\$\\{(?:vault|eddivault):[^}]+}"), "\\${vault:" + REDACTED + "}")); private SecretRedactionFilter() { // Utility class diff --git a/src/main/java/ai/labs/eddi/secrets/sanitize/SecretScrubber.java b/src/main/java/ai/labs/eddi/secrets/sanitize/SecretScrubber.java index 0af275cd88..77f72a0cdf 100644 --- a/src/main/java/ai/labs/eddi/secrets/sanitize/SecretScrubber.java +++ b/src/main/java/ai/labs/eddi/secrets/sanitize/SecretScrubber.java @@ -28,15 +28,15 @@ * token, etc.) *
      • Shannon entropy: high-entropy strings (>3.5 bits/char) that look * like API keys
      • - *
      • Vault references: existing ${eddivault:...} references are left - * untouched
      • + *
      • Vault references: existing ${vault:...} or ${eddivault:...} + * references are left untouched
      • *
    */ @ApplicationScoped public class SecretScrubber { private static final Logger LOGGER = Logger.getLogger(SecretScrubber.class); - private static final String REDACTED = "${eddivault:REDACTED}"; + private static final String REDACTED = "${vault:REDACTED}"; /** * Minimum length for entropy analysis (short strings are less likely to be @@ -70,7 +70,7 @@ public SecretScrubber(ObjectMapper objectMapper) { * * @param json * the JSON string to scrub - * @return sanitized JSON with secrets replaced by ${eddivault:REDACTED} + * @return sanitized JSON with secrets replaced by ${vault:REDACTED} */ public String scrubJson(String json) { if (json == null || json.isBlank()) { @@ -99,8 +99,8 @@ private void scrubNode(JsonNode node, String parentFieldName) { if (fieldValue.isTextual()) { String textValue = fieldValue.asText(); - // Skip existing vault references - if (textValue.contains("${eddivault:")) { + // Skip existing vault references (both new and legacy prefix) + if (textValue.contains("${vault:") || textValue.contains("${eddivault:")) { continue; } diff --git a/src/test/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsModelsTest.java b/src/test/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsModelsTest.java index 4cf4d4b420..7f36741141 100644 --- a/src/test/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsModelsTest.java +++ b/src/test/java/ai/labs/eddi/configs/mcpcalls/model/McpCallsModelsTest.java @@ -35,7 +35,7 @@ void mcpCallsConfiguration_settersAndGetters() { config.setMcpServerUrl("http://localhost:7070/mcp"); config.setName("GitHub MCP"); config.setTransport("sse"); - config.setApiKey("${eddivault:github-key}"); + config.setApiKey("${vault:github-key}"); config.setTimeoutMs(60000L); config.setToolsWhitelist(List.of("list_repos", "create_issue")); config.setToolsBlacklist(List.of("delete_repo")); @@ -47,7 +47,7 @@ void mcpCallsConfiguration_settersAndGetters() { assertEquals("http://localhost:7070/mcp", config.getMcpServerUrl()); assertEquals("GitHub MCP", config.getName()); assertEquals("sse", config.getTransport()); - assertEquals("${eddivault:github-key}", config.getApiKey()); + assertEquals("${vault:github-key}", config.getApiKey()); assertEquals(60000L, config.getTimeoutMs()); assertEquals(2, config.getToolsWhitelist().size()); assertEquals(1, config.getToolsBlacklist().size()); diff --git a/src/test/java/ai/labs/eddi/configs/variables/GlobalVariableResolverTest.java b/src/test/java/ai/labs/eddi/configs/variables/GlobalVariableResolverTest.java new file mode 100644 index 0000000000..4fea725b72 --- /dev/null +++ b/src/test/java/ai/labs/eddi/configs/variables/GlobalVariableResolverTest.java @@ -0,0 +1,250 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables; + +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** + * Unit tests for {@link GlobalVariableResolver} — regex resolution, tenant + * scoping, caching, invalidation listeners, template data injection. + */ +class GlobalVariableResolverTest { + + private static final String DEFAULT = GlobalVariable.DEFAULT_TENANT; + + private IGlobalVariableStore store; + private GlobalVariableResolver resolver; + + @BeforeEach + void setUp() { + store = mock(IGlobalVariableStore.class); + resolver = new GlobalVariableResolver(store, 2); + // Manually call init since @PostConstruct doesn't fire in unit tests + resolver.init(); + } + + // ====================== Short Form (default tenant) ====================== + + @Nested + @DisplayName("Short form: ${vars:key}") + class ShortForm { + + @Test + void resolveSimple() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("default-model", "gpt-4.1")); + assertEquals("gpt-4.1", resolver.resolveValue("${vars:default-model}")); + } + + @Test + void resolveMultiple() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("model", "gpt-4.1", "temp", "0.7")); + assertEquals("model=gpt-4.1&temp=0.7", + resolver.resolveValue("model=${vars:model}&temp=${vars:temp}")); + } + + @Test + void resolveMissing() { + when(store.getAll(DEFAULT)).thenReturn(Map.of()); + assertEquals("${vars:missing}", resolver.resolveValue("${vars:missing}"), + "Missing variables should pass through unchanged"); + } + + @Test + void resolveNullPassthrough() { + assertNull(resolver.resolveValue(null)); + } + + @Test + void resolveNoReferencePassthrough() { + String plain = "just a plain string"; + assertSame(plain, resolver.resolveValue(plain)); + verifyNoInteractions(store); + } + + @Test + void resolveMixedWithText() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("host", "api.openai.com")); + assertEquals("https://api.openai.com/v1/chat", + resolver.resolveValue("https://${vars:host}/v1/chat")); + } + + @Test + void resolveVariousKeyFormats() { + when(store.getAll(DEFAULT)).thenReturn(Map.of( + "model.name", "gpt-4", + "api-key", "sk-123", + "version_2", "v2")); + + assertEquals("gpt-4", resolver.resolveValue("${vars:model.name}")); + assertEquals("sk-123", resolver.resolveValue("${vars:api-key}")); + assertEquals("v2", resolver.resolveValue("${vars:version_2}")); + } + } + + // ====================== Full Form (explicit tenant) ====================== + + @Nested + @DisplayName("Full form: ${vars:tenantId/key}") + class FullForm { + + @Test + void resolveExplicitTenant() { + when(store.getAll("tenant-a")).thenReturn(Map.of("model", "gpt-4.1")); + assertEquals("gpt-4.1", resolver.resolveValue("${vars:tenant-a/model}")); + } + + @Test + void resolveExplicitTenantDoesNotUseContextTenant() { + // Even when context is "tenant-b", explicit tenant wins + when(store.getAll("tenant-a")).thenReturn(Map.of("key", "val-a")); + assertEquals("val-a", resolver.resolveValue("${vars:tenant-a/key}", "tenant-b")); + verify(store, never()).getAll("tenant-b"); + } + + @Test + void resolveShortFormUsesContextTenant() { + when(store.getAll("tenant-b")).thenReturn(Map.of("key", "val-b")); + assertEquals("val-b", resolver.resolveValue("${vars:key}", "tenant-b")); + } + + @Test + void resolveMixedShortAndFullForm() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("global-key", "global-val")); + when(store.getAll("t1")).thenReturn(Map.of("t1-key", "t1-val")); + assertEquals("global-val,t1-val", + resolver.resolveValue("${vars:global-key},${vars:t1/t1-key}")); + } + + @Test + void resolveNullTenantIdDefaultsToDefault() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("key", "val")); + assertEquals("val", resolver.resolveValue("${vars:key}", null), + "null tenantId should fall back to 'default'"); + } + } + + // ====================== resolveAll ====================== + + @Test + void resolveAllMap() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("model", "gpt-4.1")); + Map input = new HashMap<>(); + input.put("type", "${vars:model}"); + input.put("plain", "no-change"); + + Map result = resolver.resolveAll(input); + assertEquals("gpt-4.1", result.get("type")); + assertEquals("no-change", result.get("plain")); + } + + @Test + void resolveAllWithTenant() { + when(store.getAll("t1")).thenReturn(Map.of("model", "claude")); + Map input = new HashMap<>(); + input.put("type", "${vars:model}"); + + Map result = resolver.resolveAll(input, "t1"); + assertEquals("claude", result.get("type")); + } + + @Test + void resolveAllNullMap() { + assertNull(resolver.resolveAll(null)); + } + + @Test + void resolveAllEmptyMap() { + Map empty = Map.of(); + assertSame(empty, resolver.resolveAll(empty)); + } + + // ====================== Template Data ====================== + + @Test + void getTemplateData_defaultTenant() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("k1", "v1", "k2", "v2")); + Map data = resolver.getTemplateData(); + assertEquals("v1", data.get("k1")); + assertEquals("v2", data.get("k2")); + } + + @Test + void getTemplateData_explicitTenant() { + when(store.getAll("t1")).thenReturn(Map.of("k1", "t1-v1")); + Map data = resolver.getTemplateData("t1"); + assertEquals("t1-v1", data.get("k1")); + } + + // ====================== Caching ====================== + + @Test + void cachingAvoidsDuplicateLoads() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("k", "v")); + resolver.resolveValue("${vars:k}"); + resolver.resolveValue("${vars:k}"); + verify(store, times(1)).getAll(DEFAULT); + } + + @Test + void cachingIsPerTenant() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("k", "v-default")); + when(store.getAll("t1")).thenReturn(Map.of("k", "v-t1")); + + assertEquals("v-default", resolver.resolveValue("${vars:k}")); + assertEquals("v-t1", resolver.resolveValue("${vars:t1/k}")); + verify(store, times(1)).getAll(DEFAULT); + verify(store, times(1)).getAll("t1"); + } + + @Test + void invalidateCacheForcesReload() { + when(store.getAll(DEFAULT)).thenReturn(Map.of("k", "v1")); + resolver.resolveValue("${vars:k}"); + + when(store.getAll(DEFAULT)).thenReturn(Map.of("k", "v2")); + resolver.invalidateCache(); + assertEquals("v2", resolver.resolveValue("${vars:k}")); + verify(store, times(2)).getAll(DEFAULT); + } + + // ====================== Listeners ====================== + + @Test + void invalidationListenerFires() { + Runnable listener = mock(Runnable.class); + resolver.registerInvalidationListener(listener); + resolver.invalidateCache(); + verify(listener, times(1)).run(); + } + + @Test + void invalidationListenerExceptionDoesNotPropagate() { + Runnable badListener = mock(Runnable.class); + doThrow(new RuntimeException("boom")).when(badListener).run(); + resolver.registerInvalidationListener(badListener); + assertDoesNotThrow(() -> resolver.invalidateCache()); + } + + // ====================== Static Helpers ====================== + + @Test + void containsReference() { + assertTrue(GlobalVariableResolver.containsReference("${vars:x}")); + assertTrue(GlobalVariableResolver.containsReference("${vars:t/x}")); + assertFalse(GlobalVariableResolver.containsReference("plain text")); + assertFalse(GlobalVariableResolver.containsReference(null)); + assertFalse(GlobalVariableResolver.containsReference("${vault:x}")); + } +} diff --git a/src/test/java/ai/labs/eddi/configs/variables/model/GlobalVariableTest.java b/src/test/java/ai/labs/eddi/configs/variables/model/GlobalVariableTest.java new file mode 100644 index 0000000000..2a9d13c005 --- /dev/null +++ b/src/test/java/ai/labs/eddi/configs/variables/model/GlobalVariableTest.java @@ -0,0 +1,98 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.model; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Unit tests for {@link GlobalVariable} — record defaults, serialization, + * equality, tenant scoping. + */ +class GlobalVariableTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void fullConstructor() { + var gv = new GlobalVariable("myTenant", "default-model", "gpt-4.1", "The default LLM model", false); + assertEquals("myTenant", gv.tenantId()); + assertEquals("default-model", gv.key()); + assertEquals("gpt-4.1", gv.value()); + assertEquals("The default LLM model", gv.description()); + assertFalse(gv.exportable()); + } + + @Test + void compactConstructorDefaultsTenantAndExportable() { + var gv = new GlobalVariable(null, "x", "y", null, null); + assertEquals(GlobalVariable.DEFAULT_TENANT, gv.tenantId(), "null tenantId should default to 'default'"); + assertTrue(gv.exportable(), "null exportable should default to true"); + } + + @Test + void convenienceConstructor_keyValue() { + var gv = new GlobalVariable("key", "val"); + assertEquals(GlobalVariable.DEFAULT_TENANT, gv.tenantId()); + assertEquals("key", gv.key()); + assertEquals("val", gv.value()); + assertNull(gv.description()); + assertTrue(gv.exportable()); + } + + @Test + void convenienceConstructor_tenantKeyValue() { + var gv = new GlobalVariable("tenant1", "key", "val"); + assertEquals("tenant1", gv.tenantId()); + assertEquals("key", gv.key()); + assertEquals("val", gv.value()); + assertNull(gv.description()); + assertTrue(gv.exportable()); + } + + @Test + void equality() { + var a = new GlobalVariable("default", "k", "v", "d", true); + var b = new GlobalVariable("default", "k", "v", "d", true); + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } + + @Test + void inequality_differentTenant() { + var a = new GlobalVariable("t1", "k", "v"); + var b = new GlobalVariable("t2", "k", "v"); + assertNotEquals(a, b); + } + + @Test + void inequality_differentValue() { + var a = new GlobalVariable("k", "v1"); + var b = new GlobalVariable("k", "v2"); + assertNotEquals(a, b); + } + + @Test + void jsonSerialization() throws Exception { + var gv = new GlobalVariable("default", "model", "gpt-4.1", "default model", true); + String json = MAPPER.writeValueAsString(gv); + assertTrue(json.contains("\"key\":\"model\"")); + assertTrue(json.contains("\"value\":\"gpt-4.1\"")); + assertTrue(json.contains("\"tenantId\":\"default\"")); + + var deserialized = MAPPER.readValue(json, GlobalVariable.class); + assertEquals(gv, deserialized); + } + + @Test + void jsonNullDescription() throws Exception { + var gv = new GlobalVariable("k", "v"); + String json = MAPPER.writeValueAsString(gv); + // @JsonInclude(NON_NULL) should exclude null description + assertFalse(json.contains("\"description\""), "null description should be excluded from JSON"); + } +} diff --git a/src/test/java/ai/labs/eddi/configs/variables/mongo/GlobalVariableStoreTest.java b/src/test/java/ai/labs/eddi/configs/variables/mongo/GlobalVariableStoreTest.java new file mode 100644 index 0000000000..ab20d1deef --- /dev/null +++ b/src/test/java/ai/labs/eddi/configs/variables/mongo/GlobalVariableStoreTest.java @@ -0,0 +1,189 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.mongo; + +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.ReplaceOptions; +import com.mongodb.client.result.DeleteResult; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * Unit tests for {@link GlobalVariableStore} — MongoDB adapter with tenant + * scoping. Uses mocked {@link MongoCollection} to verify CRUD operations. + */ +@SuppressWarnings("unchecked") +class GlobalVariableStoreTest { + + private static final String DEFAULT = GlobalVariable.DEFAULT_TENANT; + + private MongoCollection collection; + private GlobalVariableStore store; + + @BeforeEach + void setUp() { + MongoDatabase database = mock(MongoDatabase.class); + collection = mock(MongoCollection.class); + when(database.getCollection("globalvariables")).thenReturn(collection); + store = new GlobalVariableStore(database); + } + + // ==================== getAll ==================== + + @Test + @DisplayName("getAll — returns empty map when no docs for tenant") + void getAllEmpty() { + FindIterable iterable = mock(FindIterable.class); + when(collection.find(any(Bson.class))).thenReturn(iterable); + + Map result = store.getAll(DEFAULT); + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + @DisplayName("getAll — returns key-value pairs for specific tenant") + void getAllWithDocuments() { + FindIterable iterable = mock(FindIterable.class); + when(collection.find(any(Bson.class))).thenReturn(iterable); + + doAnswer(invocation -> { + Consumer consumer = invocation.getArgument(0); + consumer.accept(new Document("tenantId", DEFAULT).append("key", "model").append("value", "gpt-4.1")); + consumer.accept(new Document("tenantId", DEFAULT).append("key", "temp").append("value", "0.7")); + return null; + }).when(iterable).forEach(any(Consumer.class)); + + Map result = store.getAll(DEFAULT); + assertEquals(2, result.size()); + assertEquals("gpt-4.1", result.get("model")); + assertEquals("0.7", result.get("temp")); + } + + // ==================== get ==================== + + @Test + @DisplayName("get — returns GlobalVariable when document exists") + void getFound() { + FindIterable iterable = mock(FindIterable.class); + when(collection.find(any(Bson.class))).thenReturn(iterable); + when(iterable.first()).thenReturn( + new Document("tenantId", DEFAULT) + .append("key", "model") + .append("value", "gpt-4.1") + .append("description", "Default model") + .append("exportable", true)); + + GlobalVariable result = store.get(DEFAULT, "model"); + assertNotNull(result); + assertEquals(DEFAULT, result.tenantId()); + assertEquals("model", result.key()); + assertEquals("gpt-4.1", result.value()); + assertEquals("Default model", result.description()); + assertTrue(result.exportable()); + } + + @Test + @DisplayName("get — returns null when document does not exist") + void getNotFound() { + FindIterable iterable = mock(FindIterable.class); + when(collection.find(any(Bson.class))).thenReturn(iterable); + when(iterable.first()).thenReturn(null); + + assertNull(store.get(DEFAULT, "missing")); + } + + // ==================== upsert ==================== + + @Test + @DisplayName("upsert — stores document with composite _id and tenant fields") + void upsert() { + var variable = new GlobalVariable(DEFAULT, "model", "gpt-4.1", "Default", true); + store.upsert(variable); + + ArgumentCaptor docCaptor = ArgumentCaptor.forClass(Document.class); + ArgumentCaptor optionsCaptor = ArgumentCaptor.forClass(ReplaceOptions.class); + verify(collection).replaceOne(any(Document.class), docCaptor.capture(), optionsCaptor.capture()); + + Document stored = docCaptor.getValue(); + assertEquals("default/model", stored.getString("_id")); + assertEquals(DEFAULT, stored.getString("tenantId")); + assertEquals("model", stored.getString("key")); + assertEquals("gpt-4.1", stored.getString("value")); + assertTrue(optionsCaptor.getValue().isUpsert()); + } + + @Test + @DisplayName("upsert — different tenant produces different _id") + void upsertDifferentTenant() { + var variable = new GlobalVariable("tenant-a", "model", "claude"); + store.upsert(variable); + + ArgumentCaptor docCaptor = ArgumentCaptor.forClass(Document.class); + verify(collection).replaceOne(any(Document.class), docCaptor.capture(), any(ReplaceOptions.class)); + assertEquals("tenant-a/model", docCaptor.getValue().getString("_id")); + assertEquals("tenant-a", docCaptor.getValue().getString("tenantId")); + } + + // ==================== delete ==================== + + @Test + @DisplayName("delete — calls deleteOne with tenant+key filter") + void delete() { + when(collection.deleteOne(any(Bson.class))).thenReturn(mock(DeleteResult.class)); + store.delete(DEFAULT, "model"); + verify(collection).deleteOne(any(Bson.class)); + } + + // ==================== listAll ==================== + + @Test + @DisplayName("listAll — returns empty list when no docs for tenant") + void listAllEmpty() { + FindIterable iterable = mock(FindIterable.class); + when(collection.find(any(Bson.class))).thenReturn(iterable); + + List result = store.listAll(DEFAULT); + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + @DisplayName("listAll — returns GlobalVariable objects for specific tenant") + void listAllWithDocuments() { + FindIterable iterable = mock(FindIterable.class); + when(collection.find(any(Bson.class))).thenReturn(iterable); + + doAnswer(invocation -> { + Consumer consumer = invocation.getArgument(0); + consumer.accept(new Document("tenantId", DEFAULT).append("key", "a").append("value", "1") + .append("description", "desc-a").append("exportable", true)); + consumer.accept(new Document("tenantId", DEFAULT).append("key", "b").append("value", "2") + .append("description", null).append("exportable", false)); + return null; + }).when(iterable).forEach(any(Consumer.class)); + + List result = store.listAll(DEFAULT); + assertEquals(2, result.size()); + assertEquals("a", result.get(0).key()); + assertEquals(DEFAULT, result.get(0).tenantId()); + assertEquals("b", result.get(1).key()); + } +} diff --git a/src/test/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStoreTest.java b/src/test/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStoreTest.java new file mode 100644 index 0000000000..653027ba56 --- /dev/null +++ b/src/test/java/ai/labs/eddi/configs/variables/rest/RestGlobalVariableStoreTest.java @@ -0,0 +1,134 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.variables.rest; + +import ai.labs.eddi.configs.variables.GlobalVariableResolver; +import ai.labs.eddi.configs.variables.IGlobalVariableStore; +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.NotFoundException; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** + * Unit tests for {@link RestGlobalVariableStore} — CRUD operations with tenant + * scoping, validation, and cache invalidation. + */ +class RestGlobalVariableStoreTest { + + private static final String DEFAULT = GlobalVariable.DEFAULT_TENANT; + + private IGlobalVariableStore store; + private GlobalVariableResolver resolver; + private RestGlobalVariableStore rest; + + @BeforeEach + void setUp() { + store = mock(IGlobalVariableStore.class); + resolver = mock(GlobalVariableResolver.class); + rest = new RestGlobalVariableStore(store, resolver); + } + + @Test + void listVariables() { + var expected = List.of(new GlobalVariable("k", "v")); + when(store.listAll(DEFAULT)).thenReturn(expected); + assertEquals(expected, rest.listVariables(DEFAULT)); + } + + @Test + void getVariableFound() { + var gv = new GlobalVariable("k", "v"); + when(store.get(DEFAULT, "k")).thenReturn(gv); + assertEquals(gv, rest.getVariable(DEFAULT, "k")); + } + + @Test + void getVariableNotFound() { + when(store.get(DEFAULT, "missing")).thenReturn(null); + assertThrows(NotFoundException.class, () -> rest.getVariable(DEFAULT, "missing")); + } + + @Test + void upsertVariable() { + var input = new GlobalVariable(DEFAULT, "model", "gpt-4.1", "default model", true); + Response response = rest.upsertVariable(DEFAULT, "model", input); + assertEquals(200, response.getStatus()); + verify(store).upsert(any(GlobalVariable.class)); + verify(resolver).invalidateCache(); + } + + @Test + void upsertVariablePathOverridesBody() { + // Path tenantId + key should take precedence over body values + var input = new GlobalVariable("wrong-tenant", "wrong-key", "val"); + rest.upsertVariable(DEFAULT, "correct-key", input); + + var captor = org.mockito.ArgumentCaptor.forClass(GlobalVariable.class); + verify(store).upsert(captor.capture()); + assertEquals(DEFAULT, captor.getValue().tenantId()); + assertEquals("correct-key", captor.getValue().key()); + } + + @Test + void upsertVariableInvalidKey() { + var input = new GlobalVariable("bad key!", "val"); + assertThrows(IllegalArgumentException.class, () -> rest.upsertVariable(DEFAULT, "bad key!", input)); + verifyNoInteractions(store); + } + + @Test + void upsertVariableInvalidTenantId() { + var input = new GlobalVariable("model", "val"); + assertThrows(IllegalArgumentException.class, () -> rest.upsertVariable("bad tenant!", "model", input)); + verifyNoInteractions(store); + } + + @Test + void deleteVariable() { + Response response = rest.deleteVariable(DEFAULT, "k"); + assertEquals(204, response.getStatus()); + verify(store).delete(DEFAULT, "k"); + verify(resolver).invalidateCache(); + } + + @Test + void validKeyPatterns() { + for (String key : List.of("model", "default-model", "api.key", "version_2", "A-Z.test_123")) { + assertDoesNotThrow(() -> rest.upsertVariable(DEFAULT, key, new GlobalVariable(key, "v")), + "Key should be valid: " + key); + } + } + + @Test + void validTenantIdPatterns() { + for (String tenant : List.of("default", "tenant-a", "org.example", "t_1")) { + assertDoesNotThrow(() -> rest.upsertVariable(tenant, "key", new GlobalVariable("key", "v")), + "Tenant should be valid: " + tenant); + } + } + + @Test + void invalidKeyPatterns() { + for (String key : List.of("", "has space", "key=value", "key/path")) { + assertThrows(Exception.class, () -> rest.upsertVariable(DEFAULT, key, new GlobalVariable(key, "v")), + "Key should be invalid: " + key); + } + assertThrows(Exception.class, () -> rest.upsertVariable(DEFAULT, null, new GlobalVariable(null, "v")), + "Null key should be invalid"); + } + + @Test + void upsertVariableNullBody() { + assertThrows(BadRequestException.class, () -> rest.upsertVariable(DEFAULT, "valid-key", null)); + verifyNoInteractions(store); + } +} diff --git a/src/test/java/ai/labs/eddi/datastore/postgres/PostgresGlobalVariableStoreTest.java b/src/test/java/ai/labs/eddi/datastore/postgres/PostgresGlobalVariableStoreTest.java new file mode 100644 index 0000000000..42668b9c8f --- /dev/null +++ b/src/test/java/ai/labs/eddi/datastore/postgres/PostgresGlobalVariableStoreTest.java @@ -0,0 +1,268 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.datastore.postgres; + +import ai.labs.eddi.configs.variables.model.GlobalVariable; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import javax.sql.DataSource; +import java.sql.*; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * Unit tests for {@link PostgresGlobalVariableStore} — JDBC adapter with tenant + * scoping. Uses mocked {@link DataSource} / {@link Connection} / + * {@link PreparedStatement} to verify SQL operations. + */ +@SuppressWarnings("unchecked") +class PostgresGlobalVariableStoreTest { + + private static final String DEFAULT = GlobalVariable.DEFAULT_TENANT; + + private Connection connection; + private PostgresGlobalVariableStore store; + + @BeforeEach + void setUp() throws Exception { + DataSource dataSource = mock(DataSource.class); + connection = mock(Connection.class); + when(dataSource.getConnection()).thenReturn(connection); + + // Schema creation statement + Statement stmt = mock(Statement.class); + when(connection.createStatement()).thenReturn(stmt); + + Instance instance = mock(Instance.class); + when(instance.get()).thenReturn(dataSource); + + store = new PostgresGlobalVariableStore(instance); + } + + // ==================== getAll ==================== + + @Test + @DisplayName("getAll — returns empty map when no rows for tenant") + void getAllEmpty() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(contains("WHERE tenant_id = ?"))).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(false); + + Map result = store.getAll(DEFAULT); + assertTrue(result.isEmpty()); + verify(ps).setString(1, DEFAULT); + } + + @Test + @DisplayName("getAll — returns key-value pairs for specific tenant") + void getAllWithRows() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(contains("WHERE tenant_id = ?"))).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(true, true, false); + when(rs.getString("key")).thenReturn("model", "temp"); + when(rs.getString("value")).thenReturn("gpt-4.1", "0.7"); + + Map result = store.getAll(DEFAULT); + + assertEquals(2, result.size()); + assertEquals("gpt-4.1", result.get("model")); + verify(ps).setString(1, DEFAULT); + } + + // ==================== get ==================== + + @Test + @DisplayName("get — returns GlobalVariable with tenantId when found") + void getFound() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(contains("AND \"key\" = ?"))).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(true); + when(rs.getString("tenant_id")).thenReturn(DEFAULT); + when(rs.getString("key")).thenReturn("model"); + when(rs.getString("value")).thenReturn("gpt-4.1"); + when(rs.getString("description")).thenReturn("Default model"); + when(rs.getBoolean("exportable")).thenReturn(true); + + GlobalVariable result = store.get(DEFAULT, "model"); + + assertNotNull(result); + assertEquals(DEFAULT, result.tenantId()); + assertEquals("model", result.key()); + assertEquals("gpt-4.1", result.value()); + verify(ps).setString(1, DEFAULT); + verify(ps).setString(2, "model"); + } + + @Test + @DisplayName("get — returns null when not found") + void getNotFound() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(contains("AND \"key\" = ?"))).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(false); + + assertNull(store.get(DEFAULT, "missing")); + } + + // ==================== upsert ==================== + + @Test + @DisplayName("upsert — executes INSERT ON CONFLICT with tenant_id + key") + void upsert() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(contains("ON CONFLICT (tenant_id, \"key\")"))).thenReturn(ps); + + store.upsert(new GlobalVariable(DEFAULT, "model", "gpt-4.1", "Default", true)); + + verify(ps).setString(1, DEFAULT); + verify(ps).setString(2, "model"); + verify(ps).setString(3, "gpt-4.1"); + verify(ps).setString(4, "Default"); + verify(ps).setBoolean(5, true); + verify(ps).executeUpdate(); + } + + @Test + @DisplayName("upsert — different tenant writes separate row") + void upsertDifferentTenant() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(contains("ON CONFLICT (tenant_id, \"key\")"))).thenReturn(ps); + + store.upsert(new GlobalVariable("tenant-a", "model", "claude")); + + verify(ps).setString(1, "tenant-a"); + verify(ps).setString(2, "model"); + verify(ps).setString(3, "claude"); + } + + // ==================== delete ==================== + + @Test + @DisplayName("delete — executes DELETE with tenant_id + key") + void delete() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(contains("DELETE FROM"))).thenReturn(ps); + + store.delete(DEFAULT, "model"); + + verify(ps).setString(1, DEFAULT); + verify(ps).setString(2, "model"); + verify(ps).executeUpdate(); + } + + // ==================== listAll ==================== + + @Test + @DisplayName("listAll — returns empty list when no rows for tenant") + void listAllEmpty() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(contains("WHERE tenant_id = ?"))).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(false); + + List result = store.listAll(DEFAULT); + assertTrue(result.isEmpty()); + } + + @Test + @DisplayName("listAll — returns GlobalVariable objects with tenantId") + void listAllWithRows() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(contains("WHERE tenant_id = ?"))).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(true, true, false); + when(rs.getString("tenant_id")).thenReturn(DEFAULT, DEFAULT); + when(rs.getString("key")).thenReturn("a", "b"); + when(rs.getString("value")).thenReturn("1", "2"); + when(rs.getString("description")).thenReturn("desc-a", null); + when(rs.getBoolean("exportable")).thenReturn(true, false); + + List result = store.listAll(DEFAULT); + + assertEquals(2, result.size()); + assertEquals(DEFAULT, result.get(0).tenantId()); + assertEquals("a", result.get(0).key()); + } + + // ==================== error handling ==================== + + @Test + @DisplayName("getAll — propagates SQLException as RuntimeException") + void getAllSqlException() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenThrow(new SQLException("test error")); + + RuntimeException ex = assertThrows(RuntimeException.class, () -> store.getAll(DEFAULT)); + assertTrue(ex.getMessage().contains("Failed to list all global variables")); + assertInstanceOf(SQLException.class, ex.getCause()); + } + + @Test + @DisplayName("get — propagates SQLException as RuntimeException") + void getSqlException() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenThrow(new SQLException("test error")); + + RuntimeException ex = assertThrows(RuntimeException.class, () -> store.get(DEFAULT, "key")); + assertTrue(ex.getMessage().contains("Failed to get global variable")); + } + + @Test + @DisplayName("upsert — propagates SQLException as RuntimeException") + void upsertSqlException() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeUpdate()).thenThrow(new SQLException("test error")); + + RuntimeException ex = assertThrows(RuntimeException.class, + () -> store.upsert(new GlobalVariable("k", "v"))); + assertTrue(ex.getMessage().contains("Failed to upsert global variable")); + } + + @Test + @DisplayName("delete — propagates SQLException as RuntimeException") + void deleteSqlException() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeUpdate()).thenThrow(new SQLException("test error")); + + RuntimeException ex = assertThrows(RuntimeException.class, + () -> store.delete(DEFAULT, "key")); + assertTrue(ex.getMessage().contains("Failed to delete global variable")); + } + + @Test + @DisplayName("ensureSchema — only creates table once (idempotent)") + void ensureSchemaIdempotent() throws Exception { + PreparedStatement ps = mock(PreparedStatement.class); + ResultSet rs = mock(ResultSet.class); + when(connection.prepareStatement(anyString())).thenReturn(ps); + when(ps.executeQuery()).thenReturn(rs); + when(rs.next()).thenReturn(false); + + store.getAll(DEFAULT); + store.getAll(DEFAULT); + + verify(connection, atMost(1)).createStatement(); + } +} diff --git a/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java b/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java index fb5db99add..08f791179e 100644 --- a/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java +++ b/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java @@ -280,7 +280,7 @@ void setupAgent_withVaultActive_storesVaultReference() throws Exception { var lcCaptor = ArgumentCaptor.forClass(LlmConfiguration.class); verify(langchainStore).createLlm(lcCaptor.capture()); String storedKey = lcCaptor.getValue().tasks().get(0).getParameters().get("apiKey"); - assertTrue(storedKey.startsWith("${eddivault:"), + assertTrue(storedKey.startsWith("${vault:"), "API key should be vault reference, got: " + storedKey); assertFalse(storedKey.contains("sk-live-secret"), "Plaintext key must NOT appear in LLM config when vault is active"); diff --git a/src/test/java/ai/labs/eddi/integration/GlobalVariableCrudIT.java b/src/test/java/ai/labs/eddi/integration/GlobalVariableCrudIT.java new file mode 100644 index 0000000000..2a86a2fb75 --- /dev/null +++ b/src/test/java/ai/labs/eddi/integration/GlobalVariableCrudIT.java @@ -0,0 +1,160 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.integration; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.*; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** + * Integration test for Global Variable CRUD operations. + *

    + * Tests Create → Read → Update → Delete lifecycle for + * {@code /variablestore/variables/{tenantId}/{key}}. Uses the default tenant + * ({@code "default"}) for simplicity. + */ +@QuarkusTest +@TestProfile(IntegrationTestProfile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class GlobalVariableCrudIT extends BaseIntegrationIT { + + private static final String BASE_PATH = "/variablestore/variables"; + private static final String TENANT = "default"; + private static final String TEST_KEY = "it-test-model"; + + @AfterAll + static void cleanup() { + try { + given().delete(BASE_PATH + "/" + TENANT + "/" + TEST_KEY); + } catch (Exception ignored) { + } + } + + @Test + @Order(1) + @DisplayName("List variables for default tenant (initially empty or existing)") + void listVariables() { + given().get(BASE_PATH + "/" + TENANT) + .then().assertThat() + .statusCode(200) + .contentType(ContentType.JSON) + .body("$", instanceOf(java.util.List.class)); + } + + @Test + @Order(2) + @DisplayName("Create a global variable via PUT") + void createVariable() { + String body = """ + { + "key": "%s", + "value": "gpt-4.1", + "description": "Integration test model", + "exportable": true + } + """.formatted(TEST_KEY); + + given().contentType(ContentType.JSON) + .body(body) + .put(BASE_PATH + "/" + TENANT + "/" + TEST_KEY) + .then().assertThat() + .statusCode(200); + } + + @Test + @Order(3) + @DisplayName("Read created variable by tenant and key") + void readVariable() { + given().get(BASE_PATH + "/" + TENANT + "/" + TEST_KEY) + .then().assertThat() + .statusCode(200) + .contentType(ContentType.JSON) + .body("key", equalTo(TEST_KEY)) + .body("tenantId", equalTo(TENANT)) + .body("value", equalTo("gpt-4.1")) + .body("description", equalTo("Integration test model")) + .body("exportable", equalTo(true)); + } + + @Test + @Order(4) + @DisplayName("Update variable value via PUT") + void updateVariable() { + String body = """ + { + "key": "%s", + "value": "gpt-4.1-mini", + "description": "Updated integration test model", + "exportable": false + } + """.formatted(TEST_KEY); + + given().contentType(ContentType.JSON) + .body(body) + .put(BASE_PATH + "/" + TENANT + "/" + TEST_KEY) + .then().assertThat() + .statusCode(200); + + // Verify update + given().get(BASE_PATH + "/" + TENANT + "/" + TEST_KEY) + .then().assertThat() + .statusCode(200) + .body("value", equalTo("gpt-4.1-mini")) + .body("description", equalTo("Updated integration test model")) + .body("exportable", equalTo(false)); + } + + @Test + @Order(5) + @DisplayName("Variable appears in tenant's list") + void variableInList() { + given().get(BASE_PATH + "/" + TENANT) + .then().assertThat() + .statusCode(200) + .body("key", hasItem(TEST_KEY)); + } + + @Test + @Order(6) + @DisplayName("GET non-existent key returns 404") + void getNonExistent() { + given().get(BASE_PATH + "/" + TENANT + "/does-not-exist-" + System.currentTimeMillis()) + .then().assertThat() + .statusCode(404); + } + + @Test + @Order(7) + @DisplayName("PUT with invalid key pattern returns 400") + void invalidKey() { + String body = """ + { "key": "bad key!", "value": "v" } + """; + + given().contentType(ContentType.JSON) + .body(body) + .put(BASE_PATH + "/" + TENANT + "/bad key!") + .then().assertThat() + .statusCode(400); + } + + @Test + @Order(8) + @DisplayName("Delete variable") + void deleteVariable() { + given().delete(BASE_PATH + "/" + TENANT + "/" + TEST_KEY) + .then().assertThat() + .statusCode(204); + + // Verify deletion + given().get(BASE_PATH + "/" + TENANT + "/" + TEST_KEY) + .then().assertThat() + .statusCode(404); + } +} diff --git a/src/test/java/ai/labs/eddi/integration/postgres/PostgresGlobalVariableCrudIT.java b/src/test/java/ai/labs/eddi/integration/postgres/PostgresGlobalVariableCrudIT.java new file mode 100644 index 0000000000..6d6e5f9041 --- /dev/null +++ b/src/test/java/ai/labs/eddi/integration/postgres/PostgresGlobalVariableCrudIT.java @@ -0,0 +1,25 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.integration.postgres; + +import ai.labs.eddi.integration.GlobalVariableCrudIT; +import ai.labs.eddi.integration.PostgresIntegrationTestProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; + +/** + * Runs all Global Variable CRUD tests against PostgreSQL. + *

    + * Uses {@link PostgresIntegrationTestProfile} which activates the + * {@code postgres} profile, disables MongoDB DevServices, and enables + * PostgreSQL DevServices (Testcontainers). The + * {@link ai.labs.eddi.datastore.postgres.PostgresGlobalVariableStore} is the + * active {@link ai.labs.eddi.configs.variables.IGlobalVariableStore} bean in + * this profile. + */ +@QuarkusTest +@TestProfile(PostgresIntegrationTestProfile.class) +class PostgresGlobalVariableCrudIT extends GlobalVariableCrudIT { +} diff --git a/src/test/java/ai/labs/eddi/integrations/slack/SlackChannelRouterTest.java b/src/test/java/ai/labs/eddi/integrations/slack/SlackChannelRouterTest.java index ed7a0ba87f..4edd9d0e58 100644 --- a/src/test/java/ai/labs/eddi/integrations/slack/SlackChannelRouterTest.java +++ b/src/test/java/ai/labs/eddi/integrations/slack/SlackChannelRouterTest.java @@ -8,6 +8,7 @@ import ai.labs.eddi.configs.agents.model.AgentConfiguration; import ai.labs.eddi.configs.agents.model.AgentConfiguration.ChannelConnector; import ai.labs.eddi.configs.descriptors.model.DocumentDescriptor; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.engine.api.IRestAgentAdministration; import ai.labs.eddi.engine.model.AgentDeploymentStatus; import ai.labs.eddi.engine.model.Deployment; @@ -31,6 +32,7 @@ class SlackChannelRouterTest { private IRestAgentAdministration agentAdmin; private IRestAgentStore agentStore; private SecretResolver secretResolver; + private GlobalVariableResolver globalVariableResolver; private SlackChannelRouter router; @BeforeEach @@ -38,11 +40,13 @@ void setUp() { agentAdmin = mock(IRestAgentAdministration.class); agentStore = mock(IRestAgentStore.class); secretResolver = mock(SecretResolver.class); + globalVariableResolver = mock(GlobalVariableResolver.class); - // By default, SecretResolver passes through unchanged + // By default, both resolvers pass through unchanged when(secretResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); + when(globalVariableResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); - router = new SlackChannelRouter(agentAdmin, agentStore, secretResolver); + router = new SlackChannelRouter(agentAdmin, agentStore, globalVariableResolver, secretResolver); } // ─── Agent Resolution ─── @@ -102,11 +106,11 @@ void resolveCredentials_unknownChannel_returnsEmpty() throws Exception { @Test void resolveCredentials_vaultReferencesResolved() throws Exception { // Configure SecretResolver to resolve vault references - when(secretResolver.resolveValue("${eddivault:slack-token}")).thenReturn("xoxb-resolved"); - when(secretResolver.resolveValue("${eddivault:slack-secret}")).thenReturn("resolved-secret"); + when(secretResolver.resolveValue("${vault:slack-token}")).thenReturn("xoxb-resolved"); + when(secretResolver.resolveValue("${vault:slack-secret}")).thenReturn("resolved-secret"); setupDeployedAgent("agent-1", 1, "C0123", - "${eddivault:slack-token}", "${eddivault:slack-secret}", null); + "${vault:slack-token}", "${vault:slack-secret}", null); var creds = router.resolveCredentials("C0123"); assertTrue(creds.isPresent()); @@ -236,13 +240,13 @@ void hasAnySlackChannels_falseWhenEmpty() throws Exception { @Test void resolveCredentials_vaultFailure_botTokenNull_channelStillMapped() throws Exception { // Vault throws for the botToken reference but signingSecret resolves fine - when(secretResolver.resolveValue("${eddivault:bad-token-ref}")) + when(secretResolver.resolveValue("${vault:bad-token-ref}")) .thenThrow(new RuntimeException("Vault key not found: bad-token-ref")); when(secretResolver.resolveValue("plain-secret")) .thenReturn("plain-secret"); setupDeployedAgent("agent-1", 1, "C0123", - "${eddivault:bad-token-ref}", "plain-secret", null); + "${vault:bad-token-ref}", "plain-secret", null); // Channel should still be mapped (routing works) assertEquals(Optional.of("agent-1"), router.resolveAgentId("C0123")); @@ -259,11 +263,11 @@ void resolveCredentials_vaultFailure_signingSecretNull_notInSigningSecretsSet() // Signing secret vault ref fails — should not appear in getAllSigningSecrets() when(secretResolver.resolveValue("xoxb-good-token")) .thenReturn("xoxb-good-token"); - when(secretResolver.resolveValue("${eddivault:bad-secret-ref}")) + when(secretResolver.resolveValue("${vault:bad-secret-ref}")) .thenThrow(new RuntimeException("Vault key not found")); setupDeployedAgent("agent-1", 1, "C0123", - "xoxb-good-token", "${eddivault:bad-secret-ref}", null); + "xoxb-good-token", "${vault:bad-secret-ref}", null); // Signing secrets set should be empty (failed resolution excluded) assertTrue(router.getAllSigningSecrets().isEmpty()); diff --git a/src/test/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutorTest.java b/src/test/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutorTest.java index 8367652dfd..b6179bee32 100644 --- a/src/test/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutorTest.java +++ b/src/test/java/ai/labs/eddi/modules/apicalls/impl/ApiCallExecutorTest.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.apicalls.impl; import ai.labs.eddi.configs.apicalls.model.*; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.datastore.serialization.IJsonSerialization; import ai.labs.eddi.engine.httpclient.ICompleteListener; import ai.labs.eddi.engine.httpclient.IHttpClient; @@ -50,8 +51,10 @@ void setUp() throws Exception { prePostUtils = mock(PrePostUtils.class); SecretResolver secretResolver = mock(SecretResolver.class); when(secretResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); + GlobalVariableResolver globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); - executor = new ApiCallExecutor(httpClient, jsonSerialization, runtime, prePostUtils, secretResolver); + executor = new ApiCallExecutor(httpClient, jsonSerialization, runtime, prePostUtils, globalVariableResolver, secretResolver); memory = mock(IConversationMemory.class); currentStep = mock(IWritableConversationStep.class); @@ -327,7 +330,7 @@ void execute_vaultRefInHeaderValue_isScrubbed() throws Exception { Map requestMap = new HashMap<>(); Map headers = new LinkedHashMap<>(); - headers.put("X-Custom-Auth", "${eddivault:my-secret}"); + headers.put("X-Custom-Auth", "${vault:my-secret}"); requestMap.put("headers", headers); when(mockRequest.toMap()).thenReturn(requestMap); setupSuccessResponse(200, "ok", "text/plain"); diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerExtendedTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerExtendedTest.java index efcaea9245..f12bdf1ded 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerExtendedTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerExtendedTest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.model.LlmConfiguration.A2AAgentConfig; import ai.labs.eddi.secrets.SecretResolver; import org.junit.jupiter.api.BeforeEach; @@ -32,7 +33,9 @@ class A2AToolProviderManagerExtendedTest { void setUp() { secretResolver = mock(SecretResolver.class); when(secretResolver.resolveValue(anyString())).thenAnswer(i -> i.getArgument(0)); - manager = new A2AToolProviderManager(secretResolver); + GlobalVariableResolver globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveValue(anyString())).thenAnswer(i -> i.getArgument(0)); + manager = new A2AToolProviderManager(globalVariableResolver, secretResolver); } // ─── Discovery with unreachable agents ──────────────────────── @@ -155,7 +158,7 @@ void vaultRefKey() { void eddiVaultRefKey() { var config = new A2AAgentConfig(); config.setUrl("http://192.0.2.1:1"); - config.setApiKey("${eddivault:my-key}"); + config.setApiKey("${vault:my-key}"); config.setTimeoutMs(100L); assertDoesNotThrow(() -> manager.discoverTools(List.of(config))); diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerTest.java index 78501a1cb3..3b4511f23f 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/A2AToolProviderManagerTest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.model.LlmConfiguration.A2AAgentConfig; import ai.labs.eddi.secrets.SecretResolver; import org.junit.jupiter.api.BeforeEach; @@ -28,7 +29,8 @@ class A2AToolProviderManagerTest { @BeforeEach void setUp() { SecretResolver secretResolver = mock(SecretResolver.class); - manager = new A2AToolProviderManager(secretResolver); + GlobalVariableResolver globalVariableResolver = mock(GlobalVariableResolver.class); + manager = new A2AToolProviderManager(globalVariableResolver, secretResolver); } // ─── discoverTools empty/null ───────────────────────────────── diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistryTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistryTest.java index 93650a84ea..c82559a8d5 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistryTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/ChatModelRegistryTest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.impl.builder.ILanguageModelBuilder; import ai.labs.eddi.secrets.SecretResolver; import ai.labs.eddi.secrets.model.SecretReference; @@ -73,11 +74,13 @@ public ChatModel build(Map parameters) { // Uses default buildStreaming — throws UnsupportedOperationException }); - // Create a pass-through SecretResolver mock (vault not configured) + // Create pass-through mocks SecretResolver secretResolver = mock(SecretResolver.class); when(secretResolver.resolveSecrets(any())).thenAnswer(inv -> inv.getArgument(0)); + GlobalVariableResolver globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveAll(any())).thenAnswer(inv -> inv.getArgument(0)); - registry = new ChatModelRegistry(builders, secretResolver); + registry = new ChatModelRegistry(builders, globalVariableResolver, secretResolver); } @Nested @@ -276,18 +279,20 @@ public void chat(ChatRequest chatRequest, StreamingChatResponseHandler handler) SecretResolver secretResolver = mock(SecretResolver.class); when(secretResolver.resolveSecrets(any())).thenAnswer(inv -> inv.getArgument(0)); - invalidationRegistry = new ChatModelRegistry(builders, secretResolver); + GlobalVariableResolver globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveAll(any())).thenAnswer(inv -> inv.getArgument(0)); + invalidationRegistry = new ChatModelRegistry(builders, globalVariableResolver, secretResolver); } @Test @DisplayName("invalidateForSecret evicts only models using the changed secret") void invalidateForSecret_evictsOnlyMatching() throws Exception { var targetParams = new HashMap(); - targetParams.put("apiKey", "${eddivault:openai-key}"); + targetParams.put("apiKey", "${vault:openai-key}"); ChatModel targetModel = invalidationRegistry.getOrCreate("openai", targetParams); var otherParams = new HashMap(); - otherParams.put("apiKey", "${eddivault:anthropic-key}"); + otherParams.put("apiKey", "${vault:anthropic-key}"); ChatModel otherModel = invalidationRegistry.getOrCreate("openai", otherParams); // Invalidate only the openai secret @@ -306,7 +311,7 @@ void invalidateForSecret_evictsOnlyMatching() throws Exception { @DisplayName("invalidateForSecret matches full vault reference form") void invalidateForSecret_fullForm_evicts() throws Exception { var params = new HashMap(); - params.put("apiKey", "${eddivault:default/openai-key}"); + params.put("apiKey", "${vault:default/openai-key}"); ChatModel original = invalidationRegistry.getOrCreate("openai", params); invalidationRegistry.invalidateForSecret(new SecretReference("default", "openai-key")); @@ -318,10 +323,10 @@ void invalidateForSecret_fullForm_evicts() throws Exception { @Test @DisplayName("invalidateForSecret with non-default tenant does NOT evict default tenant models") void invalidateForSecret_nonDefaultTenant_noFalsePositive() throws Exception { - // Bug regression: ${eddivault:openai-key} resolves to tenant "default". + // Bug regression: ${vault:openai-key} resolves to tenant "default". // Rotating acme's "openai-key" must NOT evict default-tenant models. var defaultParams = new HashMap(); - defaultParams.put("apiKey", "${eddivault:openai-key}"); + defaultParams.put("apiKey", "${vault:openai-key}"); ChatModel defaultModel = invalidationRegistry.getOrCreate("openai", defaultParams); // Invalidate acme tenant's secret with the same keyName @@ -336,11 +341,11 @@ void invalidateForSecret_nonDefaultTenant_noFalsePositive() throws Exception { @DisplayName("invalidateForSecret(null) clears all models") void invalidateForSecret_null_clearsAll() throws Exception { var params1 = new HashMap(); - params1.put("apiKey", "${eddivault:key1}"); + params1.put("apiKey", "${vault:key1}"); ChatModel model1 = invalidationRegistry.getOrCreate("openai", params1); var params2 = new HashMap(); - params2.put("apiKey", "${eddivault:key2}"); + params2.put("apiKey", "${vault:key2}"); ChatModel model2 = invalidationRegistry.getOrCreate("openai", params2); invalidationRegistry.invalidateForSecret(null); @@ -355,7 +360,7 @@ void invalidateForSecret_null_clearsAll() throws Exception { @DisplayName("invalidateForSecret with no matching models is a no-op") void invalidateForSecret_noMatch_leavesAllCached() throws Exception { var params = new HashMap(); - params.put("apiKey", "${eddivault:openai-key}"); + params.put("apiKey", "${vault:openai-key}"); ChatModel original = invalidationRegistry.getOrCreate("openai", params); invalidationRegistry.invalidateForSecret(new SecretReference("default", "unrelated-key")); @@ -368,7 +373,7 @@ void invalidateForSecret_noMatch_leavesAllCached() throws Exception { @DisplayName("invalidateForSecret evicts from both sync and streaming caches") void invalidateForSecret_evictsBothCaches() throws Exception { var params = new HashMap(); - params.put("apiKey", "${eddivault:openai-key}"); + params.put("apiKey", "${vault:openai-key}"); ChatModel syncOriginal = invalidationRegistry.getOrCreate("openai", params); StreamingChatModel streamOriginal = invalidationRegistry.getOrCreateStreaming("openai", params); diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactoryTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactoryTest.java index 0163e95b2b..00801f8aa6 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactoryTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingModelFactoryTest.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.llm.impl; import ai.labs.eddi.configs.rag.model.RagConfiguration; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.secrets.SecretResolver; import dev.langchain4j.model.embedding.EmbeddingModel; import org.junit.jupiter.api.BeforeEach; @@ -25,13 +26,17 @@ class EmbeddingModelFactoryTest { @Mock private SecretResolver secretResolver; + @Mock + private GlobalVariableResolver globalVariableResolver; + private EmbeddingModelFactory factory; @BeforeEach void setUp() { openMocks(this); when(secretResolver.resolveSecrets(any())).thenAnswer(inv -> inv.getArgument(0)); - factory = new EmbeddingModelFactory(secretResolver); + when(globalVariableResolver.resolveAll(any())).thenAnswer(inv -> inv.getArgument(0)); + factory = new EmbeddingModelFactory(globalVariableResolver, secretResolver); } @Test diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactoryTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactoryTest.java index bcd3dbc16a..55a3371bb4 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactoryTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/EmbeddingStoreFactoryTest.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.llm.impl; import ai.labs.eddi.configs.rag.model.RagConfiguration; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.secrets.SecretResolver; import dev.langchain4j.data.segment.TextSegment; import dev.langchain4j.store.embedding.EmbeddingStore; @@ -24,12 +25,15 @@ class EmbeddingStoreFactoryTest { private EmbeddingStoreFactory factory; private SecretResolver secretResolver; + private GlobalVariableResolver globalVariableResolver; @BeforeEach void setUp() { secretResolver = mock(SecretResolver.class); when(secretResolver.resolveSecrets(any())).thenAnswer(inv -> inv.getArgument(0)); - factory = new EmbeddingStoreFactory(secretResolver); + globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveAll(any())).thenAnswer(inv -> inv.getArgument(0)); + factory = new EmbeddingStoreFactory(globalVariableResolver, secretResolver); } @Test @@ -166,7 +170,7 @@ void pgvector_noPassword_shouldThrow() { var ex = assertThrows(IllegalArgumentException.class, () -> factory.getOrCreate(config, "kb")); assertTrue(ex.getMessage().contains("password"), "Error should mention missing password"); - assertTrue(ex.getMessage().contains("eddivault"), "Error should mention vault reference"); + assertTrue(ex.getMessage().contains("vault"), "Error should mention vault reference"); } @Test diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/LlmTaskTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/LlmTaskTest.java index 49a567c65b..78f33916f8 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/LlmTaskTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/LlmTaskTest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.configs.workflows.model.ExtensionDescriptor; import ai.labs.eddi.datastore.serialization.IJsonSerialization; import ai.labs.eddi.engine.lifecycle.exceptions.LifecycleException; @@ -96,7 +97,11 @@ public ChatResponse chat(List messages) { var toolExecutionService = mock(ToolExecutionService.class); var secretResolver = mock(SecretResolver.class); when(secretResolver.resolveSecrets(any())).thenAnswer(inv -> inv.getArgument(0)); - var chatModelRegistry = new ChatModelRegistry(languageModelApiConnectorBuilders, secretResolver); + var globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveAll(any())).thenAnswer(inv -> inv.getArgument(0)); + when(globalVariableResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); + when(globalVariableResolver.getTemplateData()).thenReturn(java.util.Map.of()); + var chatModelRegistry = new ChatModelRegistry(languageModelApiConnectorBuilders, globalVariableResolver, secretResolver); var toolResponseTruncator = new ToolResponseTruncator(new io.micrometer.core.instrument.simple.SimpleMeterRegistry()); @@ -106,6 +111,7 @@ weatherTool, apiCallExecutor, toolExecutionService, mock(McpToolProviderManager. mock(IRestAgentStore.class), mock(IRestWorkflowStore.class), mock(RagContextProvider.class), mock(IUserMemoryStore.class), new TokenCounterFactory(), mock(ConversationSummarizer.class), mock(PromptSnippetService.class), + globalVariableResolver, toolResponseTruncator, mock(ai.labs.eddi.engine.tenancy.TenantQuotaService.class)); } diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManagerTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManagerTest.java index bae695a2ce..68a2295eba 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManagerTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/McpToolProviderManagerTest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.modules.llm.impl; +import ai.labs.eddi.configs.variables.GlobalVariableResolver; import ai.labs.eddi.modules.llm.model.LlmConfiguration.McpServerConfig; import ai.labs.eddi.secrets.SecretResolver; import org.junit.jupiter.api.BeforeEach; @@ -24,12 +25,15 @@ class McpToolProviderManagerTest { private McpToolProviderManager manager; private SecretResolver secretResolver; + private GlobalVariableResolver globalVariableResolver; @BeforeEach void setUp() { secretResolver = mock(SecretResolver.class); when(secretResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); - manager = new McpToolProviderManager(secretResolver); + globalVariableResolver = mock(GlobalVariableResolver.class); + when(globalVariableResolver.resolveValue(anyString())).thenAnswer(inv -> inv.getArgument(0)); + manager = new McpToolProviderManager(globalVariableResolver, secretResolver); } @Test @@ -124,13 +128,13 @@ void testCloseClient_NonExistentUrl() { void testDiscoverTools_VaultRefResolution() { var config = new McpServerConfig(); config.setUrl("http://localhost:99999/mcp-vault-test"); - config.setApiKey("${eddivault:my-secret}"); + config.setApiKey("${vault:my-secret}"); config.setTimeoutMs(1000L); // The discoverTools call will fail to connect, but we can verify // the secret resolver was called manager.discoverTools(List.of(config)); - verify(secretResolver).resolveValue("${eddivault:my-secret}"); + verify(secretResolver).resolveValue("${vault:my-secret}"); } } diff --git a/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationModelsTest.java b/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationModelsTest.java index 6a15dfd689..33202446c0 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationModelsTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationModelsTest.java @@ -141,7 +141,7 @@ void setters() { msc.setUrl("http://localhost:7070/mcp"); msc.setName("local-mcp"); msc.setTransport("sse"); - msc.setApiKey("${eddivault:mcp-key}"); + msc.setApiKey("${vault:mcp-key}"); msc.setTimeoutMs(60000L); assertEquals("http://localhost:7070/mcp", msc.getUrl()); assertEquals("sse", msc.getTransport()); @@ -169,7 +169,7 @@ void setters() { a2a.setUrl("https://remote-agent.example.com/a2a"); a2a.setName("translator"); a2a.setSkillsFilter(List.of("translate-en-de")); - a2a.setApiKey("${eddivault:a2a-key}"); + a2a.setApiKey("${vault:a2a-key}"); a2a.setTimeoutMs(10000L); assertEquals("translator", a2a.getName()); assertEquals(1, a2a.getSkillsFilter().size()); diff --git a/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationTest.java b/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationTest.java index 1af1541f87..a7b45a936d 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/model/LlmConfigurationTest.java @@ -243,13 +243,13 @@ void roundTrip() { cfg.setUrl("https://agent.example.com"); cfg.setName("remote-agent"); cfg.setSkillsFilter(List.of("skill-1", "skill-2")); - cfg.setApiKey("${eddivault:a2a-key}"); + cfg.setApiKey("${vault:a2a-key}"); cfg.setTimeoutMs(15000L); assertEquals("https://agent.example.com", cfg.getUrl()); assertEquals("remote-agent", cfg.getName()); assertEquals(2, cfg.getSkillsFilter().size()); - assertEquals("${eddivault:a2a-key}", cfg.getApiKey()); + assertEquals("${vault:a2a-key}", cfg.getApiKey()); assertEquals(15000L, cfg.getTimeoutMs()); } } diff --git a/src/test/java/ai/labs/eddi/secrets/SecretResolverTest.java b/src/test/java/ai/labs/eddi/secrets/SecretResolverTest.java index ae1505c817..d11e386155 100644 --- a/src/test/java/ai/labs/eddi/secrets/SecretResolverTest.java +++ b/src/test/java/ai/labs/eddi/secrets/SecretResolverTest.java @@ -48,7 +48,7 @@ void resolveValue_shortForm_resolvesToPlaintext() throws ISecretProvider.SecretN var ref = new SecretReference("default", "openaiKey"); when(secretProvider.resolve(ref)).thenReturn("sk-actual-secret-key"); - String input = "Bearer ${eddivault:openaiKey}"; + String input = "Bearer ${vault:openaiKey}"; String result = resolver.resolveValue(input); assertEquals("Bearer sk-actual-secret-key", result); @@ -59,7 +59,7 @@ void resolveValue_fullForm_resolvesToPlaintext() throws ISecretProvider.SecretNo var ref = new SecretReference("myTenant", "openaiKey"); when(secretProvider.resolve(ref)).thenReturn("sk-tenant-key"); - String input = "Bearer ${eddivault:myTenant/openaiKey}"; + String input = "Bearer ${vault:myTenant/openaiKey}"; String result = resolver.resolveValue(input); assertEquals("Bearer sk-tenant-key", result); @@ -70,7 +70,7 @@ void resolveValue_multipleRefs_allResolved() throws ISecretProvider.SecretNotFou when(secretProvider.resolve(new SecretReference("default", "key1"))).thenReturn("val1"); when(secretProvider.resolve(new SecretReference("default", "key2"))).thenReturn("val2"); - String input = "${eddivault:key1}:${eddivault:key2}"; + String input = "${vault:key1}:${vault:key2}"; String result = resolver.resolveValue(input); assertEquals("val1:val2", result); @@ -81,7 +81,7 @@ void resolveValue_mixedFormats_allResolved() throws ISecretProvider.SecretNotFou when(secretProvider.resolve(new SecretReference("default", "key1"))).thenReturn("val1"); when(secretProvider.resolve(new SecretReference("acme", "key2"))).thenReturn("val2"); - String input = "${eddivault:key1}:${eddivault:acme/key2}"; + String input = "${vault:key1}:${vault:acme/key2}"; String result = resolver.resolveValue(input); assertEquals("val1:val2", result); @@ -91,7 +91,7 @@ void resolveValue_mixedFormats_allResolved() throws ISecretProvider.SecretNotFou void resolveValue_secretNotFound_keepsRef() throws ISecretProvider.SecretNotFoundException, ISecretProvider.SecretProviderException { when(secretProvider.resolve(any(SecretReference.class))).thenThrow(new ISecretProvider.SecretNotFoundException("not found")); - String input = "Bearer ${eddivault:missingKey}"; + String input = "Bearer ${vault:missingKey}"; String result = resolver.resolveValue(input); // When secret is not found, the reference should remain as-is @@ -105,7 +105,7 @@ void resolveValue_vaultNotAvailable_passthrough() { SecretResolver passthroughResolver = new SecretResolver(unavailable, meterRegistry, 5, 100); passthroughResolver.init(); - String input = "Bearer ${eddivault:key}"; + String input = "Bearer ${vault:key}"; assertEquals(input, passthroughResolver.resolveValue(input)); } @@ -114,7 +114,7 @@ void resolveValue_autoVaultKey_withAgentPrefix() throws ISecretProvider.SecretNo var ref = new SecretReference("default", "69c687.userApiKey"); when(secretProvider.resolve(ref)).thenReturn("user-secret"); - String result = resolver.resolveValue("${eddivault:69c687.userApiKey}"); + String result = resolver.resolveValue("${vault:69c687.userApiKey}"); assertEquals("user-secret", result); } diff --git a/src/test/java/ai/labs/eddi/secrets/impl/SecretVaultIntegrationTest.java b/src/test/java/ai/labs/eddi/secrets/impl/SecretVaultIntegrationTest.java index ea22fdac0c..72abe8ba22 100644 --- a/src/test/java/ai/labs/eddi/secrets/impl/SecretVaultIntegrationTest.java +++ b/src/test/java/ai/labs/eddi/secrets/impl/SecretVaultIntegrationTest.java @@ -145,7 +145,7 @@ void storeAndResolve() throws Exception { var ref = new SecretReference(TENANT, KEY_NAME); provider.store(ref, SECRET_VALUE, "Test API key", List.of("*")); - String resolved = resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + String resolved = resolver.resolveValue("${vault:" + KEY_NAME + "}"); assertEquals(SECRET_VALUE, resolved); } @@ -158,7 +158,7 @@ void resolveFullForm() throws Exception { var ref = new SecretReference("production", KEY_NAME); provider.store(ref, SECRET_VALUE, "Prod key", null); - String resolved = resolver.resolveValue("${eddivault:production/" + KEY_NAME + "}"); + String resolved = resolver.resolveValue("${vault:production/" + KEY_NAME + "}"); assertEquals(SECRET_VALUE, resolved); } @@ -171,7 +171,7 @@ void resolveMultipleRefs() throws Exception { provider.store(new SecretReference(TENANT, "apiKey"), "key-123", null, null); provider.store(new SecretReference(TENANT, "apiSecret"), "secret-456", null, null); - String input = "key=${eddivault:apiKey}&secret=${eddivault:apiSecret}"; + String input = "key=${vault:apiKey}&secret=${vault:apiSecret}"; String resolved = resolver.resolveValue(input); assertEquals("key=key-123&secret=secret-456", resolved); } @@ -190,9 +190,9 @@ void failedResolutionNotCached() throws Exception { setupSecretMocking(); // First attempt — secret doesn't exist yet - String result1 = resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + String result1 = resolver.resolveValue("${vault:" + KEY_NAME + "}"); // Should pass through unchanged (not found) - assertEquals("${eddivault:" + KEY_NAME + "}", result1); + assertEquals("${vault:" + KEY_NAME + "}", result1); // Now store the secret provider.store(new SecretReference(TENANT, KEY_NAME), SECRET_VALUE, null, null); @@ -200,7 +200,7 @@ void failedResolutionNotCached() throws Exception { // Second attempt — should now resolve successfully // The POINT of this test: we DON'T call invalidateAll() // because failed resolutions should NEVER be cached. - String result2 = resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + String result2 = resolver.resolveValue("${vault:" + KEY_NAME + "}"); assertEquals(SECRET_VALUE, result2); } @@ -213,8 +213,8 @@ void successfulResolutionIsCached() throws Exception { provider.store(new SecretReference(TENANT, KEY_NAME), SECRET_VALUE, null, null); // Resolve twice - resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); - resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + resolver.resolveValue("${vault:" + KEY_NAME + "}"); + resolver.resolveValue("${vault:" + KEY_NAME + "}"); // Second resolve should use cache — verify cache hit counter assertEquals(1.0, meterRegistry.counter("eddi.vault.cache.hits").count()); @@ -237,8 +237,8 @@ void rotateDekAndResolve() throws Exception { provider.store(new SecretReference(TENANT, "key2"), "value2", null, null); // Verify pre-rotation - assertEquals("value1", resolver.resolveValue("${eddivault:key1}")); - assertEquals("value2", resolver.resolveValue("${eddivault:key2}")); + assertEquals("value1", resolver.resolveValue("${vault:key1}")); + assertEquals("value2", resolver.resolveValue("${vault:key2}")); // Clear cache and rotate DEK resolver.invalidateAll(); @@ -249,8 +249,8 @@ void rotateDekAndResolve() throws Exception { resolver.invalidateAll(); // Verify post-rotation — secrets should still resolve to same values - assertEquals("value1", resolver.resolveValue("${eddivault:key1}")); - assertEquals("value2", resolver.resolveValue("${eddivault:key2}")); + assertEquals("value1", resolver.resolveValue("${vault:key1}")); + assertEquals("value2", resolver.resolveValue("${vault:key2}")); } @Test @@ -315,7 +315,7 @@ void rotateKekAndResolve() throws Exception { resolver.invalidateAll(); // The in-memory provider now uses the new KEK — secrets should still resolve - assertEquals(SECRET_VALUE, resolver.resolveValue("${eddivault:" + KEY_NAME + "}")); + assertEquals(SECRET_VALUE, resolver.resolveValue("${vault:" + KEY_NAME + "}")); } @Test @@ -380,11 +380,11 @@ void cacheMetrics() throws Exception { provider.store(new SecretReference(TENANT, KEY_NAME), SECRET_VALUE, null, null); // First resolve — cache miss - resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + resolver.resolveValue("${vault:" + KEY_NAME + "}"); assertEquals(1.0, meterRegistry.counter("eddi.vault.cache.misses").count()); // Second resolve — cache hit - resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + resolver.resolveValue("${vault:" + KEY_NAME + "}"); assertEquals(1.0, meterRegistry.counter("eddi.vault.cache.hits").count()); } @@ -452,13 +452,13 @@ void cacheInvalidatedOnUpdate() throws Exception { provider.store(new SecretReference(TENANT, KEY_NAME), "old-value", null, null); - String v1 = resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + String v1 = resolver.resolveValue("${vault:" + KEY_NAME + "}"); assertEquals("old-value", v1); provider.store(new SecretReference(TENANT, KEY_NAME), "new-value", null, null); resolver.invalidateCache(new SecretReference(TENANT, KEY_NAME)); - String v2 = resolver.resolveValue("${eddivault:" + KEY_NAME + "}"); + String v2 = resolver.resolveValue("${vault:" + KEY_NAME + "}"); assertEquals("new-value", v2); } @@ -471,15 +471,15 @@ void invalidateAllClearsCache() throws Exception { provider.store(new SecretReference(TENANT, "k1"), "v1", null, null); provider.store(new SecretReference(TENANT, "k2"), "v2", null, null); - resolver.resolveValue("${eddivault:k1}"); - resolver.resolveValue("${eddivault:k2}"); + resolver.resolveValue("${vault:k1}"); + resolver.resolveValue("${vault:k2}"); resolver.invalidateAll(); provider.store(new SecretReference(TENANT, "k1"), "v1-updated", null, null); provider.store(new SecretReference(TENANT, "k2"), "v2-updated", null, null); - assertEquals("v1-updated", resolver.resolveValue("${eddivault:k1}")); - assertEquals("v2-updated", resolver.resolveValue("${eddivault:k2}")); + assertEquals("v1-updated", resolver.resolveValue("${vault:k1}")); + assertEquals("v2-updated", resolver.resolveValue("${vault:k2}")); } } } diff --git a/src/test/java/ai/labs/eddi/secrets/model/SecretReferenceTest.java b/src/test/java/ai/labs/eddi/secrets/model/SecretReferenceTest.java index ab729b8dd1..acbf059364 100644 --- a/src/test/java/ai/labs/eddi/secrets/model/SecretReferenceTest.java +++ b/src/test/java/ai/labs/eddi/secrets/model/SecretReferenceTest.java @@ -14,7 +14,7 @@ class SecretReferenceTest { @Test void parse_shortForm_defaultTenant() { - var ref = SecretReference.parse("${eddivault:openaiKey}"); + var ref = SecretReference.parse("${vault:openaiKey}"); assertEquals("default", ref.tenantId()); assertEquals("openaiKey", ref.keyName()); @@ -22,7 +22,7 @@ void parse_shortForm_defaultTenant() { @Test void parse_fullForm_explicitTenant() { - var ref = SecretReference.parse("${eddivault:myTenant/openaiKey}"); + var ref = SecretReference.parse("${vault:myTenant/openaiKey}"); assertEquals("myTenant", ref.tenantId()); assertEquals("openaiKey", ref.keyName()); @@ -31,20 +31,20 @@ void parse_fullForm_explicitTenant() { @Test void toReferenceString_defaultTenant_shortForm() { var ref = new SecretReference("default", "apiKey"); - assertEquals("${eddivault:apiKey}", ref.toReferenceString()); + assertEquals("${vault:apiKey}", ref.toReferenceString()); } @Test void toReferenceString_customTenant_fullForm() { var ref = new SecretReference("acmeCorp", "apiKey"); - assertEquals("${eddivault:acmeCorp/apiKey}", ref.toReferenceString()); + assertEquals("${vault:acmeCorp/apiKey}", ref.toReferenceString()); } @Test void roundtrip_shortForm() { var ref = new SecretReference("default", "myKey"); String refStr = ref.toReferenceString(); - assertEquals("${eddivault:myKey}", refStr); + assertEquals("${vault:myKey}", refStr); var parsed = SecretReference.parse(refStr); assertEquals(ref, parsed); @@ -54,7 +54,7 @@ void roundtrip_shortForm() { void roundtrip_fullForm() { var ref = new SecretReference("tenant1", "apiKey"); String refStr = ref.toReferenceString(); - assertEquals("${eddivault:tenant1/apiKey}", refStr); + assertEquals("${vault:tenant1/apiKey}", refStr); var parsed = SecretReference.parse(refStr); assertEquals(ref, parsed); @@ -63,23 +63,23 @@ void roundtrip_fullForm() { @Test void parse_autoVaultedKey_withAgentPrefix() { // Auto-vaulted keys have agentId.keyName format - var ref = SecretReference.parse("${eddivault:69c687.userApiKey}"); + var ref = SecretReference.parse("${vault:69c687.userApiKey}"); assertEquals("default", ref.tenantId()); assertEquals("69c687.userApiKey", ref.keyName()); } @ParameterizedTest - @ValueSource(strings = {"not-a-vault-ref", "${vault:foo/bar}", "${eddivault:}"}) + @ValueSource(strings = {"not-a-vault-ref", "${vault:}"}) void parse_invalidReference_throws(String input) { assertThrows(IllegalArgumentException.class, () -> SecretReference.parse(input)); } @Test void isVaultReference_positive() { - assertTrue(SecretReference.isVaultReference("${eddivault:key}")); - assertTrue(SecretReference.isVaultReference("${eddivault:t/k}")); - assertTrue(SecretReference.isVaultReference("Bearer ${eddivault:openaiKey} extra")); + assertTrue(SecretReference.isVaultReference("${vault:key}")); + assertTrue(SecretReference.isVaultReference("${vault:t/k}")); + assertTrue(SecretReference.isVaultReference("Bearer ${vault:openaiKey} extra")); } @Test @@ -87,6 +87,34 @@ void isVaultReference_negative() { assertFalse(SecretReference.isVaultReference("plain text")); assertFalse(SecretReference.isVaultReference("")); assertFalse(SecretReference.isVaultReference(null)); - assertFalse(SecretReference.isVaultReference("${vault:different}")); + } + + // ==================== Backward Compatibility ==================== + + @Test + void parse_legacyPrefix_shortForm() { + var ref = SecretReference.parse("${eddivault:openaiKey}"); + assertEquals("default", ref.tenantId()); + assertEquals("openaiKey", ref.keyName()); + } + + @Test + void parse_legacyPrefix_fullForm() { + var ref = SecretReference.parse("${eddivault:myTenant/openaiKey}"); + assertEquals("myTenant", ref.tenantId()); + assertEquals("openaiKey", ref.keyName()); + } + + @Test + void isVaultReference_legacyPrefix_positive() { + assertTrue(SecretReference.isVaultReference("${eddivault:key}")); + assertTrue(SecretReference.isVaultReference("${eddivault:t/k}")); + } + + @Test + void toReferenceString_usesNewPrefix() { + // Even when parsed from legacy prefix, output uses the new canonical form + var ref = SecretReference.parse("${eddivault:openaiKey}"); + assertEquals("${vault:openaiKey}", ref.toReferenceString()); } } diff --git a/src/test/java/ai/labs/eddi/secrets/rest/RestSecretStoreTest.java b/src/test/java/ai/labs/eddi/secrets/rest/RestSecretStoreTest.java index f46a27ad9f..a46c2a8773 100644 --- a/src/test/java/ai/labs/eddi/secrets/rest/RestSecretStoreTest.java +++ b/src/test/java/ai/labs/eddi/secrets/rest/RestSecretStoreTest.java @@ -246,7 +246,7 @@ void storeSecret_returnsShortFormRefForDefaultTenant() throws Exception { assertEquals(201, resp.getStatus()); Map body = (Map) resp.getEntity(); - assertEquals("${eddivault:openaiKey}", body.get("reference")); + assertEquals("${vault:openaiKey}", body.get("reference")); } @Test @@ -258,6 +258,6 @@ void storeSecret_returnsFullFormRefForCustomTenant() throws Exception { assertEquals(201, resp.getStatus()); Map body = (Map) resp.getEntity(); - assertEquals("${eddivault:acme-corp/dbPassword}", body.get("reference")); + assertEquals("${vault:acme-corp/dbPassword}", body.get("reference")); } } diff --git a/src/test/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilterTest.java b/src/test/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilterTest.java index 267174e2ff..eb1404e570 100644 --- a/src/test/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilterTest.java +++ b/src/test/java/ai/labs/eddi/secrets/sanitize/SecretRedactionFilterTest.java @@ -39,10 +39,10 @@ void redact_bearerToken() { @Test void redact_vaultReference() { - String input = "Resolved secret: ${eddivault:default/agent1/apiKey}"; + String input = "Resolved secret: ${vault:default/agent1/apiKey}"; String result = SecretRedactionFilter.redact(input); - assertTrue(result.contains("${eddivault:}")); + assertTrue(result.contains("${vault:}")); assertFalse(result.contains("default/agent1/apiKey")); } diff --git a/src/test/java/ai/labs/eddi/secrets/sanitize/SecretScrubberTest.java b/src/test/java/ai/labs/eddi/secrets/sanitize/SecretScrubberTest.java index 584170e757..0a838d8328 100644 --- a/src/test/java/ai/labs/eddi/secrets/sanitize/SecretScrubberTest.java +++ b/src/test/java/ai/labs/eddi/secrets/sanitize/SecretScrubberTest.java @@ -40,7 +40,7 @@ void scrubJson_knownSecretFieldNames() throws Exception { void scrubJson_vaultReferences_passthrough() throws Exception { String json = """ { - "apiKey": "${eddivault:default/agent1/openaiKey}", + "apiKey": "${vault:default/agent1/openaiKey}", "name": "My Config" } """; @@ -48,7 +48,7 @@ void scrubJson_vaultReferences_passthrough() throws Exception { String scrubbed = scrubber.scrubJson(json); // Vault references should be preserved (they're already safe) - assertTrue(scrubbed.contains("${eddivault:default/agent1/openaiKey}")); + assertTrue(scrubbed.contains("${vault:default/agent1/openaiKey}")); assertTrue(scrubbed.contains("My Config")); }