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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(docker): image-digest update detection
Juan Denis7dc0bffb96c5
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 9f74c333..db4d7296 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -307,6 +307,10 @@ def create_app(config_name=None):from app.api.ddns import ddns_bpapp.register_blueprint(ddns_bp, url_prefix='/api/v1/ddns')+ # Register blueprints - Image update checks+ from app.api.image_updates import image_updates_bp+ app.register_blueprint(image_updates_bp, url_prefix='/api/v1/image-updates')+# Register blueprints - Nginx Advancedfrom app.api.nginx_advanced import nginx_advanced_bpapp.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')diff --git a/backend/app/api/image_updates.py b/backend/app/api/image_updates.pynew file mode 100644index 00000000..04dca6f4--- /dev/null+++ b/backend/app/api/image_updates.py@@ -0,0 +1,32 @@+from flask import Blueprint, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models.user import User+from app.services.image_update_service import ImageUpdateService++image_updates_bp = Blueprint('image_updates', __name__)+++def _admin():+ user = User.query.get(get_jwt_identity())+ return user if user and user.is_admin else None+++@image_updates_bp.route('/applications/<int:app_id>/check', methods=['POST'])+@jwt_required()+def check(app_id):+ """Run a registry-digest comparison for the application's image now."""+ if not _admin():+ return jsonify({'error': 'Admin access required'}), 403+ result = ImageUpdateService.check_application(app_id)+ if not result['success']:+ code = 404 if 'not found' in result['error'].lower() else 400+ return jsonify({'error': result['error']}), code+ return jsonify(result['check'])+++@image_updates_bp.route('/applications/<int:app_id>', methods=['GET'])+@jwt_required()+def latest(app_id):+ """Return the most recent image-update check for the application (or null)."""+ check_row = ImageUpdateService.latest_check(app_id)+ return jsonify(check_row.to_dict() if check_row else None)diff --git a/backend/app/models/application.py b/backend/app/models/application.pyindex 6e13268e..5c1766fa 100644--- a/backend/app/models/application.py+++ b/backend/app/models/application.py@@ -106,6 +106,17 @@ class Application(db.Model):}else:result['image_scan'] = None++ # Lightweight image-update badge (latest digest check only)+ latest_update = self.image_update_checks.first()+ if latest_update:+ result['image_update'] = {+ 'status': latest_update.status,+ 'update_available': latest_update.update_available,+ 'checked_at': latest_update.checked_at.isoformat() if latest_update.checked_at else None,+ }+ else:+ result['image_update'] = Noneif include_linked and self.linked_app:result['linked_app'] = {'id': self.linked_app.id,diff --git a/backend/app/models/image_update.py b/backend/app/models/image_update.pynew file mode 100644index 00000000..798bd189--- /dev/null+++ b/backend/app/models/image_update.py@@ -0,0 +1,35 @@+from datetime import datetime+from app import db+++class ImageUpdateCheck(db.Model):+ """Result of comparing an application's running image digest against the+ current digest for the same tag in its registry."""+ __tablename__ = 'image_update_checks'++ id = db.Column(db.Integer, primary_key=True)+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False, index=True)+ image_ref = db.Column(db.String(500), nullable=False)+ current_digest = db.Column(db.String(128)) # sha256:... running locally+ latest_digest = db.Column(db.String(128)) # sha256:... currently in the registry+ update_available = db.Column(db.Boolean, default=False, nullable=False)+ status = db.Column(db.String(20), default='pending') # pending, completed, failed+ error_message = db.Column(db.Text)+ checked_at = db.Column(db.DateTime, default=datetime.utcnow)++ application = db.relationship('Application', backref=db.backref(+ 'image_update_checks', lazy='dynamic',+ order_by='ImageUpdateCheck.checked_at.desc()'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'application_id': self.application_id,+ 'image_ref': self.image_ref,+ 'current_digest': self.current_digest,+ 'latest_digest': self.latest_digest,+ 'update_available': self.update_available,+ 'status': self.status,+ 'error_message': self.error_message,+ 'checked_at': self.checked_at.isoformat() if self.checked_at else None,+ }diff --git a/backend/app/services/image_update_service.py b/backend/app/services/image_update_service.pynew file mode 100644index 00000000..a5cd0ec6--- /dev/null+++ b/backend/app/services/image_update_service.py@@ -0,0 +1,87 @@+"""Detect whether a newer image is available for an application's Docker image+by comparing the locally-present digest with the registry's current digest for+the same tag. Shells out to `docker` like the rest of the Docker layer."""+import logging+import subprocess+from datetime import datetime++from app import db+from app.models import Application+from app.models.image_update import ImageUpdateCheck++logger = logging.getLogger(__name__)+++class ImageUpdateService:++ @staticmethod+ def _docker(args, timeout=60):+ return subprocess.run(['docker', *args], capture_output=True, text=True, timeout=timeout)++ @classmethod+ def _local_digest(cls, image_ref):+ """RepoDigest (sha256:...) of the locally-present image, or None when the+ image isn't pulled or was built locally (no registry digest)."""+ try:+ result = cls._docker(['image', 'inspect', image_ref, '--format', '{{index .RepoDigests 0}}'])+ if result.returncode != 0:+ return None+ out = result.stdout.strip()+ return out.split('@', 1)[1].strip() if '@sha256:' in out else None+ except Exception:+ return None++ @classmethod+ def _registry_digest(cls, image_ref):+ """Current index digest (sha256:...) for the ref's tag in its registry,+ or None when the registry is unreachable or buildx is unavailable."""+ try:+ result = cls._docker(+ ['buildx', 'imagetools', 'inspect', image_ref, '--format', '{{.Manifest.Digest}}'],+ timeout=30,+ )+ if result.returncode != 0:+ return None+ out = result.stdout.strip()+ return out if out.startswith('sha256:') else None+ except Exception:+ return None++ @classmethod+ def check_application(cls, application_id):+ app = Application.query.get(application_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}+ image_ref = app.docker_image+ if not image_ref:+ return {'success': False, 'error': 'Application has no Docker image'}++ check = ImageUpdateCheck(application_id=application_id, image_ref=image_ref, status='pending')+ db.session.add(check)+ db.session.commit()++ local = cls._local_digest(image_ref)+ remote = cls._registry_digest(image_ref)++ if local is None:+ check.status = 'failed'+ check.error_message = 'Could not read the local image digest (image not pulled, or built locally).'+ elif remote is None:+ check.status = 'failed'+ check.error_message = 'Could not query the registry digest (registry unreachable or buildx unavailable).'+ else:+ check.current_digest = local+ check.latest_digest = remote+ check.update_available = (local != remote)+ check.status = 'completed'++ check.checked_at = datetime.utcnow()+ db.session.commit()+ logger.info('Image-update check %s: %s (local=%s remote=%s)',+ image_ref, check.status, local, remote)+ return {'success': True, 'check': check.to_dict()}++ @classmethod+ def latest_check(cls, application_id):+ return ImageUpdateCheck.query.filter_by(application_id=application_id).order_by(+ ImageUpdateCheck.checked_at.desc()).first()diff --git a/backend/tests/test_image_update.py b/backend/tests/test_image_update.pynew file mode 100644index 00000000..97fd2075--- /dev/null+++ b/backend/tests/test_image_update.py@@ -0,0 +1,78 @@+"""Tests for image-digest update detection."""+import uuid++from app import db+from app.models import Application+from app.services.image_update_service import ImageUpdateService+++def _seed_app(image='nginx:latest'):+ from app.models import User+ uid = uuid.uuid4().hex[:8]+ user = User(email=f'{uid}@t.local', username=f'u{uid}',+ password_hash='x', role=User.ROLE_ADMIN, is_active=True)+ db.session.add(user)+ db.session.commit()+ row = Application(name='web', app_type='docker', source='manual',+ docker_image=image, user_id=user.id)+ db.session.add(row)+ db.session.commit()+ return row+++class TestImageUpdateService:+ def test_update_available_when_digests_differ(self, app, monkeypatch):+ a = _seed_app()+ monkeypatch.setattr(ImageUpdateService, '_local_digest', lambda ref: 'sha256:aaa')+ monkeypatch.setattr(ImageUpdateService, '_registry_digest', lambda ref: 'sha256:bbb')+ result = ImageUpdateService.check_application(a.id)+ assert result['success']+ chk = result['check']+ assert chk['status'] == 'completed'+ assert chk['update_available'] is True+ assert chk['current_digest'] == 'sha256:aaa'+ assert chk['latest_digest'] == 'sha256:bbb'++ def test_up_to_date_when_digests_match(self, app, monkeypatch):+ a = _seed_app()+ monkeypatch.setattr(ImageUpdateService, '_local_digest', lambda ref: 'sha256:same')+ monkeypatch.setattr(ImageUpdateService, '_registry_digest', lambda ref: 'sha256:same')+ chk = ImageUpdateService.check_application(a.id)['check']+ assert chk['status'] == 'completed'+ assert chk['update_available'] is False++ def test_failed_when_local_digest_unknown(self, app, monkeypatch):+ a = _seed_app()+ monkeypatch.setattr(ImageUpdateService, '_local_digest', lambda ref: None)+ monkeypatch.setattr(ImageUpdateService, '_registry_digest', lambda ref: 'sha256:bbb')+ chk = ImageUpdateService.check_application(a.id)['check']+ assert chk['status'] == 'failed'+ assert chk['update_available'] is False++ def test_no_image_returns_error(self, app):+ a = _seed_app(image=None)+ result = ImageUpdateService.check_application(a.id)+ assert result['success'] is False++ def test_badge_present_in_application_to_dict(self, app, monkeypatch):+ a = _seed_app()+ monkeypatch.setattr(ImageUpdateService, '_local_digest', lambda ref: 'sha256:aaa')+ monkeypatch.setattr(ImageUpdateService, '_registry_digest', lambda ref: 'sha256:bbb')+ ImageUpdateService.check_application(a.id)+ badge = a.to_dict()['image_update']+ assert badge is not None+ assert badge['update_available'] is True+ assert badge['status'] == 'completed'+++class TestImageUpdateApi:+ def test_check_endpoint_returns_result(self, client, auth_headers, app, monkeypatch):+ a = _seed_app()+ monkeypatch.setattr(ImageUpdateService, '_local_digest', lambda ref: 'sha256:aaa')+ monkeypatch.setattr(ImageUpdateService, '_registry_digest', lambda ref: 'sha256:bbb')+ resp = client.post(f'/api/v1/image-updates/applications/{a.id}/check', headers=auth_headers)+ assert resp.status_code == 200+ assert resp.get_json()['update_available'] is True++ def test_check_requires_auth(self, client, app):+ assert client.post('/api/v1/image-updates/applications/1/check').status_code == 401