forked from YunoHost/package_linter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpackage_linter.py
executable file
·2297 lines (1927 loc) · 86.2 KB
/
package_linter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import sys
import os
import re
import json
import shlex
import urllib.request
import subprocess
import time
import statistics
from datetime import datetime
# ############################################################################
# Helper list
# ############################################################################
# Generated April 11th using:
# cat /path/to/yunohost/data/helpers.d/* | grep "^ynh_" | tr -d '(){ ' > helperlist
# for HELPER in $(cat helperlist); do REQUIRE=$(grep -whB5 "^$HELPER" /path/to/yunohost/data/helpers.d/* | grep "Requires .* or higher\." | grep -o -E "[0-9].[0-9].[0-9]"); echo "'$HELPER': '$REQUIRE'",; done
official_helpers = {
"ynh_wait_dpkg_free": "3.3.1",
"ynh_package_is_installed": "2.2.4",
"ynh_package_version": "2.2.4",
"ynh_apt": "2.4.0",
"ynh_package_update": "2.2.4",
"ynh_package_install": "2.2.4",
"ynh_package_remove": "2.2.4",
"ynh_package_autoremove": "2.2.4",
"ynh_package_autopurge": "2.7.2",
"ynh_package_install_from_equivs": "2.2.4",
"ynh_install_app_dependencies": "2.6.4",
"ynh_add_app_dependencies": "3.8.1",
"ynh_remove_app_dependencies": "2.6.4",
"ynh_install_extra_app_dependencies": "3.8.1",
"ynh_install_extra_repo": "3.8.1",
"ynh_remove_extra_repo": "3.8.1",
"ynh_add_repo": "3.8.1",
"ynh_pin_repo": "3.8.1",
"ynh_backup": "2.4.0",
"ynh_restore": "2.6.4",
"ynh_restore_file": "2.6.4",
"ynh_bind_or_cp": "",
"ynh_store_file_checksum": "2.6.4",
"ynh_backup_if_checksum_is_different": "2.6.4",
"ynh_delete_file_checksum": "3.3.1",
"ynh_backup_archive_exists": "",
"ynh_backup_before_upgrade": "2.7.2",
"ynh_restore_upgradebackup": "2.7.2",
"ynh_add_fail2ban_config": "3.5.0",
"ynh_remove_fail2ban_config": "3.5.0",
"ynh_handle_getopts_args": "3.2.2",
"ynh_get_ram": "3.8.1",
"ynh_require_ram": "3.8.1",
"ynh_die": "2.4.0",
"ynh_print_info": "3.2.0",
"ynh_no_log": "2.6.4",
"ynh_print_log": "3.2.0",
"ynh_print_warn": "3.2.0",
"ynh_print_err": "3.2.0",
"ynh_exec_err": "3.2.0",
"ynh_exec_warn": "3.2.0",
"ynh_exec_warn_less": "3.2.0",
"ynh_exec_quiet": "3.2.0",
"ynh_exec_fully_quiet": "3.2.0",
"ynh_print_OFF": "3.2.0",
"ynh_print_ON": "3.2.0",
"ynh_script_progression": "3.5.0",
"ynh_return": "3.6.0",
"ynh_debug": "3.5.0",
"ynh_debug_exec": "3.5.0",
"ynh_use_logrotate": "2.6.4",
"ynh_remove_logrotate": "2.6.4",
"ynh_multimedia_build_main_dir": "4.2",
"ynh_multimedia_addfolder": "4.2",
"ynh_multimedia_addaccess": "4.2",
"ynh_mysql_connect_as": "2.2.4",
"ynh_mysql_execute_as_root": "2.2.4",
"ynh_mysql_execute_file_as_root": "2.2.4",
"ynh_mysql_create_db": "2.2.4",
"ynh_mysql_drop_db": "2.2.4",
"ynh_mysql_dump_db": "2.2.4",
"ynh_mysql_create_user": "2.2.4",
"ynh_mysql_user_exists": "2.2.4",
"ynh_mysql_drop_user": "2.2.4",
"ynh_mysql_setup_db": "2.6.4",
"ynh_mysql_remove_db": "2.6.4",
"ynh_find_port": "2.6.4",
"ynh_port_available": "3.8.0",
"ynh_validate_ip": "2.2.4",
"ynh_validate_ip4": "2.2.4",
"ynh_validate_ip6": "2.2.4",
"ynh_add_nginx_config": "2.7.2",
"ynh_remove_nginx_config": "2.7.2",
"ynh_install_n": "2.7.1",
"ynh_use_nodejs": "2.7.1",
"ynh_install_nodejs": "2.7.1",
"ynh_remove_nodejs": "2.7.1",
"ynh_cron_upgrade_node": "2.7.1",
"ynh_permission_create": "3.7.0",
"ynh_permission_delete": "3.7.0",
"ynh_permission_exists": "3.7.0",
"ynh_permission_url": "3.7.0",
"ynh_permission_update": "3.7.0",
"ynh_permission_has_user": "3.7.1",
"ynh_legacy_permissions_exists": "4.1",
"ynh_legacy_permissions_delete_all": "4.1",
"ynh_add_fpm_config": "2.7.2",
"ynh_remove_fpm_config": "2.7.2",
"ynh_install_php": "3.8.1",
"ynh_remove_php": "3.8.1",
"ynh_get_scalable_phpfpm": "",
"ynh_composer_exec": "4.2",
"ynh_install_composer": "4.2",
"ynh_psql_connect_as": "3.5.0",
"ynh_psql_execute_as_root": "3.5.0",
"ynh_psql_execute_file_as_root": "3.5.0",
"ynh_psql_create_db": "3.5.0",
"ynh_psql_drop_db": "3.5.0",
"ynh_psql_dump_db": "3.5.0",
"ynh_psql_create_user": "3.5.0",
"ynh_psql_user_exists": "3.5.0",
"ynh_psql_database_exists": "3.5.0",
"ynh_psql_drop_user": "3.5.0",
"ynh_psql_setup_db": "2.7.1",
"ynh_psql_remove_db": "2.7.1",
"ynh_psql_test_if_first_run": "2.7.1",
"ynh_app_setting_get": "2.2.4",
"ynh_app_setting_set": "2.2.4",
"ynh_app_setting_delete": "2.2.4",
"ynh_app_setting": "",
"ynh_webpath_available": "2.6.4",
"ynh_webpath_register": "2.6.4",
"ynh_string_random": "2.2.4",
"ynh_replace_string": "2.6.4",
"ynh_replace_special_string": "2.7.7",
"ynh_sanitize_dbid": "2.2.4",
"ynh_normalize_url_path": "2.6.4",
"ynh_add_systemd_config": "2.7.1",
"ynh_remove_systemd_config": "2.7.2",
"ynh_systemd_action": "3.5.0",
"ynh_clean_check_starting": "3.5.0",
"ynh_user_exists": "2.2.4",
"ynh_user_get_info": "2.2.4",
"ynh_user_list": "2.4.0",
"ynh_system_user_exists": "2.2.4",
"ynh_system_group_exists": "3.5.0",
"ynh_system_user_create": "2.6.4",
"ynh_system_user_delete": "2.6.4",
"ynh_exec_as": "4.1.7",
"ynh_exit_properly": "2.6.4",
"ynh_abort_if_errors": "2.6.4",
"ynh_setup_source": "2.6.4",
"ynh_local_curl": "2.6.4",
"ynh_add_config": "4.1.0",
"ynh_replace_vars": "4.1.0",
"ynh_render_template": "",
"ynh_get_debian_release": "2.7.1",
"ynh_mkdir_tmp": "",
"ynh_secure_remove": "2.6.4",
"ynh_get_plain_key": "",
"ynh_read_manifest": "3.5.0",
"ynh_app_upstream_version": "3.5.0",
"ynh_app_package_version": "3.5.0",
"ynh_check_app_version_changed": "3.5.0",
"ynh_compare_current_package_version": "3.8.0",
}
# ############################################################################
# Utilities
# ############################################################################
class c:
HEADER = "\033[94m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
MAYBE_FAIL = "\033[96m"
FAIL = "\033[91m"
END = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
class TestReport:
def __init__(self, message):
self.message = message
def display(self, prefix=""):
_print(prefix + self.style % self.message)
class Warning(TestReport):
style = c.WARNING + " ! %s " + c.END
class Error(TestReport):
style = c.FAIL + " ✘ %s" + c.END
class Info(TestReport):
style = " - %s" + c.END
class Success(TestReport):
style = c.OKGREEN + " ☺ %s ♥" + c.END
class Critical(TestReport):
style = c.FAIL + " ✘✘✘ %s" + c.END
output = "plain"
def _print(*args, **kwargs):
if output == "plain":
print(*args, **kwargs)
def report_warning_not_reliable(str):
_print(c.MAYBE_FAIL + "?", str, c.END)
def print_happy(str):
_print(c.OKGREEN + " ☺ ", str, "♥")
def urlopen(url):
try:
conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
return {"content": "", "code": e.code}
except urllib.error.URLError as e:
_print("Could not fetch %s : %s" % (url, e))
return {"content": "", "code": 0}
return {"content": conn.read().decode("UTF8"), "code": 200}
def file_exists(file_path):
return os.path.isfile(file_path) and os.stat(file_path).st_size > 0
def spdx_licenses():
cachefile = ".spdx_licenses"
if os.path.exists(cachefile) and time.time() - os.path.getmtime(cachefile) < 3600:
return open(cachefile).read()
url = "https://spdx.org/licenses/"
content = urlopen(url)["content"]
open(cachefile, "w").write(content)
return content
tests = {}
tests_reports = {
"success": [],
"info": [],
"warning": [],
"error": [],
"critical": [],
}
def test(**kwargs):
def decorator(f):
clsname = f.__qualname__.split(".")[0]
if clsname not in tests:
tests[clsname] = []
tests[clsname].append((f, kwargs))
return f
return decorator
class TestSuite:
def run_tests(self):
reports = []
for test, options in tests[self.__class__.__name__]:
if "only" in options and self.name not in options["only"]:
continue
if "ignore" in options and self.name in options["ignore"]:
continue
this_test_reports = list(test(self))
for report in this_test_reports:
report.test_name = test.__qualname__
reports += this_test_reports
# Display part
def report_type(report):
return report.__class__.__name__.lower()
if any(report_type(r) in ["warning", "error", "critical"] for r in reports):
prefix = c.WARNING + "! "
elif any(report_type(r) in ["info"] for r in reports):
prefix = "ⓘ "
else:
prefix = c.OKGREEN + "✔ "
_print(" " + c.BOLD + prefix + c.OKBLUE + self.test_suite_name + c.END)
if len(reports):
_print("")
for report in reports:
report.display(prefix=" ")
if len(reports):
_print("")
for report in reports:
tests_reports[report_type(report)].append((report.test_name, report))
def run_single_test(self, test):
reports = list(test(self))
def report_type(report):
return report.__class__.__name__.lower()
for report in reports:
report.display()
test_name = test.__qualname__
tests_reports[report_type(report)].append((test_name, report))
# ############################################################################
# Actual high-level checks
# ############################################################################
scriptnames = ["_common.sh", "install", "remove", "upgrade", "backup", "restore"]
class App(TestSuite):
def __init__(self, path):
_print(" Analyzing app %s ..." % path)
self.path = path
self.manifest_ = Manifest(self.path)
self.manifest = self.manifest_.manifest
self.scripts = {f: Script(self.path, f) for f in scriptnames}
self.configurations = Configurations(self)
self.app_catalog = AppCatalog(self.manifest["id"])
self.test_suite_name = "General stuff, misc helper usage"
_print()
def analyze(self):
self.manifest_.run_tests()
for script in [self.scripts[s] for s in scriptnames if self.scripts[s].exists]:
script.run_tests()
self.run_tests()
self.configurations.run_tests()
self.app_catalog.run_tests()
self.report()
def report(self):
_print(" =======")
# These are meant to be the last stuff running, they are based on
# previously computed errors/warning/successes
self.run_single_test(App.qualify_for_level_7)
self.run_single_test(App.qualify_for_level_8)
self.run_single_test(App.qualify_for_level_9)
if output == "json":
print(
json.dumps(
{
"success": [test for test, _ in tests_reports["success"]],
"info": [test for test, _ in tests_reports["info"]],
"warning": [test for test, _ in tests_reports["warning"]],
"error": [test for test, _ in tests_reports["error"]],
"critical": [test for test, _ in tests_reports["critical"]],
},
indent=4,
)
)
return
if tests_reports["error"] or tests_reports["critical"]:
sys.exit(1)
def qualify_for_level_7(self):
if tests_reports["critical"]:
_print(" There are some critical issues in this app :(")
elif tests_reports["error"]:
_print(" Uhoh there are some errors to be fixed :(")
elif len(tests_reports["warning"]) >= 3:
_print(" Still some warnings to be fixed :s")
elif len(tests_reports["warning"]) == 2:
_print(" Only 2 warnings remaining! You can do it!")
elif len(tests_reports["warning"]) == 1:
_print(" Only 1 warning remaining! You can do it!")
else:
yield Success(
"Not even a warning! Congratz and thank you for keeping this package up to date with good practices! This app qualifies for level 7!"
)
def qualify_for_level_8(self):
successes = [test.split(".")[1] for test, _ in tests_reports["success"]]
# Level 8 = qualifies for level 7 + maintained + long term good quality
catalog_infos = self.app_catalog.catalog_infos
is_maintained = catalog_infos and catalog_infos.get("maintained", True) is True
if not is_maintained:
_print(" The app is flagged as not maintained in the app catalog")
elif (
"qualify_for_level_7" in successes
and "is_long_term_good_quality" in successes
):
yield Success(
"The app is maintained and long-term good quality, and therefore qualifies for level 8!"
)
def qualify_for_level_9(self):
if self.app_catalog.catalog_infos.get("high_quality", False):
yield Success("The app is flagged as high-quality in the app catalog")
#########################################
# _____ _ #
# | __ \ | | #
# | | \/ ___ _ __ ___ _ __ __ _| | #
# | | __ / _ \ '_ \ / _ \ '__/ _` | | #
# | |_\ \ __/ | | | __/ | | (_| | | #
# \____/\___|_| |_|\___|_| \__,_|_| #
# #
#########################################
@test()
def mandatory_scripts(app):
filenames = (
"manifest.json",
"LICENSE",
"README.md",
"scripts/install",
"scripts/remove",
"scripts/upgrade",
"scripts/backup",
"scripts/restore",
)
for filename in filenames:
if not file_exists(app.path + "/" + filename):
yield Error("Providing %s is mandatory" % filename)
if file_exists(app.path + "/LICENSE"):
license_content = open(app.path + "/LICENSE").read()
if "File containing the license of your package" in license_content:
yield Warning("You should put an actual license in LICENSE...")
@test()
def doc_dir(app):
if not os.path.exists(app.path + "/doc"):
yield Info(
"""READMEs are to be automatically generated using https://github.com/YunoHost/apps/tree/master/tools/README-generator.
- You are encouraged to create a doc/DISCLAIMER.md file, which should contain any important information to be presented to the admin before installation. Check https://github.com/YunoHost/example_ynh/blob/master/doc/DISCLAIMER.md for more details (it should be somewhat equivalent to the old 'Known limitations' and 'Specific features' section). (It's not mandatory to create this file if you're absolutely sure there's no relevant info to show to the user)
- If relevant for this app, screenshots can be added in a doc/screenshots/ folder."""
)
@test()
def disclaimer_wording(app):
if os.path.exists(app.path + "/doc"):
if (
os.system(
r"grep -nr -q 'Any known limitations, constrains or stuff not working, such as\|Other infos that people should be' %s/doc/"
% app.path
)
== 0
):
yield Info(
"In DISCLAIMER.md: 'Any known limitations [...] such as' and 'Other infos [...] such as' are supposed to be placeholder sentences meant to explain to packagers what is the expected content, but is not an appropriate wording for end users :/"
)
@test()
def change_url_script(app):
has_domain_arg = any(
a["name"] == "domain" for a in app.manifest["arguments"].get("install", [])
)
if has_domain_arg and not file_exists(app.path + "/scripts/change_url"):
yield Info(
"Consider adding a change_url script to support changing where the app can be reached"
)
@test()
def badges_in_readme(app):
id_ = app.manifest["id"]
if not file_exists(app.path + "/README.md"):
return
content = open(app.path + "/README.md").read()
if not "dash.yunohost.org/integration/%s.svg" % id_ in content:
yield Warning(
"Please add a badge displaying the level of the app in the README. "
"Proper READMEs can be automatically generated using https://github.com/YunoHost/apps/tree/master/tools/README-generator"
"At least something like :\n "
"[![Integration level](https://dash.yunohost.org/integration/%s.svg)](https://dash.yunohost.org/appci/app/%s)\n"
" (but ideally you should check example_ynh for the full set of recommendations !)"
% (id_, id_)
)
@test()
def placeholder_help_string(self):
if (
os.system(
"grep -q 'Use the help field' %s/manifest.json 2>/dev/null" % self.path
)
== 0
):
yield Warning(
"Sounds like your manifest.json contains some default placeholder help string ('Use the help field to...') ... either replace it with an actually helpful explanation, or remove the help string entirely if you don't use it."
)
@test()
def remaining_replacebyyourapp(self):
if os.system("grep -I -qr 'REPLACEBYYOURAPP' %s 2>/dev/null" % self.path) == 0:
yield Warning("You should replace all occurences of REPLACEBYYOURAPP.")
@test()
def bad_encoding(self):
cmd = (
"file --mime-encoding $(find %s/ -type f) | grep 'iso-8859-1\|unknown-8bit' || true"
% self.path
)
bad_encoding_files = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
for file_ in bad_encoding_files:
if not file_:
continue
file_ = file_.split()[0]
yield Info(
"%s appears to be encoded as latin-1 / iso-8859-1. Please consider converting it to utf-8 to avoid funky issues. Something like 'iconv -f iso-8859-1 -t utf-8 SOURCE > DEST' should do the trick."
% file_
)
#######################################
# _ _ _ #
# | | | | | | #
# | |__| | ___| |_ __ ___ _ __ ___ #
# | __ |/ _ \ | '_ \ / _ \ '__/ __| #
# | | | | __/ | |_) | __/ | \__ \ #
# |_| |_|\___|_| .__/ \___|_| |___/ #
# | | #
# |_| #
#######################################
@test()
def helpers_now_official(app):
cmd = "grep -IhEro 'ynh_\w+ *\( *\)' '%s/scripts' | tr -d '() '" % app.path
custom_helpers = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
custom_helpers = [c.split("__")[0] for c in custom_helpers]
for custom_helper in custom_helpers:
if custom_helper in official_helpers.keys():
yield Info(
"%s is now an official helper since version '%s'"
% (custom_helper, official_helpers[custom_helper] or "?")
)
@test()
def helpers_version_requirement(app):
cmd = "grep -IhEro 'ynh_\w+ *\( *\)' '%s/scripts' | tr -d '() '" % app.path
custom_helpers = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
custom_helpers = [c.split("__")[0] for c in custom_helpers]
yunohost_version_req = (
app.manifest.get("requirements", {}).get("yunohost", "").strip(">= ")
)
cmd = "grep -IhEro 'ynh_\w+' '%s/scripts'" % app.path
helpers_used = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
helpers_used = sorted(set(helpers_used))
manifest_req = [int(i) for i in yunohost_version_req.split(".")] + [0, 0, 0]
def validate_version_requirement(helper_req):
if helper_req == "":
return True
helper_req = [int(i) for i in helper_req.split(".")]
for i in range(0, len(helper_req)):
if helper_req[i] == manifest_req[i]:
continue
return helper_req[i] <= manifest_req[i]
return True
for helper in [h for h in helpers_used if h in official_helpers.keys()]:
if helper in custom_helpers:
continue
helper_req = official_helpers[helper]
if not validate_version_requirement(helper_req):
major_diff = manifest_req[0] > int(helper_req[0])
minor_diff = helper_req.startswith(
yunohost_version_req
) # This is meant to cover the case where manifest says "3.8" vs. the helper requires "3.8.1"
message = (
"Using official helper %s implies requiring at least version %s, but manifest only requires %s"
% (helper, helper_req, yunohost_version_req)
)
yield Error(message) if major_diff else (
Info(message) if minor_diff else Warning(message)
)
@test()
def helper_consistency_apt_deps(app):
"""
Check if ynh_install_app_dependencies is present in install/upgrade/restore
so dependencies are up to date after restoration or upgrade
"""
install_script = app.scripts["install"]
if install_script.contains("ynh_install_app_dependencies"):
for name in ["upgrade", "restore"]:
if app.scripts[name].exists and not app.scripts[name].contains(
"ynh_install_app_dependencies"
):
yield Warning(
"ynh_install_app_dependencies should also be in %s script"
% name
)
cmd = (
'grep -IhEr "install_extra_app_dependencies" %s/scripts | grep -v "key" | grep -q "http://"'
% app.path
)
if os.system(cmd) == 0:
yield Info(
"When installing dependencies from extra repository, please include a `--key` argument (yes, even if it's official debian repos such as backports - because systems like Raspbian do not ship Debian's key by default!"
)
@test()
def helper_consistency_service_add(app):
occurences = {
"install": app.scripts["install"].occurences("yunohost service add")
if app.scripts["install"].exists
else [],
"upgrade": app.scripts["upgrade"].occurences("yunohost service add")
if app.scripts["upgrade"].exists
else [],
"restore": app.scripts["restore"].occurences("yunohost service add")
if app.scripts["restore"].exists
else [],
}
occurences = {
k: [sub_v.replace('"$app"', "$app") for sub_v in v]
for k, v in occurences.items()
}
all_occurences = (
occurences["install"] + occurences["upgrade"] + occurences["restore"]
)
found_inconsistency = False
found_legacy_logtype_option = False
for cmd in all_occurences:
if any(
cmd not in occurences_list for occurences_list in occurences.values()
):
found_inconsistency = True
if "--log_type systemd" in cmd:
found_legacy_logtype_option = True
if found_inconsistency:
details = [
(
" %s : " % script
+ "".join(
"\n " + cmd
for cmd in occurences[script] or ["...None?..."]
)
)
for script in occurences.keys()
]
details = "\n".join(details)
yield Warning(
"Some inconsistencies were found in the 'yunohost service add' commands between install, upgrade and restore:\n%s"
% details
)
if found_legacy_logtype_option:
yield Warning(
"Using option '--log_type systemd' with 'yunohost service add' is not relevant anymore"
)
if occurences["install"] and not app.scripts["remove"].contains(
"yunohost service remove"
):
yield Error(
"You used 'yunohost service add' in the install script, "
"but not 'yunohost service remove' in the remove script."
)
@test()
def references_to_superold_stuff(app):
if any(
script.contains("jessie")
for script in app.scripts.values()
if script.exists
):
yield Info(
"The app still contains references to jessie, which could probably be cleaned up..."
)
if any(
script.contains("/etc/php5") or script.contains("php5-fpm")
for script in app.scripts.values()
if script.exists
):
yield Error(
"This app still has references to php5 (from the jessie era!!) which tends to indicate that it's not up to date with recent packaging practices."
)
if any(
script.contains("/etc/php/7.0") or script.contains("php7.0-fpm")
for script in app.scripts.values()
if script.exists
):
yield Warning(
"This app still has references to php7.0 (from the stretch era!!) which tends to indicate that it's not up to date with recent packaging practices."
)
@test()
def conf_json_persistent_tweaking(self):
if (
os.system(
"grep -q -nr '/etc/ssowat/conf.json.persistent' %s/*/* 2>/dev/null"
% self.path
)
== 0
):
yield Error("Don't do black magic with /etc/ssowat/conf.json.persistent!")
@test()
def app_data_in_unofficial_dir(self):
allowed_locations = [
"/home/yunohost.app",
"/home/yunohost.conf",
"/home/yunohost.backup",
"/home/yunohost.multimedia",
]
cmd = (
"grep -IhEro '/home/yunohost[^/ ]*/|/home/\\$app' %s/scripts || true"
% self.path
)
home_locations = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
forbidden_locations = set(
[
location
for location in home_locations
if location and location.rstrip("/") not in allowed_locations
]
)
if forbidden_locations:
yield Warning(
"The app seems to be storing data in the 'forbidden' locations %s. The recommended pratice is rather to store data in /home/yunohost.app/$app or /home/yunohost.multimedia (depending on the use case)"
% ", ".join(forbidden_locations)
)
class Configurations(TestSuite):
def __init__(self, app):
self.app = app
self.test_suite_name = "Configuration files"
############################
# _____ __ #
# / ____| / _| #
# | | ___ _ __ | |_ #
# | | / _ \| '_ \| _| #
# | |___| (_) | | | | | #
# \_____\___/|_| |_|_| #
# #
############################
@test()
def check_process_exists(self):
app = self.app
check_process_file = app.path + "/check_process"
if not file_exists(check_process_file):
yield Warning(
"You should add a 'check_process' file to properly interface with the continuous integration system"
)
@test()
def check_process_syntax(self):
app = self.app
check_process_file = app.path + "/check_process"
if not file_exists(check_process_file):
return
if os.system("grep -q 'Level 5=1' '%s'" % check_process_file) == 0:
yield Error("Do not force Level 5=1 in check_process...")
if os.system("grep -q ' *Level [^5]=' '%s'" % check_process_file) == 0:
yield Warning(
"Setting Level x=y in check_process is obsolete / not relevant anymore"
)
@test()
def check_process_consistency(self):
app = self.app
check_process_file = app.path + "/check_process"
if not file_exists(check_process_file):
return
has_is_public_arg = any(
a["name"] == "is_public"
for a in app.manifest["arguments"].get("install", [])
)
if has_is_public_arg:
if (
os.system(r"grep -q '^\s*setup_public=1' '%s'" % check_process_file)
!= 0
):
yield Info(
"It looks like you forgot to enable setup_public test in check_process?"
)
if (
os.system(r"grep -q '^\s*setup_private=1' '%s'" % check_process_file)
!= 0
):
yield Info(
"It looks like you forgot to enable setup_private test in check_process?"
)
has_path_arg = any(
a["name"] == "path" for a in app.manifest["arguments"].get("install", [])
)
if has_path_arg:
if (
os.system(r"grep -q '^\s*setup_sub_dir=1' '%s'" % check_process_file)
!= 0
):
yield Info(
"It looks like you forgot to enable setup_sub_dir test in check_process?"
)
if app.manifest.get("multi_instance") in [True, 1, "True", "true"]:
if (
os.system(r"grep -q '^\s*multi_instance=1' '%s'" % check_process_file)
!= 0
):
yield Info(
"It looks like you forgot to enable multi_instance test in check_process?"
)
if app.scripts["backup"].exists:
if (
os.system(r"grep -q '^\s*backup_restore=1' '%s'" % check_process_file)
!= 0
):
yield Info(
"It looks like you forgot to enable backup_restore test in check_process?"
)
@test()
def misc_legacy_phpini(self):
app = self.app
if file_exists(app.path + "/conf/php-fpm.ini"):
yield Error(
"Using a separate php-fpm.ini file is deprecated. "
"Please merge your php-fpm directives directly in the pool file. "
"(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )"
)
@test()
def misc_source_management(self):
app = self.app
source_dir = os.path.join(app.path, "sources")
if (
os.path.exists(source_dir)
and len(
[
name
for name in os.listdir(source_dir)
if os.path.isfile(os.path.join(source_dir, name))
]
)
> 5
):
yield Error(
"Upstream app sources shouldn't be stored in this 'sources' folder of this git repository as a copy/paste\n"
"During installation, the package should download sources from upstream via 'ynh_setup_source'.\n"
"See the helper documentation. "
"Original discussion happened here: "
"https://github.com/YunoHost/issues/issues/201#issuecomment-391549262"
)
@test()
def src_file_checksum_type(self):
app = self.app
for filename in (
os.listdir(app.path + "/conf") if os.path.exists(app.path + "/conf") else []
):
if not filename.endswith(".src"):
continue
try:
content = open(app.path + "/conf/" + filename).read()
except Exception as e:
yield Warning("Can't open/read %s: %s" % (filename, e))
return
if "SOURCE_SUM_PRG=md5sum" in content:
yield Warning(
"%s: Using md5sum checksum is not so great for "
"security. Consider using sha256sum instead." % filename
)
@test()
def systemd_config_specific_user(self):
app = self.app
for filename in (
os.listdir(app.path + "/conf") if os.path.exists(app.path + "/conf") else []
):
# Ignore subdirs or filename not containing nginx in the name
if not filename.endswith(".service"):
continue
# Some apps only provide an override conf file, which is different
# from the full/base service config (c.f. ffsync)
if "override" in filename:
continue
try:
content = open(app.path + "/conf/" + filename).read()
except Exception as e:
yield Warning("Can't open/read %s : %s" % (filename, e))
return
matches = re.findall(r"^ *(User|Group)=(\S+)", content, flags=re.MULTILINE)
if not any(match[0] == "User" for match in matches):
yield Warning(
"You should specify a 'User=' directive in the systemd config !"
)
return
if any(match[1] in ["root", "www-data"] for match in matches):
yield Warning(
"DO NOT run the app's systemd service as root or www-data! Use a dedicated system user for this app! If your app requires administrator priviledges, you should consider adding the user to the sudoers (and restrict the commands it can use!)"
)
@test()
def systemd_config_harden_security(self):
app = self.app
for filename in (
os.listdir(app.path + "/conf") if os.path.exists(app.path + "/conf") else []
):
# Ignore subdirs or filename not containing nginx in the name