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(connections): authenticate private container registry pulls

Juan Denis298c556ec772
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 712aa9de..050ad6ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,12 @@ awaiting a stable release:
### Added
+- **Private container registries** — store credentials once under Settings →
+ Connections (GHCR, Docker Hub, GitLab, ECR, or any generic registry) and
+ ServerKit runs `docker login` before pulling a private image, then logs out.
+ Secrets are Fernet-encrypted at rest and piped via stdin (never on argv);
+ attach a registry to a service under Container Ops. Anonymous pulls are
+ unchanged. API under `/api/v1/connections/registries`.
- **Container status aggregator** — collapses an app's per-container Docker
states into one deterministic status (`running:healthy` … `degraded` …
`unknown`) at `/api/v1/status/app/<id>` and `/api/v1/status/apps`, with
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 1aa6ad50..ddaf16ce 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -14,6 +14,7 @@ from app.services.git_service import GitService
from app.services.repository_manifest_service import RepositoryManifestService
from app.services.source_connection_service import SourceConnectionService
from app.services.remote_docker_service import RemoteDockerService
+from app.services.container_registry_service import ContainerRegistryService
from app.services.image_update_service import ImageUpdateService
from app.services.container_sleep_service import ContainerSleepService
from app.services.container_scale_service import ContainerScaleService
@@ -905,6 +906,7 @@ def create_app():
port=data.get('port'),
root_path=data.get('root_path'),
docker_image=data.get('docker_image'),
+ registry_id=data.get('registry_id'),
source=data.get('source') or 'github',
compose_file=data.get('compose_file'),
systemd_unit=data.get('systemd_unit'),
@@ -1259,6 +1261,9 @@ def update_app(app_id):
app.root_path = data['root_path']
if 'docker_image' in data:
app.docker_image = data['docker_image']
+ if 'registry_id' in data:
+ # Accept null to unbind; otherwise a valid registry id.
+ app.registry_id = data['registry_id'] or None
if 'source' in data:
app.source = data['source']
if 'compose_file' in data:
@@ -1364,11 +1369,17 @@ def start_app(app_id):
user_id=current_user_id
)
else:
- result = DockerService.compose_up(
- app.root_path,
- detach=True,
- compose_file=_local_compose_file(app)
- )
+ # Authenticate a bound private registry before compose pulls the
+ # image; best-effort, always logs back out. No-op without registry_id.
+ _registry = ContainerRegistryService.login_for_app(app)
+ try:
+ result = DockerService.compose_up(
+ app.root_path,
+ detach=True,
+ compose_file=_local_compose_file(app)
+ )
+ finally:
+ ContainerRegistryService.logout_for_app(_registry)
if not result.get('success') or _agent_result_failed(result):
return jsonify({'error': _agent_result_error(result, 'Failed to start containers')}), 400
@@ -1407,10 +1418,15 @@ def apply_image_update(app_id):
return jsonify({'error': _agent_result_error(pull, 'Failed to pull image')}), 400
up = RemoteDockerService.compose_up(app.server_id, _compose_target(app), detach=True, user_id=current_user_id)
else:
- pull = DockerService.compose_pull(app.root_path, compose_file=_local_compose_file(app))
- if not pull.get('success'):
- return jsonify({'error': pull.get('error', 'Failed to pull image')}), 400
- up = DockerService.compose_up(app.root_path, detach=True, compose_file=_local_compose_file(app))
+ # Authenticate a bound private registry for the pull; always log out after.
+ _registry = ContainerRegistryService.login_for_app(app)
+ try:
+ pull = DockerService.compose_pull(app.root_path, compose_file=_local_compose_file(app))
+ if not pull.get('success'):
+ return jsonify({'error': pull.get('error', 'Failed to pull image')}), 400
+ up = DockerService.compose_up(app.root_path, detach=True, compose_file=_local_compose_file(app))
+ finally:
+ ContainerRegistryService.logout_for_app(_registry)
if not up.get('success') or _agent_result_failed(up):
return jsonify({'error': _agent_result_error(up, 'Failed to recreate containers')}), 400
diff --git a/backend/app/api/connections.py b/backend/app/api/connections.py
index dee0e95e..8e0af616 100644
--- a/backend/app/api/connections.py
+++ b/backend/app/api/connections.py
@@ -1,13 +1,19 @@
"""Unified connection registry — one normalized, read-only list of every
external account ServerKit is connected to (source, DNS, infra, registrar,
-storage). The individual write paths still live in their own blueprints; this
-is the single source of truth for "what's connected".
+storage, container registries). The individual write paths still live in their
+own blueprints; this is the single source of truth for "what's connected".
+
+Container-registry credentials (for private image pulls) are the one write path
+that lives *here*, since a registry is just another external account and has no
+other natural home — see ``container_registry_service``.
"""
-from flask import Blueprint, jsonify
+from flask import Blueprint, jsonify, request
-from app.middleware.rbac import admin_required, get_current_user
+from app.middleware.rbac import admin_required, auth_required, get_current_user
from app.services.connection_registry import ConnectionRegistry
+from app.services.container_registry_service import ContainerRegistryService
+from app.services.workspace_service import WorkspaceService
connections_bp = Blueprint('connections', __name__)
@@ -22,3 +28,81 @@ def list_connections():
user = get_current_user()
return jsonify({'connections': ConnectionRegistry.list_all(
user_id=user.id if user else None)})
+
+
+# ── Container registries ─────────────────────────────────────────────────────
+# CRUD + a login round-trip test. Listing is available to any authenticated user
+# (the app-create flow needs it to offer a registry picker); mutations are
+# admin-only, matching every other credential store.
+
+def _workspace_id():
+ user = get_current_user()
+ return WorkspaceService.resolve_workspace_id(
+ user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
+
+
+@connections_bp.route('/registries', methods=['GET'])
+@auth_required()
+def list_registries():
+ registries = ContainerRegistryService.list_registries(workspace_id=_workspace_id())
+ return jsonify({'registries': [r.to_dict() for r in registries]})
+
+
+@connections_bp.route('/registries', methods=['POST'])
+@admin_required
+def create_registry():
+ data = request.get_json() or {}
+ name = (data.get('name') or '').strip()
+ if not name:
+ return jsonify({'error': 'name is required'}), 400
+ user = get_current_user()
+ registry = ContainerRegistryService.create(
+ name=name,
+ provider=data.get('provider') or 'generic',
+ registry_url=data.get('registry_url'),
+ username=data.get('username'),
+ secret=data.get('secret'),
+ workspace_id=_workspace_id(),
+ created_by=user.id if user else None,
+ )
+ return jsonify({'registry': registry.to_dict()}), 201
+
+
+@connections_bp.route('/registries/<int:registry_id>', methods=['PUT'])
+@admin_required
+def update_registry(registry_id):
+ registry = ContainerRegistryService.get(registry_id)
+ if not registry:
+ return jsonify({'error': 'Registry not found'}), 404
+ data = request.get_json() or {}
+ registry = ContainerRegistryService.update(
+ registry,
+ name=data.get('name'),
+ provider=data.get('provider'),
+ registry_url=data.get('registry_url'),
+ username=data.get('username'),
+ secret=data.get('secret'),
+ )
+ return jsonify({'registry': registry.to_dict()})
+
+
+@connections_bp.route('/registries/<int:registry_id>', methods=['DELETE'])
+@admin_required
+def delete_registry(registry_id):
+ registry = ContainerRegistryService.get(registry_id)
+ if not registry:
+ return jsonify({'error': 'Registry not found'}), 404
+ ContainerRegistryService.delete(registry)
+ return jsonify({'success': True})
+
+
+@connections_bp.route('/registries/<int:registry_id>/test', methods=['POST'])
+@admin_required
+def test_registry(registry_id):
+ registry = ContainerRegistryService.get(registry_id)
+ if not registry:
+ return jsonify({'error': 'Registry not found'}), 404
+ result = ContainerRegistryService.test_connection(registry)
+ if result.get('success'):
+ return jsonify({'success': True, 'message': f'Logged in to {registry.login_host()}'})
+ return jsonify({'success': False, 'error': result.get('error', 'Login failed')}), 400
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 6eb59917..145dcb43 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -29,6 +29,7 @@ from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForward
from app.models.oauth_identity import OAuthIdentity
from app.models.source_connection import SourceConnection
from app.models.registrar_connection import RegistrarConnection
+from app.models.container_registry import ContainerRegistry
from app.models.api_key import ApiKey
from app.models.api_usage import ApiUsageLog, ApiUsageSummary
from app.models.event_subscription import EventSubscription, EventDelivery
@@ -72,7 +73,7 @@ __all__ = [
'WordPressCustomPlugin', 'WordPressSitePlugin',
'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile',
'EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig', 'EmailRelayConfig',
- 'OAuthIdentity', 'SourceConnection', 'RegistrarConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',
+ 'OAuthIdentity', 'SourceConnection', 'RegistrarConnection', 'ContainerRegistry', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',
'EventSubscription', 'EventDelivery', 'Invitation',
'ServerAlertThreshold', 'MetricAlert',
'AgentPlugin', 'AgentPluginInstall',
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index f4250004..19d50df2 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -30,6 +30,10 @@ class Application(db.Model):
# Docker specific
docker_image = db.Column(db.String(200), nullable=True)
container_id = db.Column(db.String(100), nullable=True)
+ # Optional private-registry binding. Set => authenticate (docker login) with
+ # the stored credentials before pulling docker_image. NULL => anonymous pull
+ # (today's behavior). See app/services/container_registry_service.py.
+ registry_id = db.Column(db.Integer, db.ForeignKey('container_registries.id'), nullable=True, index=True)
# Build packs (zero-Dockerfile deploys). When the build method routes through
# the build-pack layer, the detected plan and any user overrides are persisted
@@ -105,6 +109,7 @@ class Application(db.Model):
'root_path': self.root_path,
'docker_image': self.docker_image,
'container_id': self.container_id,
+ 'registry_id': self.registry_id,
'buildpack_type': self.buildpack_type,
'buildpack_plan': json.loads(self.buildpack_plan) if self.buildpack_plan else None,
'buildpack_overrides': json.loads(self.buildpack_overrides) if self.buildpack_overrides else None,
diff --git a/backend/app/models/container_registry.py b/backend/app/models/container_registry.py
new file mode 100644
index 00000000..43ab30fd
--- /dev/null
+++ b/backend/app/models/container_registry.py
@@ -0,0 +1,71 @@
+from datetime import datetime
+
+from app import db
+
+
+class ContainerRegistry(db.Model):
+ """Stored credentials for a private container registry.
+
+ Lets ServerKit run ``docker login`` before pulling a private image — GitHub
+ Container Registry (GHCR), a private Docker Hub repo, GitLab registry, AWS
+ ECR, or any generic registry. The secret (password / PAT / token) is
+ Fernet-encrypted at rest via ``app.utils.crypto``, mirroring
+ ``SourceConnection.access_token_encrypted``; :meth:`to_dict` never returns
+ it (it exposes a ``has_secret`` flag instead).
+
+ ``provider`` is a plain string (no enum), matching ``SourceConnection``:
+ ``ghcr`` | ``dockerhub`` | ``gitlab`` | ``ecr`` | ``generic``.
+ """
+
+ __tablename__ = 'container_registries'
+
+ # Docker Hub's canonical login host, used when registry_url is left blank.
+ DOCKERHUB_HOST = 'index.docker.io'
+
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(180), nullable=False)
+ provider = db.Column(db.String(40), nullable=False, default='generic', index=True)
+ # Host to `docker login` against, e.g. 'ghcr.io', 'registry.gitlab.com',
+ # '123456.dkr.ecr.us-east-1.amazonaws.com'. Empty => Docker Hub.
+ registry_url = db.Column(db.String(255), nullable=True)
+ username = db.Column(db.String(180), nullable=True)
+ secret_encrypted = db.Column(db.Text, nullable=True)
+ # Nullable FK — a registry can be scoped to one workspace, or global (NULL).
+ workspace_id = db.Column(db.Integer, db.ForeignKey('workspaces.id'), nullable=True, index=True)
+ created_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
+ last_used_at = db.Column(db.DateTime, nullable=True)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def login_host(self):
+ """The host to pass to ``docker login`` (blank ``registry_url`` => Docker Hub)."""
+ return (self.registry_url or '').strip() or self.DOCKERHUB_HOST
+
+ def login_username(self):
+ """The username for ``docker login``. ECR uses the fixed ``AWS`` user; any
+ other registry uses the stored username (``None`` if unset)."""
+ if self.username:
+ return self.username
+ if self.provider == 'ecr':
+ return 'AWS'
+ return None
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'provider': self.provider,
+ 'registry_url': self.registry_url,
+ 'login_host': self.login_host(),
+ 'username': self.username,
+ # Never serialize the secret — expose only whether one is stored.
+ 'has_secret': bool(self.secret_encrypted),
+ 'workspace_id': self.workspace_id,
+ 'created_by': self.created_by,
+ 'last_used_at': self.last_used_at.isoformat() if self.last_used_at else None,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
+ }
+
+ def __repr__(self):
+ return f'<ContainerRegistry {self.name} ({self.provider})>'
diff --git a/backend/app/services/connection_registry.py b/backend/app/services/connection_registry.py
index 715d7f8d..461b08e5 100644
--- a/backend/app/services/connection_registry.py
+++ b/backend/app/services/connection_registry.py
@@ -40,7 +40,7 @@ class ConnectionRegistry:
@classmethod
def list_all(cls, user_id=None):
out = []
- for fn in (cls._source, cls._dns, cls._infra, cls._registrar, cls._storage, cls._email):
+ for fn in (cls._source, cls._dns, cls._infra, cls._registrar, cls._storage, cls._email, cls._registries):
try:
out += fn(user_id) if fn is cls._source else fn()
except Exception as e: # one failing store never breaks the whole list
@@ -103,6 +103,15 @@ class ConnectionRegistry:
encrypted=True, created_at=c.created_at))
return out
+ @staticmethod
+ def _registries():
+ from app.models.container_registry import ContainerRegistry
+ return [
+ _entry('registry', c.provider, c.name, id=c.id, scope=c.login_host(),
+ encrypted=bool(c.secret_encrypted), created_at=c.created_at)
+ for c in ContainerRegistry.query.all()
+ ]
+
@staticmethod
def _storage():
from app.services.storage_provider_service import StorageProviderService
diff --git a/backend/app/services/container_registry_service.py b/backend/app/services/container_registry_service.py
new file mode 100644
index 00000000..c016ba91
--- /dev/null
+++ b/backend/app/services/container_registry_service.py
@@ -0,0 +1,209 @@
+"""Container registry credential store + ``docker login`` orchestration.
+
+Stores per-registry credentials (Fernet-encrypted secret) and runs
+``docker login`` before a private image is pulled, then ``docker logout`` to
+avoid leaving a session on disk. The secret is piped via **stdin**
+(``--password-stdin``) — never placed on argv (where it would leak into
+``ps``/process listings) or written to logs.
+
+A single ``docker login`` authenticates both ``docker pull`` and
+``docker compose pull`` for that host, so this service backs the standalone
+single-container path (``DockerService.pull_image``) and the compose path
+(``apps.start_app`` / ``apps.apply_image_update``) alike.
+"""
+import logging
+import os
+import subprocess
+from datetime import datetime
+
+from app import db
+from app.models.container_registry import ContainerRegistry
+from app.utils.crypto import encrypt_secret, decrypt_secret_safe
+
+logger = logging.getLogger(__name__)
+
+
+class ContainerRegistryService:
+ """CRUD + docker-login helpers for private container registries."""
+
+ # ── CRUD ──
+ @staticmethod
+ def list_registries(workspace_id=None):
+ """All registries visible in a workspace: the workspace's own plus every
+ global (``workspace_id IS NULL``) one. No workspace context => all."""
+ q = ContainerRegistry.query
+ if workspace_id is not None:
+ q = q.filter(db.or_(
+ ContainerRegistry.workspace_id == workspace_id,
+ ContainerRegistry.workspace_id.is_(None),
+ ))
+ return q.order_by(ContainerRegistry.created_at.desc()).all()
+
+ @staticmethod
+ def get(registry_id):
+ if not registry_id:
+ return None
+ return ContainerRegistry.query.get(registry_id)
+
+ @staticmethod
+ def create(name, provider='generic', registry_url=None, username=None,
+ secret=None, workspace_id=None, created_by=None):
+ reg = ContainerRegistry(
+ name=(name or '').strip() or 'Registry',
+ provider=(provider or 'generic').strip().lower(),
+ registry_url=(registry_url or '').strip() or None,
+ username=(username or '').strip() or None,
+ workspace_id=workspace_id,
+ created_by=created_by,
+ )
+ if secret:
+ reg.secret_encrypted = encrypt_secret(secret)
+ db.session.add(reg)
+ db.session.commit()
+ return reg
+
+ @staticmethod
+ def update(registry, *, name=None, provider=None, registry_url=None,
+ username=None, secret=None):
+ if name is not None and name.strip():
+ registry.name = name.strip()
+ if provider is not None and provider.strip():
+ registry.provider = provider.strip().lower()
+ if registry_url is not None:
+ registry.registry_url = registry_url.strip() or None
+ if username is not None:
+ registry.username = username.strip() or None
+ # Only replace the secret when a new one is actually supplied, so an edit
+ # of the label/URL never wipes the stored credential.
+ if secret:
+ registry.secret_encrypted = encrypt_secret(secret)
+ db.session.commit()
+ return registry
+
+ @staticmethod
+ def delete(registry):
+ db.session.delete(registry)
+ db.session.commit()
+
+ # ── secret resolution ──
+ @staticmethod
+ def _password(registry):
+ """Plaintext password for ``docker login``. For ECR, exchange the stored
+ AWS keys for a short-lived token lazily; otherwise decrypt the stored
+ secret."""
+ if registry.provider == 'ecr':
+ token = ContainerRegistryService.ecr_password(registry)
+ if token:
+ return token
+ if not registry.secret_encrypted:
+ return None
+ return decrypt_secret_safe(registry.secret_encrypted)
+
+ # ── docker login / logout ──
+ @staticmethod
+ def login(registry):
+ """``docker login`` the registry, piping the secret via stdin. Returns
+ ``{'success': bool, 'error'?: str}``. Never logs the secret."""
+ username = registry.login_username()
+ if not username:
+ return {'success': False, 'error': 'Registry has no username configured'}
+ password = ContainerRegistryService._password(registry)
+ if not password:
+ return {'success': False, 'error': 'No stored secret for this registry'}
+
+ host = registry.login_host()
+ # Secret goes on stdin via --password-stdin, NEVER on argv.
+ cmd = ['docker', 'login', host, '-u', username, '--password-stdin']
+ try:
+ result = subprocess.run(cmd, input=password, capture_output=True, text=True)
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ if result.returncode == 0:
+ try:
+ registry.last_used_at = datetime.utcnow()
+ db.session.commit()
+ except Exception:
+ db.session.rollback()
+ return {'success': True}
+ return {'success': False, 'error': (result.stderr or 'docker login failed').strip()}
+
+ @staticmethod
+ def logout(host):
+ """Best-effort ``docker logout`` of a host — cleanup, never raises."""
+ if not host:
+ return
+ try:
+ subprocess.run(['docker', 'logout', host], capture_output=True, text=True)
+ except Exception:
+ pass
+
+ @staticmethod
+ def test_connection(registry):
+ """``docker login`` then immediately ``docker logout`` — report
+ success/failure without leaving a session behind."""
+ result = ContainerRegistryService.login(registry)
+ ContainerRegistryService.logout(registry.login_host())
+ return result
+
+ @staticmethod
+ def ecr_password(registry):
+ """Best-effort AWS ECR token via ``aws ecr get-login-password``.
+
+ Optional/lazy: needs the AWS CLI on PATH. The stored secret may hold
+ ``ACCESS_KEY_ID:SECRET_ACCESS_KEY``; if so it is passed through the
+ environment for this one call. Returns a password string, or ``None`` if
+ the CLI is missing or the exchange fails (kept defensive so a
+ misconfigured ECR entry never crashes a deploy)."""
+ try:
+ host = registry.login_host()
+ region = None
+ parts = host.split('.')
+ if 'ecr' in parts:
+ idx = parts.index('ecr')
+ if idx + 1 < len(parts):
+ region = parts[idx + 1]
+
+ env = None
+ secret = decrypt_secret_safe(registry.secret_encrypted or '')
+ if secret and ':' in secret:
+ access_key, secret_key = secret.split(':', 1)
+ env = dict(os.environ)
+ env['AWS_ACCESS_KEY_ID'] = access_key.strip()
+ env['AWS_SECRET_ACCESS_KEY'] = secret_key.strip()
+
+ cmd = ['aws', 'ecr', 'get-login-password']
+ if region:
+ cmd += ['--region', region]
+ result = subprocess.run(cmd, capture_output=True, text=True, env=env)
+ if result.returncode == 0:
+ return result.stdout.strip()
+ logger.debug('aws ecr get-login-password failed: %s', (result.stderr or '').strip())
+ except FileNotFoundError:
+ logger.debug('aws CLI not found; cannot exchange ECR token')
+ except Exception as e: # pragma: no cover - defensive
+ logger.debug('ECR password exchange error: %s', e)
+ return None
+
+ # ── app helpers (compose + single-container deploy paths) ──
+ @staticmethod
+ def for_app(app):
+ """The ContainerRegistry bound to an app via ``registry_id``, or None."""
+ return ContainerRegistryService.get(getattr(app, 'registry_id', None))
+
+ @staticmethod
+ def login_for_app(app):
+ """``docker login`` for an app's bound registry, if any. Best-effort:
+ returns the ContainerRegistry that was logged into (so the caller can log
+ out in a ``finally``), or ``None`` when the app has no registry."""
+ registry = ContainerRegistryService.for_app(app)
+ if registry is None:
+ return None
+ ContainerRegistryService.login(registry)
+ return registry
+
+ @staticmethod
+ def logout_for_app(registry):
+ """Counterpart to :meth:`login_for_app`; no-op when ``registry`` is None."""
+ if registry is not None:
+ ContainerRegistryService.logout(registry.login_host())
diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.py
index 21f87081..8034ef9e 100644
--- a/backend/app/services/deployment_service.py
+++ b/backend/app/services/deployment_service.py
@@ -266,6 +266,19 @@ class DeploymentService:
from app.services.env_service import EnvService
env = EnvService.get_effective_env(app.id)
+ # Authenticate + pre-pull from a private registry when this app is bound
+ # to one, so the run below uses the locally-present image. Gated on
+ # registry_id: apps built from source never set it, so their locally-built
+ # image_tag is untouched (an authenticated pull of it would fail).
+ from app.services.container_registry_service import ContainerRegistryService
+ registry = ContainerRegistryService.for_app(app)
+ if registry is not None:
+ if log_callback:
+ log_callback(f"Authenticating with registry {registry.name}...")
+ pull = DockerService.pull_image(image_tag, tag=None, registry=registry)
+ if not pull.get('success'):
+ return {'success': False, 'error': pull.get('error', 'Registry pull failed')}
+
# Run new container
if log_callback:
log_callback(f"Starting container {container_name}...")
diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py
index 421a75e7..443075d5 100644
--- a/backend/app/services/docker_service.py
+++ b/backend/app/services/docker_service.py
@@ -615,10 +615,27 @@ class DockerService:
return []
@staticmethod
- def pull_image(image_name, tag='latest'):
- """Pull an image from registry."""
+ def pull_image(image_name, tag='latest', registry=None):
+ """Pull an image from a registry.
+
+ When ``registry`` (a ``ContainerRegistry``) is provided, ``docker login``
+ runs first and ``docker logout`` after, so private images pull with the
+ stored credentials. Login/pull/logout is wrapped in ``try/finally`` so we
+ always log out — even when the pull fails. The signature stays
+ backward-compatible: ``registry=None`` is an anonymous pull (today's
+ behavior).
+ """
+ full_name = f'{image_name}:{tag}' if tag else image_name
+ logged_in = False
try:
- full_name = f'{image_name}:{tag}' if tag else image_name
+ if registry is not None:
+ from app.services.container_registry_service import ContainerRegistryService
+ login = ContainerRegistryService.login(registry)
+ if not login.get('success'):
+ return {'success': False,
+ 'error': f"Registry login failed: {login.get('error')}"}
+ logged_in = True
+
result = subprocess.run(
['docker', 'pull', full_name],
capture_output=True, text=True
@@ -628,6 +645,10 @@ class DockerService:
return {'success': False, 'error': result.stderr}
except Exception as e:
return {'success': False, 'error': str(e)}
+ finally:
+ if logged_in and registry is not None:
+ from app.services.container_registry_service import ContainerRegistryService
+ ContainerRegistryService.logout(registry.login_host())
@staticmethod
def remove_image(image_id, force=False):
diff --git a/backend/migrations/versions/042_container_registries.py b/backend/migrations/versions/042_container_registries.py
new file mode 100644
index 00000000..18131df9
--- /dev/null
+++ b/backend/migrations/versions/042_container_registries.py
@@ -0,0 +1,72 @@
+"""Container registry authentication.
+
+Adds:
+- container_registries (stored, Fernet-encrypted credentials for private image pulls)
+- applications.registry_id (nullable FK — authenticate before pulling docker_image)
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot
+before Alembic, so guard on the live schema.
+
+Revision ID: 042_container_registries
+Revises: 041_wordpress_plugin_library
+Create Date: 2026-07-01
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '042_container_registries'
+down_revision = '041_wordpress_plugin_library'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ existing = set(inspector.get_table_names())
+
+ if 'container_registries' not in existing:
+ op.create_table(
+ 'container_registries',
+ sa.Column('id', sa.Integer, nullable=False),
+ sa.Column('name', sa.String(180), nullable=False),
+ sa.Column('provider', sa.String(40), nullable=False, server_default='generic'),
+ sa.Column('registry_url', sa.String(255), nullable=True),
+ sa.Column('username', sa.String(180), nullable=True),
+ sa.Column('secret_encrypted', sa.Text, nullable=True),
+ sa.Column('workspace_id', sa.Integer, nullable=True),
+ sa.Column('created_by', sa.Integer, nullable=True),
+ sa.Column('last_used_at', sa.DateTime, nullable=True),
+ sa.Column('created_at', sa.DateTime, nullable=True),
+ sa.Column('updated_at', sa.DateTime, nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']),
+ sa.ForeignKeyConstraint(['created_by'], ['users.id']),
+ )
+ op.create_index('ix_container_registries_provider', 'container_registries', ['provider'])
+ op.create_index('ix_container_registries_workspace_id', 'container_registries', ['workspace_id'])
+ op.create_index('ix_container_registries_created_at', 'container_registries', ['created_at'])
+
+ if 'applications' in existing:
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ if 'registry_id' not in cols:
+ op.add_column('applications', sa.Column('registry_id', sa.Integer, nullable=True))
+ op.create_index('ix_applications_registry_id', 'applications', ['registry_id'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ existing = set(inspector.get_table_names())
+
+ if 'applications' in existing:
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ if 'registry_id' in cols:
+ try:
+ op.drop_index('ix_applications_registry_id', table_name='applications')
+ except Exception:
+ pass
+ op.drop_column('applications', 'registry_id')
+
+ if 'container_registries' in existing:
+ op.drop_table('container_registries')
diff --git a/backend/tests/test_container_registry.py b/backend/tests/test_container_registry.py
new file mode 100644
index 00000000..a0c545ca
--- /dev/null
+++ b/backend/tests/test_container_registry.py
@@ -0,0 +1,290 @@
+"""Container registry authentication — service, API, and deploy-path wiring.
+
+Covers the proving points from docs/plans/CONTAINER_REGISTRY_AUTH.md:
+- encrypt/decrypt round-trip, secret never serialized
+- `login()` pipes the secret via stdin and never places it on argv
+- `pull_image` runs login -> pull -> logout in order, and still logs out on
+ pull failure (the try/finally)
+- the deploy path resolves an app's registry_id and authenticates before pull
+- API CRUD, masking, and admin-gating
+"""
+import subprocess
+
+import pytest
+
+from app import db
+from app.models import Application, ContainerRegistry, User
+from app.services.container_registry_service import ContainerRegistryService
+from app.services.docker_service import DockerService
+
+
+class _FakeProc:
+ def __init__(self, returncode=0, stdout='', stderr=''):
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+
+
+def registry(app):
+ reg = ContainerRegistryService.create(
+ name='GHCR (acme)', provider='ghcr', registry_url='ghcr.io',
+ username='acme-bot', secret='ghp_supersecrettoken',
+ )
+ return reg
+
+
+# ── credential storage ──────────────────────────────────────────────────────
+
+def test_secret_encrypted_at_rest_and_round_trips(app, registry):
+ # Stored ciphertext must not equal the plaintext, but must decrypt back.
+ assert registry.secret_encrypted
+ assert registry.secret_encrypted != 'ghp_supersecrettoken'
+ assert ContainerRegistryService._password(registry) == 'ghp_supersecrettoken'
+
+
+def test_to_dict_never_returns_the_secret(app, registry):
+ data = registry.to_dict()
+ assert 'secret_encrypted' not in data
+ assert 'secret' not in data
+ assert data['has_secret'] is True
+ assert data['login_host'] == 'ghcr.io'
+
+
+def test_blank_url_defaults_to_docker_hub(app):
+ reg = ContainerRegistryService.create(name='Hub', provider='dockerhub',
+ username='me', secret='pw')
+ assert reg.login_host() == ContainerRegistry.DOCKERHUB_HOST
+
+
+# ── docker login ─────────────────────────────────────────────────────────────
+
+def test_login_pipes_secret_via_stdin_never_on_argv(app, registry, monkeypatch):
+ captured = {}
+
+ def fake_run(cmd, *args, **kwargs):
+ captured['cmd'] = cmd
+ captured['input'] = kwargs.get('input')
+ return _FakeProc(returncode=0)
+
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+ result = ContainerRegistryService.login(registry)
+
+ assert result['success'] is True
+ # The secret is on stdin, and NOWHERE on the argv.
+ assert captured['input'] == 'ghp_supersecrettoken'
+ assert '--password-stdin' in captured['cmd']
+ assert 'ghp_supersecrettoken' not in captured['cmd']
+ # Sanity: it targets the right host + user.
+ assert captured['cmd'][:2] == ['docker', 'login']
+ assert 'ghcr.io' in captured['cmd']
+ assert 'acme-bot' in captured['cmd']
+
+
+def test_login_fails_cleanly_without_a_secret(app):
+ reg = ContainerRegistryService.create(name='NoSecret', provider='generic',
+ registry_url='r.example.com', username='u')
+ result = ContainerRegistryService.login(reg)
+ assert result['success'] is False
+
+
+def test_ecr_username_defaults_to_AWS(app):
+ reg = ContainerRegistryService.create(
+ name='ECR', provider='ecr',
+ registry_url='123456.dkr.ecr.us-east-1.amazonaws.com', secret='k:s')
+ assert reg.login_username() == 'AWS'
+
+
+# ── pull_image: login -> pull -> logout ordering + finally ───────────────────
+
+def _sequence_recorder():
+ """Return (calls, fake_run) capturing the docker sub-command order."""
+ calls = []
+
+ def fake_run(cmd, *args, **kwargs):
+ sub = cmd[1] if len(cmd) > 1 else cmd[0]
+ calls.append(sub)
+ # docker pull fails to exercise the finally-logout path when asked
+ if sub == 'pull' and fake_run.fail_pull:
+ return _FakeProc(returncode=1, stderr='denied')
+ return _FakeProc(returncode=0, stdout='ok')
+
+ fake_run.fail_pull = False
+ return calls, fake_run
+
+
+def test_pull_image_logs_in_then_pulls_then_logs_out(app, registry, monkeypatch):
+ calls, fake_run = _sequence_recorder()
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+
+ result = DockerService.pull_image('ghcr.io/acme/app', tag='v1', registry=registry)
+
+ assert result['success'] is True
+ assert calls == ['login', 'pull', 'logout']
+
+
+def test_pull_image_logs_out_even_when_pull_fails(app, registry, monkeypatch):
+ calls, fake_run = _sequence_recorder()
+ fake_run.fail_pull = True
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+
+ result = DockerService.pull_image('ghcr.io/acme/app', tag='v1', registry=registry)
+
+ assert result['success'] is False
+ # logout still ran despite the failed pull (the try/finally).
+ assert calls == ['login', 'pull', 'logout']
+
+
+def test_pull_image_anonymous_when_no_registry(app, monkeypatch):
+ calls, fake_run = _sequence_recorder()
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+
+ DockerService.pull_image('nginx', tag='latest')
+ assert calls == ['pull'] # no login/logout for a public pull
+
+
+def test_test_connection_logs_in_and_out(app, registry, monkeypatch):
+ calls, fake_run = _sequence_recorder()
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+
+ result = ContainerRegistryService.test_connection(registry)
+ assert result['success'] is True
+ assert calls == ['login', 'logout']
+
+
+# ── proving test: deploy path authenticates before pull ──────────────────────
+
+def test_start_app_authenticates_registry_before_compose_up(client, auth_headers, app, registry, monkeypatch):
+ """The primary path for a private-image app is compose. Starting a
+ registry-bound docker app must `docker login` before `compose up`, then log
+ out (the try/finally around the local compose branch)."""
+ owner = User.query.filter_by(username='testadmin').first()
+ application = Application(name='compose-priv', app_type='docker', status='stopped',
+ root_path='/tmp/compose-priv', registry_id=registry.id,
+ user_id=owner.id)
+ db.session.add(application)
+ db.session.commit()
+
+ order = []
+
+ def fake_run(cmd, *args, **kwargs):
+ order.append(cmd[1] if len(cmd) > 1 else cmd[0]) # login / logout
+ return _FakeProc(returncode=0)
+
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+ monkeypatch.setattr(DockerService, 'compose_up',
+ staticmethod(lambda *a, **k: order.append('compose_up') or {'success': True}))
+
+ resp = client.post(f'/api/v1/apps/{application.id}/start', headers=auth_headers)
+ assert resp.status_code == 200, resp.get_json()
+ assert 'login' in order and 'compose_up' in order and 'logout' in order
+ assert order.index('login') < order.index('compose_up') < order.index('logout')
+
+
+def test_deploy_docker_authenticates_before_pull(app, registry, monkeypatch):
+ """A Docker app bound to a registry must `docker login` before the image is
+ pulled, then run the container."""
+ from app.services.deployment_service import DeploymentService
+ from app.services.env_service import EnvService
+ from app.models.deployment import Deployment
+
+ user = User(email='[email protected]', username='owner',
+ password_hash='x', role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(user)
+ db.session.commit()
+
+ application = Application(name='private-app', app_type='docker', status='stopped',
+ docker_image='ghcr.io/acme/app:v1', registry_id=registry.id,
+ user_id=user.id)
+ db.session.add(application)
+ db.session.commit()
+
+ deployment = Deployment(app_id=application.id, version=1, version_tag='v1',
+ status='deploying', image_tag='ghcr.io/acme/app:v1',
+ deployed_by=user.id)
+ db.session.add(deployment)
+ db.session.commit()
+
+ order = []
+
+ def fake_run(cmd, *args, **kwargs):
+ order.append(cmd[1] if len(cmd) > 1 else cmd[0])
+ return _FakeProc(returncode=0, stdout='')
+
+ monkeypatch.setattr(subprocess, 'run', fake_run)
+ monkeypatch.setattr(DockerService, 'get_container', staticmethod(lambda *a, **k: None))
+ monkeypatch.setattr(EnvService, 'get_effective_env', staticmethod(lambda *a, **k: {}))
+ monkeypatch.setattr(DockerService, 'run_container',
+ staticmethod(lambda **k: order.append('run') or {'success': True, 'container_id': 'abc'}))
+
+ result = DeploymentService._deploy_docker(application, deployment)
+
+ assert result['success'] is True
+ assert 'login' in order and 'pull' in order and 'run' in order
+ assert order.index('login') < order.index('pull') < order.index('run')
+
+
+# ── API: CRUD, masking, admin-gating ─────────────────────────────────────────
+
+def test_api_crud_and_masking(client, auth_headers, app):
+ # Create
+ resp = client.post('/api/v1/connections/registries', headers=auth_headers, json={
+ 'name': 'GitLab reg', 'provider': 'gitlab', 'registry_url': 'registry.gitlab.com',
+ 'username': 'deploy', 'secret': 'glpat-abc',
+ })
+ assert resp.status_code == 201, resp.get_json()
+ created = resp.get_json()['registry']
+ assert created['has_secret'] is True
+ assert 'secret' not in created and 'secret_encrypted' not in created
+
+ reg_id = created['id']
+
+ # List (masked)
+ resp = client.get('/api/v1/connections/registries', headers=auth_headers)
+ assert resp.status_code == 200
+ listed = resp.get_json()['registries']
+ assert any(r['id'] == reg_id for r in listed)
+ assert all('secret' not in r and 'secret_encrypted' not in r for r in listed)
+
+ # Update label without touching the secret
+ resp = client.put(f'/api/v1/connections/registries/{reg_id}', headers=auth_headers,
+ json={'name': 'GitLab (renamed)'})
+ assert resp.status_code == 200
+ assert resp.get_json()['registry']['name'] == 'GitLab (renamed)'
+ reg = ContainerRegistryService.get(reg_id)
+ assert ContainerRegistryService._password(reg) == 'glpat-abc' # secret preserved
+
+ # Delete
+ resp = client.delete(f'/api/v1/connections/registries/{reg_id}', headers=auth_headers)
+ assert resp.status_code == 200
+ assert ContainerRegistryService.get(reg_id) is None
+
+
+def test_api_create_requires_admin(client, app):
+ from flask_jwt_extended import create_access_token
+ from werkzeug.security import generate_password_hash
+
+ dev = User(email='[email protected]', username='dev',
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_DEVELOPER, is_active=True)
+ db.session.add(dev)
+ db.session.commit()
+ headers = {'Authorization': f'Bearer {create_access_token(identity=dev.id)}'}
+
+ resp = client.post('/api/v1/connections/registries', headers=headers,
+ json={'name': 'x', 'provider': 'ghcr'})
+ assert resp.status_code == 403
+
+
+def test_registry_appears_in_unified_connections(client, auth_headers, app):
+ client.post('/api/v1/connections/registries', headers=auth_headers, json={
+ 'name': 'GHCR', 'provider': 'ghcr', 'registry_url': 'ghcr.io',
+ 'username': 'bot', 'secret': 'tok',
+ })
+ resp = client.get('/api/v1/connections', headers=auth_headers)
+ assert resp.status_code == 200
+ conns = resp.get_json()['connections']
+ reg_entries = [c for c in conns if c['kind'] == 'registry']
+ assert len(reg_entries) == 1
+ assert reg_entries[0]['encrypted'] is True
+ assert 'secret' not in reg_entries[0]
diff --git a/frontend/src/components/apps/ContainerOpsPanel.jsx b/frontend/src/components/apps/ContainerOpsPanel.jsx
index 2134cdb0..45eb36d4 100644
--- a/frontend/src/components/apps/ContainerOpsPanel.jsx
+++ b/frontend/src/components/apps/ContainerOpsPanel.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
-import { RefreshCw, ArrowUpCircle, Moon, Sun, Gauge as GaugeIcon } from 'lucide-react';
+import { RefreshCw, ArrowUpCircle, Moon, Sun, Gauge as GaugeIcon, Boxes } from 'lucide-react';
+import { Link } from 'react-router-dom';
import api from '../../services/api';
import { useToast } from '../../contexts/ToastContext';
import { useConfirm } from '../../hooks/useConfirm';
@@ -155,6 +156,89 @@ const ImageUpdateSection = ({ app, onChanged }) => {
);
};
+// ============================================================
+// Private registry section — which stored registry credentials to
+// authenticate with before pulling this app's image (docker login).
+// ============================================================
+const RegistrySection = ({ app, onChanged }) => {
+ const toast = useToast();
+ const [registries, setRegistries] = useState([]);
+ const [selected, setSelected] = useState(app.registry_id ?? '');
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => { setSelected(app.registry_id ?? ''); }, [app.registry_id]);
+
+ useEffect(() => {
+ let active = true;
+ (async () => {
+ try {
+ const data = await api.getContainerRegistries();
+ if (active) setRegistries(data?.registries || []);
+ } catch {
+ /* listing failing just means no picker options */
+ } finally {
+ if (active) setLoading(false);
+ }
+ })();
+ return () => { active = false; };
+ }, []);
+
+ async function handleChange(value) {
+ const next = value === '' ? null : Number(value);
+ setSelected(value);
+ setSaving(true);
+ try {
+ await api.updateApp(app.id, { registry_id: next });
+ toast.success(next ? 'Registry attached.' : 'Registry detached — pulls are anonymous.');
+ onChanged?.();
+ } catch (err) {
+ toast.error(err.message || 'Failed to update registry');
+ setSelected(app.registry_id ?? '');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div className="app-panel container-ops__section">
+ <div className="app-panel-header">
+ <Boxes />
+ <span>Private Registry</span>
+ </div>
+ <div className="app-panel-body">
+ <p className="app-panel-hint">
+ Authenticate with stored credentials before pulling this app&apos;s image. Add
+ registries under <Link to="/settings/connections">Settings → Connections</Link>.
+ </p>
+
+ <div className="container-ops__field">
+ <div className="container-ops__field-text">
+ <Label htmlFor={`registry-${app.id}`}>Registry</Label>
+ <span className="container-ops__field-hint">
+ Public images pull anonymously; pick a registry for private images.
+ </span>
+ </div>
+ <select
+ id={`registry-${app.id}`}
+ className="container-ops__select"
+ value={selected}
+ onChange={(e) => handleChange(e.target.value)}
+ disabled={loading || saving}
+ >
+ <option value="">Public (no auth)</option>
+ {registries.map((r) => (
+ <option key={r.id} value={r.id}>
+ {r.name} · {r.login_host}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ </div>
+ );
+};
+
// ============================================================
// Auto-sleep section
// ============================================================
@@ -517,6 +601,7 @@ const ContainerOpsPanel = ({ app, onChanged }) => {
return (
<div className="container-ops">
<ImageUpdateSection app={app} onChanged={onChanged} />
+ <RegistrySection app={app} onChanged={onChanged} />
<AutoSleepSection app={app} onChanged={onChanged} />
<AutoScaleSection app={app} onChanged={onChanged} />
</div>
diff --git a/frontend/src/components/icons/ProviderBrands.jsx b/frontend/src/components/icons/ProviderBrands.jsx
index 8eef6de5..f048ec1c 100644
--- a/frontend/src/components/icons/ProviderBrands.jsx
+++ b/frontend/src/components/icons/ProviderBrands.jsx
@@ -8,7 +8,7 @@
// the color with no inline styles.
import {
SiGithub, SiGitlab, SiBitbucket, SiCloudflare, SiDigitalocean,
- SiHetzner, SiVultr, SiAkamai, SiGodaddy, SiNamecheap, SiBackblaze,
+ SiHetzner, SiVultr, SiAkamai, SiGodaddy, SiNamecheap, SiBackblaze, SiDocker,
} from 'react-icons/si';
import { FaAws } from 'react-icons/fa';
import { Mail, HardDrive, Plug } from 'lucide-react';
@@ -30,6 +30,7 @@ const PROVIDER_ICONS = {
godaddy: SiGodaddy,
godaddy_dns: SiGodaddy,
namecheap: SiNamecheap,
+ container_registry: SiDocker,
smtp: Mail,
s3: HardDrive,
b2: SiBackblaze,
diff --git a/frontend/src/components/settings/connections/ConnectProviderModal.jsx b/frontend/src/components/settings/connections/ConnectProviderModal.jsx
index 5ee29c7e..dd53262e 100644
--- a/frontend/src/components/settings/connections/ConnectProviderModal.jsx
+++ b/frontend/src/components/settings/connections/ConnectProviderModal.jsx
@@ -10,7 +10,7 @@
import { useState } from 'react';
import {
CheckCircle2, ExternalLink, KeyRound, Link2, Mail, PlugZap, Server, Globe,
- HardDrive, ShieldCheck, ShieldAlert, Trash2, Activity, ChevronDown,
+ HardDrive, ShieldCheck, ShieldAlert, Trash2, Activity, ChevronDown, Boxes,
} from 'lucide-react';
import { Link } from 'react-router-dom';
import {
@@ -21,17 +21,18 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { ProviderBrandIcon } from '../../icons/ProviderBrands';
-import { deriveScope } from './providerCatalog';
+import { deriveScope, REGISTRY_PROVIDERS } from './providerCatalog';
import DnsActivity from './DnsActivity';
export default function ConnectProviderModal({
provider, open, onOpenChange, isAdmin,
- sourceStatus, sourceConfig, dnsProviders, cloudProviders, storageConfig, registrarConnections, relayConfig,
+ sourceStatus, sourceConfig, dnsProviders, cloudProviders, storageConfig, registrarConnections, containerRegistries, relayConfig,
onConnectSource, onDisconnectSource, onSaveSourceConfig,
onAddDns, onRemoveDns, onTestDns,
onAddCloud, onRemoveCloud,
onSaveStorage, onTestStorage,
onAddRegistrar, onRemoveRegistrar, onTestRegistrar,
+ onAddRegistry, onRemoveRegistry, onTestRegistry,
onSaveRelay, onTestRelay, onDisableRelay,
}) {
if (!provider) return null;
@@ -91,6 +92,14 @@ export default function ConnectProviderModal({
/>
)}
+ {provider.kind === 'registry' && (
+ <RegistryBody
+ key={provider.id} provider={provider} isAdmin={isAdmin}
+ registries={containerRegistries || []}
+ onAdd={onAddRegistry} onRemove={onRemoveRegistry} onTest={onTestRegistry}
+ />
+ )}
+
{provider.kind === 'email' && (
<EmailBody
key={provider.id} provider={provider} isAdmin={isAdmin}
@@ -575,6 +584,127 @@ function RegistrarBody({ provider, isAdmin, connections, onAdd, onRemove, onTest
);
}
+// ── Container registries: GHCR / Docker Hub / GitLab / ECR / generic ──
+// One card holds every registry; a provider selector presets the login host.
+function RegistryBody({ isAdmin, registries, onAdd, onRemove, onTest }) {
+ const [providerId, setProviderId] = useState(REGISTRY_PROVIDERS[0].id);
+ const preset = REGISTRY_PROVIDERS.find((p) => p.id === providerId) || REGISTRY_PROVIDERS[0];
+ const [form, setForm] = useState({ name: '', registry_url: REGISTRY_PROVIDERS[0].url, username: '', secret: '' });
+ const [busy, setBusy] = useState(false);
+
+ function pickProvider(id) {
+ const p = REGISTRY_PROVIDERS.find((x) => x.id === id) || REGISTRY_PROVIDERS[0];
+ setProviderId(id);
+ // Preset (or lock) the host to the provider's default.
+ setForm((f) => ({ ...f, registry_url: p.url }));
+ }
+
+ // ECR authenticates with AWS keys, no username; every other provider needs one.
+ const needsUsername = providerId !== 'ecr';
+ const canAdd = Boolean(form.name.trim() && form.secret.trim() && (!needsUsername || form.username.trim()));
+
+ async function withBusy(fn) { setBusy(true); try { return await fn(); } finally { setBusy(false); } }
+ async function add(e) {
+ e.preventDefault();
+ const payload = {
+ name: form.name.trim(),
+ provider: providerId,
+ registry_url: (form.registry_url || preset.url || '').trim(),
+ username: form.username.trim(),
+ secret: form.secret,
+ };
+ const ok = await withBusy(() => onAdd(payload));
+ if (ok) setForm({ name: '', registry_url: preset.url, username: '', secret: '' });
+ }
+
+ return (
+ <>
+ {registries.length > 0 && (
+ <div className="conn-list">
+ {registries.map((r) => (
+ <div key={r.id} className="conn-list__row">
+ <div className="conn-list__info">
+ <strong>{r.name}</strong>
+ <span className="conn-list__key">{r.login_host}{r.username ? ` · ${r.username}` : ''}</span>
+ </div>
+ <span className="conn-pill conn-pill--neutral" title="Registry provider">{r.provider}</span>
+ {isAdmin && (
+ <div className="conn-list__actions">
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => withBusy(() => onTest(r.id))}>Test</Button>
+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => withBusy(() => onRemove(r.id))} aria-label={`Remove ${r.name}`}><Trash2 size={15} /></Button>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <p className="conn-modal__note">
+ <Boxes size={15} /> Attach a registry to a service on the <Link className="conn-modal__link" to="/services/new">New Service →</Link> page to deploy its private images.
+ </p>
+
+ {!isAdmin ? (
+ <p className="conn-modal__note"><ShieldCheck size={15} /> Only administrators can add registries.</p>
+ ) : (
+ <form className="conn-form" onSubmit={add}>
+ <div className="conn-form__heading">{registries.length > 0 ? 'Add another registry' : 'Connect a registry'}</div>
+
+ <div className="conn-presets" role="radiogroup" aria-label="Registry provider">
+ {REGISTRY_PROVIDERS.map((p) => (
+ <button
+ type="button"
+ key={p.id}
+ className={`conn-presets__opt${providerId === p.id ? ' is-active' : ''}`}
+ onClick={() => pickProvider(p.id)}
+ role="radio"
+ aria-checked={providerId === p.id}
+ >
+ {p.name}
+ </button>
+ ))}
+ </div>
+
+ <div className="conn-form__grid">
+ <div className="form-group">
+ <Label htmlFor="reg-name">Connection name</Label>
+ <Input id="reg-name" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder={`${preset.name} (team)`} />
+ </div>
+ <div className="form-group">
+ <Label htmlFor="reg-url">Registry host</Label>
+ <Input
+ id="reg-url"
+ value={form.registry_url}
+ onChange={(e) => setForm((f) => ({ ...f, registry_url: e.target.value }))}
+ placeholder={preset.id === 'dockerhub' ? 'index.docker.io (Docker Hub)' : 'registry.example.com'}
+ disabled={preset.urlLocked}
+ autoComplete="off"
+ />
+ </div>
+ {needsUsername && (
+ <div className="form-group">
+ <Label htmlFor="reg-username">Username</Label>
+ <Input id="reg-username" value={form.username} onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))} placeholder={preset.usernameHint} autoComplete="off" />
+ </div>
+ )}
+ <div className={`form-group${needsUsername ? '' : ' conn-form__wide'}`}>
+ <Label htmlFor="reg-secret">{providerId === 'ecr' ? 'AWS credentials' : 'Password / token'}</Label>
+ <Input id="reg-secret" type="password" value={form.secret} onChange={(e) => setForm((f) => ({ ...f, secret: e.target.value }))} placeholder={preset.secretHint} autoComplete="off" />
+ </div>
+ </div>
+
+ <a className="conn-form__doc" href="https://docs.docker.com/engine/reference/commandline/login/" target="_blank" rel="noreferrer">
+ <ExternalLink size={13} /> How registry login works
+ </a>
+
+ <div className="conn-form__actions">
+ <Button type="submit" size="sm" disabled={busy || !canAdd}>{busy ? 'Connecting…' : 'Connect'}</Button>
+ </div>
+ </form>
+ )}
+ </>
+ );
+}
+
// ── Email: outbound SMTP relay (smarthost) ──
const SMTP_PRESETS = [
{ id: 'postmark', name: 'Postmark', host: 'smtp.postmarkapp.com', port: 587 },
diff --git a/frontend/src/components/settings/connections/ConnectionsHub.jsx b/frontend/src/components/settings/connections/ConnectionsHub.jsx
index d97dfa6a..107b1c69 100644
--- a/frontend/src/components/settings/connections/ConnectionsHub.jsx
+++ b/frontend/src/components/settings/connections/ConnectionsHub.jsx
@@ -32,6 +32,7 @@ export default function ConnectionsHub() {
const [relayConfig, setRelayConfig] = useState(null);
const [registrarConnections, setRegistrarConnections] = useState([]);
const [registrarDomains, setRegistrarDomains] = useState([]);
+ const [containerRegistries, setContainerRegistries] = useState([]);
const [allConnections, setAllConnections] = useState([]);
const [loading, setLoading] = useState(true);
const [modalProvider, setModalProvider] = useState(null);
@@ -39,7 +40,7 @@ export default function ConnectionsHub() {
const loadData = useCallback(async () => {
try {
- const [ghStatus, glStatus, bbStatus, dns, cloudP, storage, relay, regConns, regDomains, allConns] = await Promise.all([
+ const [ghStatus, glStatus, bbStatus, dns, cloudP, storage, relay, regConns, regDomains, registries, allConns] = await Promise.all([
api.getGithubSourceStatus().catch(() => null),
api.getGitlabSourceStatus().catch(() => null),
api.getBitbucketSourceStatus().catch(() => null),
@@ -49,6 +50,7 @@ export default function ConnectionsHub() {
api.getEmailRelay().catch(() => null),
api.getRegistrarConnections().then((d) => d.connections || []).catch(() => []),
api.getRegistrarDomains().then((d) => d.domains || []).catch(() => []),
+ api.getContainerRegistries().then((d) => d.registries || []).catch(() => []),
api.getAllConnections().then((d) => d.connections || []).catch(() => []),
]);
setSourceStatus({ github: ghStatus, gitlab: glStatus, bitbucket: bbStatus });
@@ -58,6 +60,7 @@ export default function ConnectionsHub() {
setRelayConfig(relay);
setRegistrarConnections(regConns);
setRegistrarDomains(regDomains);
+ setContainerRegistries(registries);
setAllConnections(allConns);
if (isAdmin) {
const [ghCfg, glCfg, bbCfg] = await Promise.all([
@@ -281,6 +284,44 @@ export default function ConnectionsHub() {
}
}, [toast]);
+ // ── Container registries ──
+ const onAddRegistry = useCallback(async (payload) => {
+ try {
+ await api.addContainerRegistry(payload);
+ toast.success(`${payload.name || 'Registry'} connected`);
+ await loadData();
+ return true;
+ } catch (err) {
+ toast.error(err.message || 'Failed to add registry');
+ return false;
+ }
+ }, [toast, loadData]);
+
+ const onRemoveRegistry = useCallback(async (id) => {
+ if (!window.confirm('Remove this container registry? Apps that pull from it will lose access.')) return false;
+ try {
+ await api.deleteContainerRegistry(id);
+ toast.success('Registry removed');
+ await loadData();
+ return true;
+ } catch (err) {
+ toast.error(err.message || 'Failed to remove registry');
+ return false;
+ }
+ }, [toast, loadData]);
+
+ const onTestRegistry = useCallback(async (id) => {
+ try {
+ const res = await api.testContainerRegistry(id);
+ if (res && res.success) toast.success(res.message || 'Login works');
+ else toast.error((res && res.error) || 'Login failed');
+ return res;
+ } catch (err) {
+ toast.error(err.message || 'Login failed');
+ return null;
+ }
+ }, [toast]);
+
// ── Per-provider card summaries ──
const summaries = useMemo(() => {
const out = {};
@@ -333,6 +374,15 @@ export default function ConnectionsHub() {
manageHref, manageLabel: 'Domains',
}
: { connected: false, statusLabel: 'Not connected', statusTone: 'neutral', scopes: [] };
+ } else if (provider.kind === 'registry') {
+ const list = containerRegistries;
+ out[provider.id] = list.length
+ ? {
+ connected: true, statusLabel: list.length === 1 ? 'Connected' : `${list.length} connected`, statusTone: 'ok',
+ subtitle: list.map((r) => r.name).join(', '),
+ scopes: [], manageHref, manageLabel: 'New service',
+ }
+ : { connected: false, statusLabel: 'Not connected', statusTone: 'neutral', scopes: [] };
} else if (provider.kind === 'storage') {
const active = storageConfig?.provider === provider.storageProvider;
const sub = storageConfig?.[provider.storageProvider];
@@ -357,7 +407,7 @@ export default function ConnectionsHub() {
}
}
return out;
- }, [sourceStatus, cloudProviders, dnsProviders, registrarConnections, registrarDomains, storageConfig, relayConfig]);
+ }, [sourceStatus, cloudProviders, dnsProviders, registrarConnections, registrarDomains, containerRegistries, storageConfig, relayConfig]);
function handleManage(provider) {
setModalProvider(provider);
@@ -428,6 +478,7 @@ export default function ConnectionsHub() {
cloudProviders={cloudProviders}
storageConfig={storageConfig}
registrarConnections={registrarConnections}
+ containerRegistries={containerRegistries}
onConnectSource={onConnectSource}
onDisconnectSource={onDisconnectSource}
onSaveSourceConfig={onSaveSourceConfig}
@@ -441,6 +492,9 @@ export default function ConnectionsHub() {
onAddRegistrar={onAddRegistrar}
onRemoveRegistrar={onRemoveRegistrar}
onTestRegistrar={onTestRegistrar}
+ onAddRegistry={onAddRegistry}
+ onRemoveRegistry={onRemoveRegistry}
+ onTestRegistry={onTestRegistry}
relayConfig={relayConfig}
onSaveRelay={onSaveRelay}
onTestRelay={onTestRelay}
diff --git a/frontend/src/components/settings/connections/providerCatalog.js b/frontend/src/components/settings/connections/providerCatalog.js
index c6df32bc..eddad9af 100644
--- a/frontend/src/components/settings/connections/providerCatalog.js
+++ b/frontend/src/components/settings/connections/providerCatalog.js
@@ -12,6 +12,7 @@
export const CONNECTION_CATEGORIES = [
{ key: 'source', label: 'Source code', blurb: 'Create services straight from a repository instead of pasting clone URLs.' },
{ key: 'infra', label: 'Infrastructure', blurb: 'Cloud accounts ServerKit can provision and manage servers in.' },
+ { key: 'registry', label: 'Container registries', blurb: 'Store a login once so ServerKit can pull private images (GHCR, Docker Hub, GitLab, ECR).' },
{ key: 'dns', label: 'DNS & domains', blurb: 'Let ServerKit manage DNS records and issue wildcard certificates automatically.' },
{ key: 'registrar', label: 'Registrars & ownership', blurb: 'Track the domains you own and when their registration expires.' },
{ key: 'email', label: 'Email & delivery', blurb: 'Outbound relays and deliverability for the mail server.' },
@@ -58,6 +59,15 @@ export const CONNECTION_PROVIDERS = [
docUrl: 'https://cloud.linode.com/profile/tokens', manageHref: '/servers',
},
+ // ── Container registries ──
+ // One card holds every registry; the add modal has a provider selector
+ // (GHCR / Docker Hub / GitLab / ECR / generic) that presets the login host.
+ {
+ id: 'container_registry', category: 'registry', name: 'Container registry', kind: 'registry',
+ blurb: 'Store credentials for a private registry so services can deploy its images.',
+ docUrl: 'https://docs.docker.com/engine/reference/commandline/login/', manageHref: '/services/new',
+ },
+
// ── DNS & domains ──
{
id: 'cloudflare', category: 'dns', name: 'Cloudflare', kind: 'dns', provider: 'cloudflare', supportsScope: true,
@@ -115,6 +125,18 @@ export function getProvider(id) {
return CONNECTION_PROVIDERS.find((p) => p.id === id) || null;
}
+// Container-registry provider presets for the add-registry form. `url` presets
+// the login host; `usernameHint`/`secretHint` label the credential fields per
+// provider. `urlLocked` means the host is fixed (Docker Hub / GHCR); a generic
+// registry lets the operator type any host.
+export const REGISTRY_PROVIDERS = [
+ { id: 'ghcr', name: 'GitHub (GHCR)', url: 'ghcr.io', urlLocked: true, usernameHint: 'GitHub username', secretHint: 'Personal access token (read:packages)' },
+ { id: 'dockerhub', name: 'Docker Hub', url: '', urlLocked: true, usernameHint: 'Docker Hub username', secretHint: 'Access token or password' },
+ { id: 'gitlab', name: 'GitLab', url: 'registry.gitlab.com', urlLocked: false, usernameHint: 'GitLab username', secretHint: 'Deploy token or PAT (read_registry)' },
+ { id: 'ecr', name: 'AWS ECR', url: '', urlLocked: false, usernameHint: 'Leave blank (uses AWS)', secretHint: 'ACCESS_KEY_ID:SECRET_ACCESS_KEY' },
+ { id: 'generic', name: 'Other / generic', url: '', urlLocked: false, usernameHint: 'Registry username', secretHint: 'Password or token' },
+];
+
// Access-level ("scope") derivation for DNS-provider records. Cloudflare with an
// account email uses a Global API Key (full account); without one it's a scoped
// token. Route 53 / GoDaddy keys derive scope from IAM / account policy we can't
diff --git a/frontend/src/services/api/connections.js b/frontend/src/services/api/connections.js
index 8cde4633..a3d3960d 100644
--- a/frontend/src/services/api/connections.js
+++ b/frontend/src/services/api/connections.js
@@ -30,3 +30,26 @@ export async function getRegistrarDomains() {
export async function syncRegistrarDomains() {
return this.request('/registrars/sync', { method: 'POST' });
}
+
+// Container registries — stored credentials for pulling private images. Listing
+// is available to any authenticated user (the app-create picker needs it);
+// mutations are admin-only server-side. Secrets are never returned (has_secret).
+export async function getContainerRegistries() {
+ return this.request('/connections/registries');
+}
+
+export async function addContainerRegistry(data) {
+ return this.request('/connections/registries', { method: 'POST', body: data });
+}
+
+export async function updateContainerRegistry(id, data) {
+ return this.request(`/connections/registries/${id}`, { method: 'PUT', body: data });
+}
+
+export async function deleteContainerRegistry(id) {
+ return this.request(`/connections/registries/${id}`, { method: 'DELETE' });
+}
+
+export async function testContainerRegistry(id) {
+ return this.request(`/connections/registries/${id}/test`, { method: 'POST' });
+}
diff --git a/frontend/src/styles/pages/_applications.scss b/frontend/src/styles/pages/_applications.scss
index 4e8cea71..26dfaa7e 100644
--- a/frontend/src/styles/pages/_applications.scss
+++ b/frontend/src/styles/pages/_applications.scss
@@ -1507,6 +1507,26 @@
text-align: right;
}
+ // registry picker (native select, themed to match the Input control)
+ &__select {
+ max-width: 280px;
+ padding: 8px 10px;
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-md;
+ background: var(--surface-2, var(--bg-card));
+ color: var(--text-strong, inherit);
+ font-size: 13px;
+
+ &:focus {
+ outline: none;
+ border-color: var(--primary-color, #6366f1);
+ }
+
+ &:disabled {
+ opacity: 0.6;
+ }
+ }
+
// grid of labelled inputs (auto-scale config)
&__grid {
display: grid;