From 919ec7587709269acc5f223daf2e586b544a0c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Pi=C3=A9dallu?= Date: Sun, 26 Sep 2021 10:37:26 +0200 Subject: [PATCH 01/81] Revamp of yunomdns : * Use ifaddr (also used by zeroconf) to find ip addresses * Use python type hinting * small cleanups --- bin/yunomdns | 166 ++++++++++++++++----------------------------------- 1 file changed, 53 insertions(+), 113 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index 862a1f477..8202b93c4 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -4,104 +4,42 @@ Pythonic declaration of mDNS .local domains for YunoHost """ -import subprocess -import re import sys import yaml - -import socket from time import sleep from typing import List, Dict +import ifaddr from zeroconf import Zeroconf, ServiceInfo -# Helper command taken from Moulinette -def check_output(args, stderr=subprocess.STDOUT, shell=True, **kwargs): - """Run command with arguments and return its output as a byte string - Overwrite some of the arguments to capture standard error in the result - and use shell by default before calling subprocess.check_output. + +def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: """ - return ( - subprocess.check_output(args, stderr=stderr, shell=shell, **kwargs) - .decode("utf-8") - .strip() - ) - -# Helper command taken from Moulinette -def _extract_inet(string, skip_netmask=False, skip_loopback=True): + Returns interfaces with their associated local IPs """ - Extract IP addresses (v4 and/or v6) from a string limited to one - address by protocol - Keyword argument: - string -- String to search in - skip_netmask -- True to skip subnet mask extraction - skip_loopback -- False to include addresses reserved for the - loopback interface + def islocal(ip: str) -> bool: + local_prefixes = ["192.168.", "10.", "172.16.", "fc00:"] + return any(ip.startswith(prefix) for prefix in local_prefixes) - Returns: - A dict of {protocol: address} with protocol one of 'ipv4' or 'ipv6' - - """ - ip4_pattern = ( - r"((25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}" - ) - ip6_pattern = r"(((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::?((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)" - ip4_pattern += r"/[0-9]{1,2})" if not skip_netmask else ")" - ip6_pattern += r"/[0-9]{1,3})" if not skip_netmask else ")" - result = {} - - for m in re.finditer(ip4_pattern, string): - addr = m.group(1) - if skip_loopback and addr.startswith("127."): - continue - - # Limit to only one result - result["ipv4"] = addr - break - - for m in re.finditer(ip6_pattern, string): - addr = m.group(1) - if skip_loopback and addr == "::1": - continue - - # Limit to only one result - result["ipv6"] = addr - break - - return result - -# Helper command taken from Moulinette -def get_network_interfaces(): - - # Get network devices and their addresses (raw infos from 'ip addr') - devices_raw = {} - output = check_output("ip --brief a").split("\n") - for line in output: - line = line.split() - iname = line[0] - ips = ' '.join(line[2:]) - - devices_raw[iname] = ips - - # Parse relevant informations for each of them - devices = { - name: _extract_inet(addrs) - for name, addrs in devices_raw.items() - if name != "lo" + interfaces = { + adapter.name: { + "ipv4": [ip.ip for ip in adapter.ips if ip.is_IPv4 and islocal(ip.ip)], + "ipv6": [ip.ip[0] for ip in adapter.ips if ip.is_IPv6 and islocal(ip.ip[0])], + } + for adapter in ifaddr.get_adapters() + if adapter.name != "lo" } + return interfaces - return devices - -if __name__ == '__main__': +def main() -> bool: ### # CONFIG ### with open('/etc/yunohost/mdns.yml', 'r') as f: config = yaml.safe_load(f) or {} - updated = False required_fields = ["interfaces", "domains"] missing_fields = [field for field in required_fields if field not in config] @@ -111,47 +49,44 @@ if __name__ == '__main__': if config['interfaces'] is None: print('No interface listed for broadcast.') - sys.exit(0) + return True if 'yunohost.local' not in config['domains']: config['domains'].append('yunohost.local') - zcs = {} - interfaces = get_network_interfaces() + zcs: Dict[Zeroconf, List[ServiceInfo]] = {} + + interfaces = get_network_local_interfaces() for interface in config['interfaces']: - infos = [] # List of ServiceInfo objects, to feed Zeroconf - ips = [] # Human-readable IPs - b_ips = [] # Binary-convered IPs + if interface not in interfaces: + print(f'Interface {interface} of config file is not present on system.') + continue - ipv4 = interfaces[interface]['ipv4'].split('/')[0] - if ipv4: - ips.append(ipv4) - b_ips.append(socket.inet_pton(socket.AF_INET, ipv4)) - - ipv6 = interfaces[interface]['ipv6'].split('/')[0] - if ipv6: - ips.append(ipv6) - b_ips.append(socket.inet_pton(socket.AF_INET6, ipv6)) + ips: List[str] = interfaces[interface]['ipv4'] + interfaces[interface]['ipv6'] # If at least one IP is listed - if ips: - # Create a Zeroconf object, and store the ServiceInfos - zc = Zeroconf(interfaces=ips) - zcs[zc]=[] - for d in config['domains']: - d_domain=d.replace('.local','') - if '.' in d_domain: - print(d_domain+'.local: subdomains are not supported.') - else: - # Create a ServiceInfo object for each .local domain - zcs[zc].append(ServiceInfo( - type_='_device-info._tcp.local.', - name=interface+': '+d_domain+'._device-info._tcp.local.', - addresses=b_ips, - port=80, - server=d+'.', - )) - print('Adding '+d+' with addresses '+str(ips)+' on interface '+interface) + if not ips: + continue + # Create a Zeroconf object, and store the ServiceInfos + zc = Zeroconf(interfaces=ips) # type: ignore + zcs[zc] = [] + + for d in config['domains']: + d_domain = d.replace('.local', '') + if '.' in d_domain: + print(f'{d_domain}.local: subdomains are not supported.') + continue + # Create a ServiceInfo object for each .local domain + zcs[zc].append( + ServiceInfo( + type_='_device-info._tcp.local.', + name=f'{interface}: {d_domain}._device-info._tcp.local.', + parsed_addresses=ips, + port=80, + server=f'{d}.', + ) + ) + print(f'Adding {d} with addresses {ips} on interface {interface}') # Run registration print("Registering...") @@ -168,6 +103,11 @@ if __name__ == '__main__': finally: print("Unregistering...") for zc, infos in zcs.items(): - for info in infos: - zc.unregister_service(info) + zc.unregister_all_services() zc.close() + + return True + + +if __name__ == "__main__": + sys.exit(0 if main() else 1) From d4395f2b4aa69424245218601993e3c37c141df8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Pi=C3=A9dallu?= Date: Sun, 26 Sep 2021 10:42:57 +0200 Subject: [PATCH 02/81] Use double-quotes --- bin/yunomdns | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index 8202b93c4..f31132514 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -38,31 +38,31 @@ def main() -> bool: # CONFIG ### - with open('/etc/yunohost/mdns.yml', 'r') as f: + with open("/etc/yunohost/mdns.yml", "r") as f: config = yaml.safe_load(f) or {} required_fields = ["interfaces", "domains"] missing_fields = [field for field in required_fields if field not in config] if missing_fields: - print("The fields %s are required" % ', '.join(missing_fields)) + print("The fields %s are required" % ", ".join(missing_fields)) - if config['interfaces'] is None: - print('No interface listed for broadcast.') + if config["interfaces"] is None: + print("No interface listed for broadcast.") return True - if 'yunohost.local' not in config['domains']: - config['domains'].append('yunohost.local') + if "yunohost.local" not in config["domains"]: + config["domains"].append("yunohost.local") zcs: Dict[Zeroconf, List[ServiceInfo]] = {} interfaces = get_network_local_interfaces() - for interface in config['interfaces']: + for interface in config["interfaces"]: if interface not in interfaces: - print(f'Interface {interface} of config file is not present on system.') + print(f"Interface {interface} of config file is not present on system.") continue - ips: List[str] = interfaces[interface]['ipv4'] + interfaces[interface]['ipv6'] + ips: List[str] = interfaces[interface]["ipv4"] + interfaces[interface]["ipv6"] # If at least one IP is listed if not ips: @@ -71,22 +71,22 @@ def main() -> bool: zc = Zeroconf(interfaces=ips) # type: ignore zcs[zc] = [] - for d in config['domains']: - d_domain = d.replace('.local', '') - if '.' in d_domain: - print(f'{d_domain}.local: subdomains are not supported.') + for d in config["domains"]: + d_domain = d.replace(".local", "") + if "." in d_domain: + print(f"{d_domain}.local: subdomains are not supported.") continue # Create a ServiceInfo object for each .local domain zcs[zc].append( ServiceInfo( - type_='_device-info._tcp.local.', - name=f'{interface}: {d_domain}._device-info._tcp.local.', + type_="_device-info._tcp.local.", + name=f"{interface}: {d_domain}._device-info._tcp.local.", parsed_addresses=ips, port=80, - server=f'{d}.', + server=f"{d}.", ) ) - print(f'Adding {d} with addresses {ips} on interface {interface}') + print(f"Adding {d} with addresses {ips} on interface {interface}") # Run registration print("Registering...") From 358885dc622d9e18c2cc283c4a1c52236537b73b Mon Sep 17 00:00:00 2001 From: tituspijean Date: Mon, 20 Sep 2021 22:07:45 +0200 Subject: [PATCH 03/81] [mdns] Avoid miserably failing if another service exists on the network also, service names do not clash anymore accross same device but different interfaces --- bin/yunomdns | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/yunomdns b/bin/yunomdns index f31132514..dfd58deee 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -92,7 +92,7 @@ def main() -> bool: print("Registering...") for zc, infos in zcs.items(): for info in infos: - zc.register_service(info) + zc.register_service(info, allow_name_change=True, cooperating_responders=True) try: print("Registered. Press Ctrl+C or stop service to stop.") From bcb48b4948a900fd153e87e325ba07c8c56f6895 Mon Sep 17 00:00:00 2001 From: tituspijean Date: Mon, 20 Sep 2021 22:14:00 +0200 Subject: [PATCH 04/81] [mdns] Make the service logs appear in systemd journal --- data/templates/mdns/yunomdns.service | 1 + 1 file changed, 1 insertion(+) diff --git a/data/templates/mdns/yunomdns.service b/data/templates/mdns/yunomdns.service index ce2641b5d..c1f1b7b06 100644 --- a/data/templates/mdns/yunomdns.service +++ b/data/templates/mdns/yunomdns.service @@ -6,6 +6,7 @@ After=network.target User=mdns Group=mdns Type=simple +Environment=PYTHONUNBUFFERED=1 ExecStart=/usr/bin/yunomdns StandardOutput=syslog From a313a86b8b6eb39b8836c47cc8c107058a6da6ed Mon Sep 17 00:00:00 2001 From: tituspijean Date: Tue, 21 Sep 2021 00:09:49 +0200 Subject: [PATCH 05/81] [mdns] Allow for multiple yunohost.local --- bin/yunomdns | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index dfd58deee..aa0697f5f 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -10,7 +10,7 @@ from time import sleep from typing import List, Dict import ifaddr -from zeroconf import Zeroconf, ServiceInfo +from zeroconf import Zeroconf, ServiceInfo, ServiceBrowser def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: @@ -32,6 +32,23 @@ def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: } return interfaces +# Listener class, to detect duplicates on the network +# Stores the list of servers in its list property +class Listener: + + def __init__(self): + self.list = [] + + def remove_service(self, zeroconf, type, name): + info = zeroconf.get_service_info(type, name) + self.list.remove(info.server) + + def update_service(self, zeroconf, type, name): + pass + + def add_service(self, zeroconf, type, name): + info = zeroconf.get_service_info(type, name) + self.list.append(info.server[:-1]) def main() -> bool: ### @@ -51,8 +68,25 @@ def main() -> bool: print("No interface listed for broadcast.") return True - if "yunohost.local" not in config["domains"]: - config["domains"].append("yunohost.local") + # Let's discover currently published .local domains accross the network + zc = Zeroconf() + listener = Listener() + browser = ServiceBrowser(zc, "_device-info._tcp.local.", listener) + sleep(2) + browser.cancel() + zc.close() + # If yunohost.local already exists, try yunohost-2.local, and so on. + def yunohost_local(i): + return "yunohost.local" if i < 2 else "yunohost-"+str(i)+".local" + i=1 + while yunohost_local(i) in listener.list: + print("Uh oh, "+yunohost_local(i)+" already exists on the network...") + if yunohost_local(i) in config['domains']: + config['domains'].remove(yunohost_local(i)) + i += 1 + if yunohost_local(i) not in config['domains']: + print("Adding "+yunohost_local(i)+" to the domains to publish.") + config['domains'].append(yunohost_local(i)) zcs: Dict[Zeroconf, List[ServiceInfo]] = {} From 07c381cec4690df90022e11c0574dfca78906c2f Mon Sep 17 00:00:00 2001 From: tituspijean Date: Sun, 26 Sep 2021 12:05:35 +0200 Subject: [PATCH 06/81] Use ipaddress lib to find private addresses --- bin/yunomdns | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index aa0697f5f..f50afd964 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -10,6 +10,7 @@ from time import sleep from typing import List, Dict import ifaddr +from ipaddress import ip_address from zeroconf import Zeroconf, ServiceInfo, ServiceBrowser @@ -18,14 +19,10 @@ def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: Returns interfaces with their associated local IPs """ - def islocal(ip: str) -> bool: - local_prefixes = ["192.168.", "10.", "172.16.", "fc00:"] - return any(ip.startswith(prefix) for prefix in local_prefixes) - interfaces = { adapter.name: { - "ipv4": [ip.ip for ip in adapter.ips if ip.is_IPv4 and islocal(ip.ip)], - "ipv6": [ip.ip[0] for ip in adapter.ips if ip.is_IPv6 and islocal(ip.ip[0])], + "ipv4": [ip.ip for ip in adapter.ips if ip.is_IPv4 and ip_address(ip.ip).is_private], + "ipv6": [ip.ip[0] for ip in adapter.ips if ip.is_IPv6 and ip_address(ip.ip[0]).is_private], } for adapter in ifaddr.get_adapters() if adapter.name != "lo" From 63504febaaf17a7efbf93f111c409764e84a0b17 Mon Sep 17 00:00:00 2001 From: tituspijean Date: Sun, 26 Sep 2021 19:40:46 +0200 Subject: [PATCH 07/81] [mdns] refine ipv6 selection with ipaddress lib Co-authored-by: =?UTF-8?q?F=C3=A9lix=20Pi=C3=A9dallu?= --- bin/yunomdns | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/yunomdns b/bin/yunomdns index f50afd964..f302f1f8c 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -22,7 +22,7 @@ def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: interfaces = { adapter.name: { "ipv4": [ip.ip for ip in adapter.ips if ip.is_IPv4 and ip_address(ip.ip).is_private], - "ipv6": [ip.ip[0] for ip in adapter.ips if ip.is_IPv6 and ip_address(ip.ip[0]).is_private], + "ipv6": [ip.ip[0] for ip in adapter.ips if ip.is_IPv6 and ip_address(ip.ip[0]).is_private and not ip_address(ip.ip[0]).is_link_local], } for adapter in ifaddr.get_adapters() if adapter.name != "lo" From da1b9089bf6fd6e39d0c905bbe8e6573658315a9 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 28 Sep 2021 23:36:24 +0200 Subject: [PATCH 08/81] Fix dns zone for dynette domains (otherwise breaks dyndns update) --- src/yunohost/dns.py | 5 +++-- src/yunohost/tests/test_dns.py | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index 0581fa82c..c003b7a56 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -428,7 +428,8 @@ def _get_dns_zone_for_domain(domain): # ... otherwise we end up constantly doing a bunch of dig requests for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS: if domain.endswith("." + ynh_dyndns_domain): - return ynh_dyndns_domain + # Keep only foo.nohost.me even if we have subsub.sub.foo.nohost.me + return '.'.join(domain.rsplit('.', 3)[-3:]) # Check cache cache_folder = "/var/cache/yunohost/dns_zones" @@ -520,7 +521,7 @@ def _get_registrar_config_section(domain): # TODO big project, integrate yunohost's dynette as a registrar-like provider # TODO big project, integrate other dyndns providers such as netlib.re, or cf the list of dyndns providers supported by cloudron... - if dns_zone in YNH_DYNDNS_DOMAINS: + if any(dns_zone.endswith('.' + ynh_dyndns_domain) for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS): registrar_infos["registrar"] = OrderedDict( { "type": "alert", diff --git a/src/yunohost/tests/test_dns.py b/src/yunohost/tests/test_dns.py index 497cab2fd..cdd37b2ea 100644 --- a/src/yunohost/tests/test_dns.py +++ b/src/yunohost/tests/test_dns.py @@ -34,8 +34,10 @@ def test_get_dns_zone_from_domain_existing(): assert ( _get_dns_zone_for_domain("non-existing-domain.yunohost.org") == "yunohost.org" ) - assert _get_dns_zone_for_domain("yolo.nohost.me") == "nohost.me" - assert _get_dns_zone_for_domain("foo.yolo.nohost.me") == "nohost.me" + assert _get_dns_zone_for_domain("yolo.nohost.me") == "yolo.nohost.me" + assert _get_dns_zone_for_domain("foo.yolo.nohost.me") == "yolo.nohost.me" + assert _get_dns_zone_for_domain("bar.foo.yolo.nohost.me") == "yolo.nohost.me" + assert _get_dns_zone_for_domain("yolo.tld") == "yolo.tld" assert _get_dns_zone_for_domain("foo.yolo.tld") == "yolo.tld" From 7d4ab4a886fd568179d642759947aef5ff26d714 Mon Sep 17 00:00:00 2001 From: yunohost-bot Date: Tue, 28 Sep 2021 21:52:29 +0000 Subject: [PATCH 09/81] [CI] Format code --- src/yunohost/dns.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index c003b7a56..e62469a53 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -429,7 +429,7 @@ def _get_dns_zone_for_domain(domain): for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS: if domain.endswith("." + ynh_dyndns_domain): # Keep only foo.nohost.me even if we have subsub.sub.foo.nohost.me - return '.'.join(domain.rsplit('.', 3)[-3:]) + return ".".join(domain.rsplit(".", 3)[-3:]) # Check cache cache_folder = "/var/cache/yunohost/dns_zones" @@ -521,7 +521,10 @@ def _get_registrar_config_section(domain): # TODO big project, integrate yunohost's dynette as a registrar-like provider # TODO big project, integrate other dyndns providers such as netlib.re, or cf the list of dyndns providers supported by cloudron... - if any(dns_zone.endswith('.' + ynh_dyndns_domain) for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS): + if any( + dns_zone.endswith("." + ynh_dyndns_domain) + for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS + ): registrar_infos["registrar"] = OrderedDict( { "type": "alert", From dc8c16c96da7bc7f5676af31f372ce2887250512 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 18:33:31 +0200 Subject: [PATCH 10/81] Wording --- locales/en.json | 2 +- locales/fr.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/locales/en.json b/locales/en.json index cf24cfc09..1977f8278 100644 --- a/locales/en.json +++ b/locales/en.json @@ -201,7 +201,7 @@ "diagnosis_domain_expiration_warning": "Some domains will expire soon!", "diagnosis_domain_expires_in": "{domain} expires in {days} days.", "diagnosis_domain_not_found_details": "The domain {domain} doesn't exist in WHOIS database or is expired!", - "diagnosis_everything_ok": "Everything looks good for {category}!", + "diagnosis_everything_ok": "Everything looks OK for {category}!", "diagnosis_failed": "Failed to fetch diagnosis result for category '{category}': {error}", "diagnosis_failed_for_category": "Diagnosis failed for category '{category}': {error}", "diagnosis_found_errors": "Found {errors} significant issue(s) related to {category}!", diff --git a/locales/fr.json b/locales/fr.json index 46535719e..bd29ad774 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -431,7 +431,7 @@ "diagnosis_cache_still_valid": "(Le cache est encore valide pour le diagnostic {category}. Il ne sera pas re-diagnostiqué pour le moment !)", "diagnosis_ignored_issues": "(+ {nb_ignored} problème(s) ignoré(s))", "diagnosis_found_warnings": "Trouvé {warnings} objet(s) pouvant être amélioré(s) pour {category}.", - "diagnosis_everything_ok": "Tout semble bien pour {category} !", + "diagnosis_everything_ok": "Tout semble OK pour {category} !", "diagnosis_failed": "Échec de la récupération du résultat du diagnostic pour la catégorie '{category}' : {error}", "diagnosis_ip_connected_ipv4": "Le serveur est connecté à Internet en IPv4 !", "diagnosis_ip_no_ipv4": "Le serveur ne dispose pas d'une adresse IPv4.", @@ -676,4 +676,4 @@ "service_not_reloading_because_conf_broken": "Le service '{name}' n'a pas été rechargé/redémarré car sa configuration est cassée : {errors}", "app_argument_password_help_keep": "Tapez sur Entrée pour conserver la valeur actuelle", "app_argument_password_help_optional": "Tapez un espace pour vider le mot de passe" -} \ No newline at end of file +} From ad3602a24fffe9fa16c0d767a1d151e0ea966de6 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 18:36:24 +0200 Subject: [PATCH 11/81] YNH_APP_PURGE to be 1 or 0 to be consistent with other bash bools --- src/yunohost/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 0013fcd82..56e4c344b 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -1160,7 +1160,7 @@ def app_remove(operation_logger, app, purge=False): env_dict["YNH_APP_INSTANCE_NAME"] = app env_dict["YNH_APP_INSTANCE_NUMBER"] = str(app_instance_nb) env_dict["YNH_APP_MANIFEST_VERSION"] = manifest.get("version", "?") - env_dict["YNH_APP_PURGE"] = str(purge) + env_dict["YNH_APP_PURGE"] = str(1 if purge else 0) env_dict["YNH_APP_BASEDIR"] = tmp_workdir_for_app operation_logger.extra.update({"env": env_dict}) From 14d3265389ad122c31944f54c5b17db65f20fb7b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 18:40:31 +0200 Subject: [PATCH 12/81] Try to include diagnosis hooks in coverage report --- .gitlab/ci/test.gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab/ci/test.gitlab-ci.yml b/.gitlab/ci/test.gitlab-ci.yml index b3aea606f..6a422ea22 100644 --- a/.gitlab/ci/test.gitlab-ci.yml +++ b/.gitlab/ci/test.gitlab-ci.yml @@ -36,7 +36,7 @@ full-tests: - *install_debs - yunohost tools postinstall -d domain.tld -p the_password --ignore-dyndns --force-diskspace script: - - python3 -m pytest --cov=yunohost tests/ src/yunohost/tests/ --junitxml=report.xml + - python3 -m pytest --cov=yunohost tests/ src/yunohost/tests/ data/hooks/diagnosis/ --junitxml=report.xml - cd tests - bash test_helpers.sh needs: From ab1100048b91dc1b9404c0996642ccca68b09062 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 19:00:05 +0200 Subject: [PATCH 13/81] yunomdns: Minor cleanups --- bin/yunomdns | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index f302f1f8c..41a9ede3e 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -29,6 +29,7 @@ def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: } return interfaces + # Listener class, to detect duplicates on the network # Stores the list of servers in its list property class Listener: @@ -47,6 +48,7 @@ class Listener: info = zeroconf.get_service_info(type, name) self.list.append(info.server[:-1]) + def main() -> bool: ### # CONFIG @@ -59,7 +61,8 @@ def main() -> bool: missing_fields = [field for field in required_fields if field not in config] if missing_fields: - print("The fields %s are required" % ", ".join(missing_fields)) + print(f"The fields {missing_fields} are required in mdns.yml") + return False if config["interfaces"] is None: print("No interface listed for broadcast.") @@ -72,17 +75,20 @@ def main() -> bool: sleep(2) browser.cancel() zc.close() + # If yunohost.local already exists, try yunohost-2.local, and so on. def yunohost_local(i): - return "yunohost.local" if i < 2 else "yunohost-"+str(i)+".local" - i=1 + return "yunohost.local" if i < 2 else f"yunohost-{i}.local" + + i = 1 while yunohost_local(i) in listener.list: - print("Uh oh, "+yunohost_local(i)+" already exists on the network...") + print(f"Uh oh, {yunohost_local(i)} already exists on the network...") if yunohost_local(i) in config['domains']: config['domains'].remove(yunohost_local(i)) i += 1 + if yunohost_local(i) not in config['domains']: - print("Adding "+yunohost_local(i)+" to the domains to publish.") + print(f"Adding {yunohost_local(i)} to the domains to publish.") config['domains'].append(yunohost_local(i)) zcs: Dict[Zeroconf, List[ServiceInfo]] = {} From f49666d22e7e17cedfab49a98a1789c12f62fc7e Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 19:14:21 +0200 Subject: [PATCH 14/81] yunomdns: fallback to domain-i.local if domain.local already published --- bin/yunomdns | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index 41a9ede3e..8a9682ff9 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -76,20 +76,27 @@ def main() -> bool: browser.cancel() zc.close() - # If yunohost.local already exists, try yunohost-2.local, and so on. - def yunohost_local(i): - return "yunohost.local" if i < 2 else f"yunohost-{i}.local" + # Always attempt to publish yunohost.local + if "yunohost.local" not in config["domains"]: + config["domains"].append("yunohost.local") - i = 1 - while yunohost_local(i) in listener.list: - print(f"Uh oh, {yunohost_local(i)} already exists on the network...") - if yunohost_local(i) in config['domains']: - config['domains'].remove(yunohost_local(i)) - i += 1 + def find_domain_not_already_published(domain): - if yunohost_local(i) not in config['domains']: - print(f"Adding {yunohost_local(i)} to the domains to publish.") - config['domains'].append(yunohost_local(i)) + # Try domain.local ... but if it's already published by another entity, + # try domain-2.local, domain-3.local, ... + + i = 1 + domain_i = domain + + while domain_i in listener.list: + print(f"Uh oh, {domain_i} already exists on the network...") + + i += 1 + domain_i = domain.replace(".local", f"-{i}.local") + + return domain_i + + config['domains'] = [find_domain_not_already_published(domain) for domain in config['domains']] zcs: Dict[Zeroconf, List[ServiceInfo]] = {} From a5e1d7e318158da38b1e3dc415a92f0e6250a460 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 20:02:32 +0200 Subject: [PATCH 15/81] yunomdns: broadcast on all interfaces with local IP by default + add a 'ban_interfaces' setting in config --- bin/yunomdns | 23 +++++++++++++++++------ data/hooks/conf_regen/37-mdns | 7 ------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index 8a9682ff9..b9f8cf2a7 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -57,16 +57,23 @@ def main() -> bool: with open("/etc/yunohost/mdns.yml", "r") as f: config = yaml.safe_load(f) or {} - required_fields = ["interfaces", "domains"] + required_fields = ["domains"] missing_fields = [field for field in required_fields if field not in config] + interfaces = get_network_local_interfaces() if missing_fields: print(f"The fields {missing_fields} are required in mdns.yml") return False - if config["interfaces"] is None: - print("No interface listed for broadcast.") - return True + if "interfaces" not in config: + config["interfaces"] = [interface + for interface, local_ips in interfaces.items() + if local_ips["ipv4"]] + + if "ban_interfaces" in config: + config["interfaces"] = [interface + for interface in config["interfaces"] + if interface not in config["ban_interfaces"]] # Let's discover currently published .local domains accross the network zc = Zeroconf() @@ -100,10 +107,10 @@ def main() -> bool: zcs: Dict[Zeroconf, List[ServiceInfo]] = {} - interfaces = get_network_local_interfaces() for interface in config["interfaces"]: + if interface not in interfaces: - print(f"Interface {interface} of config file is not present on system.") + print(f"Interface {interface} listed in config file is not present on system.") continue ips: List[str] = interfaces[interface]["ipv4"] + interfaces[interface]["ipv6"] @@ -111,6 +118,10 @@ def main() -> bool: # If at least one IP is listed if not ips: continue + + print(f"Publishing on {interface} ...") + print(ips) + # Create a Zeroconf object, and store the ServiceInfos zc = Zeroconf(interfaces=ips) # type: ignore zcs[zc] = [] diff --git a/data/hooks/conf_regen/37-mdns b/data/hooks/conf_regen/37-mdns index 1d7381e26..b2a3efe95 100755 --- a/data/hooks/conf_regen/37-mdns +++ b/data/hooks/conf_regen/37-mdns @@ -12,13 +12,6 @@ _generate_config() { [[ "$domain" =~ ^[^.]+\.local$ ]] || continue echo " - $domain" done - - echo "interfaces:" - local_network_interfaces="$(ip --brief a | grep ' 10\.\| 192\.168\.' | awk '{print $1}')" - for interface in $local_network_interfaces - do - echo " - $interface" - done } do_init_regen() { From 391de52ff214a46efe1f990c6bd7164eebc852ad Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 20:10:00 +0200 Subject: [PATCH 16/81] yunomdns: disable ipv6 for now + remove debug stuff --- bin/yunomdns | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index b9f8cf2a7..0aee28195 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -113,15 +113,17 @@ def main() -> bool: print(f"Interface {interface} listed in config file is not present on system.") continue - ips: List[str] = interfaces[interface]["ipv4"] + interfaces[interface]["ipv6"] + # Only broadcast IPv4 because IPv6 is buggy ... because we ain't using python3-ifaddr >= 0.1.7 + # Buster only ships 0.1.6 + # Bullseye ships 0.1.7 + # To be re-enabled once we're on bullseye... + # ips: List[str] = interfaces[interface]["ipv4"] + interfaces[interface]["ipv6"] + ips: List[str] = interfaces[interface]["ipv4"] # If at least one IP is listed if not ips: continue - print(f"Publishing on {interface} ...") - print(ips) - # Create a Zeroconf object, and store the ServiceInfos zc = Zeroconf(interfaces=ips) # type: ignore zcs[zc] = [] From 17aafe6f6ad74e136802221d7073160b9aa2c8f8 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 20:33:07 +0200 Subject: [PATCH 17/81] General improvement for special-use TLD / ynh dyndns domains --- data/hooks/diagnosis/12-dnsrecords.py | 18 ++++-------- data/hooks/diagnosis/21-web.py | 5 ++-- locales/en.json | 5 ++-- src/yunohost/dns.py | 40 ++++++++++++++++++--------- src/yunohost/tests/test_dns.py | 3 ++ src/yunohost/utils/dns.py | 12 ++++++++ 6 files changed, 53 insertions(+), 30 deletions(-) diff --git a/data/hooks/diagnosis/12-dnsrecords.py b/data/hooks/diagnosis/12-dnsrecords.py index 16841721f..368c3d878 100644 --- a/data/hooks/diagnosis/12-dnsrecords.py +++ b/data/hooks/diagnosis/12-dnsrecords.py @@ -8,13 +8,11 @@ from publicsuffix import PublicSuffixList from moulinette.utils.process import check_output -from yunohost.utils.dns import dig, YNH_DYNDNS_DOMAINS +from yunohost.utils.dns import dig, YNH_DYNDNS_DOMAINS, is_yunohost_dyndns_domain, is_special_use_tld from yunohost.diagnosis import Diagnoser from yunohost.domain import domain_list, _get_maindomain from yunohost.dns import _build_dns_conf, _get_dns_zone_for_domain -SPECIAL_USE_TLDS = ["local", "localhost", "onion", "test"] - class DNSRecordsDiagnoser(Diagnoser): @@ -29,13 +27,10 @@ class DNSRecordsDiagnoser(Diagnoser): all_domains = domain_list(exclude_subdomains=True)["domains"] for domain in all_domains: self.logger_debug("Diagnosing DNS conf for %s" % domain) - is_specialusedomain = any( - domain.endswith("." + tld) for tld in SPECIAL_USE_TLDS - ) + for report in self.check_domain( domain, domain == main_domain, - is_specialusedomain=is_specialusedomain, ): yield report @@ -53,7 +48,7 @@ class DNSRecordsDiagnoser(Diagnoser): for report in self.check_expiration_date(domains_from_registrar): yield report - def check_domain(self, domain, is_main_domain, is_specialusedomain): + def check_domain(self, domain, is_main_domain): base_dns_zone = _get_dns_zone_for_domain(domain) basename = domain.replace(base_dns_zone, "").rstrip(".") or "@" @@ -64,7 +59,7 @@ class DNSRecordsDiagnoser(Diagnoser): categories = ["basic", "mail", "xmpp", "extra"] - if is_specialusedomain: + if is_special_use_tld(domain): categories = [] yield dict( meta={"domain": domain}, @@ -140,10 +135,7 @@ class DNSRecordsDiagnoser(Diagnoser): if discrepancies: # For ynh-managed domains (nohost.me etc...), tell people to try to "yunohost dyndns update --force" - if any( - domain.endswith(ynh_dyndns_domain) - for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS - ): + if is_yunohost_dyndns_domain(domain): output["details"] = ["diagnosis_dns_try_dyndns_update_force"] # Otherwise point to the documentation else: diff --git a/data/hooks/diagnosis/21-web.py b/data/hooks/diagnosis/21-web.py index 2072937e5..450296e7e 100644 --- a/data/hooks/diagnosis/21-web.py +++ b/data/hooks/diagnosis/21-web.py @@ -8,6 +8,7 @@ from moulinette.utils.filesystem import read_file from yunohost.diagnosis import Diagnoser from yunohost.domain import domain_list +from yunohost.utils.dns import is_special_use_tld DIAGNOSIS_SERVER = "diagnosis.yunohost.org" @@ -34,11 +35,11 @@ class WebDiagnoser(Diagnoser): summary="diagnosis_http_nginx_conf_not_up_to_date", details=["diagnosis_http_nginx_conf_not_up_to_date_details"], ) - elif domain.endswith(".local"): + elif is_special_use_tld(domain): yield dict( meta={"domain": domain}, status="INFO", - summary="diagnosis_http_localdomain", + summary="diagnosis_http_special_use_tld", ) else: domains_to_check.append(domain) diff --git a/locales/en.json b/locales/en.json index 1977f8278..5d242b2e8 100644 --- a/locales/en.json +++ b/locales/en.json @@ -192,7 +192,7 @@ "diagnosis_dns_good_conf": "DNS records are correctly configured for domain {domain} (category {category})", "diagnosis_dns_missing_record": "According to the recommended DNS configuration, you should add a DNS record with the following info.
Type: {type}
Name: {name}
Value: {value}", "diagnosis_dns_point_to_doc": "Please check the documentation at https://yunohost.org/dns_config if you need help about configuring DNS records.", - "diagnosis_dns_specialusedomain": "Domain {domain} is based on a special-use top-level domain (TLD) and is therefore not expected to have actual DNS records.", + "diagnosis_dns_specialusedomain": "Domain {domain} is based on a special-use top-level domain (TLD) such as .local or .test and is therefore not expected to have actual DNS records.", "diagnosis_dns_try_dyndns_update_force": "This domain's DNS configuration should automatically be managed by YunoHost. If that's not the case, you can try to force an update using yunohost dyndns update --force.", "diagnosis_domain_expiration_error": "Some domains will expire VERY SOON!", "diagnosis_domain_expiration_not_found": "Unable to check the expiration date for some domains", @@ -214,7 +214,7 @@ "diagnosis_http_could_not_diagnose_details": "Error: {error}", "diagnosis_http_hairpinning_issue": "Your local network does not seem to have hairpinning enabled.", "diagnosis_http_hairpinning_issue_details": "This is probably because of your ISP box / router. As a result, people from outside your local network will be able to access your server as expected, but not people from inside the local network (like you, probably?) when using the domain name or global IP. You may be able to improve the situation by having a look at https://yunohost.org/dns_local_network", - "diagnosis_http_localdomain": "Domain {domain}, with a .local TLD, is not expected to be exposed outside the local network.", + "diagnosis_http_special_use_tld": "Domain {domain} is based on a special-use top-level domain (TLD) such as .local or .test and is therefore not expected to be exposed outside the local network.", "diagnosis_http_nginx_conf_not_up_to_date": "This domain's nginx configuration appears to have been modified manually, and prevents YunoHost from diagnosing if it's reachable on HTTP.", "diagnosis_http_nginx_conf_not_up_to_date_details": "To fix the situation, inspect the difference with the command line using yunohost tools regen-conf nginx --dry-run --with-diff and if you're ok, apply the changes with yunohost tools regen-conf nginx --force.", "diagnosis_http_ok": "Domain {domain} is reachable through HTTP from outside the local network.", @@ -308,6 +308,7 @@ "domain_deleted": "Domain deleted", "domain_deletion_failed": "Unable to delete domain {domain}: {error}", "domain_dns_conf_is_just_a_recommendation": "This command shows you the *recommended* configuration. It does not actually set up the DNS configuration for you. It is your responsability to configure your DNS zone in your registrar according to this recommendation.", + "domain_dns_conf_special_use_tld": "This domain is based on a special-use top-level domain (TLD) such as .local or .test and is therefore not expected to have actual DNS records.", "domain_dyndns_already_subscribed": "You have already subscribed to a DynDNS domain", "domain_dyndns_root_unknown": "Unknown DynDNS root domain", "domain_exists": "The domain already exists", diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index e62469a53..72c9f7c72 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -41,7 +41,7 @@ from yunohost.domain import ( _get_domain_settings, _set_domain_settings, ) -from yunohost.utils.dns import dig, YNH_DYNDNS_DOMAINS +from yunohost.utils.dns import dig, is_yunohost_dyndns_domain, is_special_use_tld from yunohost.utils.error import YunohostValidationError, YunohostError from yunohost.utils.network import get_public_ip from yunohost.log import is_unit_operation @@ -61,6 +61,9 @@ def domain_dns_suggest(domain): """ + if is_special_use_tld(domain): + return m18n.n("domain_dns_conf_special_use_tld") + _assert_domain_exists(domain) dns_conf = _build_dns_conf(domain) @@ -169,10 +172,7 @@ def _build_dns_conf(base_domain, include_empty_AAAA_if_no_ipv6=False): # If this is a ynh_dyndns_domain, we're not gonna include all the subdomains in the conf # Because dynette only accept a specific list of name/type # And the wildcard */A already covers the bulk of use cases - if any( - base_domain.endswith("." + ynh_dyndns_domain) - for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS - ): + if is_yunohost_dyndns_domain(base_domain): subdomains = [] else: subdomains = _list_subdomains_of(base_domain) @@ -426,10 +426,14 @@ def _get_dns_zone_for_domain(domain): # First, check if domain is a nohost.me / noho.st / ynh.fr # This is mainly meant to speed up things for "dyndns update" # ... otherwise we end up constantly doing a bunch of dig requests - for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS: - if domain.endswith("." + ynh_dyndns_domain): - # Keep only foo.nohost.me even if we have subsub.sub.foo.nohost.me - return ".".join(domain.rsplit(".", 3)[-3:]) + if is_yunohost_dyndns_domain(domain): + # Keep only foo.nohost.me even if we have subsub.sub.foo.nohost.me + return ".".join(domain.rsplit(".", 3)[-3:]) + + # Same thing with .local, .test, ... domains + if is_special_use_tld(domain): + # Keep only foo.local even if we have subsub.sub.foo.local + return ".".join(domain.rsplit(".", 2)[-2:]) # Check cache cache_folder = "/var/cache/yunohost/dns_zones" @@ -521,10 +525,7 @@ def _get_registrar_config_section(domain): # TODO big project, integrate yunohost's dynette as a registrar-like provider # TODO big project, integrate other dyndns providers such as netlib.re, or cf the list of dyndns providers supported by cloudron... - if any( - dns_zone.endswith("." + ynh_dyndns_domain) - for ynh_dyndns_domain in YNH_DYNDNS_DOMAINS - ): + if is_yunohost_dyndns_domain(dns_zone): registrar_infos["registrar"] = OrderedDict( { "type": "alert", @@ -534,6 +535,15 @@ def _get_registrar_config_section(domain): } ) return OrderedDict(registrar_infos) + elif is_special_use_tld(dns_zone): + registrar_infos["registrar"] = OrderedDict( + { + "type": "alert", + "style": "info", + "ask": m18n.n("domain_dns_conf_special_use_tld"), + "value": None, + } + ) try: registrar = _relevant_provider_for_domain(dns_zone)[0] @@ -607,6 +617,10 @@ def domain_dns_push(operation_logger, domain, dry_run=False, force=False, purge= _assert_domain_exists(domain) + if is_special_use_tld(domain): + logger.info(m18n.n("domain_dns_conf_special_use_tld")) + return {} + if not registrar or registrar == "None": # yes it's None as a string raise YunohostValidationError("domain_dns_push_not_applicable", domain=domain) diff --git a/src/yunohost/tests/test_dns.py b/src/yunohost/tests/test_dns.py index cdd37b2ea..a23ac7982 100644 --- a/src/yunohost/tests/test_dns.py +++ b/src/yunohost/tests/test_dns.py @@ -38,6 +38,9 @@ def test_get_dns_zone_from_domain_existing(): assert _get_dns_zone_for_domain("foo.yolo.nohost.me") == "yolo.nohost.me" assert _get_dns_zone_for_domain("bar.foo.yolo.nohost.me") == "yolo.nohost.me" + assert _get_dns_zone_for_domain("yolo.test") == "yolo.test" + assert _get_dns_zone_for_domain("foo.yolo.test") == "yolo.test" + assert _get_dns_zone_for_domain("yolo.tld") == "yolo.tld" assert _get_dns_zone_for_domain("foo.yolo.tld") == "yolo.tld" diff --git a/src/yunohost/utils/dns.py b/src/yunohost/utils/dns.py index 3db75f949..4ab17416d 100644 --- a/src/yunohost/utils/dns.py +++ b/src/yunohost/utils/dns.py @@ -23,6 +23,8 @@ from typing import List from moulinette.utils.filesystem import read_file +SPECIAL_USE_TLDS = ["local", "localhost", "onion", "test"] + YNH_DYNDNS_DOMAINS = ["nohost.me", "noho.st", "ynh.fr"] # Lazy dev caching to avoid re-reading the file multiple time when calling @@ -30,6 +32,16 @@ YNH_DYNDNS_DOMAINS = ["nohost.me", "noho.st", "ynh.fr"] external_resolvers_: List[str] = [] +def is_yunohost_dyndns_domain(domain): + + return any(domain.endswith(f".{dyndns_domain}") for dyndns_domain in YNH_DYNDNS_DOMAINS) + + +def is_special_use_tld(domain): + + return any(domain.endswith(f".{tld}") for tld in SPECIAL_USE_TLDS) + + def external_resolvers(): global external_resolvers_ From 85e6ddbeae1c2c2f43f2d84cda2faa52e8479917 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 20:50:01 +0200 Subject: [PATCH 18/81] firewall.py: fix encoding issue, remove prependline stuff --- src/yunohost/firewall.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/yunohost/firewall.py b/src/yunohost/firewall.py index 4be6810ec..a1c0b187f 100644 --- a/src/yunohost/firewall.py +++ b/src/yunohost/firewall.py @@ -31,7 +31,6 @@ from moulinette import m18n from yunohost.utils.error import YunohostError, YunohostValidationError from moulinette.utils import process from moulinette.utils.log import getActionLogger -from moulinette.utils.text import prependlines FIREWALL_FILE = "/etc/yunohost/firewall.yml" UPNP_CRON_JOB = "/etc/cron.d/yunohost-firewall-upnp" @@ -240,7 +239,7 @@ def firewall_reload(skip_upnp=False): except process.CalledProcessError as e: logger.debug( "iptables seems to be not available, it outputs:\n%s", - prependlines(e.output.rstrip(), "> "), + e.output.decode().strip(), ) logger.warning(m18n.n("iptables_unavailable")) else: @@ -273,7 +272,7 @@ def firewall_reload(skip_upnp=False): except process.CalledProcessError as e: logger.debug( "ip6tables seems to be not available, it outputs:\n%s", - prependlines(e.output.rstrip(), "> "), + e.output.decode().strip(), ) logger.warning(m18n.n("ip6tables_unavailable")) else: @@ -526,6 +525,6 @@ def _on_rule_command_error(returncode, cmd, output): '"%s" returned non-zero exit status %d:\n%s', cmd, returncode, - prependlines(output.rstrip(), "> "), + output.decode().strip(), ) return True From c44560b6f7cac9486d96a7f111059bfb2b4a4ec3 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 21:38:03 +0200 Subject: [PATCH 19/81] Misc cleanups in dns diagnoser --- data/hooks/diagnosis/12-dnsrecords.py | 33 ++++++++++++++++----------- src/yunohost/dns.py | 6 +++++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/data/hooks/diagnosis/12-dnsrecords.py b/data/hooks/diagnosis/12-dnsrecords.py index 368c3d878..85f837af5 100644 --- a/data/hooks/diagnosis/12-dnsrecords.py +++ b/data/hooks/diagnosis/12-dnsrecords.py @@ -24,8 +24,8 @@ class DNSRecordsDiagnoser(Diagnoser): main_domain = _get_maindomain() - all_domains = domain_list(exclude_subdomains=True)["domains"] - for domain in all_domains: + major_domains = domain_list(exclude_subdomains=True)["domains"] + for domain in major_domains: self.logger_debug("Diagnosing DNS conf for %s" % domain) for report in self.check_domain( @@ -37,7 +37,7 @@ class DNSRecordsDiagnoser(Diagnoser): # Check if a domain buy by the user will expire soon psl = PublicSuffixList() domains_from_registrar = [ - psl.get_public_suffix(domain) for domain in all_domains + psl.get_public_suffix(domain) for domain in major_domains ] domains_from_registrar = [ domain for domain in domains_from_registrar if "." in domain @@ -50,15 +50,6 @@ class DNSRecordsDiagnoser(Diagnoser): def check_domain(self, domain, is_main_domain): - base_dns_zone = _get_dns_zone_for_domain(domain) - basename = domain.replace(base_dns_zone, "").rstrip(".") or "@" - - expected_configuration = _build_dns_conf( - domain, include_empty_AAAA_if_no_ipv6=True - ) - - categories = ["basic", "mail", "xmpp", "extra"] - if is_special_use_tld(domain): categories = [] yield dict( @@ -68,6 +59,15 @@ class DNSRecordsDiagnoser(Diagnoser): summary="diagnosis_dns_specialusedomain", ) + base_dns_zone = _get_dns_zone_for_domain(domain) + basename = domain.replace(base_dns_zone, "").rstrip(".") or "@" + + expected_configuration = _build_dns_conf( + domain, include_empty_AAAA_if_no_ipv6=True + ) + + categories = ["basic", "mail", "xmpp", "extra"] + for category in categories: records = expected_configuration[category] @@ -79,7 +79,8 @@ class DNSRecordsDiagnoser(Diagnoser): id_ = r["type"] + ":" + r["name"] fqdn = r["name"] + "." + base_dns_zone if r["name"] != "@" else domain - # Ugly hack to not check mail records for subdomains stuff, otherwise will end up in a shitstorm of errors for people with many subdomains... + # Ugly hack to not check mail records for subdomains stuff, + # otherwise will end up in a shitstorm of errors for people with many subdomains... # Should find a cleaner solution in the suggested conf... if r["type"] in ["MX", "TXT"] and fqdn not in [ domain, @@ -126,6 +127,12 @@ class DNSRecordsDiagnoser(Diagnoser): status = "SUCCESS" summary = "diagnosis_dns_good_conf" + # If status is okay and there's actually no expected records + # (e.g. XMPP disabled) + # then let's not yield any diagnosis line + if not records and "status" == "SUCCESS": + continue + output = dict( meta={"domain": domain, "category": category}, data=results, diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index 72c9f7c72..493d7ad86 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -297,6 +297,12 @@ def _build_dns_conf(base_domain, include_empty_AAAA_if_no_ipv6=False): # Defined by custom hooks ships in apps for example ... + # FIXME : this ain't practical for apps that may want to add + # custom dns records for a subdomain ... there's no easy way for + # an app to compare the base domain is the parent of the subdomain ? + # (On the other hand, in sep 2021, it looks like no app is using + # this mechanism...) + hook_results = hook_callback("custom_dns_rules", args=[base_domain]) for hook_name, results in hook_results.items(): # From b8cb374a4925b2afa44d1f24abdb92831a92ee18 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 21:43:52 +0200 Subject: [PATCH 20/81] Add a proper _get_parent_domain --- src/yunohost/dns.py | 14 ++------------ src/yunohost/domain.py | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index 493d7ad86..fdceee26b 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -40,6 +40,8 @@ from yunohost.domain import ( domain_config_get, _get_domain_settings, _set_domain_settings, + _get_parent_domain_of, + _list_subdomains_of, ) from yunohost.utils.dns import dig, is_yunohost_dyndns_domain, is_special_use_tld from yunohost.utils.error import YunohostValidationError, YunohostError @@ -107,18 +109,6 @@ def domain_dns_suggest(domain): return result -def _list_subdomains_of(parent_domain): - - _assert_domain_exists(parent_domain) - - out = [] - for domain in domain_list()["domains"]: - if domain.endswith(f".{parent_domain}"): - out.append(domain) - - return out - - def _build_dns_conf(base_domain, include_empty_AAAA_if_no_ipv6=False): """ Internal function that will returns a data structure containing the needed diff --git a/src/yunohost/domain.py b/src/yunohost/domain.py index 1f96ced8a..f5b14748d 100644 --- a/src/yunohost/domain.py +++ b/src/yunohost/domain.py @@ -105,6 +105,33 @@ def _assert_domain_exists(domain): raise YunohostValidationError("domain_name_unknown", domain=domain) +def _list_subdomains_of(parent_domain): + + _assert_domain_exists(parent_domain) + + out = [] + for domain in domain_list()["domains"]: + if domain.endswith(f".{parent_domain}"): + out.append(domain) + + return out + + +def _get_parent_domain_of(domain): + + _assert_domain_exists(domain) + + if "." not in domain: + return domain + + parent_domain = domain.split(".", 1)[-1] + if parent_domain not in domain_list()["domains"]: + return domain # Domain is its own parent + + else: + return _get_parent_domain_of(parent_domain) + + @is_unit_operation() def domain_add(operation_logger, domain, dyndns=False): """ From d75c1a61e82738853a22f0aaec28acb2b207d6fb Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 22:11:24 +0200 Subject: [PATCH 21/81] Adapt ready_for_ACME check to the new dnsrecord result format... --- src/yunohost/certificate.py | 43 ++++++++++++++++++++++++++----------- src/yunohost/dns.py | 1 - 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/yunohost/certificate.py b/src/yunohost/certificate.py index 817f9d57a..0df428c77 100644 --- a/src/yunohost/certificate.py +++ b/src/yunohost/certificate.py @@ -851,14 +851,9 @@ def _backup_current_cert(domain): def _check_domain_is_ready_for_ACME(domain): - dnsrecords = ( - Diagnoser.get_cached_report( - "dnsrecords", - item={"domain": domain, "category": "basic"}, - warn_if_no_cache=False, - ) - or {} - ) + from yunohost.domain import _get_parent_domain_of + from yunohost.dns import _get_dns_zone_for_domain + httpreachable = ( Diagnoser.get_cached_report( "web", item={"domain": domain}, warn_if_no_cache=False @@ -866,16 +861,38 @@ def _check_domain_is_ready_for_ACME(domain): or {} ) - if not dnsrecords or not httpreachable: + parent_domain = _get_parent_domain_of(domain) + + dnsrecords = ( + Diagnoser.get_cached_report( + "dnsrecords", + item={"domain": parent_domain, "category": "basic"}, + warn_if_no_cache=False, + ) + or {} + ) + + base_dns_zone = _get_dns_zone_for_domain(domain) + record_name = domain.replace(f".{base_dns_zone}", "") if domain != base_dns_zone else "@" + A_record_status = dnsrecords.get("data").get(f"A:{record_name}") + AAAA_record_status = dnsrecords.get("data").get(f"AAAA:{record_name}") + + # Fallback to wildcard in case no result yet for the DNS name? + if not A_record_status: + A_record_status = dnsrecords.get("data").get(f"A:*") + if not AAAA_record_status: + AAAA_record_status = dnsrecords.get("data").get(f"AAAA:*") + + if not httpreachable or not dnsrecords.get("data") or (A_record_status, AAAA_record_status) == (None, None): raise YunohostValidationError( "certmanager_domain_not_diagnosed_yet", domain=domain ) # Check if IP from DNS matches public IP - if not dnsrecords.get("status") in [ - "SUCCESS", - "WARNING", - ]: # Warning is for missing IPv6 record which ain't critical for ACME + # - 'MISSING' for IPv6 ain't critical for ACME + # - IPv4 can be None assuming there's at least an IPv6, and viveversa + # - (the case where both are None is checked before) + if not (A_record_status in [None, "OK"] and AAAA_record_status in [None, "OK", "MISSING"]): raise YunohostValidationError( "certmanager_domain_dns_ip_differs_from_public_ip", domain=domain ) diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index fdceee26b..689950490 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -40,7 +40,6 @@ from yunohost.domain import ( domain_config_get, _get_domain_settings, _set_domain_settings, - _get_parent_domain_of, _list_subdomains_of, ) from yunohost.utils.dns import dig, is_yunohost_dyndns_domain, is_special_use_tld From 2e96cb28bb0bf79520f1e6e9d210f5a6ee1780b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89ric=20Gaspar?= Date: Sun, 19 Sep 2021 21:12:58 +0000 Subject: [PATCH 22/81] Translated using Weblate (French) Currently translated at 99.8% (707 of 708 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/fr/ --- locales/fr.json | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/locales/fr.json b/locales/fr.json index bd29ad774..29e6da673 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -675,5 +675,35 @@ "log_app_config_set": "Appliquer la configuration à l'application '{}'", "service_not_reloading_because_conf_broken": "Le service '{name}' n'a pas été rechargé/redémarré car sa configuration est cassée : {errors}", "app_argument_password_help_keep": "Tapez sur Entrée pour conserver la valeur actuelle", - "app_argument_password_help_optional": "Tapez un espace pour vider le mot de passe" + "app_argument_password_help_optional": "Tapez un espace pour vider le mot de passe", + "domain_registrar_is_not_configured": "Le registrar n'est pas encore configuré pour le domaine {domain}.", + "domain_dns_push_not_applicable": "La fonction de configuration DNS automatique n'est pas applicable au domaine {domain}. Vous devez configurer manuellement vos enregistrements DNS en suivant la documentation sur https://yunohost.org/dns_config.", + "domain_dns_registrar_yunohost": "Ce domaine est nohost.me / nohost.st / ynh.fr et sa configuration DNS est donc automatiquement gérée par YunoHost sans autre configuration. (voir la commande 'yunohost dyndns update')", + "domain_dns_registrar_supported": "YunoHost a détecté automatiquement que ce domaine est géré par le registrar **{registrar}**. Si vous le souhaitez, YunoHost configurera automatiquement cette zone DNS, si vous lui fournissez les identifiants API appropriés. Vous pouvez trouver de la documentation sur la façon d'obtenir vos identifiants API sur cette page : https://yunohost.org/registar_api_{registrar}. (Vous pouvez également configurer manuellement vos enregistrements DNS en suivant la documentation sur https://yunohost.org/dns )", + "domain_config_features_disclaimer": "Jusqu'à présent, l'activation/désactivation des fonctionnalités de messagerie ou XMPP n'a d'impact que sur la configuration DNS recommandée et automatique, et non sur les configurations système !", + "domain_dns_push_managed_in_parent_domain": "La fonctionnalité de configuration DNS automatique est gérée dans le domaine parent {parent_domain}.", + "domain_dns_registrar_managed_in_parent_domain": "Ce domaine est un sous-domaine de {parent_domain_link}. La configuration du registrar DNS doit être gérée dans le panneau de configuration de {parent_domain}.", + "domain_dns_registrar_not_supported": "YunoHost n'a pas pu détecter automatiquement le bureau d'enregistrement gérant ce domaine. Vous devez configurer manuellement vos enregistrements DNS en suivant la documentation sur https://yunohost.org/dns.", + "domain_dns_registrar_experimental": "Jusqu'à présent, l'interface avec l'API de **{registrar}** n'a pas été correctement testée et revue par la communauté YunoHost. L'assistance est **très expérimentale** - soyez prudent !", + "domain_dns_push_failed_to_authenticate": "Échec de l'authentification sur l'API du bureau d'enregistrement pour le domaine « {domain} ». Très probablement les informations d'identification sont incorrectes ? (Error: {error})", + "domain_dns_push_failed_to_list": "Échec de la liste des enregistrements actuels à l'aide de l'API du registraire : {error}", + "domain_dns_push_already_up_to_date": "Dossiers déjà à jour.", + "domain_dns_pushing": "Transmission des enregistrements DNS...", + "domain_dns_push_record_failed": "Échec de l'enregistrement {action} {type}/{name} : {error}", + "domain_dns_push_success": "Enregistrements DNS mis à jour !", + "domain_dns_push_failed": "La mise à jour des enregistrements DNS a échoué.", + "domain_dns_push_partial_failure": "Enregistrements DNS partiellement mis à jour : certains avertissements/erreurs ont été signalés.", + "domain_config_mail_in": "Emails entrants", + "domain_config_mail_out": "Emails sortants", + "domain_config_xmpp": "Messagerie instantanée (XMPP)", + "domain_config_auth_token": "Jeton d'authentification", + "domain_config_auth_key": "Clé d'authentification", + "domain_config_auth_secret": "Secret d'authentification", + "domain_config_api_protocol": "Protocole API", + "domain_config_auth_entrypoint": "Point d'entrée API", + "domain_config_auth_application_key": "Clé d'application", + "domain_config_auth_application_secret": "Clé secrète de l'application", + "ldap_attribute_already_exists": "L'attribut LDAP '{attribute}' existe déjà avec la valeur '{value}'", + "log_domain_config_set": "Mettre à jour la configuration du domaine '{}'", + "log_domain_dns_push": "Pousser les enregistrements DNS pour le domaine '{}'" } From df0cdd483d33e5bab5e6f1c1603f690835a74425 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 22:20:29 +0200 Subject: [PATCH 23/81] Black --- data/hooks/diagnosis/12-dnsrecords.py | 7 ++++++- src/yunohost/certificate.py | 15 ++++++++++++--- src/yunohost/utils/dns.py | 4 +++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/data/hooks/diagnosis/12-dnsrecords.py b/data/hooks/diagnosis/12-dnsrecords.py index 85f837af5..677a947a7 100644 --- a/data/hooks/diagnosis/12-dnsrecords.py +++ b/data/hooks/diagnosis/12-dnsrecords.py @@ -8,7 +8,12 @@ from publicsuffix import PublicSuffixList from moulinette.utils.process import check_output -from yunohost.utils.dns import dig, YNH_DYNDNS_DOMAINS, is_yunohost_dyndns_domain, is_special_use_tld +from yunohost.utils.dns import ( + dig, + YNH_DYNDNS_DOMAINS, + is_yunohost_dyndns_domain, + is_special_use_tld, +) from yunohost.diagnosis import Diagnoser from yunohost.domain import domain_list, _get_maindomain from yunohost.dns import _build_dns_conf, _get_dns_zone_for_domain diff --git a/src/yunohost/certificate.py b/src/yunohost/certificate.py index 0df428c77..e960098f4 100644 --- a/src/yunohost/certificate.py +++ b/src/yunohost/certificate.py @@ -873,7 +873,9 @@ def _check_domain_is_ready_for_ACME(domain): ) base_dns_zone = _get_dns_zone_for_domain(domain) - record_name = domain.replace(f".{base_dns_zone}", "") if domain != base_dns_zone else "@" + record_name = ( + domain.replace(f".{base_dns_zone}", "") if domain != base_dns_zone else "@" + ) A_record_status = dnsrecords.get("data").get(f"A:{record_name}") AAAA_record_status = dnsrecords.get("data").get(f"AAAA:{record_name}") @@ -883,7 +885,11 @@ def _check_domain_is_ready_for_ACME(domain): if not AAAA_record_status: AAAA_record_status = dnsrecords.get("data").get(f"AAAA:*") - if not httpreachable or not dnsrecords.get("data") or (A_record_status, AAAA_record_status) == (None, None): + if ( + not httpreachable + or not dnsrecords.get("data") + or (A_record_status, AAAA_record_status) == (None, None) + ): raise YunohostValidationError( "certmanager_domain_not_diagnosed_yet", domain=domain ) @@ -892,7 +898,10 @@ def _check_domain_is_ready_for_ACME(domain): # - 'MISSING' for IPv6 ain't critical for ACME # - IPv4 can be None assuming there's at least an IPv6, and viveversa # - (the case where both are None is checked before) - if not (A_record_status in [None, "OK"] and AAAA_record_status in [None, "OK", "MISSING"]): + if not ( + A_record_status in [None, "OK"] + and AAAA_record_status in [None, "OK", "MISSING"] + ): raise YunohostValidationError( "certmanager_domain_dns_ip_differs_from_public_ip", domain=domain ) diff --git a/src/yunohost/utils/dns.py b/src/yunohost/utils/dns.py index 4ab17416d..ccb6c5406 100644 --- a/src/yunohost/utils/dns.py +++ b/src/yunohost/utils/dns.py @@ -34,7 +34,9 @@ external_resolvers_: List[str] = [] def is_yunohost_dyndns_domain(domain): - return any(domain.endswith(f".{dyndns_domain}") for dyndns_domain in YNH_DYNDNS_DOMAINS) + return any( + domain.endswith(f".{dyndns_domain}") for dyndns_domain in YNH_DYNDNS_DOMAINS + ) def is_special_use_tld(domain): From 55598151c0de151ccfb662249e5776f1b6c3cecf Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 22:29:28 +0200 Subject: [PATCH 24/81] Unhappy linter is unhappy --- src/yunohost/certificate.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/yunohost/certificate.py b/src/yunohost/certificate.py index e960098f4..fe350bf95 100644 --- a/src/yunohost/certificate.py +++ b/src/yunohost/certificate.py @@ -881,9 +881,9 @@ def _check_domain_is_ready_for_ACME(domain): # Fallback to wildcard in case no result yet for the DNS name? if not A_record_status: - A_record_status = dnsrecords.get("data").get(f"A:*") + A_record_status = dnsrecords.get("data").get("A:*") if not AAAA_record_status: - AAAA_record_status = dnsrecords.get("data").get(f"AAAA:*") + AAAA_record_status = dnsrecords.get("data").get("AAAA:*") if ( not httpreachable From 5c309ecc14edce88d3769fedec3bab70c530d619 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 22:30:44 +0200 Subject: [PATCH 25/81] Update changelog for 4.3.1 --- debian/changelog | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/debian/changelog b/debian/changelog index e6bd5180e..84a29ed70 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,18 @@ +yunohost (4.3.1) testing; urgency=low + + - [fix] diagnosis: new app diagnosis grep reporing comments as issues ([#1333](https://github.com/YunoHost/yunohost/pull/1333)) + - [enh] configpanel: Bind function for hotspot (79126809) + - [enh] cli: Rework/improve prompt mecanic ([#1338](https://github.com/YunoHost/yunohost/pull/1338)) + - [fix] dyndns update broke because of buggy dns record names (da1b9089) + - [enh] dns: general improvement for special-use TLD / ynh dyndns domains (17aafe6f) + - [fix] yunomdns: various fixes/improvements ([#1335](https://github.com/YunoHost/yunohost/pull/1335)) + - [fix] certs: Adapt ready_for_ACME check to the new dnsrecord result format... (d75c1a61) + - [i18n] Translations updated for French + + Thanks to all contributors <3 ! (Éric Gaspar, Félix Piédallu, Kayou, ljf, tituspijean) + + -- Alexandre Aubin Wed, 29 Sep 2021 22:22:42 +0200 + yunohost (4.3.0) testing; urgency=low - [users] Import/export users from/to CSV ([#1089](https://github.com/YunoHost/yunohost/pull/1089)) From 80661ddca9bd2b997fb5ad80dc3454c03e9f910f Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 29 Sep 2021 22:43:38 +0200 Subject: [PATCH 26/81] debian: Bump moulinette/ssowat version requirements --- debian/control | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debian/control b/debian/control index 90bac0a0d..fe18b1de8 100644 --- a/debian/control +++ b/debian/control @@ -10,7 +10,7 @@ Package: yunohost Essential: yes Architecture: all Depends: ${python3:Depends}, ${misc:Depends} - , moulinette (>= 4.2), ssowat (>= 4.0) + , moulinette (>= 4.3), ssowat (>= 4.3) , python3-psutil, python3-requests, python3-dnspython, python3-openssl , python3-miniupnpc, python3-dbus, python3-jinja2 , python3-toml, python3-packaging, python3-publicsuffix, From f78167a99cb721b3dd18224179ffc94e36b5de6b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Thu, 30 Sep 2021 01:08:22 +0200 Subject: [PATCH 27/81] swag: Add test coverage badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9fc93740d..b256bb563 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@
[![Build status](https://shields.io/gitlab/pipeline/yunohost/yunohost/dev)](https://gitlab.com/yunohost/yunohost/-/pipelines) +![Test coverage](https://img.shields.io/gitlab/coverage/yunohost/yunohost/dev) [![GitHub license](https://img.shields.io/github/license/YunoHost/yunohost)](https://github.com/YunoHost/yunohost/blob/dev/LICENSE) [![Mastodon Follow](https://img.shields.io/mastodon/follow/28084)](https://mastodon.social/@yunohost) From 8cdd5e43d743fcba0cb2ec1b53a454787eb5ffb6 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 02:18:35 +0200 Subject: [PATCH 28/81] Simplify / fix inconsistencies in app files kept after install/upgrade --- src/yunohost/app.py | 77 ++++++++++++--------------------------------- 1 file changed, 20 insertions(+), 57 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 56e4c344b..c111de405 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -79,6 +79,17 @@ re_app_instance_name = re.compile( r"^(?P[\w-]+?)(__(?P[1-9][0-9]*))?$" ) +APP_FILES_TO_COPY = [ + "manifest.json", + "manifest.toml", + "actions.json", + "actions.toml", + "config_panel.toml", + "scripts", + "conf", + "hooks", + "doc", +] def app_catalog(full=False, with_categories=False): """ @@ -710,38 +721,11 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False hook_add(app_instance_name, extracted_app_folder + "/hooks/" + hook) # Replace scripts and manifest and conf (if exists) - os.system( - 'rm -rf "%s/scripts" "%s/manifest.toml %s/manifest.json %s/conf"' - % ( - app_setting_path, - app_setting_path, - app_setting_path, - app_setting_path, - ) - ) - - if os.path.exists(os.path.join(extracted_app_folder, "manifest.json")): - os.system( - 'mv "%s/manifest.json" "%s/scripts" %s' - % (extracted_app_folder, extracted_app_folder, app_setting_path) - ) - if os.path.exists(os.path.join(extracted_app_folder, "manifest.toml")): - os.system( - 'mv "%s/manifest.toml" "%s/scripts" %s' - % (extracted_app_folder, extracted_app_folder, app_setting_path) - ) - - for file_to_copy in [ - "actions.json", - "actions.toml", - "config_panel.toml", - "conf", - ]: + # Move scripts and manifest to the right place + for file_to_copy in APP_FILES_TO_COPY: + os.system(f"rm -rf '{app_setting_path}/{file_to_copy}'") if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - os.system( - "cp -R %s/%s %s" - % (extracted_app_folder, file_to_copy, app_setting_path) - ) + os.system(f"cp -R '{extracted_app_folder}/{file_to_copy} {app_setting_path}'") # Clean and set permissions shutil.rmtree(extracted_app_folder) @@ -945,23 +929,9 @@ def app_install( _set_app_settings(app_instance_name, app_settings) # Move scripts and manifest to the right place - if os.path.exists(os.path.join(extracted_app_folder, "manifest.json")): - os.system("cp %s/manifest.json %s" % (extracted_app_folder, app_setting_path)) - if os.path.exists(os.path.join(extracted_app_folder, "manifest.toml")): - os.system("cp %s/manifest.toml %s" % (extracted_app_folder, app_setting_path)) - os.system("cp -R %s/scripts %s" % (extracted_app_folder, app_setting_path)) - - for file_to_copy in [ - "actions.json", - "actions.toml", - "config_panel.toml", - "conf", - ]: + for file_to_copy in APP_FILES_TO_COPY: if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - os.system( - "cp -R %s/%s %s" - % (extracted_app_folder, file_to_copy, app_setting_path) - ) + os.system(f"cp -R '{extracted_app_folder}/{file_to_copy}' '{app_setting_path}'" # Initialize the main permission for the app # The permission is initialized with no url associated, and with tile disabled @@ -1038,11 +1008,7 @@ def app_install( logger.warning(m18n.n("app_remove_after_failed_install")) # Setup environment for remove script - env_dict_remove = {} - env_dict_remove["YNH_APP_ID"] = app_id - env_dict_remove["YNH_APP_INSTANCE_NAME"] = app_instance_name - env_dict_remove["YNH_APP_INSTANCE_NUMBER"] = str(instance_number) - env_dict_remove["YNH_APP_MANIFEST_VERSION"] = manifest.get("version", "?") + env_dict_remove = _make_environment_for_app_script(app_instance_name) env_dict_remove["YNH_APP_BASEDIR"] = extracted_app_folder # Execute remove script @@ -1156,12 +1122,9 @@ def app_remove(operation_logger, app, purge=False): env_dict = {} app_id, app_instance_nb = _parse_app_instance_name(app) - env_dict["YNH_APP_ID"] = app_id - env_dict["YNH_APP_INSTANCE_NAME"] = app - env_dict["YNH_APP_INSTANCE_NUMBER"] = str(app_instance_nb) - env_dict["YNH_APP_MANIFEST_VERSION"] = manifest.get("version", "?") - env_dict["YNH_APP_PURGE"] = str(1 if purge else 0) + env_dict = _make_environment_for_app_script(app) env_dict["YNH_APP_BASEDIR"] = tmp_workdir_for_app + env_dict["YNH_APP_PURGE"] = str(1 if purge else 0) operation_logger.extra.update({"env": env_dict}) operation_logger.flush() From a1ff2ced37a3ef01966e359dfeebe62114f28673 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 02:21:31 +0200 Subject: [PATCH 29/81] Clarify code that extract app from folder/gitrepo + misc other small refactors --- src/yunohost/app.py | 364 ++++++++++++++++++++------------------------ 1 file changed, 163 insertions(+), 201 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index c111de405..88deb5b6b 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -566,22 +566,22 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False if file and isinstance(file, dict): # We use this dirty hack to test chained upgrades in unit/functional tests - manifest, extracted_app_folder = _extract_app_from_file( - file[app_instance_name] - ) + new_app_src = file[app_instance_name] elif file: - manifest, extracted_app_folder = _extract_app_from_file(file) + new_app_src = file elif url: - manifest, extracted_app_folder = _fetch_app_from_git(url) + new_app_src = url elif app_dict["upgradable"] == "url_required": logger.warning(m18n.n("custom_app_url_required", app=app_instance_name)) continue elif app_dict["upgradable"] == "yes" or force: - manifest, extracted_app_folder = _fetch_app_from_git(app_instance_name) + new_app_src = app_dict["id"] else: logger.success(m18n.n("app_already_up_to_date", app=app_instance_name)) continue + manifest, extracted_app_folder = _extract_app(new_app_src) + # Manage upgrade type and avoid any upgrade if there is nothing to do upgrade_type = "UNKNOWN" # Get current_version and new version @@ -748,12 +748,7 @@ def app_manifest(app): raw_app_list = _load_apps_catalog()["apps"] - if app in raw_app_list or ("@" in app) or ("http://" in app) or ("https://" in app): - manifest, extracted_app_folder = _fetch_app_from_git(app) - elif os.path.exists(app): - manifest, extracted_app_folder = _extract_app_from_file(app) - else: - raise YunohostValidationError("app_unknown") + manifest, extracted_app_folder = _extract_app(app) shutil.rmtree(extracted_app_folder) @@ -796,19 +791,28 @@ def app_install( ) from yunohost.regenconf import manually_modified_files - def confirm_install(confirm): + # Check if disk space available + if free_space_in_directory("/") <= 512 * 1000 * 1000: + raise YunohostValidationError("disk_space_not_sufficient_install") + + def confirm_install(app): + # Ignore if there's nothing for confirm (good quality app), if --force is used # or if request on the API (confirm already implemented on the API side) - if confirm is None or force or Moulinette.interface.type == "api": + if force or Moulinette.interface.type == "api": + return + + quality = app_quality(app) + if quality == "success": return # i18n: confirm_app_install_warning # i18n: confirm_app_install_danger # i18n: confirm_app_install_thirdparty - if confirm in ["danger", "thirdparty"]: + if quality in ["danger", "thirdparty"]: answer = Moulinette.prompt( - m18n.n("confirm_app_install_" + confirm, answers="Yes, I understand"), + m18n.n("confirm_app_install_" + quality, answers="Yes, I understand"), color="red", ) if answer != "Yes, I understand": @@ -816,51 +820,13 @@ def app_install( else: answer = Moulinette.prompt( - m18n.n("confirm_app_install_" + confirm, answers="Y/N"), color="yellow" + m18n.n("confirm_app_install_" + quality, answers="Y/N"), color="yellow" ) if answer.upper() != "Y": raise YunohostError("aborting") - raw_app_list = _load_apps_catalog()["apps"] - - if app in raw_app_list or ("@" in app) or ("http://" in app) or ("https://" in app): - - # If we got an app name directly (e.g. just "wordpress"), we gonna test this name - if app in raw_app_list: - app_name_to_test = app - # If we got an url like "https://github.com/foo/bar_ynh, we want to - # extract "bar" and test if we know this app - elif ("http://" in app) or ("https://" in app): - app_name_to_test = app.strip("/").split("/")[-1].replace("_ynh", "") - else: - # FIXME : watdo if '@' in app ? - app_name_to_test = None - - if app_name_to_test in raw_app_list: - - state = raw_app_list[app_name_to_test].get("state", "notworking") - level = raw_app_list[app_name_to_test].get("level", None) - confirm = "danger" - if state in ["working", "validated"]: - if isinstance(level, int) and level >= 5: - confirm = None - elif isinstance(level, int) and level > 0: - confirm = "warning" - else: - confirm = "thirdparty" - - confirm_install(confirm) - - manifest, extracted_app_folder = _fetch_app_from_git(app) - elif os.path.exists(app): - confirm_install("thirdparty") - manifest, extracted_app_folder = _extract_app_from_file(app) - else: - raise YunohostValidationError("app_unknown") - - # Check if disk space available - if free_space_in_directory("/") <= 512 * 1000 * 1000: - raise YunohostValidationError("disk_space_not_sufficient_install") + confirm_install(app) + manifest, extracted_app_folder = _extract_app(app) # Check ID if "id" not in manifest or "__" in manifest["id"] or "." in manifest["id"]: @@ -874,7 +840,7 @@ def app_install( _assert_system_is_sane_for_app(manifest, "pre") # Check if app can be forked - instance_number = _installed_instance_number(app_id, last=True) + 1 + instance_number = _next_instance_number_for_app(app_id) if instance_number > 1: if "multi_instance" not in manifest or not is_true(manifest["multi_instance"]): raise YunohostValidationError("app_already_installed", app=app_id) @@ -1914,55 +1880,6 @@ def _set_app_settings(app_id, settings): yaml.safe_dump(settings, f, default_flow_style=False) -def _extract_app_from_file(path): - """ - Unzip / untar / copy application tarball or directory to a tmp work directory - - Keyword arguments: - path -- Path of the tarball or directory - """ - logger.debug(m18n.n("extracting")) - - path = os.path.abspath(path) - - extracted_app_folder = _make_tmp_workdir_for_app() - - if ".zip" in path: - extract_result = os.system( - f"unzip '{path}' -d {extracted_app_folder} > /dev/null 2>&1" - ) - elif ".tar" in path: - extract_result = os.system( - f"tar -xf '{path}' -C {extracted_app_folder} > /dev/null 2>&1" - ) - elif os.path.isdir(path): - shutil.rmtree(extracted_app_folder) - if path[-1] != "/": - path = path + "/" - extract_result = os.system(f"cp -a '{path}' {extracted_app_folder}") - else: - extract_result = 1 - - if extract_result != 0: - raise YunohostError("app_extraction_failed") - - try: - if len(os.listdir(extracted_app_folder)) == 1: - for folder in os.listdir(extracted_app_folder): - extracted_app_folder = extracted_app_folder + "/" + folder - manifest = _get_manifest_of_app(extracted_app_folder) - manifest["lastUpdate"] = int(time.time()) - except IOError: - raise YunohostError("app_install_files_invalid") - except ValueError as e: - raise YunohostError("app_manifest_invalid", error=e) - - logger.debug(m18n.n("done")) - - manifest["remote"] = {"type": "file", "path": path} - return manifest, extracted_app_folder - - def _get_manifest_of_app(path): "Get app manifest stored in json or in toml" @@ -2158,143 +2075,169 @@ def _set_default_ask_questions(arguments): return arguments -def _get_git_last_commit_hash(repository, reference="HEAD"): +def _app_quality(app: str) -> str: """ - Attempt to retrieve the last commit hash of a git repository - - Keyword arguments: - repository -- The URL or path of the repository - + app may in fact be an app name, an url, or a path """ - try: - cmd = "git ls-remote --exit-code {0} {1} | awk '{{print $1}}'".format( - repository, reference - ) - commit = check_output(cmd) - except subprocess.CalledProcessError: - logger.error("unable to get last commit from %s", repository) - raise ValueError("Unable to get last commit with git") + + raw_app_catalog = _load_apps_catalog()["apps"] + if app in raw_app_catalog or ("@" in app) or ("http://" in app) or ("https://" in app): + + # If we got an app name directly (e.g. just "wordpress"), we gonna test this name + if app in raw_app_list: + app_name_to_test = app + # If we got an url like "https://github.com/foo/bar_ynh, we want to + # extract "bar" and test if we know this app + elif ("http://" in app) or ("https://" in app): + app_name_to_test = app.strip("/").split("/")[-1].replace("_ynh", "") + else: + # FIXME : watdo if '@' in app ? + app_name_to_test = None + + if app_name_to_test in raw_app_list: + + state = raw_app_list[app_name_to_test].get("state", "notworking") + level = raw_app_list[app_name_to_test].get("level", None) + if state in ["working", "validated"]: + if isinstance(level, int) and level >= 5: + return "success" + elif isinstance(level, int) and level > 0: + return "warning" + return "danger" + else: + return "thirdparty" + + elif os.path.exists(app): + return "thirdparty" else: - return commit.strip() + raise YunohostValidationError("app_unknown") -def _fetch_app_from_git(app): +def _extract_app(src: str) -> Tuple[Dict, str]: """ - Unzip or untar application tarball to a tmp directory - - Keyword arguments: - app -- App_id or git repo URL + src may be an app name, an url, or a path """ - # Extract URL, branch and revision to download - if ("@" in app) or ("http://" in app) or ("https://" in app): - url = app - branch = "master" - if "/tree/" in url: - url, branch = url.split("/tree/", 1) - revision = "HEAD" - else: - app_dict = _load_apps_catalog()["apps"] + raw_app_catalog = _load_apps_catalog()["apps"] - app_id, _ = _parse_app_instance_name(app) - - if app_id not in app_dict: - raise YunohostValidationError("app_unknown") - elif "git" not in app_dict[app_id]: + # App is an appname in the catalog + if src in raw_app_catalog: + if "git" not in raw_app_catalog[src]: raise YunohostValidationError("app_unsupported_remote_type") - app_info = app_dict[app_id] + app_info = raw_app_catalog[src] url = app_info["git"]["url"] branch = app_info["git"]["branch"] revision = str(app_info["git"]["revision"]) + return _extract_app_from_gitrepo(url, branch, revision, app_info) + # App is a git repo url + elif ("@" in src) or ("http://" in src) or ("https://" in src): + url = src + branch = "master" + revision = "HEAD" + if "/tree/" in url: + url, branch = url.split("/tree/", 1) + return _extract_app_from_gitrepo(url, branch, revision, {}) + # App is a local folder + elif os.path.exists(src): + return _extract_app_from_folder(src) + else: + raise YunohostValidationError("app_unknown") + + +def _extract_app_from_folder(path: str) -> Tuple[Dict, str]: + """ + Unzip / untar / copy application tarball or directory to a tmp work directory + + Keyword arguments: + path -- Path of the tarball or directory + """ + logger.debug(m18n.n("extracting")) + + path = os.path.abspath(path) extracted_app_folder = _make_tmp_workdir_for_app() + if ".zip" in path: + extract_result = os.system( + f"unzip '{path}' -d {extracted_app_folder} > /dev/null 2>&1" + ) + elif ".tar" in path: + extract_result = os.system( + f"tar -xf '{path}' -C {extracted_app_folder} > /dev/null 2>&1" + ) + elif os.path.isdir(path): + shutil.rmtree(extracted_app_folder) + if path[-1] != "/": + path = path + "/" + extract_result = os.system(f"cp -a '{path}' {extracted_app_folder}") + else: + extract_result = 1 + + if extract_result != 0: + raise YunohostError("app_extraction_failed") + + try: + if len(os.listdir(extracted_app_folder)) == 1: + for folder in os.listdir(extracted_app_folder): + extracted_app_folder = extracted_app_folder + "/" + folder + except IOError: + raise YunohostError("app_install_files_invalid") + + manifest = _get_manifest_of_app(extracted_app_folder) + manifest["lastUpdate"] = int(time.time()) + + logger.debug(m18n.n("done")) + + manifest["remote"] = {"type": "file", "path": path} + return manifest, extracted_app_folder + + +def _extract_app_from_gitrepo(url: str, branch: str, revision: str, app_info={}: Dict) -> Tuple[Dict, str]: + logger.debug(m18n.n("downloading")) + extracted_app_folder = _make_tmp_workdir_for_app() + # Download only this commit try: # We don't use git clone because, git clone can't download # a specific revision only + ref = branch if revision == "HEAD" else revision run_commands([["git", "init", extracted_app_folder]], shell=False) run_commands( [ ["git", "remote", "add", "origin", url], - [ - "git", - "fetch", - "--depth=1", - "origin", - branch if revision == "HEAD" else revision, - ], + ["git", "fetch", "--depth=1", "origin", ref], ["git", "reset", "--hard", "FETCH_HEAD"], ], cwd=extracted_app_folder, shell=False, ) - manifest = _get_manifest_of_app(extracted_app_folder) except subprocess.CalledProcessError: raise YunohostError("app_sources_fetch_failed") - except ValueError as e: - raise YunohostError("app_manifest_invalid", error=e) else: logger.debug(m18n.n("done")) + manifest = _get_manifest_of_app(extracted_app_folder) + # Store remote repository info into the returned manifest manifest["remote"] = {"type": "git", "url": url, "branch": branch} if revision == "HEAD": try: - manifest["remote"]["revision"] = _get_git_last_commit_hash(url, branch) + # Get git last commit hash + cmd = f"git ls-remote --exit-code {url} {branch} | awk '{{print $1}}'" + manifest["remote"]["revision"] = check_output(cmd) except Exception as e: - logger.debug("cannot get last commit hash because: %s ", e) + logger.warning("cannot get last commit hash because: %s ", e) else: manifest["remote"]["revision"] = revision - manifest["lastUpdate"] = app_info["lastUpdate"] + manifest["lastUpdate"] = app_info.get("lastUpdate") return manifest, extracted_app_folder -def _installed_instance_number(app, last=False): - """ - Check if application is installed and return instance number - - Keyword arguments: - app -- id of App to check - last -- Return only last instance number - - Returns: - Number of last installed instance | List or instances - - """ - if last: - number = 0 - try: - installed_apps = os.listdir(APPS_SETTING_PATH) - except OSError: - os.makedirs(APPS_SETTING_PATH) - return 0 - - for installed_app in installed_apps: - if number == 0 and app == installed_app: - number = 1 - elif "__" in installed_app: - if app == installed_app[: installed_app.index("__")]: - if int(installed_app[installed_app.index("__") + 2 :]) > number: - number = int(installed_app[installed_app.index("__") + 2 :]) - - return number - - else: - instance_number_list = [] - instances_dict = app_map(app=app, raw=True) - for key, domain in instances_dict.items(): - for key, path in domain.items(): - instance_number_list.append(path["instance"]) - - return sorted(instance_number_list) - - -def _is_installed(app): +def _is_installed(app: str) -> bool: """ Check if application is installed @@ -2308,18 +2251,18 @@ def _is_installed(app): return os.path.isdir(APPS_SETTING_PATH + app) -def _assert_is_installed(app): +def _assert_is_installed(app: str) -> None: if not _is_installed(app): raise YunohostValidationError( "app_not_installed", app=app, all_apps=_get_all_installed_apps_id() ) -def _installed_apps(): +def _installed_apps() -> List[str]: return os.listdir(APPS_SETTING_PATH) -def _check_manifest_requirements(manifest, app_instance_name): +def _check_manifest_requirements(manifest: Dict, app: str): """Check if required packages are met from the manifest""" packaging_format = int(manifest.get("packaging_format", 0)) @@ -2331,7 +2274,7 @@ def _check_manifest_requirements(manifest, app_instance_name): if not requirements: return - logger.debug(m18n.n("app_requirements_checking", app=app_instance_name)) + logger.debug(m18n.n("app_requirements_checking", app=app)) # Iterate over requirements for pkgname, spec in requirements.items(): @@ -2342,7 +2285,7 @@ def _check_manifest_requirements(manifest, app_instance_name): pkgname=pkgname, version=version, spec=spec, - app=app_instance_name, + app=app, ) @@ -2513,6 +2456,25 @@ def _parse_app_instance_name(app_instance_name): return (appid, app_instance_nb) +def _next_instance_number_for_app(app): + + # Get list of sibling apps, such as {app}, {app}__2, {app}__4 + apps = _installed_apps() + sibling_app_ids = [a for a in apps if a == app or a.startswith(f"{app}__")] + + # Find the list of ids, such as [1, 2, 4] + sibling_ids = [_parse_app_instance_name(a)[1] for a in sibling_app_ids] + + # Find the first 'i' that's not in the sibling_ids list already + i = 1 + while True: + if i not in sibling_ids: + return i + else: + i += 1 + + + # # ############################### # # Applications list management # From f84d8618bcc01bcd6f569723b7db8bc9e146a16b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 02:22:23 +0200 Subject: [PATCH 30/81] Offload legacy app patching stuff to utils/legacy.py to limit the size of app.py --- src/yunohost/app.py | 212 +---------------- src/yunohost/backup.py | 6 +- .../0016_php70_to_php73_pools.py | 3 +- src/yunohost/utils/legacy.py | 217 +++++++++++++++++- 4 files changed, 222 insertions(+), 216 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 88deb5b6b..011c953e0 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -534,6 +534,7 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False ) from yunohost.permission import permission_sync_to_user from yunohost.regenconf import manually_modified_files + from yunohost.utils.legacy import _patch_legacy_php_versions, _patch_legacy_helpers apps = app # Check if disk space available @@ -790,6 +791,7 @@ def app_install( permission_sync_to_user, ) from yunohost.regenconf import manually_modified_files + from yunohost.utils.legacy import _patch_legacy_php_versions, _patch_legacy_helpers # Check if disk space available if free_space_in_directory("/") <= 512 * 1000 * 1000: @@ -2769,213 +2771,3 @@ def _assert_system_is_sane_for_app(manifest, when): raise YunohostValidationError("dpkg_is_broken") elif when == "post": raise YunohostError("this_action_broke_dpkg") - - -LEGACY_PHP_VERSION_REPLACEMENTS = [ - ("/etc/php5", "/etc/php/7.3"), - ("/etc/php/7.0", "/etc/php/7.3"), - ("/var/run/php5-fpm", "/var/run/php/php7.3-fpm"), - ("/var/run/php/php7.0-fpm", "/var/run/php/php7.3-fpm"), - ("php5", "php7.3"), - ("php7.0", "php7.3"), - ( - 'phpversion="${phpversion:-7.0}"', - 'phpversion="${phpversion:-7.3}"', - ), # Many helpers like the composer ones use 7.0 by default ... - ( - '"$phpversion" == "7.0"', - '$(bc <<< "$phpversion >= 7.3") -eq 1', - ), # patch ynh_install_php to refuse installing/removing php <= 7.3 -] - - -def _patch_legacy_php_versions(app_folder): - - files_to_patch = [] - files_to_patch.extend(glob.glob("%s/conf/*" % app_folder)) - files_to_patch.extend(glob.glob("%s/scripts/*" % app_folder)) - files_to_patch.extend(glob.glob("%s/scripts/*/*" % app_folder)) - files_to_patch.extend(glob.glob("%s/scripts/.*" % app_folder)) - files_to_patch.append("%s/manifest.json" % app_folder) - files_to_patch.append("%s/manifest.toml" % app_folder) - - for filename in files_to_patch: - - # Ignore non-regular files - if not os.path.isfile(filename): - continue - - c = ( - "sed -i " - + "".join( - "-e 's@{pattern}@{replace}@g' ".format(pattern=p, replace=r) - for p, r in LEGACY_PHP_VERSION_REPLACEMENTS - ) - + "%s" % filename - ) - os.system(c) - - -def _patch_legacy_php_versions_in_settings(app_folder): - - settings = read_yaml(os.path.join(app_folder, "settings.yml")) - - if settings.get("fpm_config_dir") == "/etc/php/7.0/fpm": - settings["fpm_config_dir"] = "/etc/php/7.3/fpm" - if settings.get("fpm_service") == "php7.0-fpm": - settings["fpm_service"] = "php7.3-fpm" - if settings.get("phpversion") == "7.0": - settings["phpversion"] = "7.3" - - # We delete these checksums otherwise the file will appear as manually modified - list_to_remove = ["checksum__etc_php_7.0_fpm_pool", "checksum__etc_nginx_conf.d"] - settings = { - k: v - for k, v in settings.items() - if not any(k.startswith(to_remove) for to_remove in list_to_remove) - } - - write_to_yaml(app_folder + "/settings.yml", settings) - - -def _patch_legacy_helpers(app_folder): - - files_to_patch = [] - files_to_patch.extend(glob.glob("%s/scripts/*" % app_folder)) - files_to_patch.extend(glob.glob("%s/scripts/.*" % app_folder)) - - stuff_to_replace = { - # Replace - # sudo yunohost app initdb $db_user -p $db_pwd - # by - # ynh_mysql_setup_db --db_user=$db_user --db_name=$db_user --db_pwd=$db_pwd - "yunohost app initdb": { - "pattern": r"(sudo )?yunohost app initdb \"?(\$\{?\w+\}?)\"?\s+-p\s\"?(\$\{?\w+\}?)\"?", - "replace": r"ynh_mysql_setup_db --db_user=\2 --db_name=\2 --db_pwd=\3", - "important": True, - }, - # Replace - # sudo yunohost app checkport whaterver - # by - # ynh_port_available whatever - "yunohost app checkport": { - "pattern": r"(sudo )?yunohost app checkport", - "replace": r"ynh_port_available", - "important": True, - }, - # We can't migrate easily port-available - # .. but at the time of writing this code, only two non-working apps are using it. - "yunohost tools port-available": {"important": True}, - # Replace - # yunohost app checkurl "${domain}${path_url}" -a "${app}" - # by - # ynh_webpath_register --app=${app} --domain=${domain} --path_url=${path_url} - "yunohost app checkurl": { - "pattern": r"(sudo )?yunohost app checkurl \"?(\$\{?\w+\}?)\/?(\$\{?\w+\}?)\"?\s+-a\s\"?(\$\{?\w+\}?)\"?", - "replace": r"ynh_webpath_register --app=\4 --domain=\2 --path_url=\3", - "important": True, - }, - # Remove - # Automatic diagnosis data from YunoHost - # __PRE_TAG1__$(yunohost tools diagnosis | ...)__PRE_TAG2__" - # - "yunohost tools diagnosis": { - "pattern": r"(Automatic diagnosis data from YunoHost( *\n)*)? *(__\w+__)? *\$\(yunohost tools diagnosis.*\)(__\w+__)?", - "replace": r"", - "important": False, - }, - # Old $1, $2 in backup/restore scripts... - "app=$2": { - "only_for": ["scripts/backup", "scripts/restore"], - "pattern": r"app=\$2", - "replace": r"app=$YNH_APP_INSTANCE_NAME", - "important": True, - }, - # Old $1, $2 in backup/restore scripts... - "backup_dir=$1": { - "only_for": ["scripts/backup", "scripts/restore"], - "pattern": r"backup_dir=\$1", - "replace": r"backup_dir=.", - "important": True, - }, - # Old $1, $2 in backup/restore scripts... - "restore_dir=$1": { - "only_for": ["scripts/restore"], - "pattern": r"restore_dir=\$1", - "replace": r"restore_dir=.", - "important": True, - }, - # Old $1, $2 in install scripts... - # We ain't patching that shit because it ain't trivial to patch all args... - "domain=$1": {"only_for": ["scripts/install"], "important": True}, - } - - for helper, infos in stuff_to_replace.items(): - infos["pattern"] = ( - re.compile(infos["pattern"]) if infos.get("pattern") else None - ) - infos["replace"] = infos.get("replace") - - for filename in files_to_patch: - - # Ignore non-regular files - if not os.path.isfile(filename): - continue - - try: - content = read_file(filename) - except MoulinetteError: - continue - - replaced_stuff = False - show_warning = False - - for helper, infos in stuff_to_replace.items(): - - # Ignore if not relevant for this file - if infos.get("only_for") and not any( - filename.endswith(f) for f in infos["only_for"] - ): - continue - - # If helper is used, attempt to patch the file - if helper in content and infos["pattern"]: - content = infos["pattern"].sub(infos["replace"], content) - replaced_stuff = True - if infos["important"]: - show_warning = True - - # If the helper is *still* in the content, it means that we - # couldn't patch the deprecated helper in the previous lines. In - # that case, abort the install or whichever step is performed - if helper in content and infos["important"]: - raise YunohostValidationError( - "This app is likely pretty old and uses deprecated / outdated helpers that can't be migrated easily. It can't be installed anymore.", - raw_msg=True, - ) - - if replaced_stuff: - - # Check the app do load the helper - # If it doesn't, add the instruction ourselve (making sure it's after the #!/bin/bash if it's there... - if filename.split("/")[-1] in [ - "install", - "remove", - "upgrade", - "backup", - "restore", - ]: - source_helpers = "source /usr/share/yunohost/helpers" - if source_helpers not in content: - content.replace("#!/bin/bash", "#!/bin/bash\n" + source_helpers) - if source_helpers not in content: - content = source_helpers + "\n" + content - - # Actually write the new content in the file - write_to_file(filename, content) - - if show_warning: - # And complain about those damn deprecated helpers - logger.error( - r"/!\ Packagers ! This app uses a very old deprecated helpers ... Yunohost automatically patched the helpers to use the new recommended practice, but please do consider fixing the upstream code right now ..." - ) diff --git a/src/yunohost/backup.py b/src/yunohost/backup.py index a47fba5f7..b650cb3da 100644 --- a/src/yunohost/backup.py +++ b/src/yunohost/backup.py @@ -49,10 +49,6 @@ from yunohost.app import ( app_info, _is_installed, _make_environment_for_app_script, - _patch_legacy_helpers, - _patch_legacy_php_versions, - _patch_legacy_php_versions_in_settings, - LEGACY_PHP_VERSION_REPLACEMENTS, _make_tmp_workdir_for_app, ) from yunohost.hook import ( @@ -1190,6 +1186,7 @@ class RestoreManager: """ Apply dirty patch to redirect php5 and php7.0 files to php7.3 """ + from yunohost.utils.legacy import LEGACY_PHP_VERSION_REPLACEMENTS backup_csv = os.path.join(self.work_dir, "backup.csv") @@ -1351,6 +1348,7 @@ class RestoreManager: app_instance_name -- (string) The app name to restore (no app with this name should be already install) """ + from yunohost.utils.legacy import _patch_legacy_php_versions, _patch_legacy_php_versions_in_settings, _patch_legacy_helpers from yunohost.user import user_group_list from yunohost.permission import ( permission_create, diff --git a/src/yunohost/data_migrations/0016_php70_to_php73_pools.py b/src/yunohost/data_migrations/0016_php70_to_php73_pools.py index 6b424f211..fed96c9c8 100644 --- a/src/yunohost/data_migrations/0016_php70_to_php73_pools.py +++ b/src/yunohost/data_migrations/0016_php70_to_php73_pools.py @@ -4,7 +4,8 @@ from shutil import copy2 from moulinette.utils.log import getActionLogger -from yunohost.app import _is_installed, _patch_legacy_php_versions_in_settings +from yunohost.app import _is_installed +from yunohost.utils.legacy import _patch_legacy_php_versions_in_settings from yunohost.tools import Migration from yunohost.service import _run_service_command diff --git a/src/yunohost/utils/legacy.py b/src/yunohost/utils/legacy.py index eb92dd71f..7ae98bed8 100644 --- a/src/yunohost/utils/legacy.py +++ b/src/yunohost/utils/legacy.py @@ -1,7 +1,10 @@ import os +import re +import glob from moulinette import m18n +from moulinette.core import MoulinetteError from moulinette.utils.log import getActionLogger -from moulinette.utils.filesystem import write_to_json, read_yaml +from moulinette.utils.filesystem import read_file, write_to_file, write_to_json, write_to_yaml, read_yaml from yunohost.user import user_list from yunohost.app import ( @@ -14,6 +17,8 @@ from yunohost.permission import ( user_permission_update, permission_sync_to_user, ) +from yunohost.utils.error import YunohostValidationError + logger = getActionLogger("yunohost.legacy") @@ -237,3 +242,213 @@ def translate_legacy_rules_in_ssowant_conf_json_persistent(): logger.warning( "YunoHost automatically translated some legacy rules in /etc/ssowat/conf.json.persistent to match the new permission system" ) + + +LEGACY_PHP_VERSION_REPLACEMENTS = [ + ("/etc/php5", "/etc/php/7.3"), + ("/etc/php/7.0", "/etc/php/7.3"), + ("/var/run/php5-fpm", "/var/run/php/php7.3-fpm"), + ("/var/run/php/php7.0-fpm", "/var/run/php/php7.3-fpm"), + ("php5", "php7.3"), + ("php7.0", "php7.3"), + ( + 'phpversion="${phpversion:-7.0}"', + 'phpversion="${phpversion:-7.3}"', + ), # Many helpers like the composer ones use 7.0 by default ... + ( + '"$phpversion" == "7.0"', + '$(bc <<< "$phpversion >= 7.3") -eq 1', + ), # patch ynh_install_php to refuse installing/removing php <= 7.3 +] + + +def _patch_legacy_php_versions(app_folder): + + files_to_patch = [] + files_to_patch.extend(glob.glob("%s/conf/*" % app_folder)) + files_to_patch.extend(glob.glob("%s/scripts/*" % app_folder)) + files_to_patch.extend(glob.glob("%s/scripts/*/*" % app_folder)) + files_to_patch.extend(glob.glob("%s/scripts/.*" % app_folder)) + files_to_patch.append("%s/manifest.json" % app_folder) + files_to_patch.append("%s/manifest.toml" % app_folder) + + for filename in files_to_patch: + + # Ignore non-regular files + if not os.path.isfile(filename): + continue + + c = ( + "sed -i " + + "".join( + "-e 's@{pattern}@{replace}@g' ".format(pattern=p, replace=r) + for p, r in LEGACY_PHP_VERSION_REPLACEMENTS + ) + + "%s" % filename + ) + os.system(c) + + +def _patch_legacy_php_versions_in_settings(app_folder): + + settings = read_yaml(os.path.join(app_folder, "settings.yml")) + + if settings.get("fpm_config_dir") == "/etc/php/7.0/fpm": + settings["fpm_config_dir"] = "/etc/php/7.3/fpm" + if settings.get("fpm_service") == "php7.0-fpm": + settings["fpm_service"] = "php7.3-fpm" + if settings.get("phpversion") == "7.0": + settings["phpversion"] = "7.3" + + # We delete these checksums otherwise the file will appear as manually modified + list_to_remove = ["checksum__etc_php_7.0_fpm_pool", "checksum__etc_nginx_conf.d"] + settings = { + k: v + for k, v in settings.items() + if not any(k.startswith(to_remove) for to_remove in list_to_remove) + } + + write_to_yaml(app_folder + "/settings.yml", settings) + + +def _patch_legacy_helpers(app_folder): + + files_to_patch = [] + files_to_patch.extend(glob.glob("%s/scripts/*" % app_folder)) + files_to_patch.extend(glob.glob("%s/scripts/.*" % app_folder)) + + stuff_to_replace = { + # Replace + # sudo yunohost app initdb $db_user -p $db_pwd + # by + # ynh_mysql_setup_db --db_user=$db_user --db_name=$db_user --db_pwd=$db_pwd + "yunohost app initdb": { + "pattern": r"(sudo )?yunohost app initdb \"?(\$\{?\w+\}?)\"?\s+-p\s\"?(\$\{?\w+\}?)\"?", + "replace": r"ynh_mysql_setup_db --db_user=\2 --db_name=\2 --db_pwd=\3", + "important": True, + }, + # Replace + # sudo yunohost app checkport whaterver + # by + # ynh_port_available whatever + "yunohost app checkport": { + "pattern": r"(sudo )?yunohost app checkport", + "replace": r"ynh_port_available", + "important": True, + }, + # We can't migrate easily port-available + # .. but at the time of writing this code, only two non-working apps are using it. + "yunohost tools port-available": {"important": True}, + # Replace + # yunohost app checkurl "${domain}${path_url}" -a "${app}" + # by + # ynh_webpath_register --app=${app} --domain=${domain} --path_url=${path_url} + "yunohost app checkurl": { + "pattern": r"(sudo )?yunohost app checkurl \"?(\$\{?\w+\}?)\/?(\$\{?\w+\}?)\"?\s+-a\s\"?(\$\{?\w+\}?)\"?", + "replace": r"ynh_webpath_register --app=\4 --domain=\2 --path_url=\3", + "important": True, + }, + # Remove + # Automatic diagnosis data from YunoHost + # __PRE_TAG1__$(yunohost tools diagnosis | ...)__PRE_TAG2__" + # + "yunohost tools diagnosis": { + "pattern": r"(Automatic diagnosis data from YunoHost( *\n)*)? *(__\w+__)? *\$\(yunohost tools diagnosis.*\)(__\w+__)?", + "replace": r"", + "important": False, + }, + # Old $1, $2 in backup/restore scripts... + "app=$2": { + "only_for": ["scripts/backup", "scripts/restore"], + "pattern": r"app=\$2", + "replace": r"app=$YNH_APP_INSTANCE_NAME", + "important": True, + }, + # Old $1, $2 in backup/restore scripts... + "backup_dir=$1": { + "only_for": ["scripts/backup", "scripts/restore"], + "pattern": r"backup_dir=\$1", + "replace": r"backup_dir=.", + "important": True, + }, + # Old $1, $2 in backup/restore scripts... + "restore_dir=$1": { + "only_for": ["scripts/restore"], + "pattern": r"restore_dir=\$1", + "replace": r"restore_dir=.", + "important": True, + }, + # Old $1, $2 in install scripts... + # We ain't patching that shit because it ain't trivial to patch all args... + "domain=$1": {"only_for": ["scripts/install"], "important": True}, + } + + for helper, infos in stuff_to_replace.items(): + infos["pattern"] = ( + re.compile(infos["pattern"]) if infos.get("pattern") else None + ) + infos["replace"] = infos.get("replace") + + for filename in files_to_patch: + + # Ignore non-regular files + if not os.path.isfile(filename): + continue + + try: + content = read_file(filename) + except MoulinetteError: + continue + + replaced_stuff = False + show_warning = False + + for helper, infos in stuff_to_replace.items(): + + # Ignore if not relevant for this file + if infos.get("only_for") and not any( + filename.endswith(f) for f in infos["only_for"] + ): + continue + + # If helper is used, attempt to patch the file + if helper in content and infos["pattern"]: + content = infos["pattern"].sub(infos["replace"], content) + replaced_stuff = True + if infos["important"]: + show_warning = True + + # If the helper is *still* in the content, it means that we + # couldn't patch the deprecated helper in the previous lines. In + # that case, abort the install or whichever step is performed + if helper in content and infos["important"]: + raise YunohostValidationError( + "This app is likely pretty old and uses deprecated / outdated helpers that can't be migrated easily. It can't be installed anymore.", + raw_msg=True, + ) + + if replaced_stuff: + + # Check the app do load the helper + # If it doesn't, add the instruction ourselve (making sure it's after the #!/bin/bash if it's there... + if filename.split("/")[-1] in [ + "install", + "remove", + "upgrade", + "backup", + "restore", + ]: + source_helpers = "source /usr/share/yunohost/helpers" + if source_helpers not in content: + content.replace("#!/bin/bash", "#!/bin/bash\n" + source_helpers) + if source_helpers not in content: + content = source_helpers + "\n" + content + + # Actually write the new content in the file + write_to_file(filename, content) + + if show_warning: + # And complain about those damn deprecated helpers + logger.error( + r"/!\ Packagers ! This app uses a very old deprecated helpers ... Yunohost automatically patched the helpers to use the new recommended practice, but please do consider fixing the upstream code right now ..." + ) From 206b430a9f66c698821f5fc56d1cfaa967e1361c Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 02:50:30 +0200 Subject: [PATCH 31/81] Offload appcatalog stuff to a separate file to limit the size of app.py --- .gitlab/ci/test.gitlab-ci.yml | 4 +- src/yunohost/app.py | 296 ++---------------- ...est_appscatalog.py => test_app_catalog.py} | 2 +- src/yunohost/tools.py | 4 +- 4 files changed, 31 insertions(+), 275 deletions(-) rename src/yunohost/tests/{test_appscatalog.py => test_app_catalog.py} (99%) diff --git a/.gitlab/ci/test.gitlab-ci.yml b/.gitlab/ci/test.gitlab-ci.yml index 6a422ea22..1aad46fbe 100644 --- a/.gitlab/ci/test.gitlab-ci.yml +++ b/.gitlab/ci/test.gitlab-ci.yml @@ -113,10 +113,10 @@ test-apps: test-appscatalog: extends: .test-stage script: - - python3 -m pytest src/yunohost/tests/test_appscatalog.py + - python3 -m pytest src/yunohost/tests/test_app_catalog.py only: changes: - - src/yunohost/app.py + - src/yunohost/app_calalog.py test-appurl: extends: .test-stage diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 011c953e0..7cddca3e9 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -31,15 +31,12 @@ import yaml import time import re import subprocess -import glob import tempfile from collections import OrderedDict -from typing import List +from typing import List, Tuple, Dict from moulinette import Moulinette, m18n -from moulinette.core import MoulinetteError from moulinette.utils.log import getActionLogger -from moulinette.utils.network import download_json from moulinette.utils.process import run_commands, check_output from moulinette.utils.filesystem import ( read_file, @@ -48,8 +45,6 @@ from moulinette.utils.filesystem import ( read_yaml, write_to_file, write_to_json, - write_to_yaml, - mkdir, ) from yunohost.utils import packages @@ -64,17 +59,13 @@ from yunohost.utils.i18n import _value_for_locale from yunohost.utils.error import YunohostError, YunohostValidationError from yunohost.utils.filesystem import free_space_in_directory from yunohost.log import is_unit_operation, OperationLogger +from yunohost.app_catalog import app_catalog, app_search, _load_apps_catalog, app_fetchlist # noqa logger = getActionLogger("yunohost.app") APPS_SETTING_PATH = "/etc/yunohost/apps/" APP_TMP_WORKDIRS = "/var/cache/yunohost/app_tmp_work_dirs" -APPS_CATALOG_CACHE = "/var/cache/yunohost/repo" -APPS_CATALOG_CONF = "/etc/yunohost/apps_catalog.yml" -APPS_CATALOG_API_VERSION = 2 -APPS_CATALOG_DEFAULT_URL = "https://app.yunohost.org/default" - re_app_instance_name = re.compile( r"^(?P[\w-]+?)(__(?P[1-9][0-9]*))?$" ) @@ -91,80 +82,6 @@ APP_FILES_TO_COPY = [ "doc", ] -def app_catalog(full=False, with_categories=False): - """ - Return a dict of apps available to installation from Yunohost's app catalog - """ - - # Get app list from catalog cache - catalog = _load_apps_catalog() - installed_apps = set(_installed_apps()) - - # Trim info for apps if not using --full - for app, infos in catalog["apps"].items(): - infos["installed"] = app in installed_apps - - infos["manifest"]["description"] = _value_for_locale( - infos["manifest"]["description"] - ) - - if not full: - catalog["apps"][app] = { - "description": infos["manifest"]["description"], - "level": infos["level"], - } - else: - infos["manifest"]["arguments"] = _set_default_ask_questions( - infos["manifest"].get("arguments", {}) - ) - - # Trim info for categories if not using --full - for category in catalog["categories"]: - category["title"] = _value_for_locale(category["title"]) - category["description"] = _value_for_locale(category["description"]) - for subtags in category.get("subtags", []): - subtags["title"] = _value_for_locale(subtags["title"]) - - if not full: - catalog["categories"] = [ - {"id": c["id"], "description": c["description"]} - for c in catalog["categories"] - ] - - if not with_categories: - return {"apps": catalog["apps"]} - else: - return {"apps": catalog["apps"], "categories": catalog["categories"]} - - -def app_search(string): - """ - Return a dict of apps whose description or name match the search string - """ - - # Retrieve a simple dict listing all apps - catalog_of_apps = app_catalog() - - # Selecting apps according to a match in app name or description - matching_apps = {"apps": {}} - for app in catalog_of_apps["apps"].items(): - if re.search(string, app[0], flags=re.IGNORECASE) or re.search( - string, app[1]["description"], flags=re.IGNORECASE - ): - matching_apps["apps"][app[0]] = app[1] - - return matching_apps - - -# Old legacy function... -def app_fetchlist(): - logger.warning( - "'yunohost app fetchlist' is deprecated. Please use 'yunohost tools update --apps' instead" - ) - from yunohost.tools import tools_update - - tools_update(target="apps") - def app_list(full=False, installed=False, filter=None): """ @@ -1728,22 +1645,6 @@ ynh_app_config_run $1 return values -def _get_all_installed_apps_id(): - """ - Return something like: - ' * app1 - * app2 - * ...' - """ - - all_apps_ids = sorted(_installed_apps()) - - all_apps_ids_formatted = "\n * ".join(all_apps_ids) - all_apps_ids_formatted = "\n * " + all_apps_ids_formatted - - return all_apps_ids_formatted - - def _get_app_actions(app_id): "Get app config panel stored in json or in toml" actions_toml_path = os.path.join(APPS_SETTING_PATH, app_id, "actions.toml") @@ -2239,6 +2140,13 @@ def _extract_app_from_gitrepo(url: str, branch: str, revision: str, app_info={}: return manifest, extracted_app_folder +# +# ############################### # +# Small utilities # +# ############################### # +# + + def _is_installed(app: str) -> bool: """ Check if application is installed @@ -2264,6 +2172,22 @@ def _installed_apps() -> List[str]: return os.listdir(APPS_SETTING_PATH) +def _get_all_installed_apps_id(): + """ + Return something like: + ' * app1 + * app2 + * ...' + """ + + all_apps_ids = sorted(_installed_apps()) + + all_apps_ids_formatted = "\n * ".join(all_apps_ids) + all_apps_ids_formatted = "\n * " + all_apps_ids_formatted + + return all_apps_ids_formatted + + def _check_manifest_requirements(manifest: Dict, app: str): """Check if required packages are met from the manifest""" @@ -2476,176 +2400,6 @@ def _next_instance_number_for_app(app): i += 1 - -# -# ############################### # -# Applications list management # -# ############################### # -# - - -def _initialize_apps_catalog_system(): - """ - This function is meant to intialize the apps_catalog system with YunoHost's default app catalog. - """ - - default_apps_catalog_list = [{"id": "default", "url": APPS_CATALOG_DEFAULT_URL}] - - try: - logger.debug( - "Initializing apps catalog system with YunoHost's default app list" - ) - write_to_yaml(APPS_CATALOG_CONF, default_apps_catalog_list) - except Exception as e: - raise YunohostError( - "Could not initialize the apps catalog system... : %s" % str(e) - ) - - logger.success(m18n.n("apps_catalog_init_success")) - - -def _read_apps_catalog_list(): - """ - Read the json corresponding to the list of apps catalogs - """ - - try: - list_ = read_yaml(APPS_CATALOG_CONF) - # Support the case where file exists but is empty - # by returning [] if list_ is None - return list_ if list_ else [] - except Exception as e: - raise YunohostError("Could not read the apps_catalog list ... : %s" % str(e)) - - -def _actual_apps_catalog_api_url(base_url): - - return "{base_url}/v{version}/apps.json".format( - base_url=base_url, version=APPS_CATALOG_API_VERSION - ) - - -def _update_apps_catalog(): - """ - Fetches the json for each apps_catalog and update the cache - - apps_catalog_list is for example : - [ {"id": "default", "url": "https://app.yunohost.org/default/"} ] - - Then for each apps_catalog, the actual json URL to be fetched is like : - https://app.yunohost.org/default/vX/apps.json - - And store it in : - /var/cache/yunohost/repo/default.json - """ - - apps_catalog_list = _read_apps_catalog_list() - - logger.info(m18n.n("apps_catalog_updating")) - - # Create cache folder if needed - if not os.path.exists(APPS_CATALOG_CACHE): - logger.debug("Initialize folder for apps catalog cache") - mkdir(APPS_CATALOG_CACHE, mode=0o750, parents=True, uid="root") - - for apps_catalog in apps_catalog_list: - apps_catalog_id = apps_catalog["id"] - actual_api_url = _actual_apps_catalog_api_url(apps_catalog["url"]) - - # Fetch the json - try: - apps_catalog_content = download_json(actual_api_url) - except Exception as e: - raise YunohostError( - "apps_catalog_failed_to_download", - apps_catalog=apps_catalog_id, - error=str(e), - ) - - # Remember the apps_catalog api version for later - apps_catalog_content["from_api_version"] = APPS_CATALOG_API_VERSION - - # Save the apps_catalog data in the cache - cache_file = "{cache_folder}/{list}.json".format( - cache_folder=APPS_CATALOG_CACHE, list=apps_catalog_id - ) - try: - write_to_json(cache_file, apps_catalog_content) - except Exception as e: - raise YunohostError( - "Unable to write cache data for %s apps_catalog : %s" - % (apps_catalog_id, str(e)) - ) - - logger.success(m18n.n("apps_catalog_update_success")) - - -def _load_apps_catalog(): - """ - Read all the apps catalog cache files and build a single dict (merged_catalog) - corresponding to all known apps and categories - """ - - merged_catalog = {"apps": {}, "categories": []} - - for apps_catalog_id in [L["id"] for L in _read_apps_catalog_list()]: - - # Let's load the json from cache for this catalog - cache_file = "{cache_folder}/{list}.json".format( - cache_folder=APPS_CATALOG_CACHE, list=apps_catalog_id - ) - - try: - apps_catalog_content = ( - read_json(cache_file) if os.path.exists(cache_file) else None - ) - except Exception as e: - raise YunohostError( - "Unable to read cache for apps_catalog %s : %s" % (cache_file, e), - raw_msg=True, - ) - - # Check that the version of the data matches version .... - # ... otherwise it means we updated yunohost in the meantime - # and need to update the cache for everything to be consistent - if ( - not apps_catalog_content - or apps_catalog_content.get("from_api_version") != APPS_CATALOG_API_VERSION - ): - logger.info(m18n.n("apps_catalog_obsolete_cache")) - _update_apps_catalog() - apps_catalog_content = read_json(cache_file) - - del apps_catalog_content["from_api_version"] - - # Add apps from this catalog to the output - for app, info in apps_catalog_content["apps"].items(): - - # (N.B. : there's a small edge case where multiple apps catalog could be listing the same apps ... - # in which case we keep only the first one found) - if app in merged_catalog["apps"]: - logger.warning( - "Duplicate app %s found between apps catalog %s and %s" - % (app, apps_catalog_id, merged_catalog["apps"][app]["repository"]) - ) - continue - - info["repository"] = apps_catalog_id - merged_catalog["apps"][app] = info - - # Annnnd categories - merged_catalog["categories"] += apps_catalog_content["categories"] - - return merged_catalog - - -# -# ############################### # -# Small utilities # -# ############################### # -# - - def _make_tmp_workdir_for_app(app=None): # Create parent dir if it doesn't exists yet diff --git a/src/yunohost/tests/test_appscatalog.py b/src/yunohost/tests/test_app_catalog.py similarity index 99% rename from src/yunohost/tests/test_appscatalog.py rename to src/yunohost/tests/test_app_catalog.py index a2619a660..8423b868e 100644 --- a/src/yunohost/tests/test_appscatalog.py +++ b/src/yunohost/tests/test_app_catalog.py @@ -9,7 +9,7 @@ from moulinette import m18n from moulinette.utils.filesystem import read_json, write_to_json, write_to_yaml from yunohost.utils.error import YunohostError -from yunohost.app import ( +from yunohost.app_catalog import ( _initialize_apps_catalog_system, _read_apps_catalog_list, _update_apps_catalog, diff --git a/src/yunohost/tools.py b/src/yunohost/tools.py index ed8c04153..4cdd62d8f 100644 --- a/src/yunohost/tools.py +++ b/src/yunohost/tools.py @@ -37,10 +37,12 @@ from moulinette.utils.process import check_output, call_async_output from moulinette.utils.filesystem import read_yaml, write_to_yaml from yunohost.app import ( - _update_apps_catalog, app_info, app_upgrade, +) +from yunohost.app_catalog import ( _initialize_apps_catalog_system, + _update_apps_catalog, ) from yunohost.domain import domain_add from yunohost.dyndns import _dyndns_available, _dyndns_provides From 1e046dcd37a2f6d0365be4003e86622e58dd285d Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 02:50:38 +0200 Subject: [PATCH 32/81] Misc typoz --- src/yunohost/app.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 7cddca3e9..8dcb5aef3 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -609,7 +609,7 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False if upgrade_failed or broke_the_system: # display this if there are remaining apps - if apps[number + 1 :]: + if apps[number + 1:]: not_upgraded_apps = apps[number:] logger.error( m18n.n( @@ -664,8 +664,6 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False def app_manifest(app): - raw_app_list = _load_apps_catalog()["apps"] - manifest, extracted_app_folder = _extract_app(app) shutil.rmtree(extracted_app_folder) @@ -721,7 +719,7 @@ def app_install( if force or Moulinette.interface.type == "api": return - quality = app_quality(app) + quality = _app_quality(app) if quality == "success": return @@ -816,7 +814,7 @@ def app_install( # Move scripts and manifest to the right place for file_to_copy in APP_FILES_TO_COPY: if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - os.system(f"cp -R '{extracted_app_folder}/{file_to_copy}' '{app_setting_path}'" + os.system(f"cp -R '{extracted_app_folder}/{file_to_copy}' '{app_setting_path}'") # Initialize the main permission for the app # The permission is initialized with no url associated, and with tile disabled @@ -976,6 +974,7 @@ def app_remove(operation_logger, app, purge=False): purge -- Remove with all app data """ + from yunohost.utils.legacy import _patch_legacy_php_versions, _patch_legacy_helpers from yunohost.hook import hook_exec, hook_remove, hook_callback from yunohost.permission import ( user_permission_list, @@ -1987,7 +1986,7 @@ def _app_quality(app: str) -> str: if app in raw_app_catalog or ("@" in app) or ("http://" in app) or ("https://" in app): # If we got an app name directly (e.g. just "wordpress"), we gonna test this name - if app in raw_app_list: + if app in raw_app_catalog: app_name_to_test = app # If we got an url like "https://github.com/foo/bar_ynh, we want to # extract "bar" and test if we know this app @@ -1997,10 +1996,10 @@ def _app_quality(app: str) -> str: # FIXME : watdo if '@' in app ? app_name_to_test = None - if app_name_to_test in raw_app_list: + if app_name_to_test in raw_app_catalog: - state = raw_app_list[app_name_to_test].get("state", "notworking") - level = raw_app_list[app_name_to_test].get("level", None) + state = raw_app_catalog[app_name_to_test].get("state", "notworking") + level = raw_app_catalog[app_name_to_test].get("level", None) if state in ["working", "validated"]: if isinstance(level, int) and level >= 5: return "success" @@ -2096,7 +2095,7 @@ def _extract_app_from_folder(path: str) -> Tuple[Dict, str]: return manifest, extracted_app_folder -def _extract_app_from_gitrepo(url: str, branch: str, revision: str, app_info={}: Dict) -> Tuple[Dict, str]: +def _extract_app_from_gitrepo(url: str, branch: str, revision: str, app_info: Dict = {}) -> Tuple[Dict, str]: logger.debug(m18n.n("downloading")) From 80f4b892e65b6838146bc520da8feb7991327a32 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 03:05:14 +0200 Subject: [PATCH 33/81] Prevent full-domain app to be moved to a subpath with change-url ? --- src/yunohost/app.py | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 8dcb5aef3..f221e2406 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -33,7 +33,7 @@ import re import subprocess import tempfile from collections import OrderedDict -from typing import List, Tuple, Dict +from typing import List, Tuple, Dict, Any from moulinette import Moulinette, m18n from moulinette.utils.log import getActionLogger @@ -51,7 +51,6 @@ from yunohost.utils import packages from yunohost.utils.config import ( ConfigPanel, ask_questions_and_parse_answers, - Question, DomainQuestion, PathQuestion, ) @@ -384,8 +383,9 @@ def app_change_url(operation_logger, app, domain, path): "app_change_url_identical_domains", domain=domain, path=path ) - # Check the url is available - _assert_no_conflicting_apps(domain, path, ignore_app=app) + app_setting_path = os.path.join(APPS_SETTING_PATH, app) + path_requirement = _guess_webapp_path_requirement(app_setting_path) + _validate_webpath_requirement({"domain": domain, "path": path}, path_requirement, ignore_app=app) tmp_workdir_for_app = _make_tmp_workdir_for_app(app=app) @@ -777,8 +777,8 @@ def app_install( } # Validate domain / path availability for webapps - path_requirement = _guess_webapp_path_requirement(questions, extracted_app_folder) - _validate_webpath_requirement(questions, path_requirement) + path_requirement = _guess_webapp_path_requirement(extracted_app_folder) + _validate_webpath_requirement(args, path_requirement) # Attempt to patch legacy helpers ... _patch_legacy_helpers(extracted_app_folder) @@ -2214,13 +2214,16 @@ def _check_manifest_requirements(manifest: Dict, app: str): ) -def _guess_webapp_path_requirement(questions: List[Question], app_folder: str) -> str: +def _guess_webapp_path_requirement(app_folder: str) -> str: # If there's only one "domain" and "path", validate that domain/path # is an available url and normalize the path. - domain_questions = [question for question in questions if question.type == "domain"] - path_questions = [question for question in questions if question.type == "path"] + manifest = _get_manifest_of_app(app_folder) + raw_questions = manifest.get("arguments", {}).get("install", {}) + + domain_questions = [question for question in raw_questions if question.get("type") == "domain"] + path_questions = [question for question in raw_questions if question.get("type") == "path"] if len(domain_questions) == 0 and len(path_questions) == 0: return "" @@ -2248,22 +2251,17 @@ def _guess_webapp_path_requirement(questions: List[Question], app_folder: str) - def _validate_webpath_requirement( - questions: List[Question], path_requirement: str + args: Dict[str, Any], path_requirement: str, ignore_app=None ) -> None: - domain_questions = [question for question in questions if question.type == "domain"] - path_questions = [question for question in questions if question.type == "path"] + domain = args.get("domain") + path = args.get("path") if path_requirement == "domain_and_path": - - domain = domain_questions[0].value - path = path_questions[0].value - _assert_no_conflicting_apps(domain, path, full_domain=True) + _assert_no_conflicting_apps(domain, path, ignore_app=ignore_app) elif path_requirement == "full_domain": - - domain = domain_questions[0].value - _assert_no_conflicting_apps(domain, "/", full_domain=True) + _assert_no_conflicting_apps(domain, "/", full_domain=True, ignore_app=ignore_app) def _get_conflicting_apps(domain, path, ignore_app=None): From 5fc493058df2766097494b710f5f628fafaf81a2 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 03:10:26 +0200 Subject: [PATCH 34/81] Aaaaaand I forgot to commit app_catalog.py ... --- src/yunohost/app_catalog.py | 255 ++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 src/yunohost/app_catalog.py diff --git a/src/yunohost/app_catalog.py b/src/yunohost/app_catalog.py new file mode 100644 index 000000000..e4ffa1db6 --- /dev/null +++ b/src/yunohost/app_catalog.py @@ -0,0 +1,255 @@ +import os +import re + +from moulinette import m18n +from moulinette.utils.log import getActionLogger +from moulinette.utils.network import download_json +from moulinette.utils.filesystem import ( + read_json, + read_yaml, + write_to_json, + write_to_yaml, + mkdir, +) + +from yunohost.utils.i18n import _value_for_locale +from yunohost.utils.error import YunohostError + +logger = getActionLogger("yunohost.app_catalog") + +APPS_CATALOG_CACHE = "/var/cache/yunohost/repo" +APPS_CATALOG_CONF = "/etc/yunohost/apps_catalog.yml" +APPS_CATALOG_API_VERSION = 2 +APPS_CATALOG_DEFAULT_URL = "https://app.yunohost.org/default" + + +# Old legacy function... +def app_fetchlist(): + logger.warning( + "'yunohost app fetchlist' is deprecated. Please use 'yunohost tools update --apps' instead" + ) + from yunohost.tools import tools_update + + tools_update(target="apps") + + +def app_catalog(full=False, with_categories=False): + """ + Return a dict of apps available to installation from Yunohost's app catalog + """ + + from yunohost.app import _installed_apps, _set_default_ask_questions + + # Get app list from catalog cache + catalog = _load_apps_catalog() + installed_apps = set(_installed_apps()) + + # Trim info for apps if not using --full + for app, infos in catalog["apps"].items(): + infos["installed"] = app in installed_apps + + infos["manifest"]["description"] = _value_for_locale( + infos["manifest"]["description"] + ) + + if not full: + catalog["apps"][app] = { + "description": infos["manifest"]["description"], + "level": infos["level"], + } + else: + infos["manifest"]["arguments"] = _set_default_ask_questions( + infos["manifest"].get("arguments", {}) + ) + + # Trim info for categories if not using --full + for category in catalog["categories"]: + category["title"] = _value_for_locale(category["title"]) + category["description"] = _value_for_locale(category["description"]) + for subtags in category.get("subtags", []): + subtags["title"] = _value_for_locale(subtags["title"]) + + if not full: + catalog["categories"] = [ + {"id": c["id"], "description": c["description"]} + for c in catalog["categories"] + ] + + if not with_categories: + return {"apps": catalog["apps"]} + else: + return {"apps": catalog["apps"], "categories": catalog["categories"]} + + +def app_search(string): + """ + Return a dict of apps whose description or name match the search string + """ + + # Retrieve a simple dict listing all apps + catalog_of_apps = app_catalog() + + # Selecting apps according to a match in app name or description + matching_apps = {"apps": {}} + for app in catalog_of_apps["apps"].items(): + if re.search(string, app[0], flags=re.IGNORECASE) or re.search( + string, app[1]["description"], flags=re.IGNORECASE + ): + matching_apps["apps"][app[0]] = app[1] + + return matching_apps + + +def _initialize_apps_catalog_system(): + """ + This function is meant to intialize the apps_catalog system with YunoHost's default app catalog. + """ + + default_apps_catalog_list = [{"id": "default", "url": APPS_CATALOG_DEFAULT_URL}] + + try: + logger.debug( + "Initializing apps catalog system with YunoHost's default app list" + ) + write_to_yaml(APPS_CATALOG_CONF, default_apps_catalog_list) + except Exception as e: + raise YunohostError( + "Could not initialize the apps catalog system... : %s" % str(e) + ) + + logger.success(m18n.n("apps_catalog_init_success")) + + +def _read_apps_catalog_list(): + """ + Read the json corresponding to the list of apps catalogs + """ + + try: + list_ = read_yaml(APPS_CATALOG_CONF) + # Support the case where file exists but is empty + # by returning [] if list_ is None + return list_ if list_ else [] + except Exception as e: + raise YunohostError("Could not read the apps_catalog list ... : %s" % str(e)) + + +def _actual_apps_catalog_api_url(base_url): + + return "{base_url}/v{version}/apps.json".format( + base_url=base_url, version=APPS_CATALOG_API_VERSION + ) + + +def _update_apps_catalog(): + """ + Fetches the json for each apps_catalog and update the cache + + apps_catalog_list is for example : + [ {"id": "default", "url": "https://app.yunohost.org/default/"} ] + + Then for each apps_catalog, the actual json URL to be fetched is like : + https://app.yunohost.org/default/vX/apps.json + + And store it in : + /var/cache/yunohost/repo/default.json + """ + + apps_catalog_list = _read_apps_catalog_list() + + logger.info(m18n.n("apps_catalog_updating")) + + # Create cache folder if needed + if not os.path.exists(APPS_CATALOG_CACHE): + logger.debug("Initialize folder for apps catalog cache") + mkdir(APPS_CATALOG_CACHE, mode=0o750, parents=True, uid="root") + + for apps_catalog in apps_catalog_list: + apps_catalog_id = apps_catalog["id"] + actual_api_url = _actual_apps_catalog_api_url(apps_catalog["url"]) + + # Fetch the json + try: + apps_catalog_content = download_json(actual_api_url) + except Exception as e: + raise YunohostError( + "apps_catalog_failed_to_download", + apps_catalog=apps_catalog_id, + error=str(e), + ) + + # Remember the apps_catalog api version for later + apps_catalog_content["from_api_version"] = APPS_CATALOG_API_VERSION + + # Save the apps_catalog data in the cache + cache_file = "{cache_folder}/{list}.json".format( + cache_folder=APPS_CATALOG_CACHE, list=apps_catalog_id + ) + try: + write_to_json(cache_file, apps_catalog_content) + except Exception as e: + raise YunohostError( + "Unable to write cache data for %s apps_catalog : %s" + % (apps_catalog_id, str(e)) + ) + + logger.success(m18n.n("apps_catalog_update_success")) + + +def _load_apps_catalog(): + """ + Read all the apps catalog cache files and build a single dict (merged_catalog) + corresponding to all known apps and categories + """ + + merged_catalog = {"apps": {}, "categories": []} + + for apps_catalog_id in [L["id"] for L in _read_apps_catalog_list()]: + + # Let's load the json from cache for this catalog + cache_file = "{cache_folder}/{list}.json".format( + cache_folder=APPS_CATALOG_CACHE, list=apps_catalog_id + ) + + try: + apps_catalog_content = ( + read_json(cache_file) if os.path.exists(cache_file) else None + ) + except Exception as e: + raise YunohostError( + "Unable to read cache for apps_catalog %s : %s" % (cache_file, e), + raw_msg=True, + ) + + # Check that the version of the data matches version .... + # ... otherwise it means we updated yunohost in the meantime + # and need to update the cache for everything to be consistent + if ( + not apps_catalog_content + or apps_catalog_content.get("from_api_version") != APPS_CATALOG_API_VERSION + ): + logger.info(m18n.n("apps_catalog_obsolete_cache")) + _update_apps_catalog() + apps_catalog_content = read_json(cache_file) + + del apps_catalog_content["from_api_version"] + + # Add apps from this catalog to the output + for app, info in apps_catalog_content["apps"].items(): + + # (N.B. : there's a small edge case where multiple apps catalog could be listing the same apps ... + # in which case we keep only the first one found) + if app in merged_catalog["apps"]: + logger.warning( + "Duplicate app %s found between apps catalog %s and %s" + % (app, apps_catalog_id, merged_catalog["apps"][app]["repository"]) + ) + continue + + info["repository"] = apps_catalog_id + merged_catalog["apps"][app] = info + + # Annnnd categories + merged_catalog["categories"] += apps_catalog_content["categories"] + + return merged_catalog From 313897d18421e150a119e3de0d66d3fb1f50e340 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 03:33:12 +0200 Subject: [PATCH 35/81] Simplify _check_manifest_requirements --- src/yunohost/app.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index f221e2406..87b02cd19 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -538,7 +538,7 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False upgrade_type = "UPGRADE_FULL" # Check requirements - _check_manifest_requirements(manifest, app_instance_name=app_instance_name) + _check_manifest_requirements(manifest) _assert_system_is_sane_for_app(manifest, "pre") app_setting_path = os.path.join(APPS_SETTING_PATH, app_instance_name) @@ -753,7 +753,7 @@ def app_install( label = label if label else manifest["name"] # Check requirements - _check_manifest_requirements(manifest, app_id) + _check_manifest_requirements(manifest) _assert_system_is_sane_for_app(manifest, "pre") # Check if app can be forked @@ -2187,7 +2187,7 @@ def _get_all_installed_apps_id(): return all_apps_ids_formatted -def _check_manifest_requirements(manifest: Dict, app: str): +def _check_manifest_requirements(manifest: Dict): """Check if required packages are met from the manifest""" packaging_format = int(manifest.get("packaging_format", 0)) @@ -2199,6 +2199,8 @@ def _check_manifest_requirements(manifest: Dict, app: str): if not requirements: return + app = manifest.get("id", "?") + logger.debug(m18n.n("app_requirements_checking", app=app)) # Iterate over requirements From a26145ece0c41c5b84e359e1b157cc42cb587a85 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 03:42:59 +0200 Subject: [PATCH 36/81] Simplify(?) YNH_APP_BASEDIR creation, to happen in _make_env_for_app_script --- src/yunohost/app.py | 23 ++++++++++------------- src/yunohost/backup.py | 13 ++++--------- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 87b02cd19..df4dd089c 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -390,12 +390,11 @@ def app_change_url(operation_logger, app, domain, path): tmp_workdir_for_app = _make_tmp_workdir_for_app(app=app) # Prepare env. var. to pass to script - env_dict = _make_environment_for_app_script(app) + env_dict = _make_environment_for_app_script(app, workdir=tmp_workdir_for_app) env_dict["YNH_APP_OLD_DOMAIN"] = old_domain env_dict["YNH_APP_OLD_PATH"] = old_path env_dict["YNH_APP_NEW_DOMAIN"] = domain env_dict["YNH_APP_NEW_PATH"] = path - env_dict["YNH_APP_BASEDIR"] = tmp_workdir_for_app if domain != old_domain: operation_logger.related_to.append(("domain", old_domain)) @@ -544,12 +543,11 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False app_setting_path = os.path.join(APPS_SETTING_PATH, app_instance_name) # Prepare env. var. to pass to script - env_dict = _make_environment_for_app_script(app_instance_name) + env_dict = _make_environment_for_app_script(app_instance_name, workdir=extracted_app_folder) env_dict["YNH_APP_UPGRADE_TYPE"] = upgrade_type env_dict["YNH_APP_MANIFEST_VERSION"] = str(app_new_version) env_dict["YNH_APP_CURRENT_VERSION"] = str(app_current_version) env_dict["NO_BACKUP_UPGRADE"] = "1" if no_safety_backup else "0" - env_dict["YNH_APP_BASEDIR"] = extracted_app_folder # We'll check that the app didn't brutally edit some system configuration manually_modified_files_before_install = manually_modified_files() @@ -829,8 +827,7 @@ def app_install( ) # Prepare env. var. to pass to script - env_dict = _make_environment_for_app_script(app_instance_name, args=args) - env_dict["YNH_APP_BASEDIR"] = extracted_app_folder + env_dict = _make_environment_for_app_script(app_instance_name, args=args, workdir=extracted_app_folder) env_dict_for_logging = env_dict.copy() for question in questions: @@ -891,8 +888,7 @@ def app_install( logger.warning(m18n.n("app_remove_after_failed_install")) # Setup environment for remove script - env_dict_remove = _make_environment_for_app_script(app_instance_name) - env_dict_remove["YNH_APP_BASEDIR"] = extracted_app_folder + env_dict_remove = _make_environment_for_app_script(app_instance_name, workdir=extracted_app_folder) # Execute remove script operation_logger_remove = OperationLogger( @@ -1006,8 +1002,7 @@ def app_remove(operation_logger, app, purge=False): env_dict = {} app_id, app_instance_nb = _parse_app_instance_name(app) - env_dict = _make_environment_for_app_script(app) - env_dict["YNH_APP_BASEDIR"] = tmp_workdir_for_app + env_dict = _make_environment_for_app_script(app, workdir=tmp_workdir_for_app) env_dict["YNH_APP_PURGE"] = str(1 if purge else 0) operation_logger.extra.update({"env": env_dict}) @@ -1501,9 +1496,8 @@ def app_action_run(operation_logger, app, action, args=None): tmp_workdir_for_app = _make_tmp_workdir_for_app(app=app) - env_dict = _make_environment_for_app_script(app, args=args, args_prefix="ACTION_") + env_dict = _make_environment_for_app_script(app, args=args, args_prefix="ACTION_", workdir=tmp_workdir_for_app) env_dict["YNH_ACTION"] = action - env_dict["YNH_APP_BASEDIR"] = tmp_workdir_for_app _, action_script = tempfile.mkstemp(dir=tmp_workdir_for_app) @@ -2328,7 +2322,7 @@ def _assert_no_conflicting_apps(domain, path, ignore_app=None, full_domain=False ) -def _make_environment_for_app_script(app, args={}, args_prefix="APP_ARG_"): +def _make_environment_for_app_script(app, args={}, args_prefix="APP_ARG_", workdir=None): app_setting_path = os.path.join(APPS_SETTING_PATH, app) @@ -2342,6 +2336,9 @@ def _make_environment_for_app_script(app, args={}, args_prefix="APP_ARG_"): "YNH_APP_MANIFEST_VERSION": manifest.get("version", "?"), } + if workdir: + env_dict["YNH_APP_BASEDIR"] = workdir + for arg_name, arg_value in args.items(): env_dict["YNH_%s%s" % (args_prefix, arg_name.upper())] = str(arg_value) diff --git a/src/yunohost/backup.py b/src/yunohost/backup.py index b650cb3da..5664af3a0 100644 --- a/src/yunohost/backup.py +++ b/src/yunohost/backup.py @@ -1483,7 +1483,9 @@ class RestoreManager: logger.debug(m18n.n("restore_running_app_script", app=app_instance_name)) # Prepare env. var. to pass to script - env_dict = _make_environment_for_app_script(app_instance_name) + # FIXME : workdir should be a tmp workdir + app_workdir = os.path.join(self.work_dir, "apps", app_instance_name, "settings") + env_dict = _make_environment_for_app_script(app_instance_name, workdir=app_workdir) env_dict.update( { "YNH_BACKUP_DIR": self.work_dir, @@ -1491,9 +1493,6 @@ class RestoreManager: "YNH_APP_BACKUP_DIR": os.path.join( self.work_dir, "apps", app_instance_name, "backup" ), - "YNH_APP_BASEDIR": os.path.join( - self.work_dir, "apps", app_instance_name, "settings" - ), } ) @@ -1530,11 +1529,7 @@ class RestoreManager: remove_script = os.path.join(app_scripts_in_archive, "remove") # Setup environment for remove script - env_dict_remove = _make_environment_for_app_script(app_instance_name) - env_dict_remove["YNH_APP_BASEDIR"] = os.path.join( - self.work_dir, "apps", app_instance_name, "settings" - ) - + env_dict_remove = _make_environment_for_app_script(app_instance_name, workdir=app_workdir) remove_operation_logger = OperationLogger( "remove_on_failed_restore", [("app", app_instance_name)], From 680e13c0442a9adc590e2f6ae78d245b69da3e4d Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 03:45:40 +0200 Subject: [PATCH 37/81] Make mypy happier --- src/yunohost/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index df4dd089c..0f4c14b7a 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -1988,7 +1988,7 @@ def _app_quality(app: str) -> str: app_name_to_test = app.strip("/").split("/")[-1].replace("_ynh", "") else: # FIXME : watdo if '@' in app ? - app_name_to_test = None + return "thirdparty" if app_name_to_test in raw_app_catalog: From 2bda85c80042f0687415c9ed436db53695d04545 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 03:46:13 +0200 Subject: [PATCH 38/81] Stale i18n string --- locales/en.json | 1 - 1 file changed, 1 deletion(-) diff --git a/locales/en.json b/locales/en.json index 5d242b2e8..53b0a7e83 100644 --- a/locales/en.json +++ b/locales/en.json @@ -36,7 +36,6 @@ "app_manifest_install_ask_is_public": "Should this app be exposed to anonymous visitors?", "app_manifest_install_ask_password": "Choose an administration password for this app", "app_manifest_install_ask_path": "Choose the URL path (after the domain) where this app should be installed", - "app_manifest_invalid": "Something is wrong with the app manifest: {error}", "app_not_correctly_installed": "{app} seems to be incorrectly installed", "app_not_installed": "Could not find {app} in the list of installed apps: {all_apps}", "app_not_properly_removed": "{app} has not been properly removed", From 11be8cc4c02f0b60f00f2b2e1aca3f8c83075dcf Mon Sep 17 00:00:00 2001 From: ericgaspar Date: Fri, 1 Oct 2021 09:43:39 +0200 Subject: [PATCH 39/81] Update nodejs --- data/helpers.d/nodejs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data/helpers.d/nodejs b/data/helpers.d/nodejs index a796b68fd..06b948d00 100644 --- a/data/helpers.d/nodejs +++ b/data/helpers.d/nodejs @@ -1,6 +1,6 @@ #!/bin/bash -n_version=7.3.0 +n_version=7.5.0 n_install_dir="/opt/node_n" node_version_path="$n_install_dir/n/versions/node" # N_PREFIX is the directory of n, it needs to be loaded as a environment variable. @@ -17,7 +17,7 @@ ynh_install_n () { ynh_print_info --message="Installation of N - Node.js version management" # Build an app.src for n echo "SOURCE_URL=https://github.com/tj/n/archive/v${n_version}.tar.gz -SOURCE_SUM=b908b0fc86922ede37e89d1030191285209d7d521507bf136e62895e5797847f" > "$YNH_APP_BASEDIR/conf/n.src" +SOURCE_SUM=d4da7ea91f680de0c9b5876e097e2a793e8234fcd0f7ca87a0599b925be087a3" > "$YNH_APP_BASEDIR/conf/n.src" # Download and extract n ynh_setup_source --dest_dir="$n_install_dir/git" --source_id=n # Install n From 171b3b25d9d4cb7aad8b2cbbc5aeb7eee6243a1f Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 16:13:57 +0200 Subject: [PATCH 40/81] Improve check that arg is a yunohost repo url --- src/yunohost/app.py | 25 +++++++++++++++++++++++-- src/yunohost/tests/test_appurl.py | 30 +++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 0f4c14b7a..5b6d1a7f8 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -69,6 +69,10 @@ re_app_instance_name = re.compile( r"^(?P[\w-]+?)(__(?P[1-9][0-9]*))?$" ) +APP_REPO_URL = re.compile( + r"^https://[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_./]+/[a-zA-Z0-9-_.]+_ynh(/?(-/)?tree/[a-zA-Z0-9-_]+)?(\.git)?/?$" +) + APP_FILES_TO_COPY = [ "manifest.json", "manifest.toml", @@ -1971,13 +1975,24 @@ def _set_default_ask_questions(arguments): return arguments +def _is_app_repo_url(string: str) -> bool: + + string = string.strip() + + # Dummy test for ssh-based stuff ... should probably be improved somehow + if '@' in string: + return True + + return APP_REPO_URL.match(string) + + def _app_quality(app: str) -> str: """ app may in fact be an app name, an url, or a path """ raw_app_catalog = _load_apps_catalog()["apps"] - if app in raw_app_catalog or ("@" in app) or ("http://" in app) or ("https://" in app): + if app in raw_app_catalog or _is_app_repo_url(app): # If we got an app name directly (e.g. just "wordpress"), we gonna test this name if app in raw_app_catalog: @@ -2027,10 +2042,14 @@ def _extract_app(src: str) -> Tuple[Dict, str]: revision = str(app_info["git"]["revision"]) return _extract_app_from_gitrepo(url, branch, revision, app_info) # App is a git repo url - elif ("@" in src) or ("http://" in src) or ("https://" in src): + elif _is_app_repo_url(src): url = src branch = "master" revision = "HEAD" + # gitlab urls may look like 'https://domain/org/group/repo/-/tree/testing' + # compated to github urls looking like 'https://domain/org/repo/tree/testing' + if '/-/' in url: + url = url.replace('/-/', '/') if "/tree/" in url: url, branch = url.split("/tree/", 1) return _extract_app_from_gitrepo(url, branch, revision, {}) @@ -2038,6 +2057,8 @@ def _extract_app(src: str) -> Tuple[Dict, str]: elif os.path.exists(src): return _extract_app_from_folder(src) else: + if "http://" in src or "https://" in src: + logger.error(f"{src} is not a valid app url: app url are expected to look like https://domain.tld/path/to/repo_ynh") raise YunohostValidationError("app_unknown") diff --git a/src/yunohost/tests/test_appurl.py b/src/yunohost/tests/test_appurl.py index 5954d239a..d50877445 100644 --- a/src/yunohost/tests/test_appurl.py +++ b/src/yunohost/tests/test_appurl.py @@ -4,7 +4,7 @@ import os from .conftest import get_test_apps_dir from yunohost.utils.error import YunohostError -from yunohost.app import app_install, app_remove +from yunohost.app import app_install, app_remove, _is_app_repo_url from yunohost.domain import _get_maindomain, domain_url_available from yunohost.permission import _validate_and_sanitize_permission_url @@ -28,6 +28,34 @@ def teardown_function(function): pass +def test_repo_url_definition(): + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh.git") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/tree/testing") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/tree/testing/") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foo-bar-123_ynh") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/foo_bar_123_ynh") + assert _is_app_repo_url("https://github.com/YunoHost-Apps/FooBar123_ynh") + assert _is_app_repo_url("https://github.com/labriqueinternet/vpnclient_ynh") + assert _is_app_repo_url("https://framagit.org/YunoHost/apps/nodebb_ynh") + assert _is_app_repo_url("https://framagit.org/YunoHost/apps/nodebb_ynh/-/tree/testing") + assert _is_app_repo_url("https://gitlab.com/yunohost-apps/foobar_ynh") + assert _is_app_repo_url("https://code.antopie.org/miraty/qr_ynh") + assert _is_app_repo_url("https://gitlab.domainepublic.net/Neutrinet/neutrinet_ynh/-/tree/unstable") + assert _is_app_repo_url("git@github.com:YunoHost-Apps/foobar_ynh.git") + + assert not _is_app_repo_url("github.com/YunoHost-Apps/foobar_ynh") + assert not _is_app_repo_url("http://github.com/YunoHost-Apps/foobar_ynh") + assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar_wat") + assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar_ynh_wat") + assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar/tree/testing") + assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar_ynh_wat/tree/testing") + assert not _is_app_repo_url("https://framagit.org/YunoHost/apps/") + assert not _is_app_repo_url("https://framagit.org/YunoHost/apps/pwet") + assert not _is_app_repo_url("https://framagit.org/YunoHost/apps/pwet_foo") + + def test_urlavailable(): # Except the maindomain/macnuggets to be available From 34d9573121a4bd5caea2974f27c20be3cf20726b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 16:46:05 +0200 Subject: [PATCH 41/81] Misc fixes for app repo url check / parsing --- src/yunohost/app.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 5b6d1a7f8..3fede8dcd 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -1986,21 +1986,21 @@ def _is_app_repo_url(string: str) -> bool: return APP_REPO_URL.match(string) -def _app_quality(app: str) -> str: +def _app_quality(src: str) -> str: """ app may in fact be an app name, an url, or a path """ raw_app_catalog = _load_apps_catalog()["apps"] - if app in raw_app_catalog or _is_app_repo_url(app): + if src in raw_app_catalog or _is_app_repo_url(src): # If we got an app name directly (e.g. just "wordpress"), we gonna test this name - if app in raw_app_catalog: - app_name_to_test = app + if src in raw_app_catalog: + app_name_to_test = src # If we got an url like "https://github.com/foo/bar_ynh, we want to # extract "bar" and test if we know this app - elif ("http://" in app) or ("https://" in app): - app_name_to_test = app.strip("/").split("/")[-1].replace("_ynh", "") + elif ("http://" in src) or ("https://" in src): + app_name_to_test = src.strip("/").split("/")[-1].replace("_ynh", "") else: # FIXME : watdo if '@' in app ? return "thirdparty" @@ -2018,9 +2018,11 @@ def _app_quality(app: str) -> str: else: return "thirdparty" - elif os.path.exists(app): + elif os.path.exists(src): return "thirdparty" else: + if "http://" in src or "https://" in src: + logger.error(f"{src} is not a valid app url: app url are expected to look like https://domain.tld/path/to/repo_ynh") raise YunohostValidationError("app_unknown") @@ -2043,7 +2045,7 @@ def _extract_app(src: str) -> Tuple[Dict, str]: return _extract_app_from_gitrepo(url, branch, revision, app_info) # App is a git repo url elif _is_app_repo_url(src): - url = src + url = src.strip().strip("/") branch = "master" revision = "HEAD" # gitlab urls may look like 'https://domain/org/group/repo/-/tree/testing' From 3883343e1a414fe32a1e29adf2087e4f5051fbfe Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 17:51:05 +0200 Subject: [PATCH 42/81] swag: Add version badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b256bb563..df3a4bb9f 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@
+![Version](https://img.shields.io/github/v/tag/yunohost/yunohost?label=version&sort=semver) [![Build status](https://shields.io/gitlab/pipeline/yunohost/yunohost/dev)](https://gitlab.com/yunohost/yunohost/-/pipelines) ![Test coverage](https://img.shields.io/gitlab/coverage/yunohost/yunohost/dev) [![GitHub license](https://img.shields.io/github/license/YunoHost/yunohost)](https://github.com/YunoHost/yunohost/blob/dev/LICENSE) From 310b664fab6c9ebef3b94575956f3654c366211f Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 19:20:21 +0200 Subject: [PATCH 43/81] Clarify return type for mypy --- src/yunohost/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 3fede8dcd..36b65f873 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -1983,7 +1983,7 @@ def _is_app_repo_url(string: str) -> bool: if '@' in string: return True - return APP_REPO_URL.match(string) + return bool(APP_REPO_URL.match(string)) def _app_quality(src: str) -> str: From 0f0f26f5c48af161da16eaf4775e95e6bcab25fc Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 19:25:32 +0200 Subject: [PATCH 44/81] For some reason these tests now wanted to interactively ask for is_public arg ... don't know why it was working before ... --- src/yunohost/tests/test_permission.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/yunohost/tests/test_permission.py b/src/yunohost/tests/test_permission.py index b33c2f213..00799d0fd 100644 --- a/src/yunohost/tests/test_permission.py +++ b/src/yunohost/tests/test_permission.py @@ -1049,7 +1049,7 @@ def test_permission_app_remove(): def test_permission_app_change_url(): app_install( os.path.join(get_test_apps_dir(), "permissions_app_ynh"), - args="domain=%s&domain_2=%s&path=%s&admin=%s" + args="domain=%s&domain_2=%s&path=%s&is_public=1&admin=%s" % (maindomain, other_domains[0], "/urlpermissionapp", "alice"), force=True, ) @@ -1072,7 +1072,7 @@ def test_permission_app_change_url(): def test_permission_protection_management_by_helper(): app_install( os.path.join(get_test_apps_dir(), "permissions_app_ynh"), - args="domain=%s&domain_2=%s&path=%s&admin=%s" + args="domain=%s&domain_2=%s&path=%s&is_public=1&admin=%s" % (maindomain, other_domains[0], "/urlpermissionapp", "alice"), force=True, ) @@ -1135,7 +1135,7 @@ def test_permission_legacy_app_propagation_on_ssowat(): app_install( os.path.join(get_test_apps_dir(), "legacy_app_ynh"), - args="domain=%s&domain_2=%s&path=%s" + args="domain=%s&domain_2=%s&path=%s&is_public=1" % (maindomain, other_domains[0], "/legacy"), force=True, ) From 3daac24443eb02f449d5e1c6ce6b2b91d38c5e7b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 19:25:36 +0200 Subject: [PATCH 45/81] Typos --- src/yunohost/app.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 36b65f873..b6150d152 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -645,7 +645,7 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False for file_to_copy in APP_FILES_TO_COPY: os.system(f"rm -rf '{app_setting_path}/{file_to_copy}'") if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - os.system(f"cp -R '{extracted_app_folder}/{file_to_copy} {app_setting_path}'") + os.system(f"cp -R '{extracted_app_folder}/{file_to_copy}' '{app_setting_path}'") # Clean and set permissions shutil.rmtree(extracted_app_folder) @@ -2089,7 +2089,7 @@ def _extract_app_from_folder(path: str) -> Tuple[Dict, str]: shutil.rmtree(extracted_app_folder) if path[-1] != "/": path = path + "/" - extract_result = os.system(f"cp -a '{path}' {extracted_app_folder}") + extract_result = os.system(f"cp -a '{path}' '{extracted_app_folder}'") else: extract_result = 1 From 6c03cf2b118b1c0178aad905819e6fe623ff5ec2 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Fri, 1 Oct 2021 20:22:59 +0200 Subject: [PATCH 46/81] Yoloattempt to try to cleanup some ugly os.system --- src/yunohost/app.py | 44 +++++++++++++++++++----------------------- src/yunohost/dns.py | 4 ++-- src/yunohost/domain.py | 4 ++-- src/yunohost/dyndns.py | 19 +++++++++--------- src/yunohost/hook.py | 5 ++--- src/yunohost/tools.py | 26 +++++++++++-------------- 6 files changed, 46 insertions(+), 56 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index b6150d152..cf4b47681 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -45,6 +45,10 @@ from moulinette.utils.filesystem import ( read_yaml, write_to_file, write_to_json, + cp, + rm, + chown, + chmod, ) from yunohost.utils import packages @@ -643,15 +647,15 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False # Replace scripts and manifest and conf (if exists) # Move scripts and manifest to the right place for file_to_copy in APP_FILES_TO_COPY: - os.system(f"rm -rf '{app_setting_path}/{file_to_copy}'") + rm(f'{app_setting_path}/{file_to_copy}', recursive=True, force=True) if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - os.system(f"cp -R '{extracted_app_folder}/{file_to_copy}' '{app_setting_path}'") + cp(f'{extracted_app_folder}/{file_to_copy}', f'{app_setting_path}/{file_to_copy}', recursive=True) # Clean and set permissions shutil.rmtree(extracted_app_folder) - os.system("chmod 600 %s" % app_setting_path) - os.system("chmod 400 %s/settings.yml" % app_setting_path) - os.system("chown -R root: %s" % app_setting_path) + chmod(app_setting_path, 0o600) + chmod(f"{app_setting_path}/settings.yml", 0o400) + chown(app_setting_path, "root", recursive=True) # So much win logger.success(m18n.n("app_upgraded", app=app_instance_name)) @@ -816,7 +820,7 @@ def app_install( # Move scripts and manifest to the right place for file_to_copy in APP_FILES_TO_COPY: if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - os.system(f"cp -R '{extracted_app_folder}/{file_to_copy}' '{app_setting_path}'") + cp(f'{extracted_app_folder}/{file_to_copy}', f'{app_setting_path}/{file_to_copy}', recursive=True) # Initialize the main permission for the app # The permission is initialized with no url associated, and with tile disabled @@ -955,9 +959,9 @@ def app_install( # Clean and set permissions shutil.rmtree(extracted_app_folder) - os.system("chmod 600 %s" % app_setting_path) - os.system("chmod 400 %s/settings.yml" % app_setting_path) - os.system("chown -R root: %s" % app_setting_path) + chmod(app_setting_path, 0o600) + chmod(f"{app_setting_path}/settings.yml", 0o400) + chown(app_setting_path, "root", recursive=True) logger.success(m18n.n("installation_complete")) @@ -1153,7 +1157,7 @@ def app_makedefault(operation_logger, app, domain=None): write_to_json( "/etc/ssowat/conf.json.persistent", ssowat_conf, sort_keys=True, indent=4 ) - os.system("chmod 644 /etc/ssowat/conf.json.persistent") + chmod("/etc/ssowat/conf.json.persistent", 0o644) logger.success(m18n.n("ssowat_conf_updated")) @@ -2077,24 +2081,16 @@ def _extract_app_from_folder(path: str) -> Tuple[Dict, str]: extracted_app_folder = _make_tmp_workdir_for_app() - if ".zip" in path: - extract_result = os.system( - f"unzip '{path}' -d {extracted_app_folder} > /dev/null 2>&1" - ) - elif ".tar" in path: - extract_result = os.system( - f"tar -xf '{path}' -C {extracted_app_folder} > /dev/null 2>&1" - ) - elif os.path.isdir(path): + if os.path.isdir(path): shutil.rmtree(extracted_app_folder) if path[-1] != "/": path = path + "/" - extract_result = os.system(f"cp -a '{path}' '{extracted_app_folder}'") + cp(path, extracted_app_folder, recursive=True) else: - extract_result = 1 - - if extract_result != 0: - raise YunohostError("app_extraction_failed") + try: + shutil.unpack_archive(path, extracted_app_folder) + except Exception: + raise YunohostError("app_extraction_failed") try: if len(os.listdir(extracted_app_folder)) == 1: diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index 689950490..b0d40db9e 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -32,7 +32,7 @@ from collections import OrderedDict from moulinette import m18n, Moulinette from moulinette.utils.log import getActionLogger -from moulinette.utils.filesystem import read_file, write_to_file, read_toml +from moulinette.utils.filesystem import read_file, write_to_file, read_toml, mkdir from yunohost.domain import ( domain_list, @@ -471,7 +471,7 @@ def _get_dns_zone_for_domain(domain): # Check if there's a NS record for that domain answer = dig(parent, rdtype="NS", full_answers=True, resolvers="force_external") if answer[0] == "ok": - os.system(f"mkdir -p {cache_folder}") + mkdir(cache_folder, parents=True) write_to_file(cache_file, parent) return parent diff --git a/src/yunohost/domain.py b/src/yunohost/domain.py index f5b14748d..b40831d25 100644 --- a/src/yunohost/domain.py +++ b/src/yunohost/domain.py @@ -29,7 +29,7 @@ from typing import Dict, Any from moulinette import m18n, Moulinette from moulinette.core import MoulinetteError from moulinette.utils.log import getActionLogger -from moulinette.utils.filesystem import write_to_file, read_yaml, write_to_yaml +from moulinette.utils.filesystem import write_to_file, read_yaml, write_to_yaml, rm from yunohost.app import ( app_ssowatconf, @@ -328,7 +328,7 @@ def domain_remove(operation_logger, domain, remove_apps=False, force=False): ] for stuff in stuff_to_delete: - os.system("rm -rf {stuff}") + rm(stuff, force=True, recursive=True) # Sometime we have weird issues with the regenconf where some files # appears as manually modified even though they weren't touched ... diff --git a/src/yunohost/dyndns.py b/src/yunohost/dyndns.py index 519fbc8f0..e33cf4f22 100644 --- a/src/yunohost/dyndns.py +++ b/src/yunohost/dyndns.py @@ -33,7 +33,7 @@ import subprocess from moulinette import m18n from moulinette.core import MoulinetteError from moulinette.utils.log import getActionLogger -from moulinette.utils.filesystem import write_to_file, read_file +from moulinette.utils.filesystem import write_to_file, read_file, rm, chown, chmod from moulinette.utils.network import download_json from yunohost.utils.error import YunohostError, YunohostValidationError @@ -152,13 +152,12 @@ def dyndns_subscribe( os.system( "cd /etc/yunohost/dyndns && " - "dnssec-keygen -a hmac-sha512 -b 512 -r /dev/urandom -n USER %s" - % domain - ) - os.system( - "chmod 600 /etc/yunohost/dyndns/*.key /etc/yunohost/dyndns/*.private" + f"dnssec-keygen -a hmac-sha512 -b 512 -r /dev/urandom -n USER {domain}" ) + chmod("/etc/yunohost/dyndns", 0o600, recursive=True) + chown("/etc/yunohost/dyndns", "root", recursive=True) + private_file = glob.glob("/etc/yunohost/dyndns/*%s*.private" % domain)[0] key_file = glob.glob("/etc/yunohost/dyndns/*%s*.key" % domain)[0] with open(key_file) as f: @@ -175,12 +174,12 @@ def dyndns_subscribe( timeout=30, ) except Exception as e: - os.system("rm -f %s" % private_file) - os.system("rm -f %s" % key_file) + rm(private_file, force=True) + rm(key_file, force=True) raise YunohostError("dyndns_registration_failed", error=str(e)) if r.status_code != 201: - os.system("rm -f %s" % private_file) - os.system("rm -f %s" % key_file) + rm(private_file, force=True) + rm(key_file, force=True) try: error = json.loads(r.text)["error"] except Exception: diff --git a/src/yunohost/hook.py b/src/yunohost/hook.py index c55809fce..20757bf3c 100644 --- a/src/yunohost/hook.py +++ b/src/yunohost/hook.py @@ -34,7 +34,7 @@ from importlib import import_module from moulinette import m18n, Moulinette from yunohost.utils.error import YunohostError, YunohostValidationError from moulinette.utils import log -from moulinette.utils.filesystem import read_yaml +from moulinette.utils.filesystem import read_yaml, cp HOOK_FOLDER = "/usr/share/yunohost/hooks/" CUSTOM_HOOK_FOLDER = "/etc/yunohost/hooks.d/" @@ -60,8 +60,7 @@ def hook_add(app, file): os.makedirs(CUSTOM_HOOK_FOLDER + action) finalpath = CUSTOM_HOOK_FOLDER + action + "/" + priority + "-" + app - os.system("cp %s %s" % (file, finalpath)) - os.system("chown -hR admin: %s" % HOOK_FOLDER) + cp(file, finalpath) return {"hook": finalpath} diff --git a/src/yunohost/tools.py b/src/yunohost/tools.py index 4cdd62d8f..671f8768c 100644 --- a/src/yunohost/tools.py +++ b/src/yunohost/tools.py @@ -34,7 +34,7 @@ from typing import List from moulinette import Moulinette, m18n from moulinette.utils.log import getActionLogger from moulinette.utils.process import check_output, call_async_output -from moulinette.utils.filesystem import read_yaml, write_to_yaml +from moulinette.utils.filesystem import read_yaml, write_to_yaml, cp, mkdir, rm from yunohost.app import ( app_info, @@ -1147,13 +1147,11 @@ class Migration(object): backup_folder = "/home/yunohost.backup/premigration/" + time.strftime( "%Y%m%d-%H%M%S", time.gmtime() ) - os.makedirs(backup_folder, 0o750) + mkdir(backup_folder, 0o750, parents=True) os.system("systemctl stop slapd") - os.system(f"cp -r --preserve /etc/ldap {backup_folder}/ldap_config") - os.system(f"cp -r --preserve /var/lib/ldap {backup_folder}/ldap_db") - os.system( - f"cp -r --preserve /etc/yunohost/apps {backup_folder}/apps_settings" - ) + cp("/etc/ldap", f"{backup_folder}/ldap_config", recursive=True) + cp("/var/lib/ldap", f"{backup_folder}/ldap_db", recursive=True) + cp("/etc/yunohost/apps", f"{backup_folder}/apps_settings", recursive=True) except Exception as e: raise YunohostError( "migration_ldap_can_not_backup_before_migration", error=str(e) @@ -1169,17 +1167,15 @@ class Migration(object): ) os.system("systemctl stop slapd") # To be sure that we don't keep some part of the old config - os.system("rm -r /etc/ldap/slapd.d") - os.system(f"cp -r --preserve {backup_folder}/ldap_config/. /etc/ldap/") - os.system(f"cp -r --preserve {backup_folder}/ldap_db/. /var/lib/ldap/") - os.system( - f"cp -r --preserve {backup_folder}/apps_settings/. /etc/yunohost/apps/" - ) + rm("/etc/ldap/slapd.d", force=True, recursive=True) + cp(f"{backup_folder}/ldap_config", "/etc/ldap", recursive=True) + cp(f"{backup_folder}/ldap_db", "/var/lib/ldap", recursive=True) + cp(f"{backup_folder}/apps_settings", "/etc/yunohost/apps", recursive=True) os.system("systemctl start slapd") - os.system(f"rm -r {backup_folder}") + rm(backup_folder, force=True, recursive=True) logger.info(m18n.n("migration_ldap_rollback_success")) raise else: - os.system(f"rm -r {backup_folder}") + rm(backup_folder, force=True, recursive=True) return func From 4fda262bc0c69b68d2288d9773215b581bab945c Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Sat, 2 Oct 2021 01:59:16 +0200 Subject: [PATCH 47/81] fix tests: Missing mkdir on force --- src/yunohost/dns.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/dns.py b/src/yunohost/dns.py index b0d40db9e..534ade918 100644 --- a/src/yunohost/dns.py +++ b/src/yunohost/dns.py @@ -471,7 +471,7 @@ def _get_dns_zone_for_domain(domain): # Check if there's a NS record for that domain answer = dig(parent, rdtype="NS", full_answers=True, resolvers="force_external") if answer[0] == "ok": - mkdir(cache_folder, parents=True) + mkdir(cache_folder, parents=True, force=True) write_to_file(cache_file, parent) return parent From a40ecdc98610c67dee5cfd75f83f596e8ba4d634 Mon Sep 17 00:00:00 2001 From: yunohost-bot Date: Sat, 2 Oct 2021 02:29:22 +0000 Subject: [PATCH 48/81] [CI] Format code --- src/yunohost/app.py | 81 ++++++++++++++++++++++--------- src/yunohost/backup.py | 14 ++++-- src/yunohost/tests/test_appurl.py | 20 ++++++-- src/yunohost/tools.py | 12 ++++- src/yunohost/utils/legacy.py | 8 ++- 5 files changed, 102 insertions(+), 33 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index cf4b47681..fd088bce9 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -62,7 +62,12 @@ from yunohost.utils.i18n import _value_for_locale from yunohost.utils.error import YunohostError, YunohostValidationError from yunohost.utils.filesystem import free_space_in_directory from yunohost.log import is_unit_operation, OperationLogger -from yunohost.app_catalog import app_catalog, app_search, _load_apps_catalog, app_fetchlist # noqa +from yunohost.app_catalog import ( + app_catalog, + app_search, + _load_apps_catalog, + app_fetchlist, +) # noqa logger = getActionLogger("yunohost.app") @@ -393,7 +398,9 @@ def app_change_url(operation_logger, app, domain, path): app_setting_path = os.path.join(APPS_SETTING_PATH, app) path_requirement = _guess_webapp_path_requirement(app_setting_path) - _validate_webpath_requirement({"domain": domain, "path": path}, path_requirement, ignore_app=app) + _validate_webpath_requirement( + {"domain": domain, "path": path}, path_requirement, ignore_app=app + ) tmp_workdir_for_app = _make_tmp_workdir_for_app(app=app) @@ -551,7 +558,9 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False app_setting_path = os.path.join(APPS_SETTING_PATH, app_instance_name) # Prepare env. var. to pass to script - env_dict = _make_environment_for_app_script(app_instance_name, workdir=extracted_app_folder) + env_dict = _make_environment_for_app_script( + app_instance_name, workdir=extracted_app_folder + ) env_dict["YNH_APP_UPGRADE_TYPE"] = upgrade_type env_dict["YNH_APP_MANIFEST_VERSION"] = str(app_new_version) env_dict["YNH_APP_CURRENT_VERSION"] = str(app_current_version) @@ -615,7 +624,7 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False if upgrade_failed or broke_the_system: # display this if there are remaining apps - if apps[number + 1:]: + if apps[number + 1 :]: not_upgraded_apps = apps[number:] logger.error( m18n.n( @@ -647,9 +656,13 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False # Replace scripts and manifest and conf (if exists) # Move scripts and manifest to the right place for file_to_copy in APP_FILES_TO_COPY: - rm(f'{app_setting_path}/{file_to_copy}', recursive=True, force=True) + rm(f"{app_setting_path}/{file_to_copy}", recursive=True, force=True) if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - cp(f'{extracted_app_folder}/{file_to_copy}', f'{app_setting_path}/{file_to_copy}', recursive=True) + cp( + f"{extracted_app_folder}/{file_to_copy}", + f"{app_setting_path}/{file_to_copy}", + recursive=True, + ) # Clean and set permissions shutil.rmtree(extracted_app_folder) @@ -820,7 +833,11 @@ def app_install( # Move scripts and manifest to the right place for file_to_copy in APP_FILES_TO_COPY: if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)): - cp(f'{extracted_app_folder}/{file_to_copy}', f'{app_setting_path}/{file_to_copy}', recursive=True) + cp( + f"{extracted_app_folder}/{file_to_copy}", + f"{app_setting_path}/{file_to_copy}", + recursive=True, + ) # Initialize the main permission for the app # The permission is initialized with no url associated, and with tile disabled @@ -835,7 +852,9 @@ def app_install( ) # Prepare env. var. to pass to script - env_dict = _make_environment_for_app_script(app_instance_name, args=args, workdir=extracted_app_folder) + env_dict = _make_environment_for_app_script( + app_instance_name, args=args, workdir=extracted_app_folder + ) env_dict_for_logging = env_dict.copy() for question in questions: @@ -896,7 +915,9 @@ def app_install( logger.warning(m18n.n("app_remove_after_failed_install")) # Setup environment for remove script - env_dict_remove = _make_environment_for_app_script(app_instance_name, workdir=extracted_app_folder) + env_dict_remove = _make_environment_for_app_script( + app_instance_name, workdir=extracted_app_folder + ) # Execute remove script operation_logger_remove = OperationLogger( @@ -1504,7 +1525,9 @@ def app_action_run(operation_logger, app, action, args=None): tmp_workdir_for_app = _make_tmp_workdir_for_app(app=app) - env_dict = _make_environment_for_app_script(app, args=args, args_prefix="ACTION_", workdir=tmp_workdir_for_app) + env_dict = _make_environment_for_app_script( + app, args=args, args_prefix="ACTION_", workdir=tmp_workdir_for_app + ) env_dict["YNH_ACTION"] = action _, action_script = tempfile.mkstemp(dir=tmp_workdir_for_app) @@ -1984,7 +2007,7 @@ def _is_app_repo_url(string: str) -> bool: string = string.strip() # Dummy test for ssh-based stuff ... should probably be improved somehow - if '@' in string: + if "@" in string: return True return bool(APP_REPO_URL.match(string)) @@ -1992,7 +2015,7 @@ def _is_app_repo_url(string: str) -> bool: def _app_quality(src: str) -> str: """ - app may in fact be an app name, an url, or a path + app may in fact be an app name, an url, or a path """ raw_app_catalog = _load_apps_catalog()["apps"] @@ -2026,13 +2049,15 @@ def _app_quality(src: str) -> str: return "thirdparty" else: if "http://" in src or "https://" in src: - logger.error(f"{src} is not a valid app url: app url are expected to look like https://domain.tld/path/to/repo_ynh") + logger.error( + f"{src} is not a valid app url: app url are expected to look like https://domain.tld/path/to/repo_ynh" + ) raise YunohostValidationError("app_unknown") def _extract_app(src: str) -> Tuple[Dict, str]: """ - src may be an app name, an url, or a path + src may be an app name, an url, or a path """ raw_app_catalog = _load_apps_catalog()["apps"] @@ -2054,8 +2079,8 @@ def _extract_app(src: str) -> Tuple[Dict, str]: revision = "HEAD" # gitlab urls may look like 'https://domain/org/group/repo/-/tree/testing' # compated to github urls looking like 'https://domain/org/repo/tree/testing' - if '/-/' in url: - url = url.replace('/-/', '/') + if "/-/" in url: + url = url.replace("/-/", "/") if "/tree/" in url: url, branch = url.split("/tree/", 1) return _extract_app_from_gitrepo(url, branch, revision, {}) @@ -2064,7 +2089,9 @@ def _extract_app(src: str) -> Tuple[Dict, str]: return _extract_app_from_folder(src) else: if "http://" in src or "https://" in src: - logger.error(f"{src} is not a valid app url: app url are expected to look like https://domain.tld/path/to/repo_ynh") + logger.error( + f"{src} is not a valid app url: app url are expected to look like https://domain.tld/path/to/repo_ynh" + ) raise YunohostValidationError("app_unknown") @@ -2108,7 +2135,9 @@ def _extract_app_from_folder(path: str) -> Tuple[Dict, str]: return manifest, extracted_app_folder -def _extract_app_from_gitrepo(url: str, branch: str, revision: str, app_info: Dict = {}) -> Tuple[Dict, str]: +def _extract_app_from_gitrepo( + url: str, branch: str, revision: str, app_info: Dict = {} +) -> Tuple[Dict, str]: logger.debug(m18n.n("downloading")) @@ -2237,8 +2266,12 @@ def _guess_webapp_path_requirement(app_folder: str) -> str: manifest = _get_manifest_of_app(app_folder) raw_questions = manifest.get("arguments", {}).get("install", {}) - domain_questions = [question for question in raw_questions if question.get("type") == "domain"] - path_questions = [question for question in raw_questions if question.get("type") == "path"] + domain_questions = [ + question for question in raw_questions if question.get("type") == "domain" + ] + path_questions = [ + question for question in raw_questions if question.get("type") == "path" + ] if len(domain_questions) == 0 and len(path_questions) == 0: return "" @@ -2276,7 +2309,9 @@ def _validate_webpath_requirement( _assert_no_conflicting_apps(domain, path, ignore_app=ignore_app) elif path_requirement == "full_domain": - _assert_no_conflicting_apps(domain, "/", full_domain=True, ignore_app=ignore_app) + _assert_no_conflicting_apps( + domain, "/", full_domain=True, ignore_app=ignore_app + ) def _get_conflicting_apps(domain, path, ignore_app=None): @@ -2341,7 +2376,9 @@ def _assert_no_conflicting_apps(domain, path, ignore_app=None, full_domain=False ) -def _make_environment_for_app_script(app, args={}, args_prefix="APP_ARG_", workdir=None): +def _make_environment_for_app_script( + app, args={}, args_prefix="APP_ARG_", workdir=None +): app_setting_path = os.path.join(APPS_SETTING_PATH, app) diff --git a/src/yunohost/backup.py b/src/yunohost/backup.py index 5664af3a0..cce66597a 100644 --- a/src/yunohost/backup.py +++ b/src/yunohost/backup.py @@ -1348,7 +1348,11 @@ class RestoreManager: app_instance_name -- (string) The app name to restore (no app with this name should be already install) """ - from yunohost.utils.legacy import _patch_legacy_php_versions, _patch_legacy_php_versions_in_settings, _patch_legacy_helpers + from yunohost.utils.legacy import ( + _patch_legacy_php_versions, + _patch_legacy_php_versions_in_settings, + _patch_legacy_helpers, + ) from yunohost.user import user_group_list from yunohost.permission import ( permission_create, @@ -1485,7 +1489,9 @@ class RestoreManager: # Prepare env. var. to pass to script # FIXME : workdir should be a tmp workdir app_workdir = os.path.join(self.work_dir, "apps", app_instance_name, "settings") - env_dict = _make_environment_for_app_script(app_instance_name, workdir=app_workdir) + env_dict = _make_environment_for_app_script( + app_instance_name, workdir=app_workdir + ) env_dict.update( { "YNH_BACKUP_DIR": self.work_dir, @@ -1529,7 +1535,9 @@ class RestoreManager: remove_script = os.path.join(app_scripts_in_archive, "remove") # Setup environment for remove script - env_dict_remove = _make_environment_for_app_script(app_instance_name, workdir=app_workdir) + env_dict_remove = _make_environment_for_app_script( + app_instance_name, workdir=app_workdir + ) remove_operation_logger = OperationLogger( "remove_on_failed_restore", [("app", app_instance_name)], diff --git a/src/yunohost/tests/test_appurl.py b/src/yunohost/tests/test_appurl.py index d50877445..186b76cdf 100644 --- a/src/yunohost/tests/test_appurl.py +++ b/src/yunohost/tests/test_appurl.py @@ -32,17 +32,25 @@ def test_repo_url_definition(): assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh") assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/") assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh.git") - assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/tree/testing") - assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/tree/testing/") + assert _is_app_repo_url( + "https://github.com/YunoHost-Apps/foobar123_ynh/tree/testing" + ) + assert _is_app_repo_url( + "https://github.com/YunoHost-Apps/foobar123_ynh/tree/testing/" + ) assert _is_app_repo_url("https://github.com/YunoHost-Apps/foo-bar-123_ynh") assert _is_app_repo_url("https://github.com/YunoHost-Apps/foo_bar_123_ynh") assert _is_app_repo_url("https://github.com/YunoHost-Apps/FooBar123_ynh") assert _is_app_repo_url("https://github.com/labriqueinternet/vpnclient_ynh") assert _is_app_repo_url("https://framagit.org/YunoHost/apps/nodebb_ynh") - assert _is_app_repo_url("https://framagit.org/YunoHost/apps/nodebb_ynh/-/tree/testing") + assert _is_app_repo_url( + "https://framagit.org/YunoHost/apps/nodebb_ynh/-/tree/testing" + ) assert _is_app_repo_url("https://gitlab.com/yunohost-apps/foobar_ynh") assert _is_app_repo_url("https://code.antopie.org/miraty/qr_ynh") - assert _is_app_repo_url("https://gitlab.domainepublic.net/Neutrinet/neutrinet_ynh/-/tree/unstable") + assert _is_app_repo_url( + "https://gitlab.domainepublic.net/Neutrinet/neutrinet_ynh/-/tree/unstable" + ) assert _is_app_repo_url("git@github.com:YunoHost-Apps/foobar_ynh.git") assert not _is_app_repo_url("github.com/YunoHost-Apps/foobar_ynh") @@ -50,7 +58,9 @@ def test_repo_url_definition(): assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar_wat") assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar_ynh_wat") assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar/tree/testing") - assert not _is_app_repo_url("https://github.com/YunoHost-Apps/foobar_ynh_wat/tree/testing") + assert not _is_app_repo_url( + "https://github.com/YunoHost-Apps/foobar_ynh_wat/tree/testing" + ) assert not _is_app_repo_url("https://framagit.org/YunoHost/apps/") assert not _is_app_repo_url("https://framagit.org/YunoHost/apps/pwet") assert not _is_app_repo_url("https://framagit.org/YunoHost/apps/pwet_foo") diff --git a/src/yunohost/tools.py b/src/yunohost/tools.py index 671f8768c..e89081abd 100644 --- a/src/yunohost/tools.py +++ b/src/yunohost/tools.py @@ -1151,7 +1151,11 @@ class Migration(object): os.system("systemctl stop slapd") cp("/etc/ldap", f"{backup_folder}/ldap_config", recursive=True) cp("/var/lib/ldap", f"{backup_folder}/ldap_db", recursive=True) - cp("/etc/yunohost/apps", f"{backup_folder}/apps_settings", recursive=True) + cp( + "/etc/yunohost/apps", + f"{backup_folder}/apps_settings", + recursive=True, + ) except Exception as e: raise YunohostError( "migration_ldap_can_not_backup_before_migration", error=str(e) @@ -1170,7 +1174,11 @@ class Migration(object): rm("/etc/ldap/slapd.d", force=True, recursive=True) cp(f"{backup_folder}/ldap_config", "/etc/ldap", recursive=True) cp(f"{backup_folder}/ldap_db", "/var/lib/ldap", recursive=True) - cp(f"{backup_folder}/apps_settings", "/etc/yunohost/apps", recursive=True) + cp( + f"{backup_folder}/apps_settings", + "/etc/yunohost/apps", + recursive=True, + ) os.system("systemctl start slapd") rm(backup_folder, force=True, recursive=True) logger.info(m18n.n("migration_ldap_rollback_success")) diff --git a/src/yunohost/utils/legacy.py b/src/yunohost/utils/legacy.py index 7ae98bed8..87c163f1b 100644 --- a/src/yunohost/utils/legacy.py +++ b/src/yunohost/utils/legacy.py @@ -4,7 +4,13 @@ import glob from moulinette import m18n from moulinette.core import MoulinetteError from moulinette.utils.log import getActionLogger -from moulinette.utils.filesystem import read_file, write_to_file, write_to_json, write_to_yaml, read_yaml +from moulinette.utils.filesystem import ( + read_file, + write_to_file, + write_to_json, + write_to_yaml, + read_yaml, +) from yunohost.user import user_list from yunohost.app import ( From b88074b00752f0af193253294e936d7ae53143eb Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Sat, 2 Oct 2021 20:23:23 +0200 Subject: [PATCH 49/81] Make linter happy --- src/yunohost/app.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index fd088bce9..a65ac76c7 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -62,12 +62,12 @@ from yunohost.utils.i18n import _value_for_locale from yunohost.utils.error import YunohostError, YunohostValidationError from yunohost.utils.filesystem import free_space_in_directory from yunohost.log import is_unit_operation, OperationLogger -from yunohost.app_catalog import ( +from yunohost.app_catalog import ( # noqa app_catalog, app_search, _load_apps_catalog, app_fetchlist, -) # noqa +) logger = getActionLogger("yunohost.app") From 4640d4577d5a9f146a9211acb65b6f69e674aa7d Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Sat, 2 Oct 2021 20:24:13 +0200 Subject: [PATCH 50/81] Moar mypy --- src/yunohost/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index a65ac76c7..4f9c3147f 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -2401,7 +2401,7 @@ def _make_environment_for_app_script( return env_dict -def _parse_app_instance_name(app_instance_name): +def _parse_app_instance_name(app_instance_name: str) -> Tuple[str, int]: """ Parse a Yunohost app instance name and extracts the original appid and the application instance number From 9c4ea1ccc6fa42f8ddb5905715bfce0254e7f9fc Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Mon, 4 Oct 2021 01:16:20 +0200 Subject: [PATCH 51/81] Try to make mypy happy --- src/yunohost/app.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 4f9c3147f..f4dd2aa1f 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -2424,13 +2424,16 @@ def _parse_app_instance_name(app_instance_name: str) -> Tuple[str, int]: True """ match = re_app_instance_name.match(app_instance_name) - assert match, "Could not parse app instance name : %s" % app_instance_name + assert match, f"Could not parse app instance name : {app_instance_name}" appid = match.groupdict().get("appid") - app_instance_nb = ( - int(match.groupdict().get("appinstancenb")) - if match.groupdict().get("appinstancenb") is not None - else 1 - ) + app_instance_nb = match.groupdict().get("appinstancenb") or "1" + if not appid: + raise Exception(f"Could not parse app instance name : {app_instance_name}") + if not str(app_instance_nb).isdigit(): + raise Exception(f"Could not parse app instance name : {app_instance_name}") + else: + app_instance_nb = int(str(app_instance_nb)) + return (appid, app_instance_nb) From 42da17181910761dc993ab5cbee3bb9012d8c1bc Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Mon, 4 Oct 2021 01:24:16 +0200 Subject: [PATCH 52/81] Add proper test for parse_app_instance_name --- src/yunohost/app.py | 24 ++++++++---------------- src/yunohost/tests/test_appurl.py | 14 +++++++++++++- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index f4dd2aa1f..1c05ce20b 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -2406,22 +2406,14 @@ def _parse_app_instance_name(app_instance_name: str) -> Tuple[str, int]: Parse a Yunohost app instance name and extracts the original appid and the application instance number - >>> _parse_app_instance_name('yolo') == ('yolo', 1) - True - >>> _parse_app_instance_name('yolo1') == ('yolo1', 1) - True - >>> _parse_app_instance_name('yolo__0') == ('yolo__0', 1) - True - >>> _parse_app_instance_name('yolo__1') == ('yolo', 1) - True - >>> _parse_app_instance_name('yolo__23') == ('yolo', 23) - True - >>> _parse_app_instance_name('yolo__42__72') == ('yolo__42', 72) - True - >>> _parse_app_instance_name('yolo__23qdqsd') == ('yolo__23qdqsd', 1) - True - >>> _parse_app_instance_name('yolo__23qdqsd56') == ('yolo__23qdqsd56', 1) - True + 'yolo' -> ('yolo', 1) + 'yolo1' -> ('yolo1', 1) + 'yolo__0' -> ('yolo__0', 1) + 'yolo__1' -> ('yolo', 1) + 'yolo__23' -> ('yolo', 23) + 'yolo__42__72' -> ('yolo__42', 72) + 'yolo__23qdqsd' -> ('yolo__23qdqsd', 1) + 'yolo__23qdqsd56' -> ('yolo__23qdqsd56', 1) """ match = re_app_instance_name.match(app_instance_name) assert match, f"Could not parse app instance name : {app_instance_name}" diff --git a/src/yunohost/tests/test_appurl.py b/src/yunohost/tests/test_appurl.py index 186b76cdf..ca953dcf7 100644 --- a/src/yunohost/tests/test_appurl.py +++ b/src/yunohost/tests/test_appurl.py @@ -4,7 +4,7 @@ import os from .conftest import get_test_apps_dir from yunohost.utils.error import YunohostError -from yunohost.app import app_install, app_remove, _is_app_repo_url +from yunohost.app import app_install, app_remove, _is_app_repo_url, _parse_app_instance_name from yunohost.domain import _get_maindomain, domain_url_available from yunohost.permission import _validate_and_sanitize_permission_url @@ -28,6 +28,18 @@ def teardown_function(function): pass +def test_parse_app_instance_name(): + + assert _parse_app_instance_name('yolo') == ('yolo', 1) + assert _parse_app_instance_name('yolo1') == ('yolo1', 1) + assert _parse_app_instance_name('yolo__0') == ('yolo__0', 1) + assert _parse_app_instance_name('yolo__1') == ('yolo', 1) + assert _parse_app_instance_name('yolo__23') == ('yolo', 23) + assert _parse_app_instance_name('yolo__42__72') == ('yolo__42', 72) + assert _parse_app_instance_name('yolo__23qdqsd') == ('yolo__23qdqsd', 1) + assert _parse_app_instance_name('yolo__23qdqsd56') == ('yolo__23qdqsd56', 1) + + def test_repo_url_definition(): assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh") assert _is_app_repo_url("https://github.com/YunoHost-Apps/foobar123_ynh/") From 6ad07d2c837bc894f89671e1dcc1d4d815c597ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M?= Date: Thu, 30 Sep 2021 04:30:15 +0000 Subject: [PATCH 53/81] Translated using Weblate (Galician) Currently translated at 100.0% (707 of 707 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/gl/ --- locales/gl.json | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/locales/gl.json b/locales/gl.json index ebb65be02..d70d7a561 100644 --- a/locales/gl.json +++ b/locales/gl.json @@ -17,7 +17,7 @@ "app_argument_required": "Requírese o argumento '{name}'", "app_argument_password_no_default": "Erro ao procesar o argumento do contrasinal '{name}': o argumento do contrasinal non pode ter un valor por defecto por razón de seguridade", "app_argument_invalid": "Elixe un valor válido para o argumento '{name}': {error}", - "app_argument_choice_invalid": "Usa unha destas opcións '{choices}' para o argumento '{name}' no lugar de '{value}'", + "app_argument_choice_invalid": "Elixe un valor válido para o argumento '{name}': '{value}' non está entre as opcións dispoñibles ({choices})", "backup_archive_writing_error": "Non se puideron engadir os ficheiros '{source}' (chamados no arquivo '{dest}' para ser copiados dentro do arquivo comprimido '{archive}'", "backup_archive_system_part_not_available": "A parte do sistema '{part}' non está dispoñible nesta copia", "backup_archive_corrupted": "Semella que o arquivo de copia '{archive}' está estragado : {error}", @@ -102,7 +102,7 @@ "backup_copying_to_organize_the_archive": "Copiando {size}MB para organizar o arquivo", "backup_cleaning_failed": "Non se puido baleirar o cartafol temporal para a copia", "backup_cant_mount_uncompress_archive": "Non se puido montar o arquivo sen comprimir porque está protexido contra escritura", - "backup_ask_for_copying_if_needed": "Queres realizar a copia de apoio utilizando temporalmente {size}MB? (Faise deste xeito porque algúns ficheiros non hai xeito de preparalos usando unha forma máis eficiente).", + "backup_ask_for_copying_if_needed": "Queres realizar a copia de apoio utilizando temporalmente {size}MB? (Faise deste xeito porque algúns ficheiros non hai xeito de preparalos usando unha forma máis eficiente.)", "backup_running_hooks": "Executando os ganchos da copia...", "backup_permission": "Permiso de copia para {app}", "backup_output_symlink_dir_broken": "O directorio de arquivo '{path}' é unha ligazón simbólica rota. Pode ser que esqueceses re/montar ou conectar o medio de almacenaxe ao que apunta.", @@ -455,7 +455,7 @@ "migration_0015_modified_files": "Ten en conta que os seguintes ficheiros semella que foron modificados manualmente e poderían ser sobrescritos na actualización: {manually_modified_files}", "migration_0015_problematic_apps_warning": "Ten en conta que se detectaron as seguintes apps que poderían ser problemáticas. Semella que non foron instaladas usando o catálogo de YunoHost, ou non están marcadas como 'funcionais'. En consecuencia, non se pode garantir que seguirán funcionando após a actualización: {problematic_apps}", "diagnosis_http_localdomain": "O dominio {domain}, cun TLD .local, non é de agardar que esté exposto ao exterior da rede local.", - "diagnosis_dns_specialusedomain": "O dominio {domain} baséase un dominio de nivel alto e uso especial (TLD) polo que non é de agardar que realmente teña rexistros DNS.", + "diagnosis_dns_specialusedomain": "O dominio {domain} baséase un dominio de nivel alto e uso especial (TLD) como .local ou .test polo que non é de agardar que realmente teña rexistros DNS.", "upnp_enabled": "UPnP activado", "upnp_disabled": "UPnP desactivado", "permission_creation_failed": "Non se creou o permiso '{permission}': {error}", @@ -675,5 +675,39 @@ "config_version_not_supported": "A versión do panel de configuración '{version}' non está soportada.", "file_extension_not_accepted": "Rexeitouse o ficheiro '{path}' porque a súa extensión non está entre as aceptadas: {accept}", "invalid_number_max": "Ten que ser menor de {max}", - "service_not_reloading_because_conf_broken": "Non se recargou/reiniciou o servizo '{name}' porque a súa configuración está estragada: {errors}" -} \ No newline at end of file + "service_not_reloading_because_conf_broken": "Non se recargou/reiniciou o servizo '{name}' porque a súa configuración está estragada: {errors}", + "diagnosis_http_special_use_tld": "O dominio {domain} baséase nun dominio de alto-nivel (TLD) especial como .local ou .test e por isto non é de agardar que esté exposto fóra da rede local.", + "domain_dns_conf_special_use_tld": "Este dominio baséase nun dominio de alto-nivel (TLD) de uso especial como .local ou .test e por isto non é de agardar que teña rexistros DNS asociados.", + "domain_dns_registrar_managed_in_parent_domain": "Este dominio é un subdominio de {parent_domain_link}. A configuración DNS debe xestionarse no panel de configuración de {parent_domain}'s.", + "domain_dns_registrar_not_supported": "YunoHost non é quen de detectar a rexistradora que xestiona o dominio. Debes configurar manualmente os seus rexistros DNS seguindo a documentación en https://yunohost.org/dns.", + "domain_dns_registrar_experimental": "Ata o momento, a interface coa API de **{registar}** aínda non foi comprobada e revisada pola comunidade YunoHost. O soporte é **moi experimental** - ten coidado!", + "domain_dns_push_failed_to_list": "Non se pode mostrar a lista actual de rexistros na API da rexistradora: {error}", + "domain_dns_push_already_up_to_date": "Rexistros ao día, nada que facer.", + "domain_dns_pushing": "Enviando rexistros DNS...", + "domain_dns_push_record_failed": "Fallou {action} do rexistro {type}/{name}: {error}", + "domain_dns_push_success": "Rexistros DNS actualizados!", + "domain_dns_push_failed": "Fallou completamente a actualización dos rexistros DNS.", + "domain_config_features_disclaimer": "Ata o momento, activar/desactivar as funcións de email ou XMPP só ten impacto na configuración automática da configuración DNS, non na configuración do sistema!", + "domain_config_mail_in": "Emails entrantes", + "domain_config_mail_out": "Emails saíntes", + "domain_config_xmpp": "Mensaxería instantánea (XMPP)", + "domain_config_auth_secret": "Segreda de autenticación", + "domain_config_api_protocol": "Protocolo API", + "domain_config_auth_application_key": "Chave da aplicación", + "domain_config_auth_application_secret": "Chave segreda da aplicación", + "domain_config_auth_consumer_key": "Chave consumidora", + "log_domain_dns_push": "Enviar rexistros DNS para o dominio '{}'", + "other_available_options": "... e outras {n} opcións dispoñibles non mostradas", + "domain_dns_registrar_yunohost": "Este dominio un dos de nohost.me / nohost.st / ynh.fr e a configuración DNS xestionaa directamente YunoHost se máis requisitos. (mira o comando 'yunohost dyndns update')", + "domain_dns_registrar_supported": "YunoHost detectou automáticamente que este dominio está xestionado pola rexistradora **{registar}**. Se queres, YunoHost pode configurar automáticamente as súas zonas DNS, se proporcionas as credenciais de acceso á API. Podes ver a documentación sobre como obter as credenciais da API nesta páxina: https://yunohost.org/registar_api_{registrar}. (Tamén podes configurar manualmente os rexistros DNS seguindo a documentación en https://yunohost.org/dns )", + "domain_dns_push_partial_failure": "Actualización parcial dos rexistros DNS: informouse dalgúns avisos/erros.", + "domain_config_auth_token": "Token de autenticación", + "domain_config_auth_key": "Chave de autenticación", + "domain_config_auth_entrypoint": "Punto de entrada da API", + "domain_dns_push_failed_to_authenticate": "Fallou a autenticación na API da rexistradora do dominio '{domain}'. Comprobaches que sexan as credenciais correctas? (Erro: {error})", + "domain_registrar_is_not_configured": "A rexistradora non aínda non está configurada para o dominio {domain}.", + "domain_dns_push_not_applicable": "A función de rexistro DNS automático non é aplicable ao dominio {domain}. Debes configurar manualmente os teus rexistros DNS seguindo a documentación de https://yunohost.org/dns_config.", + "domain_dns_push_managed_in_parent_domain": "A función de rexistro DNS automático está xestionada polo dominio nai {parent_domain}.", + "ldap_attribute_already_exists": "Xa existe o atributo LDAP '{attribute}' con valor '{value}'", + "log_domain_config_set": "Actualizar configuración para o dominio '{}'" +} From 707866e222105a744403cb286078dea472f52be3 Mon Sep 17 00:00:00 2001 From: Tymofii-Lytvynenko Date: Thu, 30 Sep 2021 19:03:23 +0000 Subject: [PATCH 54/81] Translated using Weblate (Ukrainian) Currently translated at 96.1% (680 of 707 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/uk/ --- locales/uk.json | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/locales/uk.json b/locales/uk.json index 35923908f..814fa56a9 100644 --- a/locales/uk.json +++ b/locales/uk.json @@ -16,7 +16,7 @@ "app_argument_required": "Аргумент '{name}' необхідний", "app_argument_password_no_default": "Помилка під час розбору аргументу пароля '{name}': аргумент пароля не може мати типове значення з причин безпеки", "app_argument_invalid": "Виберіть правильне значення для аргументу '{name}': {error}", - "app_argument_choice_invalid": "Використовуйте один з цих варіантів '{choices}' для аргументу '{name}' замість '{value}'", + "app_argument_choice_invalid": "Виберіть дійсне значення для аргументу '{name}': '{value}' не є серед доступних варіантів ({choices})", "app_already_up_to_date": "{app} має найостаннішу версію", "app_already_installed_cant_change_url": "Цей застосунок уже встановлено. URL-адреса не може бути змінена тільки цією функцією. Перевірте в `app changeurl`, якщо вона доступна.", "app_already_installed": "{app} уже встановлено", @@ -482,7 +482,7 @@ "diagnosis_domain_expiration_not_found_details": "Відомості WHOIS для домену {domain} не містять даних про строк дії?", "diagnosis_domain_not_found_details": "Домен {domain} не існує в базі даних WHOIS або строк його дії сплив!", "diagnosis_domain_expiration_not_found": "Неможливо перевірити строк дії деяких доменів", - "diagnosis_dns_specialusedomain": "Домен {domain} заснований на домені верхнього рівня спеціального призначення (TLD) і тому не очікується, що у нього будуть актуальні записи DNS.", + "diagnosis_dns_specialusedomain": "Домен {domain} заснований на домені верхнього рівня спеціального призначення (TLD) такого як .local або .test і тому не очікується, що у нього будуть актуальні записи DNS.", "diagnosis_dns_try_dyndns_update_force": "Конфігурація DNS цього домену повинна автоматично управлятися YunoHost. Якщо це не так, ви можете спробувати примусово оновити її за допомогою команди yunohost dyndns update --force.", "diagnosis_dns_point_to_doc": "Якщо вам потрібна допомога з налаштування DNS-записів, зверніться до документації на сайті https://yunohost.org/dns_config.", "diagnosis_dns_discrepancy": "Наступний запис DNS, схоже, не відповідає рекомендованій конфігурації:
Тип: {type}
Назва: {name}
Поточне значення: {current}
Очікуване значення: {value}", @@ -504,7 +504,7 @@ "diagnosis_ip_connected_ipv4": "Сервер під'єднаний до Інтернету через IPv4!", "diagnosis_no_cache": "Для категорії «{category}» ще немає кеша діагностики", "diagnosis_failed": "Не вдалося отримати результат діагностики для категорії '{category}': {error}", - "diagnosis_everything_ok": "Усе виглядає добре для {category}!", + "diagnosis_everything_ok": "Здається, для категорії '{category}' все справно!", "diagnosis_found_warnings": "Знайдено {warnings} пунктів, які можна поліпшити для {category}.", "diagnosis_found_errors_and_warnings": "Знайдено {errors} істотний (і) питання (и) (і {warnings} попередження (я)), що відносяться до {category}!", "diagnosis_found_errors": "Знайдена {errors} важлива проблема (і), пов'язана з {category}!", @@ -675,5 +675,13 @@ "log_app_config_set": "Застосувати конфігурацію до застосунку '{}'", "service_not_reloading_because_conf_broken": "Неможливо перезавантажити/перезапустити службу '{name}', тому що її конфігурацію порушено: {errors}", "app_argument_password_help_optional": "Введіть один пробіл, щоб очистити пароль", - "app_argument_password_help_keep": "Натисніть Enter, щоб зберегти поточне значення" -} \ No newline at end of file + "app_argument_password_help_keep": "Натисніть Enter, щоб зберегти поточне значення", + "domain_registrar_is_not_configured": "Реєстратор ще не конфігуровано для домену {domain}.", + "domain_dns_push_not_applicable": "Функція автоматичної конфігурації DNS не застосовується до домену {domain}. Вам слід вручну конфігурувати записи DNS відповідно до документації за адресою https://yunohost.org/dns_config.", + "domain_dns_registrar_not_supported": "YunoHost не зміг автоматично виявити реєстратора, який обробляє цей домен. Вам слід вручну конфігурувати записи DNS відповідно до документації за адресою https://yunohost.org/dns.", + "diagnosis_http_special_use_tld": "Домен {domain} базується на спеціальному домені верхнього рівня (TLD), такому як .local або .test, і тому не очікується, що він буде відкритий за межами локальної мережі.", + "domain_dns_push_managed_in_parent_domain": "Функцією автоконфігурації DNS керує батьківський домен {parent_domain}.", + "domain_dns_registrar_managed_in_parent_domain": "Цей домен є піддоменом {parent_domain_link}. Конфігурацією реєстратора DNS слід керувати на панелі конфігурації {parent_domain}.", + "domain_dns_registrar_yunohost": "Цей домен є nohost.me/nohost.st/ynh.fr, тому його конфігурація DNS автоматично обробляється YunoHost без будь-якої подальшої конфігурації. (див. команду 'yunohost dyndns update')", + "domain_dns_conf_special_use_tld": "Цей домен засновано на спеціальному домені верхнього рівня (TLD), такому як .local або .test, і тому не очікується, що він матиме актуальні записи DNS." +} From fe82fafa6d4cf565903e206c5bf918f5de28a577 Mon Sep 17 00:00:00 2001 From: ppr Date: Sun, 3 Oct 2021 09:15:09 +0000 Subject: [PATCH 55/81] Translated using Weblate (French) Currently translated at 99.1% (700 of 706 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/fr/ --- locales/fr.json | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/locales/fr.json b/locales/fr.json index 29e6da673..ba2042ffb 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -4,7 +4,7 @@ "admin_password_change_failed": "Impossible de changer le mot de passe", "admin_password_changed": "Le mot de passe d'administration a été modifié", "app_already_installed": "{app} est déjà installé", - "app_argument_choice_invalid": "Choix invalide pour le paramètre '{name}'. Les valeurs acceptées sont {choices}, au lieu de '{value}'", + "app_argument_choice_invalid": "Choisir une valeur valide pour l'argument '{name}' : '{value}' ne fait pas partie des choix disponibles ({choices})", "app_argument_invalid": "Valeur invalide pour le paramètre '{name}' : {error}", "app_argument_required": "Le paramètre '{name}' est requis", "app_extraction_failed": "Impossible d'extraire les fichiers d'installation", @@ -632,7 +632,7 @@ "global_settings_setting_security_webadmin_allowlist": "Adresses IP autorisées à accéder à la webadmin. Elles doivent être séparées par une virgule.", "global_settings_setting_security_webadmin_allowlist_enabled": "Autoriser seulement certaines IP à accéder à la webadmin.", "diagnosis_http_localdomain": "Le domaine {domain}, avec un TLD .local, ne devrait pas être exposé en dehors du réseau local.", - "diagnosis_dns_specialusedomain": "Le domaine {domain} est basé sur un domaine de premier niveau (TLD) à usage spécial et ne devrait donc pas avoir d'enregistrements DNS réels.", + "diagnosis_dns_specialusedomain": "Le domaine {domain} est basé sur un domaine de premier niveau (TLD) à usage spécial comme .local ou .test et ne devrait donc pas avoir d'enregistrements DNS réels.", "invalid_password": "Mot de passe incorrect", "ldap_server_is_down_restart_it": "Le service LDAP est en panne, essayez de le redémarrer...", "ldap_server_down": "Impossible d'atteindre le serveur LDAP", @@ -705,5 +705,7 @@ "domain_config_auth_application_secret": "Clé secrète de l'application", "ldap_attribute_already_exists": "L'attribut LDAP '{attribute}' existe déjà avec la valeur '{value}'", "log_domain_config_set": "Mettre à jour la configuration du domaine '{}'", - "log_domain_dns_push": "Pousser les enregistrements DNS pour le domaine '{}'" + "log_domain_dns_push": "Pousser les enregistrements DNS pour le domaine '{}'", + "diagnosis_http_special_use_tld": "Le domaine {domain} est basé sur un domaine de premier niveau (TLD) à usage spécial tel que .local ou .test et n'est donc pas censé être exposé en dehors du réseau local.", + "domain_dns_conf_special_use_tld": "Ce domaine est basé sur un domaine de premier niveau (TLD) à usage spécial tel que .local ou .test et ne devrait donc pas avoir d'enregistrements DNS réels." } From 9019d75cb8281873b62b4d51aa0211f0734bca0a Mon Sep 17 00:00:00 2001 From: ppr Date: Sun, 3 Oct 2021 09:18:06 +0000 Subject: [PATCH 56/81] Translated using Weblate (French) Currently translated at 99.7% (704 of 706 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/fr/ --- locales/fr.json | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/locales/fr.json b/locales/fr.json index ba2042ffb..10f05a848 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -593,7 +593,7 @@ "diagnosis_package_installed_from_sury": "Des paquets du système devraient être rétrogradé de version", "additional_urls_already_added": "URL supplémentaire '{url}' déjà ajoutée pour la permission '{permission}'", "unknown_main_domain_path": "Domaine ou chemin inconnu pour '{app}'. Vous devez spécifier un domaine et un chemin pour pouvoir spécifier une URL pour l'autorisation.", - "show_tile_cant_be_enabled_for_regex": "Vous ne pouvez pas activer 'show_tile' pour le moment, car l'URL de l'autorisation '{permission}' est une expression régulière", + "show_tile_cant_be_enabled_for_regex": "Vous ne pouvez pas activer 'show_tile' pour le moment, cela car l'URL de l'autorisation '{permission}' est une expression régulière", "show_tile_cant_be_enabled_for_url_not_defined": "Vous ne pouvez pas activer 'show_tile' pour le moment, car vous devez d'abord définir une URL pour l'autorisation '{permission}'", "regex_with_only_domain": "Vous ne pouvez pas utiliser une expression régulière pour le domaine, uniquement pour le chemin", "regex_incompatible_with_tile": "/!\\ Packagers ! La permission '{permission}' a 'show_tile' définie sur 'true' et vous ne pouvez donc pas définir une URL regex comme URL principale", @@ -678,7 +678,7 @@ "app_argument_password_help_optional": "Tapez un espace pour vider le mot de passe", "domain_registrar_is_not_configured": "Le registrar n'est pas encore configuré pour le domaine {domain}.", "domain_dns_push_not_applicable": "La fonction de configuration DNS automatique n'est pas applicable au domaine {domain}. Vous devez configurer manuellement vos enregistrements DNS en suivant la documentation sur https://yunohost.org/dns_config.", - "domain_dns_registrar_yunohost": "Ce domaine est nohost.me / nohost.st / ynh.fr et sa configuration DNS est donc automatiquement gérée par YunoHost sans autre configuration. (voir la commande 'yunohost dyndns update')", + "domain_dns_registrar_yunohost": "Ce domaine est de type nohost.me / nohost.st / ynh.fr et sa configuration DNS est donc automatiquement gérée par YunoHost sans qu'il n'y ait d'autre configuration à faire. (voir la commande 'yunohost dyndns update')", "domain_dns_registrar_supported": "YunoHost a détecté automatiquement que ce domaine est géré par le registrar **{registrar}**. Si vous le souhaitez, YunoHost configurera automatiquement cette zone DNS, si vous lui fournissez les identifiants API appropriés. Vous pouvez trouver de la documentation sur la façon d'obtenir vos identifiants API sur cette page : https://yunohost.org/registar_api_{registrar}. (Vous pouvez également configurer manuellement vos enregistrements DNS en suivant la documentation sur https://yunohost.org/dns )", "domain_config_features_disclaimer": "Jusqu'à présent, l'activation/désactivation des fonctionnalités de messagerie ou XMPP n'a d'impact que sur la configuration DNS recommandée et automatique, et non sur les configurations système !", "domain_dns_push_managed_in_parent_domain": "La fonctionnalité de configuration DNS automatique est gérée dans le domaine parent {parent_domain}.", @@ -707,5 +707,7 @@ "log_domain_config_set": "Mettre à jour la configuration du domaine '{}'", "log_domain_dns_push": "Pousser les enregistrements DNS pour le domaine '{}'", "diagnosis_http_special_use_tld": "Le domaine {domain} est basé sur un domaine de premier niveau (TLD) à usage spécial tel que .local ou .test et n'est donc pas censé être exposé en dehors du réseau local.", - "domain_dns_conf_special_use_tld": "Ce domaine est basé sur un domaine de premier niveau (TLD) à usage spécial tel que .local ou .test et ne devrait donc pas avoir d'enregistrements DNS réels." + "domain_dns_conf_special_use_tld": "Ce domaine est basé sur un domaine de premier niveau (TLD) à usage spécial tel que .local ou .test et ne devrait donc pas avoir d'enregistrements DNS réels.", + "other_available_options": "... et {n} autres options disponibles non affichées", + "domain_config_auth_consumer_key": "Consumer key" } From 98c411ec9e09fe332346f7f68c208da170903045 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89ric=20Gaspar?= Date: Sun, 3 Oct 2021 10:03:26 +0000 Subject: [PATCH 57/81] Translated using Weblate (French) Currently translated at 100.0% (706 of 706 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/fr/ --- locales/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locales/fr.json b/locales/fr.json index 10f05a848..08224a2a0 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -685,7 +685,7 @@ "domain_dns_registrar_managed_in_parent_domain": "Ce domaine est un sous-domaine de {parent_domain_link}. La configuration du registrar DNS doit être gérée dans le panneau de configuration de {parent_domain}.", "domain_dns_registrar_not_supported": "YunoHost n'a pas pu détecter automatiquement le bureau d'enregistrement gérant ce domaine. Vous devez configurer manuellement vos enregistrements DNS en suivant la documentation sur https://yunohost.org/dns.", "domain_dns_registrar_experimental": "Jusqu'à présent, l'interface avec l'API de **{registrar}** n'a pas été correctement testée et revue par la communauté YunoHost. L'assistance est **très expérimentale** - soyez prudent !", - "domain_dns_push_failed_to_authenticate": "Échec de l'authentification sur l'API du bureau d'enregistrement pour le domaine « {domain} ». Très probablement les informations d'identification sont incorrectes ? (Error: {error})", + "domain_dns_push_failed_to_authenticate": "Échec de l'authentification sur l'API du bureau d'enregistrement pour le domaine « {domain} ». Très probablement les informations d'identification sont incorrectes ? (Erreur : {error})", "domain_dns_push_failed_to_list": "Échec de la liste des enregistrements actuels à l'aide de l'API du registraire : {error}", "domain_dns_push_already_up_to_date": "Dossiers déjà à jour.", "domain_dns_pushing": "Transmission des enregistrements DNS...", From fb4d870e1f871764e65db267c7c6f55ddaab9c64 Mon Sep 17 00:00:00 2001 From: mifegui Date: Sun, 3 Oct 2021 15:56:23 +0000 Subject: [PATCH 58/81] Translated using Weblate (Portuguese) Currently translated at 29.4% (208 of 706 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/pt/ --- locales/pt.json | 71 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 67 insertions(+), 4 deletions(-) diff --git a/locales/pt.json b/locales/pt.json index 534e0cb27..d285948be 100644 --- a/locales/pt.json +++ b/locales/pt.json @@ -109,7 +109,7 @@ "backup_output_directory_forbidden": "Escolha um diretório de saída diferente. Backups não podem ser criados nos subdiretórios /bin, /boot, /dev, /etc, /lib, /root, /run, /sbin, /sys, /usr, /var ou /home/yunohost.backup/archives", "app_already_installed_cant_change_url": "Este aplicativo já está instalado. A URL não pode ser alterada apenas por esta função. Confira em `app changeurl` se está disponível.", "app_already_up_to_date": "{app} já está atualizado", - "app_argument_choice_invalid": "Use uma das opções '{choices}' para o argumento '{name}' em vez de '{value}'", + "app_argument_choice_invalid": "Escolha um valor válido para o argumento '{name}' : '{value}' não está entre as opções disponíveis ({choices})", "app_argument_invalid": "Escolha um valor válido para o argumento '{name}': {error}", "app_argument_required": "O argumento '{name}' é obrigatório", "app_location_unavailable": "Esta url ou não está disponível ou está em conflito com outra(s) aplicação(ões) já instalada(s):\n{apps}", @@ -182,7 +182,7 @@ "backup_csv_creation_failed": "Não foi possível criar o arquivo CSV necessário para a restauração", "backup_csv_addition_failed": "Não foi possível adicionar os arquivos que estarão no backup ao arquivo CSV", "backup_create_size_estimation": "O arquivo irá conter cerca de {size} de dados.", - "backup_couldnt_bind": "Não foi possível vincular {src} ao {dest}", + "backup_couldnt_bind": "Não foi possível vincular {src} ao {dest}.", "certmanager_attempt_to_replace_valid_cert": "Você está tentando sobrescrever um certificado bom e válido para o domínio {domain}! (Use --force para prosseguir mesmo assim)", "backup_with_no_restore_script_for_app": "A aplicação {app} não tem um script de restauração, você não será capaz de automaticamente restaurar o backup dessa aplicação.", "backup_with_no_backup_script_for_app": "A aplicação '{app}' não tem um script de backup. Ignorando.", @@ -191,5 +191,68 @@ "backup_running_hooks": "Executando os hooks de backup...", "backup_permission": "Permissão de backup para {app}", "backup_output_symlink_dir_broken": "O diretório de seu arquivo '{path}' é um link simbólico quebrado. Talvez você tenha esquecido de re/montar ou conectar o dispositivo de armazenamento para onde o link aponta.", - "backup_output_directory_required": "Você deve especificar um diretório de saída para o backup" -} \ No newline at end of file + "backup_output_directory_required": "Você deve especificar um diretório de saída para o backup", + "diagnosis_description_apps": "Aplicações", + "diagnosis_apps_allgood": "Todos os apps instalados respeitam práticas básicas de empacotamento", + "diagnosis_apps_issue": "Um problema foi encontrado para o app {app}", + "diagnosis_apps_not_in_app_catalog": "Esta aplicação não está no catálogo de aplicações do YunoHost. Se estava no passado e foi removida, você deve considerar desinstalar este app já que ele não mais receberá atualizações e pode comprometer a integridade e segurança do seu sistema.", + "diagnosis_apps_broken": "Esta aplicação está atualmente marcada como quebrada no catálogo de apps do YunoHost. Isto pode ser um problema temporário enquanto os mantenedores consertam o problema. Enquanto isso, atualizar este app está desabilitado.", + "diagnosis_apps_bad_quality": "Esta aplicação está atualmente marcada como quebrada no catálogo de apps do YunoHost. Isto pode ser um problema temporário enquanto os mantenedores consertam o problema. Enquanto isso, atualizar este app está desabilitado.", + "diagnosis_apps_outdated_ynh_requirement": "A versão instalada deste app requer tão somente yunohost >= 2.x, o que tende a indicar que o app não está atualizado com as práticas de empacotamento recomendadas. Você deve considerar seriamente atualizá-lo.", + "diagnosis_apps_deprecated_practices": "A versão instalada deste app usa práticas de empacotamento extremamente velhas que não são mais usadas. Você deve considerar seriamente atualizá-lo.", + "certmanager_domain_http_not_working": "O domínio {domain} não parece estar acessível por HTTP. Por favor cheque a categoria 'Web' no diagnóstico para mais informações. (Se você sabe o que está fazendo, use '--no-checks' para desativar estas checagens.)", + "diagnosis_description_regenconf": "Configurações do sistema", + "diagnosis_description_services": "Cheque de status dos serviços", + "diagnosis_basesystem_hardware": "A arquitetura hardware do servidor é {virt} {arch}", + "diagnosis_description_web": "Web", + "diagnosis_basesystem_ynh_single_version": "Versão {package}: {version} ({repo})", + "diagnosis_basesystem_ynh_main_version": "O servidor está rodando YunoHost {main_version} ({repo})", + "app_config_unable_to_apply": "Falha ao aplicar valores do painel de configuração.", + "app_config_unable_to_read": "Falha ao ler valores do painel de configuração.", + "config_apply_failed": "Aplicar as novas configuração falhou: {error}", + "config_cant_set_value_on_section": "Você não pode setar um único valor na seção de configuração inteira.", + "config_validate_time": "Deve ser um horário válido como HH:MM", + "config_validate_url": "Deve ser uma URL válida", + "config_version_not_supported": "Versões do painel de configuração '{version}' não são suportadas.", + "danger": "Perigo:", + "diagnosis_basesystem_ynh_inconsistent_versions": "Você está executando versões inconsistentes dos pacotes YunoHost... provavelmente por causa de uma atualização parcial ou que falhou.", + "diagnosis_description_basesystem": "Sistema base", + "certmanager_cert_signing_failed": "Não foi possível assinar o novo certificado", + "certmanager_unable_to_parse_self_CA_name": "Não foi possível processar nome da autoridade de auto-assinatura (arquivo: {file})", + "confirm_app_install_warning": "Aviso: Pode ser que essa aplicação funcione, mas ela não está bem integrada ao YunoHost. Algumas funcionalidades como single sign-on e backup/restauração podem não estar disponíveis. Instalar mesmo assim? [{answers}] ", + "config_forbidden_keyword": "A palavra chave '{keyword}' é reservada, você não pode criar ou usar um painel de configuração com uma pergunta com esse id.", + "config_no_panel": "Painel de configuração não encontrado.", + "config_unknown_filter_key": "A chave de filtro '{filter_key}' está incorreta.", + "config_validate_color": "Deve ser uma cor RGB hexadecimal válida", + "config_validate_date": "Deve ser uma data válida como no formato AAAA-MM-DD", + "config_validate_email": "Deve ser um email válido", + "diagnosis_basesystem_kernel": "O servidor está rodando Linux kernel {kernel_version}", + "diagnosis_cache_still_valid": "(O cache para a categoria de diagnóstico {category} ainda é valido. Não será diagnosticada novamente ainda)", + "diagnosis_cant_run_because_of_dep": "Impossível fazer diagnóstico para {category} enquanto ainda existem problemas importantes relacionados a {dep}.", + "diagnosis_diskusage_low": "Unidade de armazenamento {mountpoint} (no dispositivo {device}_) tem somente {free} ({free_percent}%) de espaço restante (de {total}). Tenha cuidado.", + "diagnosis_description_ip": "Conectividade internet", + "diagnosis_description_dnsrecords": "Registros DNS", + "diagnosis_description_mail": "Email", + "certmanager_domain_not_diagnosed_yet": "Ainda não há resultado de diagnóstico para o domínio {domain}. Por favor re-execute um diagnóstico para as categorias 'Registros DNS' e 'Web' na seção de diagnósticos para checar se o domínio está pronto para o Let's Encrypt. (Ou, se você souber o que está fazendo, use '--no-checks' para desativar estas checagens.)", + "diagnosis_basesystem_host": "O Servidor está rodando Debian {debian_version}", + "diagnosis_description_systemresources": "Recursos do sistema", + "certmanager_acme_not_configured_for_domain": "O challenge ACME não pode ser realizado para {domain} porque o código correspondente na configuração do nginx está ausente... Por favor tenha certeza de que sua configuração do nginx está atualizada executando o comando `yunohost tools regen-conf nginx --dry-run --with-diff`.", + "certmanager_attempt_to_renew_nonLE_cert": "O certificado para o domínio '{domain}' não foi emitido pelo Let's Encrypt. Não é possível renová-lo automaticamente!", + "certmanager_attempt_to_renew_valid_cert": "O certificado para o domínio '{domain}' não esta prestes a expirar! (Você pode usar --force se saber o que está fazendo)", + "certmanager_cannot_read_cert": "Algo de errado aconteceu ao tentar abrir o atual certificado para o domínio {domain} (arquivo: {file}), motivo: {reason}", + "certmanager_cert_install_success": "Certificado Let's Encrypt foi instalado para o domínio '{domain}'", + "certmanager_cert_install_success_selfsigned": "Certificado autoassinado foi instalado para o domínio '{domain}'", + "certmanager_certificate_fetching_or_enabling_failed": "Tentativa de usar o novo certificado para o domínio {domain} não funcionou...", + "certmanager_domain_cert_not_selfsigned": "O certificado para o domínio {domain} não é autoassinado. Você tem certeza que quer substituí-lo? (Use '--force' para fazê-lo)", + "certmanager_domain_dns_ip_differs_from_public_ip": "O registro de DNS para o domínio '{domain}' é diferente do IP deste servidor. Por favor cheque a categoria 'Registros DNS' (básico) no diagnóstico para mais informações. Se você modificou recentemente o registro 'A', espere um tempo para ele se propagar (alguns serviços de checagem de propagação de DNS estão disponíveis online). (Se você sabe o que está fazendo, use '--no-checks' para desativar estas checagens.)", + "certmanager_hit_rate_limit": "Foram emitidos certificados demais para este conjunto de domínios {domain} recentemente. Por favor tente novamente mais tarde. Veja https://letsencrypt.org/docs/rate-limits/ para mais detalhes", + "certmanager_no_cert_file": "Não foi possível ler o arquivo de certificado para o domínio {domain} (arquivo: {file})", + "certmanager_self_ca_conf_file_not_found": "Não foi possível encontrar o arquivo de configuração para a autoridade de auto-assinatura (arquivo: {file})", + "confirm_app_install_danger": "ATENÇÃO! Sabe-se que esta aplicação ainda é experimental (isso se não que explicitamente não funciona)! Você provavelmente NÃO deve instalar ela a não ser que você saiba o que você está fazendo. NENHUM SUPORTE será fornecido se esta aplicação não funcionar ou quebrar o seu sistema... Se você está disposto a tomar esse rico de toda forma, digite '{answers}'", + "confirm_app_install_thirdparty": "ATENÇÃO! Essa aplicação não faz parte do catálogo do YunoHost. Instalar aplicações de terceiros pode comprometer a integridade e segurança do seu sistema. Você provavelmente NÃO deve instalá-la a não ser que você saiba o que você está fazendo. NENHUM SUPORTE será fornecido se este app não funcionar ou quebrar seu sistema... Se você está disposto a tomar este risco de toda forma, digite '{answers}'", + "diagnosis_description_ports": "Exposição de portas", + "diagnosis_basesystem_hardware_model": "O modelo do servidor é {model}", + "diagnosis_backports_in_sources_list": "Parece que o apt (o gerenciador de pacotes) está configurado para usar o repositório backport. A não ser que você saiba o que você esteá fazendo, desencorajamos fortemente a instalação de pacotes de backports porque é provável que crie instabilidades ou conflitos no seu sistema.", + "certmanager_cert_renew_success": "Certificado Let's Encrypt renovado para o domínio '{domain}'", + "certmanager_warning_subdomain_dns_record": "O subdomínio '{subdomain}' não resolve para o mesmo IP que '{domain}'. Algumas funcionalidades não estarão disponíveis até que você conserte isto e regenere o certificado." +} From 30ed2cd0b0d59328f7bb228d876406e7bac78ffe Mon Sep 17 00:00:00 2001 From: Tymofii-Lytvynenko Date: Sun, 3 Oct 2021 14:20:03 +0000 Subject: [PATCH 59/81] Translated using Weblate (Ukrainian) Currently translated at 100.0% (706 of 706 strings) Translation: YunoHost/core Translate-URL: https://translate.yunohost.org/projects/yunohost/core/uk/ --- locales/uk.json | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/locales/uk.json b/locales/uk.json index 814fa56a9..b54d81fbd 100644 --- a/locales/uk.json +++ b/locales/uk.json @@ -683,5 +683,31 @@ "domain_dns_push_managed_in_parent_domain": "Функцією автоконфігурації DNS керує батьківський домен {parent_domain}.", "domain_dns_registrar_managed_in_parent_domain": "Цей домен є піддоменом {parent_domain_link}. Конфігурацією реєстратора DNS слід керувати на панелі конфігурації {parent_domain}.", "domain_dns_registrar_yunohost": "Цей домен є nohost.me/nohost.st/ynh.fr, тому його конфігурація DNS автоматично обробляється YunoHost без будь-якої подальшої конфігурації. (див. команду 'yunohost dyndns update')", - "domain_dns_conf_special_use_tld": "Цей домен засновано на спеціальному домені верхнього рівня (TLD), такому як .local або .test, і тому не очікується, що він матиме актуальні записи DNS." + "domain_dns_conf_special_use_tld": "Цей домен засновано на спеціальному домені верхнього рівня (TLD), такому як .local або .test, і тому не очікується, що він матиме актуальні записи DNS.", + "domain_dns_registrar_supported": "YunoHost автоматично визначив, що цей домен обслуговується реєстратором **{registrar}**. Якщо ви хочете, YunoHost автоматично налаштує цю DNS-зону, якщо ви надасте йому відповідні облікові дані API. Ви можете знайти документацію про те, як отримати реєстраційні дані API на цій сторінці: https://yunohost.org/registar_api_{registrar}. (Ви також можете вручну налаштувати свої DNS-записи, дотримуючись документації на https://yunohost.org/dns)", + "domain_dns_registrar_experimental": "Поки що інтерфейс з API **{registrar}** не був належним чином протестований і перевірений спільнотою YunoHost. Підтримка є **дуже експериментальною** - будьте обережні!", + "domain_dns_push_success": "Записи DNS оновлено!", + "domain_dns_push_failed": "Оновлення записів DNS зазнало невдачі.", + "domain_dns_push_partial_failure": "DNS-записи частково оновлено: повідомлялося про деякі попередження/помилки.", + "domain_config_mail_in": "Вхідні електронні листи", + "domain_config_mail_out": "Вихідні електронні листи", + "domain_config_auth_token": "Токен автентифікації", + "domain_config_auth_entrypoint": "Точка входу API", + "domain_config_auth_consumer_key": "Ключ споживача", + "domain_dns_push_failed_to_authenticate": "Неможливо пройти автентифікацію на API реєстратора для домену '{domain}'. Ймовірно, облікові дані недійсні? (Помилка: {error})", + "domain_dns_push_failed_to_list": "Не вдалося скласти список поточних записів за допомогою API реєстратора: {error}", + "domain_dns_push_record_failed": "Не вдалося виконати дію {action} запису {type}/{name} : {error}", + "domain_config_features_disclaimer": "Поки що вмикання/вимикання функцій пошти або XMPP впливає тільки на рекомендовану та автоконфігурацію DNS, але не на конфігурацію системи!", + "domain_config_xmpp": "Миттєвий обмін повідомленнями (XMPP)", + "domain_config_auth_key": "Ключ автентифікації", + "domain_config_auth_secret": "Секрет автентифікації", + "domain_config_api_protocol": "API-протокол", + "domain_config_auth_application_key": "Ключ застосунку", + "domain_config_auth_application_secret": "Таємний ключ застосунку", + "log_domain_config_set": "Оновлення конфігурації для домену '{}'", + "log_domain_dns_push": "Передавання записів DNS для домену '{}'", + "other_available_options": "...і {n} інших доступних опцій, які не показано", + "domain_dns_pushing": "Передання записів DNS...", + "ldap_attribute_already_exists": "Атрибут LDAP '{attribute}' вже існує зі значенням '{value}'", + "domain_dns_push_already_up_to_date": "Записи вже оновлені, нічого не потрібно робити." } From 592a998230eb44a3365bd8a795c53598dc76e35b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Mon, 4 Oct 2021 01:28:49 +0200 Subject: [PATCH 60/81] Update locales/fr.json --- locales/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locales/fr.json b/locales/fr.json index 08224a2a0..123270bd6 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -4,7 +4,7 @@ "admin_password_change_failed": "Impossible de changer le mot de passe", "admin_password_changed": "Le mot de passe d'administration a été modifié", "app_already_installed": "{app} est déjà installé", - "app_argument_choice_invalid": "Choisir une valeur valide pour l'argument '{name}' : '{value}' ne fait pas partie des choix disponibles ({choices})", + "app_argument_choice_invalid": "Choisissez une valeur valide pour l'argument '{name}' : '{value}' ne fait pas partie des choix disponibles ({choices})", "app_argument_invalid": "Valeur invalide pour le paramètre '{name}' : {error}", "app_argument_required": "Le paramètre '{name}' est requis", "app_extraction_failed": "Impossible d'extraire les fichiers d'installation", From a552700ca344f21fa390f03e67a5bfedd64bb4db Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Mon, 4 Oct 2021 01:34:16 +0200 Subject: [PATCH 61/81] Update changelog for 4.3.1.1 --- debian/changelog | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/debian/changelog b/debian/changelog index 84a29ed70..a10c83888 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,13 @@ +yunohost (4.3.1.1) testing; urgency=low + + - [enh] app helpers: Update n version ([#1347](https://github.com/YunoHost/yunohost/pull/1347)) + - [enh] Misc app.py refactoring + Prevent change_url from being used to move a fulldomain app to a subpath ([#1346](https://github.com/YunoHost/yunohost/pull/1346)) + - [i18n] Translations updated for French, Galician, Portuguese, Ukrainian + + Thanks to all contributors <3 ! (Éric Gaspar, José M, mifegui, ppr, Tymofii-Lytvynenko) + + -- Alexandre Aubin Mon, 04 Oct 2021 01:33:22 +0200 + yunohost (4.3.1) testing; urgency=low - [fix] diagnosis: new app diagnosis grep reporing comments as issues ([#1333](https://github.com/YunoHost/yunohost/pull/1333)) From a68f98d8007be816d07695125502a8346d1dbbab Mon Sep 17 00:00:00 2001 From: yunohost-bot Date: Sun, 3 Oct 2021 23:56:11 +0000 Subject: [PATCH 62/81] [CI] Format code --- src/yunohost/tests/test_appurl.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/yunohost/tests/test_appurl.py b/src/yunohost/tests/test_appurl.py index ca953dcf7..cf2c6c2c3 100644 --- a/src/yunohost/tests/test_appurl.py +++ b/src/yunohost/tests/test_appurl.py @@ -4,7 +4,12 @@ import os from .conftest import get_test_apps_dir from yunohost.utils.error import YunohostError -from yunohost.app import app_install, app_remove, _is_app_repo_url, _parse_app_instance_name +from yunohost.app import ( + app_install, + app_remove, + _is_app_repo_url, + _parse_app_instance_name, +) from yunohost.domain import _get_maindomain, domain_url_available from yunohost.permission import _validate_and_sanitize_permission_url @@ -30,14 +35,14 @@ def teardown_function(function): def test_parse_app_instance_name(): - assert _parse_app_instance_name('yolo') == ('yolo', 1) - assert _parse_app_instance_name('yolo1') == ('yolo1', 1) - assert _parse_app_instance_name('yolo__0') == ('yolo__0', 1) - assert _parse_app_instance_name('yolo__1') == ('yolo', 1) - assert _parse_app_instance_name('yolo__23') == ('yolo', 23) - assert _parse_app_instance_name('yolo__42__72') == ('yolo__42', 72) - assert _parse_app_instance_name('yolo__23qdqsd') == ('yolo__23qdqsd', 1) - assert _parse_app_instance_name('yolo__23qdqsd56') == ('yolo__23qdqsd56', 1) + assert _parse_app_instance_name("yolo") == ("yolo", 1) + assert _parse_app_instance_name("yolo1") == ("yolo1", 1) + assert _parse_app_instance_name("yolo__0") == ("yolo__0", 1) + assert _parse_app_instance_name("yolo__1") == ("yolo", 1) + assert _parse_app_instance_name("yolo__23") == ("yolo", 23) + assert _parse_app_instance_name("yolo__42__72") == ("yolo__42", 72) + assert _parse_app_instance_name("yolo__23qdqsd") == ("yolo__23qdqsd", 1) + assert _parse_app_instance_name("yolo__23qdqsd56") == ("yolo__23qdqsd56", 1) def test_repo_url_definition(): From 75b36f3b4a816e9410c909043a759649ff253f8a Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Mon, 4 Oct 2021 03:40:41 +0200 Subject: [PATCH 63/81] tests: Try to fix mypy again /o\ --- src/yunohost/app.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 1c05ce20b..821ef06b0 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -2418,13 +2418,13 @@ def _parse_app_instance_name(app_instance_name: str) -> Tuple[str, int]: match = re_app_instance_name.match(app_instance_name) assert match, f"Could not parse app instance name : {app_instance_name}" appid = match.groupdict().get("appid") - app_instance_nb = match.groupdict().get("appinstancenb") or "1" + app_instance_nb_ = match.groupdict().get("appinstancenb") or "1" if not appid: raise Exception(f"Could not parse app instance name : {app_instance_name}") - if not str(app_instance_nb).isdigit(): + if not str(app_instance_nb_).isdigit(): raise Exception(f"Could not parse app instance name : {app_instance_name}") else: - app_instance_nb = int(str(app_instance_nb)) + app_instance_nb = int(str(app_instance_nb_)) return (appid, app_instance_nb) From 2157576bf6446f95243a3a848bf0ec990ee015c0 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Mon, 4 Oct 2021 03:47:12 +0200 Subject: [PATCH 64/81] i18n typos --- locales/gl.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/locales/gl.json b/locales/gl.json index d70d7a561..987093df8 100644 --- a/locales/gl.json +++ b/locales/gl.json @@ -680,7 +680,7 @@ "domain_dns_conf_special_use_tld": "Este dominio baséase nun dominio de alto-nivel (TLD) de uso especial como .local ou .test e por isto non é de agardar que teña rexistros DNS asociados.", "domain_dns_registrar_managed_in_parent_domain": "Este dominio é un subdominio de {parent_domain_link}. A configuración DNS debe xestionarse no panel de configuración de {parent_domain}'s.", "domain_dns_registrar_not_supported": "YunoHost non é quen de detectar a rexistradora que xestiona o dominio. Debes configurar manualmente os seus rexistros DNS seguindo a documentación en https://yunohost.org/dns.", - "domain_dns_registrar_experimental": "Ata o momento, a interface coa API de **{registar}** aínda non foi comprobada e revisada pola comunidade YunoHost. O soporte é **moi experimental** - ten coidado!", + "domain_dns_registrar_experimental": "Ata o momento, a interface coa API de **{registrar}** aínda non foi comprobada e revisada pola comunidade YunoHost. O soporte é **moi experimental** - ten coidado!", "domain_dns_push_failed_to_list": "Non se pode mostrar a lista actual de rexistros na API da rexistradora: {error}", "domain_dns_push_already_up_to_date": "Rexistros ao día, nada que facer.", "domain_dns_pushing": "Enviando rexistros DNS...", @@ -699,7 +699,7 @@ "log_domain_dns_push": "Enviar rexistros DNS para o dominio '{}'", "other_available_options": "... e outras {n} opcións dispoñibles non mostradas", "domain_dns_registrar_yunohost": "Este dominio un dos de nohost.me / nohost.st / ynh.fr e a configuración DNS xestionaa directamente YunoHost se máis requisitos. (mira o comando 'yunohost dyndns update')", - "domain_dns_registrar_supported": "YunoHost detectou automáticamente que este dominio está xestionado pola rexistradora **{registar}**. Se queres, YunoHost pode configurar automáticamente as súas zonas DNS, se proporcionas as credenciais de acceso á API. Podes ver a documentación sobre como obter as credenciais da API nesta páxina: https://yunohost.org/registar_api_{registrar}. (Tamén podes configurar manualmente os rexistros DNS seguindo a documentación en https://yunohost.org/dns )", + "domain_dns_registrar_supported": "YunoHost detectou automáticamente que este dominio está xestionado pola rexistradora **{registrar}**. Se queres, YunoHost pode configurar automáticamente as súas zonas DNS, se proporcionas as credenciais de acceso á API. Podes ver a documentación sobre como obter as credenciais da API nesta páxina: https://yunohost.org/registrar_api_{registrar}. (Tamén podes configurar manualmente os rexistros DNS seguindo a documentación en https://yunohost.org/dns )", "domain_dns_push_partial_failure": "Actualización parcial dos rexistros DNS: informouse dalgúns avisos/erros.", "domain_config_auth_token": "Token de autenticación", "domain_config_auth_key": "Chave de autenticación", From 4739859598cc7240a58a6175941f109cb78b8ab6 Mon Sep 17 00:00:00 2001 From: Kay0u Date: Mon, 4 Oct 2021 11:52:12 +0200 Subject: [PATCH 65/81] fix app upgrade --- src/yunohost/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 821ef06b0..81b79ff48 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -507,7 +507,7 @@ def app_upgrade(app=[], url=None, file=None, force=False, no_safety_backup=False logger.warning(m18n.n("custom_app_url_required", app=app_instance_name)) continue elif app_dict["upgradable"] == "yes" or force: - new_app_src = app_dict["id"] + new_app_src = app_dict["manifest"]["id"] else: logger.success(m18n.n("app_already_up_to_date", app=app_instance_name)) continue From 9863263a284c933a29f8e001b73996db087f3629 Mon Sep 17 00:00:00 2001 From: Kay0u Date: Mon, 4 Oct 2021 12:21:10 +0200 Subject: [PATCH 66/81] test to install/upgrade/remove an app from the manifest --- src/yunohost/tests/test_apps.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/yunohost/tests/test_apps.py b/src/yunohost/tests/test_apps.py index 43125341b..db75aad02 100644 --- a/src/yunohost/tests/test_apps.py +++ b/src/yunohost/tests/test_apps.py @@ -189,6 +189,29 @@ def test_legacy_app_install_main_domain(): assert app_is_not_installed(main_domain, "legacy_app") +def test_app_from_catalog(): + main_domain = _get_maindomain() + + app_install("my_webapp", args="domain={main_domain}&path=/site&with_sftp=0&password=superpassword&is_public=1&with_mysql=0") + app_map_ = app_map(raw=True) + assert main_domain in app_map_ + assert "/site" in app_map_[main_domain] + assert "id" in app_map_[main_domain]["/site"] + assert app_map_[main_domain]["/site"]["id"] == "my_webapp" + + assert app_is_installed(main_domain, "my_webapp") + assert app_is_exposed_on_http(main_domain, "/site", "Custom Web App") + + # Try upgrade, should do nothing + app_upgrade("my_webapp") + # Force upgrade, should upgrade to the same version + app_upgrade("my_webapp", force=True) + + app_remove("my_webapp") + + assert app_is_not_installed(main_domain, "my_webapp") + + def test_legacy_app_install_secondary_domain(secondary_domain): install_legacy_app(secondary_domain, "/legacy") From 96e7f1444d866d1603014373756d5dea74e2de12 Mon Sep 17 00:00:00 2001 From: Kay0u Date: Mon, 4 Oct 2021 13:29:46 +0200 Subject: [PATCH 67/81] fix string in test_apps --- src/yunohost/tests/test_apps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/tests/test_apps.py b/src/yunohost/tests/test_apps.py index db75aad02..bba769ec4 100644 --- a/src/yunohost/tests/test_apps.py +++ b/src/yunohost/tests/test_apps.py @@ -192,7 +192,7 @@ def test_legacy_app_install_main_domain(): def test_app_from_catalog(): main_domain = _get_maindomain() - app_install("my_webapp", args="domain={main_domain}&path=/site&with_sftp=0&password=superpassword&is_public=1&with_mysql=0") + app_install("my_webapp", args=f"domain={main_domain}&path=/site&with_sftp=0&password=superpassword&is_public=1&with_mysql=0") app_map_ = app_map(raw=True) assert main_domain in app_map_ assert "/site" in app_map_[main_domain] From 32998b118586259481b950f4b7874473e9f57fd5 Mon Sep 17 00:00:00 2001 From: Kay0u Date: Mon, 4 Oct 2021 14:33:30 +0200 Subject: [PATCH 68/81] my_webapp is to clean too --- src/yunohost/tests/test_apps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/tests/test_apps.py b/src/yunohost/tests/test_apps.py index bba769ec4..33af7256f 100644 --- a/src/yunohost/tests/test_apps.py +++ b/src/yunohost/tests/test_apps.py @@ -41,7 +41,7 @@ def clean(): os.system("mkdir -p /etc/ssowat/") app_ssowatconf() - test_apps = ["break_yo_system", "legacy_app", "legacy_app__2", "full_domain_app"] + test_apps = ["break_yo_system", "legacy_app", "legacy_app__2", "full_domain_app", "my_webapp"] for test_app in test_apps: From 27721749da10db3979b5629fdb3bbe83f3e00b89 Mon Sep 17 00:00:00 2001 From: yunohost-bot Date: Mon, 4 Oct 2021 12:50:57 +0000 Subject: [PATCH 69/81] [CI] Format code --- src/yunohost/tests/test_apps.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/yunohost/tests/test_apps.py b/src/yunohost/tests/test_apps.py index 33af7256f..22e18ec9a 100644 --- a/src/yunohost/tests/test_apps.py +++ b/src/yunohost/tests/test_apps.py @@ -41,7 +41,13 @@ def clean(): os.system("mkdir -p /etc/ssowat/") app_ssowatconf() - test_apps = ["break_yo_system", "legacy_app", "legacy_app__2", "full_domain_app", "my_webapp"] + test_apps = [ + "break_yo_system", + "legacy_app", + "legacy_app__2", + "full_domain_app", + "my_webapp", + ] for test_app in test_apps: @@ -192,7 +198,10 @@ def test_legacy_app_install_main_domain(): def test_app_from_catalog(): main_domain = _get_maindomain() - app_install("my_webapp", args=f"domain={main_domain}&path=/site&with_sftp=0&password=superpassword&is_public=1&with_mysql=0") + app_install( + "my_webapp", + args=f"domain={main_domain}&path=/site&with_sftp=0&password=superpassword&is_public=1&with_mysql=0", + ) app_map_ = app_map(raw=True) assert main_domain in app_map_ assert "/site" in app_map_[main_domain] From 54d901ad7820f3bb1895fba86ff651add08a048b Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 12:26:21 +0200 Subject: [PATCH 70/81] config: handle case where file quetion didnt get modified from webadmin, in which case self.value contains a path --- src/yunohost/utils/config.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/yunohost/utils/config.py b/src/yunohost/utils/config.py index 27a9e1533..2a1159042 100644 --- a/src/yunohost/utils/config.py +++ b/src/yunohost/utils/config.py @@ -1019,10 +1019,9 @@ class FileQuestion(Question): FileQuestion.upload_dirs += [upload_dir] logger.debug(f"Saving file {self.name} for file question into {file_path}") - if Moulinette.interface.type != "api": + if Moulinette.interface.type != "api" or (self.value.startswith("/") and os.path.exists(self.value)): content = read_file(str(self.value), file_mode="rb") - - if Moulinette.interface.type == "api": + else: content = b64decode(self.value) write_to_file(file_path, content, file_mode="wb") From 753c4e34ed37889efc7846951042fff2c7836589 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 12:32:23 +0200 Subject: [PATCH 71/81] Typo/wording --- data/helpers.d/config | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data/helpers.d/config b/data/helpers.d/config index d12316996..accedfce3 100644 --- a/data/helpers.d/config +++ b/data/helpers.d/config @@ -104,7 +104,7 @@ _ynh_app_config_apply_one() { cp "${!short_setting}" "$bind_file" fi ynh_store_file_checksum --file="$bind_file" --update_only - ynh_print_info --message="File '$bind_file' overwrited with ${!short_setting}" + ynh_print_info --message="File '$bind_file' overwritten with ${!short_setting}" fi # Save value in app settings @@ -124,7 +124,7 @@ _ynh_app_config_apply_one() { ynh_backup_if_checksum_is_different --file="$bind_file" echo "${!short_setting}" > "$bind_file" ynh_store_file_checksum --file="$bind_file" --update_only - ynh_print_info --message="File '$bind_file' overwrited with the content you provieded in '${short_setting}' question" + ynh_print_info --message="File '$bind_file' overwritten with the content provided in question '${short_setting}'" # Set value into a kind of key/value file else From 941cc29438e08a9a5f6579e099dd4fd7661c1758 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 12:35:06 +0200 Subject: [PATCH 72/81] bind_key -> bind_key_ to prevent yunohost from redacting key names which leads to broken log metadata.yml somehow --- data/helpers.d/config | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/data/helpers.d/config b/data/helpers.d/config index accedfce3..3f856ffa4 100644 --- a/data/helpers.d/config +++ b/data/helpers.d/config @@ -51,15 +51,15 @@ _ynh_app_config_get_one() { then bind=":/etc/yunohost/apps/$app/settings.yml" fi - local bind_key="$(echo "$bind" | cut -d: -f1)" - bind_key=${bind_key:-$short_setting} - if [[ "$bind_key" == *">"* ]]; + local bind_key_="$(echo "$bind" | cut -d: -f1)" + bind_key_=${bind_key_:-$short_setting} + if [[ "$bind_key_" == *">"* ]]; then - bind_after="$(echo "${bind_key}" | cut -d'>' -f1)" - bind_key="$(echo "${bind_key}" | cut -d'>' -f2)" + bind_after="$(echo "${bind_key_}" | cut -d'>' -f1)" + bind_key_="$(echo "${bind_key_}" | cut -d'>' -f2)" fi local bind_file="$(echo "$bind" | cut -d: -f2 | sed s@__FINALPATH__@$final_path@ | sed s/__APP__/$app/)" - old[$short_setting]="$(ynh_read_var_in_file --file="${bind_file}" --key="${bind_key}" --after="${bind_after}")" + old[$short_setting]="$(ynh_read_var_in_file --file="${bind_file}" --key="${bind_key_}" --after="${bind_after}")" fi } @@ -129,22 +129,22 @@ _ynh_app_config_apply_one() { # Set value into a kind of key/value file else local bind_after="" - local bind_key="$(echo "$bind" | cut -d: -f1)" - bind_key=${bind_key:-$short_setting} - if [[ "$bind_key" == *">"* ]]; + local bind_key_="$(echo "$bind" | cut -d: -f1)" + bind_key_=${bind_key_:-$short_setting} + if [[ "$bind_key_" == *">"* ]]; then - bind_after="$(echo "${bind_key}" | cut -d'>' -f1)" - bind_key="$(echo "${bind_key}" | cut -d'>' -f2)" + bind_after="$(echo "${bind_key_}" | cut -d'>' -f1)" + bind_key_="$(echo "${bind_key_}" | cut -d'>' -f2)" fi local bind_file="$(echo "$bind" | cut -d: -f2 | sed s@__FINALPATH__@$final_path@ | sed s/__APP__/$app/)" ynh_backup_if_checksum_is_different --file="$bind_file" - ynh_write_var_in_file --file="${bind_file}" --key="${bind_key}" --value="${!short_setting}" --after="${bind_after}" + ynh_write_var_in_file --file="${bind_file}" --key="${bind_key_}" --value="${!short_setting}" --after="${bind_after}" ynh_store_file_checksum --file="$bind_file" --update_only # We stored the info in settings in order to be able to upgrade the app ynh_app_setting_set --app=$app --key=$short_setting --value="${!short_setting}" - ynh_print_info --message="Configuration key '$bind_key' edited into $bind_file" + ynh_print_info --message="Configuration key '$bind_key_' edited into $bind_file" fi fi From 61ec02c97cb6d39b7a5ce3c665cbe1700e7493fa Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 12:47:32 +0200 Subject: [PATCH 73/81] lint: Kill bare excepts --- src/yunohost/log.py | 2 +- src/yunohost/permission.py | 2 +- tox.ini | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/yunohost/log.py b/src/yunohost/log.py index c99c1bbc9..d73a62cd0 100644 --- a/src/yunohost/log.py +++ b/src/yunohost/log.py @@ -407,7 +407,7 @@ def is_unit_operation( if isinstance(value, IOBase): try: context[field] = value.name - except: + except Exception: context[field] = "IOBase" operation_logger = OperationLogger(op_key, related_to, args=context) diff --git a/src/yunohost/permission.py b/src/yunohost/permission.py index 80d3b8602..1856046d6 100644 --- a/src/yunohost/permission.py +++ b/src/yunohost/permission.py @@ -474,7 +474,7 @@ def permission_create( protected=protected, sync_perm=sync_perm, ) - except: + except Exception: permission_delete(permission, force=True) raise diff --git a/tox.ini b/tox.ini index e79c70fec..733a0613d 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,7 @@ deps = py37-mypy: mypy >= 0.900 commands = py37-lint: flake8 src doc data tests --ignore E402,E501,E203,W503 --exclude src/yunohost/vendor - py37-invalidcode: flake8 src data --exclude src/yunohost/tests,src/yunohost/vendor --select F + py37-invalidcode: flake8 src data --exclude src/yunohost/tests,src/yunohost/vendor --select F,E722 py37-black-check: black --check --diff src doc data tests py37-black-run: black src doc data tests py37-mypy: mypy --ignore-missing-import --install-types --non-interactive --follow-imports silent src/yunohost/ --exclude (acme_tiny|data_migrations) From b0e8a58b244037db65480450521f3fa3014a4915 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 12:49:33 +0200 Subject: [PATCH 74/81] lint: Invalid escape sequences --- data/hooks/diagnosis/80-apps.py | 2 +- tox.ini | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/data/hooks/diagnosis/80-apps.py b/data/hooks/diagnosis/80-apps.py index a75193a45..5aec48ed8 100644 --- a/data/hooks/diagnosis/80-apps.py +++ b/data/hooks/diagnosis/80-apps.py @@ -76,7 +76,7 @@ class AppDiagnoser(Diagnoser): for deprecated_helper in deprecated_helpers: if ( os.system( - f"grep -hr '{deprecated_helper}' {app['setting_path']}/scripts/ | grep -v -q '^\s*#'" + f"grep -hr '{deprecated_helper}' {app['setting_path']}/scripts/ | grep -v -q '^\\s*#'" ) == 0 ): diff --git a/tox.ini b/tox.ini index 733a0613d..267134e57 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,7 @@ deps = py37-mypy: mypy >= 0.900 commands = py37-lint: flake8 src doc data tests --ignore E402,E501,E203,W503 --exclude src/yunohost/vendor - py37-invalidcode: flake8 src data --exclude src/yunohost/tests,src/yunohost/vendor --select F,E722 + py37-invalidcode: flake8 src data --exclude src/yunohost/tests,src/yunohost/vendor --select F,E722,W605 py37-black-check: black --check --diff src doc data tests py37-black-run: black src doc data tests py37-mypy: mypy --ignore-missing-import --install-types --non-interactive --follow-imports silent src/yunohost/ --exclude (acme_tiny|data_migrations) From de4b3825ab80a7b0f57639908812b0e00b7fc49d Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 12:50:25 +0200 Subject: [PATCH 75/81] Ambiguous var name --- src/yunohost/user.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yunohost/user.py b/src/yunohost/user.py index 7d89af443..c9f70e152 100644 --- a/src/yunohost/user.py +++ b/src/yunohost/user.py @@ -677,7 +677,7 @@ def user_import(operation_logger, csvfile, update=False, delete=False): def to_list(str_list): L = str_list.split(",") if str_list else [] - L = [l.strip() for l in L] + L = [element.strip() for element in L] return L existing_users = user_list()["users"] From 1baebeba6d5d095e8c7f88cd785b668fe83941ef Mon Sep 17 00:00:00 2001 From: yunohost-bot Date: Tue, 5 Oct 2021 11:13:38 +0000 Subject: [PATCH 76/81] [CI] Format code --- src/yunohost/utils/config.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/yunohost/utils/config.py b/src/yunohost/utils/config.py index 2a1159042..2363545cf 100644 --- a/src/yunohost/utils/config.py +++ b/src/yunohost/utils/config.py @@ -1019,7 +1019,9 @@ class FileQuestion(Question): FileQuestion.upload_dirs += [upload_dir] logger.debug(f"Saving file {self.name} for file question into {file_path}") - if Moulinette.interface.type != "api" or (self.value.startswith("/") and os.path.exists(self.value)): + if Moulinette.interface.type != "api" or ( + self.value.startswith("/") and os.path.exists(self.value) + ): content = read_file(str(self.value), file_mode="rb") else: content = b64decode(self.value) From 4cd5e9b632113dc595940de766a83be13aebfb31 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Tue, 5 Oct 2021 13:46:06 +0200 Subject: [PATCH 77/81] app_info: return a new is_webapp info meant to be used by API --- src/yunohost/app.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 81b79ff48..2b8d71abf 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -168,6 +168,9 @@ def app_info(app, full=False): absolute_app_name, _ = _parse_app_instance_name(app) ret["from_catalog"] = _load_apps_catalog()["apps"].get(absolute_app_name, {}) ret["upgradable"] = _app_upgradable(ret) + + ret["is_webapp"] = ("domain" in settings and "path" in settings) + ret["supports_change_url"] = os.path.exists( os.path.join(setting_path, "scripts", "change_url") ) From 74256845525799c674df5984afe2ec18974dbcd0 Mon Sep 17 00:00:00 2001 From: ljf Date: Wed, 6 Oct 2021 02:37:27 +0200 Subject: [PATCH 78/81] [enh] Add visible attribute support in cli --- src/yunohost/tests/test_questions.py | 96 ++++++++++++++ src/yunohost/utils/config.py | 182 ++++++++++++++++++++++++--- 2 files changed, 259 insertions(+), 19 deletions(-) diff --git a/src/yunohost/tests/test_questions.py b/src/yunohost/tests/test_questions.py index cf4e67733..b39990b73 100644 --- a/src/yunohost/tests/test_questions.py +++ b/src/yunohost/tests/test_questions.py @@ -15,6 +15,7 @@ from yunohost.utils.config import ( PathQuestion, BooleanQuestion, FileQuestion, + evaluate_simple_js_expression ) from yunohost.utils.error import YunohostError, YunohostValidationError @@ -2093,3 +2094,98 @@ def test_normalize_path(): assert PathQuestion.normalize("/macnuggets/") == "/macnuggets" assert PathQuestion.normalize("macnuggets/") == "/macnuggets" assert PathQuestion.normalize("////macnuggets///") == "/macnuggets" + +def test_simple_evaluate(): + context = { + 'a1': 1, + 'b2': 2, + 'c10': 10, + 'foo': 'bar', + 'comp': '1>2', + 'empty': '', + 'lorem': 'Lorem ipsum dolor et si qua met!', + 'warning': 'Warning! This sentence will fail!', + 'quote': "Je s'apelle Groot", + 'and_': '&&', + 'object': { 'a': 'Security risk' } + } + supported = { + '42': 42, + '9.5': 9.5, + "'bopbidibopbopbop'": 'bopbidibopbopbop', + 'true': True, + 'false': False, + 'null': None, + + # Math + '1 * (2 + 3 * (4 - 3))': 5, + '1 * (2 + 3 * (4 - 3)) > 10 - 2 || 3 * 2 > 9 - 2 * 3': True, + '(9 - 2) * 3 - 10': 11, + '12 - 2 * -2 + (3 - 4) * 3.1': 12.9, + '9 / 12 + 12 * 3 - 5': 31.75, + '9 / 12 + 12 * (3 - 5)': -23.25, + '12 > 13.1': False, + '12 < 14': True, + '12 <= 14': True, + '12 >= 14': False, + '12 == 14': False, + '12 % 5 > 3': False, + '12 != 14': True, + '9 - 1 > 10 && 3 * 5 > 10': False, + '9 - 1 > 10 || 3 * 5 > 10': True, + 'a1 > 0 || a1 < -12': True, + 'a1 > 0 && a1 < -12': False, + 'a1 + 1 > 0 && -a1 > -12': True, + '-(a1 + 1) < 0 || -(a1 + 2) > -12': True, + '-a1 * 2': -2, + '(9 - 2) * 3 - c10': 11, + '(9 - b2) * 3 - c10': 11, + 'c10 > b2': True, + + # String + "foo == 'bar'":True, + "foo != 'bar'":False, + 'foo == "bar" && 1 > 0':True, + '!!foo': True, + '!foo': False, + 'foo': 'bar', + '!(foo > "baa") || 1 > 2': False, + '!(foo > "baa") || 1 < 2': True, + 'empty == ""': True, + '1 == "1"': True, + '1.0 == "1"': True, + '1 == "aaa"': False, + "'I am ' + b2 + ' years'": 'I am 2 years', + "quote == 'Je s\\'apelle Groot'": True, + "lorem == 'Lorem ipsum dolor et si qua met!'": True, + "and_ == '&&'": True, + "warning == 'Warning! This sentence will fail!'": True, + + # Match + "match(lorem, '^Lorem [ia]psumE?')": bool, + "match(foo, '^Lorem [ia]psumE?')": None, + "match(lorem, '^Lorem [ia]psumE?') && 1 == 1": bool, + + # No code + "": False, + " ": False, + } + trigger_errors = { + "object.a": YunohostError, # Keep unsupported, for security reasons + 'a1 ** b2': YunohostError, # Keep unsupported, for security reasons + '().__class__.__bases__[0].__subclasses__()': YunohostError, # Very dangerous code + 'a1 > 11 ? 1 : 0': SyntaxError, + 'c10 > b2 == false': YunohostError, # JS and Python doesn't do the same thing for this situation + 'c10 > b2 == true': YunohostError, + } + + for expression, result in supported.items(): + if result == bool: + assert bool(evaluate_simple_js_expression(expression, context)), expression + else: + assert evaluate_simple_js_expression(expression, context) == result, expression + + for expression, error in trigger_errors.items(): + with pytest.raises(error): + evaluate_simple_js_expression(expression, context) + diff --git a/src/yunohost/utils/config.py b/src/yunohost/utils/config.py index 2363545cf..0f18fad0d 100644 --- a/src/yunohost/utils/config.py +++ b/src/yunohost/utils/config.py @@ -24,6 +24,8 @@ import re import urllib.parse import tempfile import shutil +import ast +import operator as op from collections import OrderedDict from typing import Optional, Dict, List, Union, Any, Mapping @@ -46,6 +48,138 @@ from yunohost.log import OperationLogger logger = getActionLogger("yunohost.config") CONFIG_PANEL_VERSION_SUPPORTED = 1.0 +# Those js-like evaluate functions are used to eval safely visible attributes +# The goal is to evaluate in the same way than js simple-evaluate +# https://github.com/shepherdwind/simple-evaluate +def evaluate_simple_ast(node, context={}): + operators = { + ast.Not: op.not_, + ast.Mult: op.mul, + ast.Div: op.truediv, # number + ast.Mod: op.mod, # number + ast.Add: op.add, #str + ast.Sub: op.sub, #number + ast.USub: op.neg, # Negative number + ast.Gt: op.gt, + ast.Lt: op.lt, + ast.GtE: op.ge, + ast.LtE: op.le, + ast.Eq: op.eq, + ast.NotEq: op.ne + } + context['true'] = True + context['false'] = False + context['null'] = None + + # Variable + if isinstance(node, ast.Name): # Variable + return context[node.id] + + # Python <=3.7 String + elif isinstance(node, ast.Str): + return node.s + + # Python <=3.7 Number + elif isinstance(node, ast.Num): + return node.n + + # Boolean, None and Python 3.8 for Number, Boolean, String and None + elif isinstance(node, (ast.Constant, ast.NameConstant)): + return node.value + + # + - * / % + elif isinstance(node, ast.BinOp) and type(node.op) in operators: # + left = evaluate_simple_ast(node.left, context) + right = evaluate_simple_ast(node.right, context) + if type(node.op) == ast.Add: + if isinstance(left, str) or isinstance(right, str): # support 'I am ' + 42 + left = str(left) + right = str(right) + elif type(left) != type(right): # support "111" - "1" -> 110 + left = float(left) + right = float(right) + + return operators[type(node.op)](left, right) + + # Comparison + # JS and Python don't give the same result for multi operators + # like True == 10 > 2. + elif isinstance(node, ast.Compare) and len(node.comparators) == 1: # + left = evaluate_simple_ast(node.left, context) + right = evaluate_simple_ast(node.comparators[0], context) + operator = node.ops[0] + if isinstance(left, (int, float)) or isinstance(right, (int, float)): + try: + left = float(left) + right = float(right) + except ValueError: + return type(operator) == ast.NotEq + try: + return operators[type(operator)](left, right) + except TypeError: # support "e" > 1 -> False like in JS + return False + + # and / or + elif isinstance(node, ast.BoolOp): # + values = node.values + for value in node.values: + value = evaluate_simple_ast(value, context) + if isinstance(node.op, ast.And) and not value: + return False + elif isinstance(node.op, ast.Or) and value: + return True + return isinstance(node.op, ast.And) + + # not / USub (it's negation number -\d) + elif isinstance(node, ast.UnaryOp): # e.g., -1 + return operators[type(node.op)](evaluate_simple_ast(node.operand, context)) + + # match function call + elif isinstance(node, ast.Call) and node.func.__dict__.get('id') == 'match': + return re.match( + evaluate_simple_ast(node.args[1], context), + context[node.args[0].id] + ) + + # Unauthorized opcode + else: + opcode = str(type(node)) + raise YunohostError(f"Unauthorize opcode '{opcode}' in visible attribute", raw_msg=True) + +def js_to_python(expr): + in_string = None + py_expr = "" + i = 0 + escaped = False + for char in expr: + if char in r"\"'": + # Start a string + if not in_string: + in_string = char + + # Finish a string + elif in_string == char and not escaped: + in_string = None + + # If we are not in a string, replace operators + elif not in_string: + if char == "!" and expr[i +1] != "=": + char = "not " + elif char in "|&" and py_expr[-1:] == char: + py_expr = py_expr[:-1] + char = " and " if char == "&" else " or " + + # Determine if next loop will be in escaped mode + escaped = char == "\\" and not escaped + py_expr += char + i+=1 + return py_expr + +def evaluate_simple_js_expression(expr, context={}): + if not expr.strip(): + return False + node = ast.parse(js_to_python(expr), mode="eval").body + return evaluate_simple_ast(node, context) class ConfigPanel: def __init__(self, config_path, save_path=None): @@ -466,11 +600,13 @@ class Question(object): hide_user_input_in_prompt = False pattern: Optional[Dict] = None - def __init__(self, question: Dict[str, Any]): + def __init__(self, question: Dict[str, Any], context: Dict[str, Any] = {}): self.name = question["name"] self.type = question.get("type", "string") self.default = question.get("default", None) self.optional = question.get("optional", False) + self.visible = question.get("visible", None) + self.context = context self.choices = question.get("choices", []) self.pattern = question.get("pattern", self.pattern) self.ask = question.get("ask", {"en": self.name}) @@ -512,6 +648,15 @@ class Question(object): ) def ask_if_needed(self): + + if self.visible and not evaluate_simple_js_expression(self.visible, context=self.context): + # FIXME There could be several use case if the question is not displayed: + # - we doesn't want to give a specific value + # - we want to keep the previous value + # - we want the default value + self.value = None + return self.value + for i in range(5): # Display question if no value filled or if it's a readonly message if Moulinette.interface.type == "cli" and os.isatty(1): @@ -577,7 +722,7 @@ class Question(object): # Prevent displaying a shitload of choices # (e.g. 100+ available users when choosing an app admin...) choices = ( - list(self.choices.values()) + list(self.choices.keys()) if isinstance(self.choices, dict) else self.choices ) @@ -710,8 +855,8 @@ class PasswordQuestion(Question): default_value = "" forbidden_chars = "{}" - def __init__(self, question): - super().__init__(question) + def __init__(self, question, context: Dict[str, Any] = {}): + super().__init__(question, context) self.redact = True if self.default is not None: raise YunohostValidationError( @@ -829,8 +974,8 @@ class BooleanQuestion(Question): choices="yes/no", ) - def __init__(self, question): - super().__init__(question) + def __init__(self, question, context: Dict[str, Any] = {}): + super().__init__(question, context) self.yes = question.get("yes", 1) self.no = question.get("no", 0) if self.default is None: @@ -850,10 +995,10 @@ class BooleanQuestion(Question): class DomainQuestion(Question): argument_type = "domain" - def __init__(self, question): + def __init__(self, question, context: Dict[str, Any] = {}): from yunohost.domain import domain_list, _get_maindomain - super().__init__(question) + super().__init__(question, context) if self.default is None: self.default = _get_maindomain() @@ -876,11 +1021,11 @@ class DomainQuestion(Question): class UserQuestion(Question): argument_type = "user" - def __init__(self, question): + def __init__(self, question, context: Dict[str, Any] = {}): from yunohost.user import user_list, user_info from yunohost.domain import _get_maindomain - super().__init__(question) + super().__init__(question, context) self.choices = list(user_list()["users"].keys()) if not self.choices: @@ -902,8 +1047,8 @@ class NumberQuestion(Question): argument_type = "number" default_value = None - def __init__(self, question): - super().__init__(question) + def __init__(self, question, context: Dict[str, Any] = {}): + super().__init__(question, context) self.min = question.get("min", None) self.max = question.get("max", None) self.step = question.get("step", None) @@ -954,8 +1099,8 @@ class DisplayTextQuestion(Question): argument_type = "display_text" readonly = True - def __init__(self, question): - super().__init__(question) + def __init__(self, question, context: Dict[str, Any] = {}): + super().__init__(question, context) self.optional = True self.style = question.get( @@ -989,8 +1134,8 @@ class FileQuestion(Question): if os.path.exists(upload_dir): shutil.rmtree(upload_dir) - def __init__(self, question): - super().__init__(question) + def __init__(self, question, context: Dict[str, Any] = {}): + super().__init__(question, context) self.accept = question.get("accept", "") def _prevalidate(self): @@ -1089,9 +1234,8 @@ def ask_questions_and_parse_answers( for question in questions: question_class = ARGUMENTS_TYPE_PARSERS[question.get("type", "string")] question["value"] = prefilled_answers.get(question["name"]) - question = question_class(question) - - question.ask_if_needed() + question = question_class(question, prefilled_answers) + prefilled_answers[question.name] = question.ask_if_needed() out.append(question) return out From eb8a59751ec112fc74526e53cb7c107be9b5228a Mon Sep 17 00:00:00 2001 From: yunohost-bot Date: Wed, 6 Oct 2021 00:57:04 +0000 Subject: [PATCH 79/81] [CI] Format code --- src/yunohost/app.py | 2 +- src/yunohost/tests/test_questions.py | 118 +++++++++++++-------------- src/yunohost/utils/config.py | 58 +++++++------ 3 files changed, 93 insertions(+), 85 deletions(-) diff --git a/src/yunohost/app.py b/src/yunohost/app.py index 2b8d71abf..fe5281384 100644 --- a/src/yunohost/app.py +++ b/src/yunohost/app.py @@ -169,7 +169,7 @@ def app_info(app, full=False): ret["from_catalog"] = _load_apps_catalog()["apps"].get(absolute_app_name, {}) ret["upgradable"] = _app_upgradable(ret) - ret["is_webapp"] = ("domain" in settings and "path" in settings) + ret["is_webapp"] = "domain" in settings and "path" in settings ret["supports_change_url"] = os.path.exists( os.path.join(setting_path, "scripts", "change_url") diff --git a/src/yunohost/tests/test_questions.py b/src/yunohost/tests/test_questions.py index b39990b73..c21ff8c40 100644 --- a/src/yunohost/tests/test_questions.py +++ b/src/yunohost/tests/test_questions.py @@ -15,7 +15,7 @@ from yunohost.utils.config import ( PathQuestion, BooleanQuestion, FileQuestion, - evaluate_simple_js_expression + evaluate_simple_js_expression, ) from yunohost.utils.error import YunohostError, YunohostValidationError @@ -2095,97 +2095,95 @@ def test_normalize_path(): assert PathQuestion.normalize("macnuggets/") == "/macnuggets" assert PathQuestion.normalize("////macnuggets///") == "/macnuggets" + def test_simple_evaluate(): context = { - 'a1': 1, - 'b2': 2, - 'c10': 10, - 'foo': 'bar', - 'comp': '1>2', - 'empty': '', - 'lorem': 'Lorem ipsum dolor et si qua met!', - 'warning': 'Warning! This sentence will fail!', - 'quote': "Je s'apelle Groot", - 'and_': '&&', - 'object': { 'a': 'Security risk' } + "a1": 1, + "b2": 2, + "c10": 10, + "foo": "bar", + "comp": "1>2", + "empty": "", + "lorem": "Lorem ipsum dolor et si qua met!", + "warning": "Warning! This sentence will fail!", + "quote": "Je s'apelle Groot", + "and_": "&&", + "object": {"a": "Security risk"}, } supported = { - '42': 42, - '9.5': 9.5, - "'bopbidibopbopbop'": 'bopbidibopbopbop', - 'true': True, - 'false': False, - 'null': None, - + "42": 42, + "9.5": 9.5, + "'bopbidibopbopbop'": "bopbidibopbopbop", + "true": True, + "false": False, + "null": None, # Math - '1 * (2 + 3 * (4 - 3))': 5, - '1 * (2 + 3 * (4 - 3)) > 10 - 2 || 3 * 2 > 9 - 2 * 3': True, - '(9 - 2) * 3 - 10': 11, - '12 - 2 * -2 + (3 - 4) * 3.1': 12.9, - '9 / 12 + 12 * 3 - 5': 31.75, - '9 / 12 + 12 * (3 - 5)': -23.25, - '12 > 13.1': False, - '12 < 14': True, - '12 <= 14': True, - '12 >= 14': False, - '12 == 14': False, - '12 % 5 > 3': False, - '12 != 14': True, - '9 - 1 > 10 && 3 * 5 > 10': False, - '9 - 1 > 10 || 3 * 5 > 10': True, - 'a1 > 0 || a1 < -12': True, - 'a1 > 0 && a1 < -12': False, - 'a1 + 1 > 0 && -a1 > -12': True, - '-(a1 + 1) < 0 || -(a1 + 2) > -12': True, - '-a1 * 2': -2, - '(9 - 2) * 3 - c10': 11, - '(9 - b2) * 3 - c10': 11, - 'c10 > b2': True, - + "1 * (2 + 3 * (4 - 3))": 5, + "1 * (2 + 3 * (4 - 3)) > 10 - 2 || 3 * 2 > 9 - 2 * 3": True, + "(9 - 2) * 3 - 10": 11, + "12 - 2 * -2 + (3 - 4) * 3.1": 12.9, + "9 / 12 + 12 * 3 - 5": 31.75, + "9 / 12 + 12 * (3 - 5)": -23.25, + "12 > 13.1": False, + "12 < 14": True, + "12 <= 14": True, + "12 >= 14": False, + "12 == 14": False, + "12 % 5 > 3": False, + "12 != 14": True, + "9 - 1 > 10 && 3 * 5 > 10": False, + "9 - 1 > 10 || 3 * 5 > 10": True, + "a1 > 0 || a1 < -12": True, + "a1 > 0 && a1 < -12": False, + "a1 + 1 > 0 && -a1 > -12": True, + "-(a1 + 1) < 0 || -(a1 + 2) > -12": True, + "-a1 * 2": -2, + "(9 - 2) * 3 - c10": 11, + "(9 - b2) * 3 - c10": 11, + "c10 > b2": True, # String - "foo == 'bar'":True, - "foo != 'bar'":False, - 'foo == "bar" && 1 > 0':True, - '!!foo': True, - '!foo': False, - 'foo': 'bar', + "foo == 'bar'": True, + "foo != 'bar'": False, + 'foo == "bar" && 1 > 0': True, + "!!foo": True, + "!foo": False, + "foo": "bar", '!(foo > "baa") || 1 > 2': False, '!(foo > "baa") || 1 < 2': True, 'empty == ""': True, '1 == "1"': True, '1.0 == "1"': True, '1 == "aaa"': False, - "'I am ' + b2 + ' years'": 'I am 2 years', + "'I am ' + b2 + ' years'": "I am 2 years", "quote == 'Je s\\'apelle Groot'": True, "lorem == 'Lorem ipsum dolor et si qua met!'": True, "and_ == '&&'": True, "warning == 'Warning! This sentence will fail!'": True, - # Match "match(lorem, '^Lorem [ia]psumE?')": bool, "match(foo, '^Lorem [ia]psumE?')": None, "match(lorem, '^Lorem [ia]psumE?') && 1 == 1": bool, - # No code "": False, " ": False, } trigger_errors = { - "object.a": YunohostError, # Keep unsupported, for security reasons - 'a1 ** b2': YunohostError, # Keep unsupported, for security reasons - '().__class__.__bases__[0].__subclasses__()': YunohostError, # Very dangerous code - 'a1 > 11 ? 1 : 0': SyntaxError, - 'c10 > b2 == false': YunohostError, # JS and Python doesn't do the same thing for this situation - 'c10 > b2 == true': YunohostError, + "object.a": YunohostError, # Keep unsupported, for security reasons + "a1 ** b2": YunohostError, # Keep unsupported, for security reasons + "().__class__.__bases__[0].__subclasses__()": YunohostError, # Very dangerous code + "a1 > 11 ? 1 : 0": SyntaxError, + "c10 > b2 == false": YunohostError, # JS and Python doesn't do the same thing for this situation + "c10 > b2 == true": YunohostError, } for expression, result in supported.items(): if result == bool: assert bool(evaluate_simple_js_expression(expression, context)), expression else: - assert evaluate_simple_js_expression(expression, context) == result, expression + assert ( + evaluate_simple_js_expression(expression, context) == result + ), expression for expression, error in trigger_errors.items(): with pytest.raises(error): evaluate_simple_js_expression(expression, context) - diff --git a/src/yunohost/utils/config.py b/src/yunohost/utils/config.py index 0f18fad0d..e38cfbb3a 100644 --- a/src/yunohost/utils/config.py +++ b/src/yunohost/utils/config.py @@ -55,24 +55,24 @@ def evaluate_simple_ast(node, context={}): operators = { ast.Not: op.not_, ast.Mult: op.mul, - ast.Div: op.truediv, # number - ast.Mod: op.mod, # number - ast.Add: op.add, #str - ast.Sub: op.sub, #number - ast.USub: op.neg, # Negative number + ast.Div: op.truediv, # number + ast.Mod: op.mod, # number + ast.Add: op.add, # str + ast.Sub: op.sub, # number + ast.USub: op.neg, # Negative number ast.Gt: op.gt, ast.Lt: op.lt, ast.GtE: op.ge, ast.LtE: op.le, ast.Eq: op.eq, - ast.NotEq: op.ne + ast.NotEq: op.ne, } - context['true'] = True - context['false'] = False - context['null'] = None + context["true"] = True + context["false"] = False + context["null"] = None # Variable - if isinstance(node, ast.Name): # Variable + if isinstance(node, ast.Name): # Variable return context[node.id] # Python <=3.7 String @@ -88,14 +88,16 @@ def evaluate_simple_ast(node, context={}): return node.value # + - * / % - elif isinstance(node, ast.BinOp) and type(node.op) in operators: # + elif ( + isinstance(node, ast.BinOp) and type(node.op) in operators + ): # left = evaluate_simple_ast(node.left, context) right = evaluate_simple_ast(node.right, context) if type(node.op) == ast.Add: - if isinstance(left, str) or isinstance(right, str): # support 'I am ' + 42 + if isinstance(left, str) or isinstance(right, str): # support 'I am ' + 42 left = str(left) right = str(right) - elif type(left) != type(right): # support "111" - "1" -> 110 + elif type(left) != type(right): # support "111" - "1" -> 110 left = float(left) right = float(right) @@ -104,7 +106,9 @@ def evaluate_simple_ast(node, context={}): # Comparison # JS and Python don't give the same result for multi operators # like True == 10 > 2. - elif isinstance(node, ast.Compare) and len(node.comparators) == 1: # + elif ( + isinstance(node, ast.Compare) and len(node.comparators) == 1 + ): # left = evaluate_simple_ast(node.left, context) right = evaluate_simple_ast(node.comparators[0], context) operator = node.ops[0] @@ -116,11 +120,11 @@ def evaluate_simple_ast(node, context={}): return type(operator) == ast.NotEq try: return operators[type(operator)](left, right) - except TypeError: # support "e" > 1 -> False like in JS + except TypeError: # support "e" > 1 -> False like in JS return False # and / or - elif isinstance(node, ast.BoolOp): # + elif isinstance(node, ast.BoolOp): # values = node.values for value in node.values: value = evaluate_simple_ast(value, context) @@ -131,20 +135,22 @@ def evaluate_simple_ast(node, context={}): return isinstance(node.op, ast.And) # not / USub (it's negation number -\d) - elif isinstance(node, ast.UnaryOp): # e.g., -1 + elif isinstance(node, ast.UnaryOp): # e.g., -1 return operators[type(node.op)](evaluate_simple_ast(node.operand, context)) # match function call - elif isinstance(node, ast.Call) and node.func.__dict__.get('id') == 'match': + elif isinstance(node, ast.Call) and node.func.__dict__.get("id") == "match": return re.match( - evaluate_simple_ast(node.args[1], context), - context[node.args[0].id] + evaluate_simple_ast(node.args[1], context), context[node.args[0].id] ) # Unauthorized opcode else: opcode = str(type(node)) - raise YunohostError(f"Unauthorize opcode '{opcode}' in visible attribute", raw_msg=True) + raise YunohostError( + f"Unauthorize opcode '{opcode}' in visible attribute", raw_msg=True + ) + def js_to_python(expr): in_string = None @@ -163,7 +169,7 @@ def js_to_python(expr): # If we are not in a string, replace operators elif not in_string: - if char == "!" and expr[i +1] != "=": + if char == "!" and expr[i + 1] != "=": char = "not " elif char in "|&" and py_expr[-1:] == char: py_expr = py_expr[:-1] @@ -172,15 +178,17 @@ def js_to_python(expr): # Determine if next loop will be in escaped mode escaped = char == "\\" and not escaped py_expr += char - i+=1 + i += 1 return py_expr + def evaluate_simple_js_expression(expr, context={}): if not expr.strip(): return False node = ast.parse(js_to_python(expr), mode="eval").body return evaluate_simple_ast(node, context) + class ConfigPanel: def __init__(self, config_path, save_path=None): self.config_path = config_path @@ -649,7 +657,9 @@ class Question(object): def ask_if_needed(self): - if self.visible and not evaluate_simple_js_expression(self.visible, context=self.context): + if self.visible and not evaluate_simple_js_expression( + self.visible, context=self.context + ): # FIXME There could be several use case if the question is not displayed: # - we doesn't want to give a specific value # - we want to keep the previous value From 99d2637cfe55fdfe2c654710a3e331abf7d9a925 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 6 Oct 2021 13:04:24 +0200 Subject: [PATCH 80/81] FileQuestion: self.value may not be an str --- src/yunohost/utils/config.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/yunohost/utils/config.py b/src/yunohost/utils/config.py index 0f18fad0d..e0fe1416b 100644 --- a/src/yunohost/utils/config.py +++ b/src/yunohost/utils/config.py @@ -1164,9 +1164,11 @@ class FileQuestion(Question): FileQuestion.upload_dirs += [upload_dir] logger.debug(f"Saving file {self.name} for file question into {file_path}") - if Moulinette.interface.type != "api" or ( - self.value.startswith("/") and os.path.exists(self.value) - ): + + def is_file_path(s): + return isinstance(s, str) and s.startswith("/") and os.path.exists(s) + + if Moulinette.interface.type != "api" or is_file_path(self.value): content = read_file(str(self.value), file_mode="rb") else: content = b64decode(self.value) From 23bd32b3cdf435013ffc8fd4229ffa0c185daac0 Mon Sep 17 00:00:00 2001 From: Alexandre Aubin Date: Wed, 6 Oct 2021 13:45:15 +0200 Subject: [PATCH 81/81] Fix linters --- src/yunohost/utils/config.py | 43 ++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/yunohost/utils/config.py b/src/yunohost/utils/config.py index e0fe1416b..fbaecfbe0 100644 --- a/src/yunohost/utils/config.py +++ b/src/yunohost/utils/config.py @@ -121,7 +121,6 @@ def evaluate_simple_ast(node, context={}): # and / or elif isinstance(node, ast.BoolOp): # - values = node.values for value in node.values: value = evaluate_simple_ast(value, context) if isinstance(node.op, ast.And) and not value: @@ -600,7 +599,7 @@ class Question(object): hide_user_input_in_prompt = False pattern: Optional[Dict] = None - def __init__(self, question: Dict[str, Any], context: Dict[str, Any] = {}): + def __init__(self, question: Dict[str, Any], context: Mapping[str, Any] = {}): self.name = question["name"] self.type = question.get("type", "string") self.default = question.get("default", None) @@ -855,7 +854,7 @@ class PasswordQuestion(Question): default_value = "" forbidden_chars = "{}" - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): super().__init__(question, context) self.redact = True if self.default is not None: @@ -974,7 +973,7 @@ class BooleanQuestion(Question): choices="yes/no", ) - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): super().__init__(question, context) self.yes = question.get("yes", 1) self.no = question.get("no", 0) @@ -995,7 +994,7 @@ class BooleanQuestion(Question): class DomainQuestion(Question): argument_type = "domain" - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): from yunohost.domain import domain_list, _get_maindomain super().__init__(question, context) @@ -1021,7 +1020,7 @@ class DomainQuestion(Question): class UserQuestion(Question): argument_type = "user" - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): from yunohost.user import user_list, user_info from yunohost.domain import _get_maindomain @@ -1047,7 +1046,7 @@ class NumberQuestion(Question): argument_type = "number" default_value = None - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): super().__init__(question, context) self.min = question.get("min", None) self.max = question.get("max", None) @@ -1099,7 +1098,7 @@ class DisplayTextQuestion(Question): argument_type = "display_text" readonly = True - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): super().__init__(question, context) self.optional = True @@ -1134,7 +1133,7 @@ class FileQuestion(Question): if os.path.exists(upload_dir): shutil.rmtree(upload_dir) - def __init__(self, question, context: Dict[str, Any] = {}): + def __init__(self, question, context: Mapping[str, Any] = {}): super().__init__(question, context) self.accept = question.get("accept", "") @@ -1205,15 +1204,15 @@ ARGUMENTS_TYPE_PARSERS = { def ask_questions_and_parse_answers( - questions: Dict, prefilled_answers: Union[str, Mapping[str, Any]] = {} + raw_questions: Dict, prefilled_answers: Union[str, Mapping[str, Any]] = {} ) -> List[Question]: """Parse arguments store in either manifest.json or actions.json or from a config panel against the user answers when they are present. Keyword arguments: - questions -- the arguments description store in yunohost - format from actions.json/toml, manifest.json/toml - or config_panel.json/toml + raw_questions -- the arguments description store in yunohost + format from actions.json/toml, manifest.json/toml + or config_panel.json/toml prefilled_answers -- a url "query-string" such as "domain=yolo.test&path=/foobar&admin=sam" or a dict such as {"domain": "yolo.test", "path": "/foobar", "admin": "sam"} """ @@ -1224,20 +1223,22 @@ def ask_questions_and_parse_answers( # whereas parse.qs return list of values (which is useful for tags, etc) # For now, let's not migrate this piece of code to parse_qs # Because Aleks believes some bits of the app CI rely on overriding values (e.g. foo=foo&...&foo=bar) - prefilled_answers = dict( + answers = dict( urllib.parse.parse_qsl(prefilled_answers or "", keep_blank_values=True) ) + elif isinstance(prefilled_answers, Mapping): + answers = {**prefilled_answers} + else: + answers = {} - if not prefilled_answers: - prefilled_answers = {} out = [] - for question in questions: - question_class = ARGUMENTS_TYPE_PARSERS[question.get("type", "string")] - question["value"] = prefilled_answers.get(question["name"]) - question = question_class(question, prefilled_answers) - prefilled_answers[question.name] = question.ask_if_needed() + for raw_question in raw_questions: + question_class = ARGUMENTS_TYPE_PARSERS[raw_question.get("type", "string")] + raw_question["value"] = answers.get(raw_question["name"]) + question = question_class(raw_question, context=answers) + answers[question.name] = question.ask_if_needed() out.append(question) return out