Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat: inject shared variables into the deploy env (under local precedence)

Juan Denisf015ecb7f858
diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.py
index 39ac981d..21f87081 100644
--- a/backend/app/services/deployment_service.py
+++ b/backend/app/services/deployment_service.py
@@ -260,13 +260,11 @@ class DeploymentService:
if app.port:
ports.append(f"{app.port}:{app.port}")
- env = {}
- # Get env vars from app config if available
+ # Resolved deploy env: shared variable groups (workspace < project <
+ # environment < direct) underneath the app's own local env vars, which
+ # take precedence. get_effective_env returns a decrypted {key: value}.
from app.services.env_service import EnvService
- env_vars = EnvService.get_env_vars(app.id)
- if env_vars.get('success'):
- for var in env_vars.get('variables', []):
- env[var['key']] = var['value']
+ env = EnvService.get_effective_env(app.id)
# Run new container
if log_callback:
diff --git a/backend/app/services/env_service.py b/backend/app/services/env_service.py
index 46f9a41a..283f8954 100644
--- a/backend/app/services/env_service.py
+++ b/backend/app/services/env_service.py
@@ -5,10 +5,13 @@ Handles CRUD operations for application environment variables,
including encryption, history tracking, and .env file operations.
"""
+import logging
import re
from app import db
from app.models import Application, EnvironmentVariable, EnvironmentVariableHistory
+logger = logging.getLogger(__name__)
+
class EnvService:
"""Service for managing application environment variables."""
@@ -36,6 +39,57 @@ class EnvService:
return [ev.to_dict(include_value=True, mask_secrets=mask_secrets) for ev in env_vars]
+ @staticmethod
+ def get_effective_env(application_id):
+ """Resolve the environment an app's container should actually receive.
+
+ Merges, lowest → highest precedence:
+
+ shared variable groups (workspace < project < environment < direct)
+ < the app's own local environment variables
+
+ So a key set both in a shared group and locally yields the LOCAL value
+ (matching the "Set locally — local value applies" hint in the UI), and
+ shared groups fill in everything the app doesn't define itself.
+
+ Returns a plain ``{key: value}`` dict with secrets DECRYPTED — this is
+ the value injected into the running container, so callers must treat it
+ as sensitive. Shared resolution is best-effort: if it fails, the app's
+ local env vars are still returned so a deploy is never blocked.
+ """
+ app = Application.query.get(application_id)
+ if not app:
+ return {}
+
+ merged = {}
+
+ # 1) Shared variable groups — the base layer (lowest precedence).
+ try:
+ from app.services.shared_resource_service import SharedResourceService
+ context = {
+ # scope_id is stored as a string when groups are created, so
+ # coerce the app's numeric ids to match on lookup.
+ 'workspace_id': str(app.workspace_id) if app.workspace_id is not None else None,
+ 'project_id': str(app.project_id) if app.project_id is not None else None,
+ 'environment_id': str(app.environment_id) if app.environment_id is not None else None,
+ }
+ resolved = SharedResourceService.resolve_hierarchical(
+ 'application', application_id, context=context,
+ mask_secrets=False, interpolate=True,
+ )
+ for entry in resolved or []:
+ key = entry.get('key')
+ if key:
+ merged[key] = entry.get('value')
+ except Exception as e: # best-effort — never block a deploy on shared vars
+ logger.warning('Shared variable resolution failed for app %s: %s', application_id, e)
+
+ # 2) Local env vars — the override layer (highest precedence wins).
+ for ev in EnvironmentVariable.query.filter_by(application_id=application_id).all():
+ merged[ev.key] = ev.value # decrypted via the model's `value` property
+
+ return merged
+
@staticmethod
def get_env_var(application_id, key):
"""Get a single environment variable by key."""
diff --git a/backend/tests/test_effective_env.py b/backend/tests/test_effective_env.py
new file mode 100644
index 00000000..94198dd2
--- /dev/null
+++ b/backend/tests/test_effective_env.py
@@ -0,0 +1,137 @@
+"""Effective deploy env: shared variable groups merged under local env vars,
+and proof that the docker deploy path injects the merged result."""
+import types
+
+
+def _make_app(workspace_id=None, project_id=None, environment_id=None, port=8080):
+ from app import db
+ from app.models.application import Application
+ a = Application(
+ name='svc', app_type='docker', status='running', user_id=1, port=port,
+ workspace_id=workspace_id, project_id=project_id, environment_id=environment_id,
+ )
+ db.session.add(a)
+ db.session.commit()
+ return a
+
+
+def _set_local(app_id, key, value, is_secret=False):
+ from app import db
+ from app.models import EnvironmentVariable
+ ev = EnvironmentVariable(application_id=app_id, key=key, is_secret=is_secret)
+ ev.value = value # encrypted via the model's value setter
+ db.session.add(ev)
+ db.session.commit()
+ return ev
+
+
+def _make_scoped_group(scope_type, scope_id, key, value):
+ """A group scoped to a workspace/project/environment auto-applies to apps in
+ that scope (no attachment needed)."""
+ from app import db
+ from app.models.shared_resource import SharedVariableGroup, SharedVariable
+ g = SharedVariableGroup(scope_type=scope_type, scope_id=str(scope_id), name=f'{scope_type}-grp')
+ db.session.add(g)
+ db.session.commit()
+ v = SharedVariable(group_id=g.id, key=key, is_secret=False)
+ v.value = value
+ db.session.add(v)
+ db.session.commit()
+ return g
+
+
+def test_local_only_when_no_shared(app):
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_app(workspace_id=1)
+ _set_local(a.id, 'FOO', 'foo')
+ _set_local(a.id, 'BAR', 'bar')
+ env = EnvService.get_effective_env(a.id)
+ assert env == {'FOO': 'foo', 'BAR': 'bar'}
+
+
+def test_shared_fills_in_missing_keys(app):
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_app(workspace_id=7)
+ _make_scoped_group('workspace', 7, 'SHARED_KEY', 'shared_val')
+ _set_local(a.id, 'LOCAL_KEY', 'local_val')
+ env = EnvService.get_effective_env(a.id)
+ assert env['SHARED_KEY'] == 'shared_val' # came from the shared group
+ assert env['LOCAL_KEY'] == 'local_val'
+
+
+def test_local_overrides_shared_same_key(app):
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_app(workspace_id=11)
+ _make_scoped_group('workspace', 11, 'DATABASE_URL', 'shared://db')
+ _set_local(a.id, 'DATABASE_URL', 'local://db')
+ env = EnvService.get_effective_env(a.id)
+ # The app's own value wins — matches the "local value applies" UI hint.
+ assert env['DATABASE_URL'] == 'local://db'
+
+
+def test_shared_hierarchy_under_local(app):
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_app(workspace_id=20, environment_id=30)
+ _make_scoped_group('workspace', 20, 'TIER', 'ws')
+ _make_scoped_group('environment', 30, 'TIER', 'env')
+ # environment scope outranks workspace scope (both below local)
+ env = EnvService.get_effective_env(a.id)
+ assert env['TIER'] == 'env'
+ _set_local(a.id, 'TIER', 'local')
+ assert EnvService.get_effective_env(a.id)['TIER'] == 'local'
+
+
+def test_shared_resolution_failure_is_best_effort(app, monkeypatch):
+ from app.services.env_service import EnvService
+ from app.services.shared_resource_service import SharedResourceService
+ with app.app_context():
+ a = _make_app(workspace_id=1)
+ _set_local(a.id, 'KEEP', 'me')
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError('shared store down')
+ monkeypatch.setattr(SharedResourceService, 'resolve_hierarchical', _boom)
+
+ env = EnvService.get_effective_env(a.id)
+ assert env == {'KEEP': 'me'} # deploy never blocked by shared failure
+
+
+def test_deploy_docker_injects_effective_env(app, monkeypatch):
+ """The docker deploy path must hand run_container the merged env (shared
+ underneath local), not just local env vars."""
+ from app.services import deployment_service as ds_mod
+ from app.services.deployment_service import DeploymentService
+
+ with app.app_context():
+ a = _make_app(workspace_id=42)
+ _make_scoped_group('workspace', 42, 'SHARED_ONLY', 'from_group')
+ _make_scoped_group('workspace', 42, 'OVERRIDE_ME', 'group_value')
+ _set_local(a.id, 'OVERRIDE_ME', 'local_value')
+ _set_local(a.id, 'LOCAL_ONLY', 'local_only')
+
+ captured = {}
+
+ class FakeDocker:
+ @staticmethod
+ def get_container(name):
+ return None
+
+ @staticmethod
+ def run_container(**kwargs):
+ captured.update(kwargs)
+ return {'success': True, 'container_id': 'deadbeef'}
+
+ monkeypatch.setattr(ds_mod, 'DockerService', FakeDocker)
+
+ deployment = types.SimpleNamespace(image_tag='myimg:1.0')
+ result = DeploymentService._deploy_docker(a, deployment)
+ assert result['success'] is True
+
+ env = captured.get('env') or {}
+ assert env['SHARED_ONLY'] == 'from_group' # shared var reached the container
+ assert env['OVERRIDE_ME'] == 'local_value' # local won the collision
+ assert env['LOCAL_ONLY'] == 'local_only'
diff --git a/frontend/src/components/shared/EnvironmentVariablesPanel.jsx b/frontend/src/components/shared/EnvironmentVariablesPanel.jsx
index dc7b00fd..603d1e9b 100644
--- a/frontend/src/components/shared/EnvironmentVariablesPanel.jsx
+++ b/frontend/src/components/shared/EnvironmentVariablesPanel.jsx
@@ -13,8 +13,9 @@ import { useToast } from '../../contexts/ToastContext';
* Provenance: when the hierarchical resolver is available, each variable shows
* which scope it won at (workspace < project < environment < direct attachment).
* For applications we also cross-check the app's LOCAL env vars: shared groups
- * are a facade and are NOT injected into the running container, so when the same
- * key exists locally the local value is what actually applies — we flag that.
+ * ARE injected into the container at deploy, but the app's own local env vars
+ * take precedence, so when the same key exists locally the local value is what
+ * actually applies — we flag that collision.
*
* Props:
* resourceType one of SharedResourceService.RESOURCE_TYPES
@@ -146,9 +147,9 @@ const EnvironmentVariablesPanel = ({ resourceType, resourceId }) => {
{resourceType === 'application' && localKeys && (
<p className="shared-vars-panel__hint shared-vars-panel__hint--note">
- Shared groups are a facade — they are not yet injected into the
- running container. Where a key also exists in this app&apos;s own
- Environment tab, the local value is what the container uses.
+ Shared variables are injected into the container at deploy. The
+ app&apos;s own Environment tab takes precedence, so where a key also
+ exists locally the local value is what the container uses.
</p>
)}