Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: operator only contain env variables in dot env (#1753)

ming1b1a5d42c810
diff --git a/kubernetes/operator/internal/controller/env.go b/kubernetes/operator/internal/controller/env.go
index df9af75c4..fc91d3abd 100644
--- a/kubernetes/operator/internal/controller/env.go
+++ b/kubernetes/operator/internal/controller/env.go
@@ -1,14 +1,17 @@
package controller
import (
+ "context"
"crypto/rand"
"encoding/base64"
"fmt"
"os"
"sort"
+ "strconv"
"strings"
corev1 "k8s.io/api/core/v1"
+ "sigs.k8s.io/controller-runtime/pkg/client"
)
const (
@@ -153,31 +156,35 @@ func NewEnvVarManager() *EnvVarManager {
// 1. Highest priority: CR spec env vars
// 2. Medium priority: Operator env vars with OPTLF_ prefix
// 3. Lowest priority: Hardcoded defaults
-func (m *EnvVarManager) GetLangflowEnvVars(crEnvVars []corev1.EnvVar) map[string]string {
- return m.mergeEnvVars(m.DefaultLangflowEnvVars, LANGFLOW_ENV_PREFIX, crEnvVars)
+func (m *EnvVarManager) GetLangflowEnvVars(ctx context.Context, c client.Client, namespace string, crEnvVars []corev1.EnvVar) (map[string]string, error) {
+ return m.mergeEnvVars(ctx, c, namespace, m.DefaultLangflowEnvVars, LANGFLOW_ENV_PREFIX, crEnvVars)
}
// GetBackendEnvVars returns merged Backend env vars with three-level priority:
-// 1. Highest priority: CR spec env vars
+// 1. Highest priority: CR spec env vars (including resolved secrets/configmaps)
// 2. Medium priority: Operator env vars with OPTORBE_ prefix
// 3. Lowest priority: Hardcoded defaults
-func (m *EnvVarManager) GetBackendEnvVars(crEnvVars []corev1.EnvVar) map[string]string {
- return m.mergeEnvVars(m.DefaultOpenRagBEEnvVars, OPENRAGBE_ENV_PREFIX, crEnvVars)
+func (m *EnvVarManager) GetBackendEnvVars(ctx context.Context, c client.Client, namespace string, crEnvVars []corev1.EnvVar) (map[string]string, error) {
+ return m.mergeEnvVars(ctx, c, namespace, m.DefaultOpenRagBEEnvVars, OPENRAGBE_ENV_PREFIX, crEnvVars)
}
// GetFrontendEnvVars returns merged Frontend env vars with three-level priority:
-// 1. Highest priority: CR spec env vars
+// 1. Highest priority: CR spec env vars (including resolved secrets/configmaps)
// 2. Medium priority: Operator env vars with OPTORFE_ prefix
// 3. Lowest priority: Hardcoded defaults
-func (m *EnvVarManager) GetFrontendEnvVars(crEnvVars []corev1.EnvVar) map[string]string {
- return m.mergeEnvVars(m.DefaultOpenRagFEEnvVars, OPENRAGFE_ENV_PREFIX, crEnvVars)
+func (m *EnvVarManager) GetFrontendEnvVars(ctx context.Context, c client.Client, namespace string, crEnvVars []corev1.EnvVar) (map[string]string, error) {
+ return m.mergeEnvVars(ctx, c, namespace, m.DefaultOpenRagFEEnvVars, OPENRAGFE_ENV_PREFIX, crEnvVars)
}
// mergeEnvVars implements the three-level override priority:
// Level 1 (Lowest): hardcoded defaults
// Level 2 (Medium): operator environment variables with prefix
-// Level 3 (Highest): CR spec env vars
-func (m *EnvVarManager) mergeEnvVars(defaults map[string]string, prefix string, crEnvVars []corev1.EnvVar) map[string]string {
+// Level 3 (Highest): CR spec env vars (including resolved secret/configmap references)
+//
+// ALL env vars (including those from secrets) are resolved and added to the result map.
+// This ensures they appear ONLY in the .env file, not in the container's Env field,
+// so they don't show up when users run 'env' command in the pod.
+func (m *EnvVarManager) mergeEnvVars(ctx context.Context, c client.Client, namespace string, defaults map[string]string, prefix string, crEnvVars []corev1.EnvVar) (map[string]string, error) {
result := make(map[string]string)
// Level 1: Start with hardcoded defaults (lowest priority)
@@ -203,17 +210,104 @@ func (m *EnvVarManager) mergeEnvVars(defaults map[string]string, prefix string,
}
// Level 3: Override with CR spec env vars (highest priority)
+ // Resolve ALL types of env vars (direct values, secrets, configmaps)
for _, envVar := range crEnvVars {
- // Only process direct value assignments (not valueFrom)
if envVar.Value != "" {
+ // Direct value assignment
result[envVar.Name] = envVar.Value
+ } else if envVar.ValueFrom != nil {
+ // Resolve valueFrom references
+ value, found, err := resolveEnvVarValue(ctx, c, namespace, &envVar)
+ if err != nil {
+ return nil, fmt.Errorf("failed to resolve env var %s: %w", envVar.Name, err)
+ }
+ if !found {
+ // If the reference was optional and not found, skip it without error
+ continue
+ }
+ result[envVar.Name] = value
+ }
+ }
+
+ return result, nil
+}
+
+// resolveEnvVarValue resolves a Kubernetes EnvVarSource to its actual string value.
+// Supports secretKeyRef and configMapKeyRef. fieldRef is not supported as it requires
+// runtime pod information (like pod name, namespace) that isn't available at reconcile time.
+func resolveEnvVarValue(ctx context.Context, c client.Client, namespace string, envVar *corev1.EnvVar) (string, bool, error) {
+ if envVar.ValueFrom == nil {
+ return "", false, nil
+ }
+
+ // Resolve secret reference
+ if envVar.ValueFrom.SecretKeyRef != nil {
+ secret := &corev1.Secret{}
+ secretName := envVar.ValueFrom.SecretKeyRef.Name
+ secretKey := envVar.ValueFrom.SecretKeyRef.Key
+
+ err := c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: secretName}, secret)
+ if err != nil {
+ // If optional is true, don't fail on missing secret
+ if envVar.ValueFrom.SecretKeyRef.Optional != nil && *envVar.ValueFrom.SecretKeyRef.Optional {
+ return "", false, nil
+ }
+ return "", false, fmt.Errorf("failed to get secret %s: %w", secretName, err)
+ }
+
+ value, ok := secret.Data[secretKey]
+ if !ok {
+ if envVar.ValueFrom.SecretKeyRef.Optional != nil && *envVar.ValueFrom.SecretKeyRef.Optional {
+ return "", false, nil
+ }
+ return "", false, fmt.Errorf("key %s not found in secret %s", secretKey, secretName)
}
+
+ return string(value), true, nil
+ }
+
+ // Resolve configmap reference
+ if envVar.ValueFrom.ConfigMapKeyRef != nil {
+ configMap := &corev1.ConfigMap{}
+ configMapName := envVar.ValueFrom.ConfigMapKeyRef.Name
+ configMapKey := envVar.ValueFrom.ConfigMapKeyRef.Key
+
+ err := c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: configMapName}, configMap)
+ if err != nil {
+ if envVar.ValueFrom.ConfigMapKeyRef.Optional != nil && *envVar.ValueFrom.ConfigMapKeyRef.Optional {
+ return "", false, nil
+ }
+ return "", false, fmt.Errorf("failed to get configmap %s: %w", configMapName, err)
+ }
+
+ value, ok := configMap.Data[configMapKey]
+ if !ok {
+ if envVar.ValueFrom.ConfigMapKeyRef.Optional != nil && *envVar.ValueFrom.ConfigMapKeyRef.Optional {
+ return "", false, nil
+ }
+ return "", false, fmt.Errorf("key %s not found in configmap %s", configMapKey, configMapName)
+ }
+
+ return value, true, nil
+ }
+
+ // fieldRef and resourceFieldRef cannot be resolved at reconcile time
+ if envVar.ValueFrom.FieldRef != nil {
+ return "", false, fmt.Errorf("fieldRef is not supported in spec.env (requires runtime pod info). Use direct values or secretKeyRef instead")
+ }
+
+ if envVar.ValueFrom.ResourceFieldRef != nil {
+ return "", false, fmt.Errorf("resourceFieldRef is not supported in spec.env. Use direct values or secretKeyRef instead")
}
- return result
+ // no supported valueFrom type found
+ return "", false, nil
}
-// BuildEnvFileContent converts a map of env vars to .env file format
+// BuildEnvFileContent converts a map of env vars to .env file format.
+// Values are always double-quoted with special characters escaped so that
+// arbitrary secret/configmap content cannot corrupt the file.
+// python-dotenv (>=1.0.0) interprets these escape sequences correctly.
func (m *EnvVarManager) BuildEnvFileContent(envVars map[string]string) string {
// Sort keys to ensure deterministic output
keys := make([]string, 0, len(envVars))
@@ -226,7 +320,7 @@ func (m *EnvVarManager) BuildEnvFileContent(envVars map[string]string) string {
for _, k := range keys {
b.WriteString(k)
b.WriteString("=")
- b.WriteString(envVars[k])
+ b.WriteString(strconv.Quote(envVars[k]))
b.WriteString("\n")
}
return b.String()
diff --git a/kubernetes/operator/internal/controller/env_example_test.go b/kubernetes/operator/internal/controller/env_example_test.go
index 5de093503..043d1abbb 100644
--- a/kubernetes/operator/internal/controller/env_example_test.go
+++ b/kubernetes/operator/internal/controller/env_example_test.go
@@ -1,6 +1,7 @@
package controller
import (
+ "context"
"fmt"
"os"
@@ -27,7 +28,8 @@ func Example_envVarPriority() {
}
// Get merged env vars with all three levels applied
- mergedEnvVars := manager.GetLangflowEnvVars(crEnvVars)
+ // Use nil client since we're only testing direct values (no secrets to resolve)
+ mergedEnvVars, _ := manager.GetLangflowEnvVars(context.Background(), nil, "default", crEnvVars)
// Check the results
fmt.Printf("LANGFLOW_AUTO_LOGIN: %s (from defaults)\n", mergedEnvVars["LANGFLOW_AUTO_LOGIN"])
@@ -71,9 +73,10 @@ func Example_componentSpecificPrefixes() {
}()
// Each component gets its own prefix
- lfVars := manager.GetLangflowEnvVars(nil)
- beVars := manager.GetBackendEnvVars(nil)
- feVars := manager.GetFrontendEnvVars(nil)
+ // Use nil client since we're only testing direct values (no secrets to resolve)
+ lfVars, _ := manager.GetLangflowEnvVars(context.Background(), nil, "default", nil)
+ beVars, _ := manager.GetBackendEnvVars(context.Background(), nil, "default", nil)
+ feVars, _ := manager.GetFrontendEnvVars(context.Background(), nil, "default", nil)
fmt.Printf("Langflow WORKERS: %s\n", lfVars["WORKERS"])
fmt.Printf("Backend WORKERS: %s\n", beVars["WORKERS"])
diff --git a/kubernetes/operator/internal/controller/env_test.go b/kubernetes/operator/internal/controller/env_test.go
index 108b29dce..d8887ebdd 100644
--- a/kubernetes/operator/internal/controller/env_test.go
+++ b/kubernetes/operator/internal/controller/env_test.go
@@ -1,11 +1,16 @@
package controller
import (
+ "context"
"os"
"testing"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/runtime"
+ "sigs.k8s.io/controller-runtime/pkg/client/fake"
)
func TestEnvVarManager_ThreeLevelPriority(t *testing.T) {
@@ -31,7 +36,9 @@ func TestEnvVarManager_ThreeLevelPriority(t *testing.T) {
{Name: "VAR_C", Value: "cr_c"},
}
- result := manager.GetLangflowEnvVars(crEnvVars)
+ // No secrets to resolve, so ctx and client can be nil
+ result, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", crEnvVars)
+ require.NoError(t, err)
// Verify priority:
// VAR_A: only in defaults -> should be "default_a"
@@ -62,17 +69,20 @@ func TestEnvVarManager_OperatorEnvPrefixFiltering(t *testing.T) {
}()
// Test Langflow - should only pick up OPTLF_
- lfResult := manager.GetLangflowEnvVars(nil)
+ lfResult, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", nil)
+ require.NoError(t, err)
assert.Equal(t, "langflow_value", lfResult["TEST_VAR"], "Langflow should use OPTLF_ prefixed var")
// Test Backend - should only pick up OPTORBE_
manager.DefaultOpenRagBEEnvVars = map[string]string{"TEST_VAR": "default"}
- beResult := manager.GetBackendEnvVars(nil)
+ beResult, err := manager.GetBackendEnvVars(context.Background(), nil, "test-ns", nil)
+ require.NoError(t, err)
assert.Equal(t, "backend_value", beResult["TEST_VAR"], "Backend should use OPTORBE_ prefixed var")
// Test Frontend - should only pick up OPTORFE_
manager.DefaultOpenRagFEEnvVars = map[string]string{"TEST_VAR": "default"}
- feResult := manager.GetFrontendEnvVars(nil)
+ feResult, err := manager.GetFrontendEnvVars(context.Background(), nil, "test-ns", nil)
+ require.NoError(t, err)
assert.Equal(t, "frontend_value", feResult["TEST_VAR"], "Frontend should use OPTORFE_ prefixed var")
}
@@ -95,7 +105,8 @@ func TestEnvVarManager_CREnvVarOverride(t *testing.T) {
{Name: "LOG_LEVEL", Value: "DEBUG"},
}
- result := manager.GetLangflowEnvVars(crEnvVars)
+ result, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", crEnvVars)
+ require.NoError(t, err)
assert.Equal(t, "postgresql://cr.db", result["DATABASE_URL"], "CR should override operator env")
assert.Equal(t, "DEBUG", result["LOG_LEVEL"], "CR should override defaults")
@@ -108,21 +119,39 @@ func TestEnvVarManager_EmptyCREnvVars(t *testing.T) {
},
}
- result := manager.GetLangflowEnvVars(nil)
+ result, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", nil)
+ require.NoError(t, err)
assert.Equal(t, "default1", result["VAR1"], "Should use defaults when no CR env vars")
- result = manager.GetLangflowEnvVars([]corev1.EnvVar{})
+ result, err = manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", []corev1.EnvVar{})
+ require.NoError(t, err)
assert.Equal(t, "default1", result["VAR1"], "Should use defaults when empty CR env vars")
}
func TestEnvVarManager_CREnvVarWithValueFrom(t *testing.T) {
+ // Create scheme and fake client with a secret
+ s := runtime.NewScheme()
+ _ = corev1.AddToScheme(s)
+
+ secret := &corev1.Secret{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "my-secret",
+ Namespace: "test-ns",
+ },
+ Data: map[string][]byte{
+ "key": []byte("resolved_secret_value"),
+ },
+ }
+
+ fakeClient := fake.NewClientBuilder().WithScheme(s).WithObjects(secret).Build()
+
manager := &EnvVarManager{
DefaultLangflowEnvVars: map[string]string{
"SECRET_KEY": "default_secret",
},
}
- // CR env var with valueFrom should be ignored (can't be evaluated in this context)
+ // CR env var with valueFrom should be RESOLVED (new behavior)
crEnvVars := []corev1.EnvVar{
{
Name: "SECRET_KEY",
@@ -135,9 +164,10 @@ func TestEnvVarManager_CREnvVarWithValueFrom(t *testing.T) {
},
}
- result := manager.GetLangflowEnvVars(crEnvVars)
- // Should keep default since valueFrom can't be evaluated here
- assert.Equal(t, "default_secret", result["SECRET_KEY"], "Should keep default when CR has valueFrom")
+ result, err := manager.GetLangflowEnvVars(context.Background(), fakeClient, "test-ns", crEnvVars)
+ require.NoError(t, err)
+ // Should resolve secret and use the resolved value (NEW behavior)
+ assert.Equal(t, "resolved_secret_value", result["SECRET_KEY"], "Should resolve secret from valueFrom")
}
func TestEnvVarManager_BuildEnvFileContent(t *testing.T) {
@@ -151,16 +181,16 @@ func TestEnvVarManager_BuildEnvFileContent(t *testing.T) {
content := manager.BuildEnvFileContent(envVars)
- // Should contain all three vars in key=value format
- assert.Contains(t, content, "VAR1=value1")
- assert.Contains(t, content, "VAR2=value2")
- assert.Contains(t, content, "VAR3=value3")
+ // Should contain all three vars in quoted key=value format
+ assert.Contains(t, content, `VAR1="value1"`)
+ assert.Contains(t, content, `VAR2="value2"`)
+ assert.Contains(t, content, `VAR3="value3"`)
// Should have newlines
assert.Contains(t, content, "\n")
// Should be deterministic (alphabetically sorted)
- expected := "VAR1=value1\nVAR2=value2\nVAR3=value3\n"
+ expected := "VAR1=\"value1\"\nVAR2=\"value2\"\nVAR3=\"value3\"\n"
assert.Equal(t, expected, content, "Output should be deterministic and sorted")
// Verify determinism by calling multiple times
@@ -187,7 +217,8 @@ func TestEnvVarManager_RealWorldScenario(t *testing.T) {
{Name: "LANGFLOW_LOG_LEVEL", Value: "ERROR"},
}
- result := manager.GetLangflowEnvVars(crEnvVars)
+ result, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", crEnvVars)
+ require.NoError(t, err)
// Verify the three-level priority worked correctly
assert.Equal(t, "true", result["LANGFLOW_AUTO_LOGIN"], "Default should be used")
@@ -340,7 +371,8 @@ func TestEnvVarManager_EnsureRequiredEnvVars_Integration(t *testing.T) {
manager := NewEnvVarManager()
// Get the default Langflow env vars
- envVars := manager.GetLangflowEnvVars(nil)
+ envVars, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", nil)
+ require.NoError(t, err)
// Verify LANGFLOW_VARIABLES_TO_GET_FROM_ENVIRONMENT exists
requiredVarsStr, exists := envVars["LANGFLOW_VARIABLES_TO_GET_FROM_ENVIRONMENT"]
@@ -382,7 +414,8 @@ func TestEnvVarManager_EnsureRequiredEnvVars_CustomList(t *testing.T) {
},
}
- envVars := manager.GetLangflowEnvVars(nil)
+ envVars, err := manager.GetLangflowEnvVars(context.Background(), nil, "test-ns", nil)
+ require.NoError(t, err)
manager.EnsureRequiredEnvVars(envVars)
// Verify custom variables are handled
diff --git a/kubernetes/operator/internal/controller/openrag_controller.go b/kubernetes/operator/internal/controller/openrag_controller.go
index 773edf91f..a40be5c47 100644
--- a/kubernetes/operator/internal/controller/openrag_controller.go
+++ b/kubernetes/operator/internal/controller/openrag_controller.go
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
+ "strconv"
"strings"
"time"
@@ -216,7 +217,15 @@ func parseEnvValue(envContent, key string) string {
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, prefix) {
- return strings.TrimPrefix(line, prefix)
+ val := strings.TrimPrefix(line, prefix)
+ // Unquote values written by BuildEnvFileContent (KEY="value" format).
+ // strconv.Unquote handles escape sequences in a single pass, avoiding
+ // ordering bugs (e.g. \\n must become \n, not a newline).
+ // Falls through for legacy unquoted values for backward compatibility.
+ if unquoted, err := strconv.Unquote(val); err == nil {
+ return unquoted
+ }
+ return val
}
}
return ""
@@ -283,7 +292,11 @@ func (r *OpenRAGReconciler) reconcileEnvSecrets(ctx context.Context, o *openragv
func (r *OpenRAGReconciler) buildBackendEnv(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string) (string, error) {
// Start with defaults, operator env, and CR env (three-level priority)
- envVars := r.EnvVarManager.GetBackendEnvVars(o.Spec.Backend.Env)
+ // This now resolves ALL env vars (including secrets/configmaps) for inclusion in .env file
+ envVars, err := r.EnvVarManager.GetBackendEnvVars(ctx, r.Client, targetNS, o.Spec.Backend.Env)
+ if err != nil {
+ return "", fmt.Errorf("failed to merge backend env vars: %w", err)
+ }
// Get or generate encryption key (AES-256)
// Priority: 1) User-provided secret in CR, 2) Existing value in .env, 3) Generate new
@@ -469,7 +482,11 @@ func (r *OpenRAGReconciler) buildBackendEnv(ctx context.Context, o *openragv1alp
func (r *OpenRAGReconciler) buildLangflowEnv(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string) (string, error) {
// Start with defaults, operator env, and CR env (three-level priority)
- envVars := r.EnvVarManager.GetLangflowEnvVars(o.Spec.Langflow.Env)
+ // This now resolves ALL env vars (including secrets/configmaps) for inclusion in .env file
+ envVars, err := r.EnvVarManager.GetLangflowEnvVars(ctx, r.Client, targetNS, o.Spec.Langflow.Env)
+ if err != nil {
+ return "", fmt.Errorf("failed to merge langflow env vars: %w", err)
+ }
// Get or generate Langflow secret key (Fernet key - base64, shared with backend)
langflowSecretKey, err := r.getOrGenerateSecret(ctx, o, targetNS, o.Spec.Langflow.SecretKeySecret, "LANGFLOW_SECRET_KEY", resourceName("lf-env"), generateBase64SecretKey)
@@ -775,9 +792,10 @@ func (r *OpenRAGReconciler) backendDeployment(o *openragv1alpha1.OpenRAG, target
mounts = append(mounts, corev1.VolumeMount{Name: "backend-data", MountPath: "/app/backend-data"})
}
- // All sensitive values are now consolidated in the .env file
- // Only use additional env vars from the CR spec
- envVars := spec.Env
+ // ALL env vars (including spec.Env) are now in the .env file
+ // Container Env should be empty to prevent values from showing in 'env' command
+ // The .env file is mounted and sourced by the application
+ var envVars []corev1.EnvVar // Empty - all vars are in .env file
baseLabels := componentLabels(o.Name, "be")
deploymentLabels := mergeDeploymentLabels(baseLabels, spec.Labels)
@@ -897,9 +915,10 @@ func (r *OpenRAGReconciler) langflowDeployment(o *openragv1alpha1.OpenRAG, targe
initContainers = nil
}
- // All sensitive values are now consolidated in the .env file
- // Only use additional env vars from the CR spec
- envVars := spec.Env
+ // ALL env vars (including spec.Env) are now in the .env file
+ // Container Env should be empty to prevent values from showing in 'env' command
+ // The .env file is mounted and sourced by the application
+ var envVars []corev1.EnvVar // Empty - all vars are in .env file
baseLabels := componentLabels(o.Name, "lf")
deploymentLabels := mergeDeploymentLabels(baseLabels, spec.Labels)
diff --git a/kubernetes/operator/internal/controller/openrag_controller_env_behavior_test.go b/kubernetes/operator/internal/controller/openrag_controller_env_behavior_test.go
new file mode 100644
index 000000000..e2b5c6dd1
--- /dev/null
+++ b/kubernetes/operator/internal/controller/openrag_controller_env_behavior_test.go
@@ -0,0 +1,294 @@
+package controller
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ corev1 "k8s.io/api/core/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+// TestComponentSpec_Env_DirectValues_GoToEnvFileOnly verifies that
+// env vars with direct values (e.g., {Name: "FOO", Value: "bar"}) are included in
+// the .env file ONLY, and NOT in the container's environment variables.
+func TestComponentSpec_Env_DirectValues_GoToEnvFileOnly(t *testing.T) {
+ s := newScheme(t)
+ cr := minimalCR("test-openrag", "test-ns")
+ r, _ := reconciler(s, cr)
+ cr.Spec.Backend.Env = []corev1.EnvVar{
+ {Name: "CUSTOM_VAR", Value: "custom_value"},
+ {Name: "ANOTHER_VAR", Value: "another_value"},
+ }
+
+ // Check .env file content contains direct values
+ backendEnvContent, err := r.buildBackendEnv(context.Background(), cr, "test-ns")
+ require.NoError(t, err)
+ assert.Contains(t, backendEnvContent, `CUSTOM_VAR="custom_value"`,
+ "Direct value should be in .env file")
+ assert.Contains(t, backendEnvContent, `ANOTHER_VAR="another_value"`,
+ "Direct value should be in .env file")
+
+ // Check container env is EMPTY (no spec.Env)
+ deploy := r.backendDeployment(cr, "test-ns", "hash123")
+ containerEnv := deploy.Spec.Template.Spec.Containers[0].Env
+
+ // Container Env should be empty or only contain operator-managed vars
+ // It should NOT contain CUSTOM_VAR or ANOTHER_VAR
+ for _, env := range containerEnv {
+ assert.NotEqual(t, "CUSTOM_VAR", env.Name, "CUSTOM_VAR should NOT be in container env")
+ assert.NotEqual(t, "ANOTHER_VAR", env.Name, "ANOTHER_VAR should NOT be in container env")
+ }
+}
+
+// TestComponentSpec_Env_SecretRefs_ResolvedToEnvFile verifies that
+// env vars with secret references (e.g., {Name: "FOO", ValueFrom: {SecretKeyRef: ...}})
+// are RESOLVED at reconcile time and the actual value is embedded in the .env file.
+// They do NOT appear in the container's environment variables.
+func TestComponentSpec_Env_SecretRefs_ResolvedToEnvFile(t *testing.T) {
+ s := newScheme(t)
+
+ // Create a secret with password
+ secret := &corev1.Secret{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "db-secret",
+ Namespace: "test-ns",
+ },
+ Data: map[string][]byte{
+ "password": []byte("super-secret-password"),
+ },
+ }
+
+ cr := minimalCR("test-openrag", "test-ns")
+ r, _ := reconciler(s, cr, secret)
+
+ cr.Spec.Backend.Env = []corev1.EnvVar{
+ {
+ Name: "DATABASE_PASSWORD",
+ ValueFrom: &corev1.EnvVarSource{
+ SecretKeyRef: &corev1.SecretKeySelector{
+ LocalObjectReference: corev1.LocalObjectReference{Name: "db-secret"},
+ Key: "password",
+ },
+ },
+ },
+ {Name: "REGULAR_VAR", Value: "regular_value"},
+ }
+
+ // Check .env file content - should contain RESOLVED secret value
+ backendEnvContent, err := r.buildBackendEnv(context.Background(), cr, "test-ns")
+ require.NoError(t, err)
+ assert.Contains(t, backendEnvContent, `DATABASE_PASSWORD="super-secret-password"`,
+ ".env file should contain RESOLVED secret value")
+ assert.Contains(t, backendEnvContent, `REGULAR_VAR="regular_value"`,
+ ".env file should contain direct values")
+
+ // Check container env - should be EMPTY (no spec.Env)
+ deploy := r.backendDeployment(cr, "test-ns", "hash123")
+ containerEnv := deploy.Spec.Template.Spec.Containers[0].Env
+
+ // Container Env should NOT contain DATABASE_PASSWORD or REGULAR_VAR
+ for _, env := range containerEnv {
+ assert.NotEqual(t, "DATABASE_PASSWORD", env.Name, "DATABASE_PASSWORD should NOT be in container env")
+ assert.NotEqual(t, "REGULAR_VAR", env.Name, "REGULAR_VAR should NOT be in container env")
+ }
+}
+
+// TestComponentSpec_Env_ConfigMapRefs_ResolvedToEnvFile verifies that
+// configmap references are resolved and embedded in .env file.
+func TestComponentSpec_Env_ConfigMapRefs_ResolvedToEnvFile(t *testing.T) {
+ s := newScheme(t)
+
+ // Create a configmap
+ configMap := &corev1.ConfigMap{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "api-config",
+ Namespace: "test-ns",
+ },
+ Data: map[string]string{
+ "endpoint": "https://api.example.com",
+ },
+ }
+
+ cr := minimalCR("test-openrag", "test-ns")
+ r, _ := reconciler(s, cr, configMap)
+
+ cr.Spec.Backend.Env = []corev1.EnvVar{
+ {
+ Name: "API_ENDPOINT",
+ ValueFrom: &corev1.EnvVarSource{
+ ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
+ LocalObjectReference: corev1.LocalObjectReference{Name: "api-config"},
+ Key: "endpoint",
+ },
+ },
+ },
+ }
+
+ // Check .env file - should contain resolved value
+ backendEnvContent, err := r.buildBackendEnv(context.Background(), cr, "test-ns")
+ require.NoError(t, err)
+ assert.Contains(t, backendEnvContent, `API_ENDPOINT="https://api.example.com"`,
+ ".env file should contain resolved configmap value")
+
+ // Check container env - should be empty
+ deploy := r.backendDeployment(cr, "test-ns", "hash123")
+ containerEnv := deploy.Spec.Template.Spec.Containers[0].Env
+
+ for _, env := range containerEnv {
+ assert.NotEqual(t, "API_ENDPOINT", env.Name, "API_ENDPOINT should NOT be in container env")
+ }
+}
+
+// TestComponentSpec_Env_Langflow_SameBehavior verifies that Langflow component
+// has the same behavior: all env vars resolved and in .env file only.
+func TestComponentSpec_Env_Langflow_SameBehavior(t *testing.T) {
+ s := newScheme(t)
+
+ secret := &corev1.Secret{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "lf-secret",
+ Namespace: "test-ns",
+ },
+ Data: map[string][]byte{
+ "key": []byte("secret-value"),
+ },
+ }
+
+ cr := minimalCR("test-openrag", "test-ns")
+ r, _ := reconciler(s, cr, secret)
+
+ cr.Spec.Langflow.Env = []corev1.EnvVar{
+ {Name: "DIRECT_VAR", Value: "direct_value"},
+ {
+ Name: "SECRET_VAR",
+ ValueFrom: &corev1.EnvVarSource{
+ SecretKeyRef: &corev1.SecretKeySelector{
+ LocalObjectReference: corev1.LocalObjectReference{Name: "lf-secret"},
+ Key: "key",
+ },
+ },
+ },
+ }
+
+ // Check .env file
+ langflowEnvContent, err := r.buildLangflowEnv(context.Background(), cr, "test-ns")
+ require.NoError(t, err)
+ assert.Contains(t, langflowEnvContent, `DIRECT_VAR="direct_value"`,
+ "Direct value should be in Langflow .env file")
+ assert.Contains(t, langflowEnvContent, `SECRET_VAR="secret-value"`,
+ "Resolved secret value should be in Langflow .env file")
+
+ // Check container env is empty
+ deploy := r.langflowDeployment(cr, "test-ns", "hash123")
+ containerEnv := deploy.Spec.Template.Spec.Containers[0].Env
+
+ for _, env := range containerEnv {
+ assert.NotEqual(t, "DIRECT_VAR", env.Name, "DIRECT_VAR should NOT be in container env")
+ assert.NotEqual(t, "SECRET_VAR", env.Name, "SECRET_VAR should NOT be in container env")
+ }
+}
+
+// TestComponentSpec_Env_FieldRef_RejectedWithError verifies that field references
+// (like pod name, namespace) are rejected because they cannot be resolved at reconcile time.
+func TestComponentSpec_Env_FieldRef_RejectedWithError(t *testing.T) {
+ s := newScheme(t)
+ cr := minimalCR("test-openrag", "test-ns")
+ r, _ := reconciler(s, cr)
+
+ cr.Spec.Backend.Env = []corev1.EnvVar{
+ {
+ Name: "POD_NAME",
+ ValueFrom: &corev1.EnvVarSource{
+ FieldRef: &corev1.ObjectFieldSelector{
+ FieldPath: "metadata.name",
+ },
+ },
+ },
+ }
+
+ // Should fail with clear error message
+ _, err := r.buildBackendEnv(context.Background(), cr, "test-ns")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "fieldRef is not supported",
+ "Should reject fieldRef with helpful error message")
+}
+
+// TestComponentSpec_Env_MixedTypes_AllResolvedToEnvFile verifies that when a CR has
+// a mix of direct values and references, they are ALL resolved and put in .env file only.
+func TestComponentSpec_Env_MixedTypes_AllResolvedToEnvFile(t *testing.T) {
+ s := newScheme(t)
+
+ secret := &corev1.Secret{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "my-secret",
+ Namespace: "test-ns",
+ },
+ Data: map[string][]byte{
+ "key1": []byte("secret-value-1"),
+ },
+ }
+
+ configMap := &corev1.ConfigMap{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "my-config",
+ Namespace: "test-ns",
+ },
+ Data: map[string]string{
+ "key2": "config-value-2",
+ },
+ }
+
+ cr := minimalCR("test-openrag", "test-ns")
+ r, _ := reconciler(s, cr, secret, configMap)
+
+ cr.Spec.Backend.Env = []corev1.EnvVar{
+ {Name: "LITERAL_1", Value: "value1"},
+ {
+ Name: "SECRET_REF",
+ ValueFrom: &corev1.EnvVarSource{
+ SecretKeyRef: &corev1.SecretKeySelector{
+ LocalObjectReference: corev1.LocalObjectReference{Name: "my-secret"},
+ Key: "key1",
+ },
+ },
+ },
+ {Name: "LITERAL_2", Value: "value2"},
+ {
+ Name: "CONFIGMAP_REF",
+ ValueFrom: &corev1.EnvVarSource{
+ ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
+ LocalObjectReference: corev1.LocalObjectReference{Name: "my-config"},
+ Key: "key2",
+ },
+ },
+ },
+ {Name: "LITERAL_3", Value: "value3"},
+ }
+
+ // Check .env file - should contain ALL 5 resolved values
+ backendEnvContent, err := r.buildBackendEnv(context.Background(), cr, "test-ns")
+ require.NoError(t, err)
+ assert.Contains(t, backendEnvContent, `LITERAL_1="value1"`)
+ assert.Contains(t, backendEnvContent, `SECRET_REF="secret-value-1"`)
+ assert.Contains(t, backendEnvContent, `LITERAL_2="value2"`)
+ assert.Contains(t, backendEnvContent, `CONFIGMAP_REF="config-value-2"`)
+ assert.Contains(t, backendEnvContent, `LITERAL_3="value3"`)
+
+ // Check container env - should be empty (no spec.Env vars)
+ deploy := r.backendDeployment(cr, "test-ns", "hash123")
+ containerEnv := deploy.Spec.Template.Spec.Containers[0].Env
+
+ // Verify none of the 5 env vars are in container env
+ envNames := make(map[string]bool)
+ for _, env := range containerEnv {
+ envNames[env.Name] = true
+ }
+
+ assert.False(t, envNames["LITERAL_1"], "LITERAL_1 should NOT be in container env")
+ assert.False(t, envNames["SECRET_REF"], "SECRET_REF should NOT be in container env")
+ assert.False(t, envNames["LITERAL_2"], "LITERAL_2 should NOT be in container env")
+ assert.False(t, envNames["CONFIGMAP_REF"], "CONFIGMAP_REF should NOT be in container env")
+ assert.False(t, envNames["LITERAL_3"], "LITERAL_3 should NOT be in container env")
+}
diff --git a/kubernetes/operator/internal/controller/openrag_controller_test.go b/kubernetes/operator/internal/controller/openrag_controller_test.go
index 986c3e874..846101a7d 100644
--- a/kubernetes/operator/internal/controller/openrag_controller_test.go
+++ b/kubernetes/operator/internal/controller/openrag_controller_test.go
@@ -235,8 +235,8 @@ func TestReconcile_BackendEnvContainsLangflowURL(t *testing.T) {
if envContent == "" && sec.StringData != nil {
envContent = sec.StringData[".env"]
}
- assert.Contains(t, envContent, "LANGFLOW_URL=http://"+resourceName("lf")+":7860")
- assert.Contains(t, envContent, "OPENRAG_BACKEND_INTERNAL_URL=http://"+resourceName("be")+":8000")
+ assert.Contains(t, envContent, `LANGFLOW_URL="http://`+resourceName("lf")+`:7860"`)
+ assert.Contains(t, envContent, `OPENRAG_BACKEND_INTERNAL_URL="http://`+resourceName("be")+`:8000"`)
}
func TestReconcile_LangflowMountsPVC(t *testing.T) {
@@ -1114,9 +1114,9 @@ func TestReconcile_CustomServiceName_OperatorCreates(t *testing.T) {
if envContent == "" && secret.StringData != nil {
envContent = secret.StringData[".env"]
}
- assert.Contains(t, envContent, "LANGFLOW_URL=http://"+resourceName("lf")+":7860",
+ assert.Contains(t, envContent, `LANGFLOW_URL="http://`+resourceName("lf")+`:7860"`,
"Backend env should reference default langflow service")
- assert.Contains(t, envContent, "OPENRAG_BACKEND_INTERNAL_URL=http://my-backend-svc:8000",
+ assert.Contains(t, envContent, `OPENRAG_BACKEND_INTERNAL_URL="http://my-backend-svc:8000"`,
"Backend env should reference custom backend service name")
}
@@ -1222,9 +1222,9 @@ func TestReconcile_CustomServiceName_Langflow_UsedInBackendEnv(t *testing.T) {
if envContent == "" && secret.StringData != nil {
envContent = secret.StringData[".env"]
}
- assert.Contains(t, envContent, "LANGFLOW_URL=http://custom-lf-svc:7860",
+ assert.Contains(t, envContent, `LANGFLOW_URL="http://custom-lf-svc:7860"`,
"Backend env should reference custom langflow service name")
- assert.Contains(t, envContent, "OPENRAG_BACKEND_INTERNAL_URL=http://"+resourceName("be")+":8000",
+ assert.Contains(t, envContent, `OPENRAG_BACKEND_INTERNAL_URL="http://`+resourceName("be")+`:8000"`,
"Backend env should reference default backend service")
}