Skip to content

Commit

Permalink
Add validation util for custom compose app
Browse files Browse the repository at this point in the history
  • Loading branch information
sonicaj committed Aug 8, 2024
1 parent b753367 commit 72007ef
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
17 changes: 2 additions & 15 deletions src/middlewared/middlewared/plugins/apps/custom_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from middlewared.service import Service, ValidationErrors

from .compose_utils import compose_action
from .custom_app_utils import validate_payload
from .ix_apps.lifecycle import update_app_config
from .ix_apps.metadata import update_app_metadata
from .ix_apps.path import get_installed_app_path
Expand All @@ -23,21 +24,7 @@ def create(self, data, job=None):
"""
Create a custom app.
"""
verrors = ValidationErrors()
compose_keys = ('custom_compose_config', 'custom_compose_config_string')
if all(not data.get(k) for k in compose_keys):
verrors.add('app_create.custom_compose_config', 'This field is required')
elif all(data.get(k) for k in compose_keys):
verrors.add('app_create.custom_compose_config_string', 'Only one of these fields should be provided')

compose_config = data.get('custom_compose_config')
if data.get('custom_compose_config_string'):
try:
compose_config = yaml.YAMLError(data['custom_compose_config_string'])
except yaml.YAMLError:
verrors.add('app_create.custom_compose_config_string', 'Invalid YAML provided')

verrors.check()
compose_config = validate_payload(data, 'app_create')

# For debug purposes
job = job or type('dummy_job', (object,), {'set_progress': lambda *args: None})()
Expand Down
23 changes: 23 additions & 0 deletions src/middlewared/middlewared/plugins/apps/custom_app_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import yaml

from middlewared.service import ValidationErrors


def validate_payload(data: dict, schema: str) -> dict:
verrors = ValidationErrors()
compose_keys = ('custom_compose_config', 'custom_compose_config_string')
if all(not data.get(k) for k in compose_keys):
verrors.add(f'{schema}.custom_compose_config', 'This field is required')
elif all(data.get(k) for k in compose_keys):
verrors.add(f'{schema}.custom_compose_config_string', 'Only one of these fields should be provided')

compose_config = data.get('custom_compose_config')
if data.get('custom_compose_config_string'):
try:
compose_config = yaml.YAMLError(data['custom_compose_config_string'])
except yaml.YAMLError:
verrors.add('app_create.custom_compose_config_string', 'Invalid YAML provided')

verrors.check()

return compose_config

0 comments on commit 72007ef

Please sign in to comment.