/
nextcloud.nix
926 lines (799 loc) · 30.3 KB
/
nextcloud.nix
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
{ pkgs, lib, config, ... }:
let
inherit (lib) types mkOption;
cfg = config.nextcloud;
urlScheme = if cfg.useSSL then "https" else "http";
maybePort = let
needsExplicit = !lib.elem cfg.port [ 80 443 ];
in lib.optionalString needsExplicit ":${toString cfg.port}";
upstreamInfo = lib.importJSON ./deps/upstream.json;
themeBreezeDark = pkgs.fetchFromGitHub {
owner = "mwalbeck";
repo = "nextcloud-breeze-dark";
rev = "6a1c90ae97f6b60772ce7756e77d3d2b6b2b41df";
sha256 = "0sdzscz2pq7g674inkc6cryqsdnrpin2hsvvaqzngld6vp1z7h04";
};
occ = lib.escapeShellArg "${package}/occ";
occUser = pkgs.writeScriptBin "nextcloud-occ" ''
#!${pkgs.stdenv.shell} -e
export NEXTCLOUD_CONFIG_DIR=${lib.escapeShellArg nextcloudConfigDir}
export __NEXTCLOUD_VERSION=${lib.escapeShellArg package.version}
set -a
source /var/lib/nextcloud/secrets.env
set +a
exec ${lib.escapeShellArg "${pkgs.utillinux}/bin/runuser"} \
-u nextcloud -g nextcloud -- ${phpCli} ${occ} "$@"
'';
postgresql = config.services.postgresql.package;
dbShell = pkgs.writeScriptBin "nextcloud-dbshell" ''
export PGHOST=/run/postgresql
exec ${lib.escapeShellArg "${pkgs.utillinux}/bin/runuser"} \
-u nextcloud -g nextcloud -- \
${lib.escapeShellArg "${postgresql}/bin/psql"} \
nextcloud \
"$@"
'';
opcache = pkgs.runCommand "nextcloud-opcache-${package.version}" rec {
nativeBuildInputs = [ php ];
inherit package;
preloader = pkgs.writeScript "opcache-preloader.sh" ''
#!${pkgs.stdenv.shell}
${lib.escapeShellArgs [
"${php}/bin/php"
"-d" "zend_extension=opcache.so"
"-d" "opcache.enable=1"
"-d" "opcache.enable_cli=1"
"-d" "opcache.max_accelerated_files=100000"
"-d" "opcache.file_cache_only=1"
"-d" "assert.exception=1"
"-d" "error_reporting=E_ALL"
"-d" "display_errors=stderr"
]} -d "opcache.file_cache=$out" "$1" &> /dev/null || :
'';
} ''
mkdir "$out"
"$preloader" "$package/occ"
find "$package" -type f -name '*.php' -print0 \
| xargs -0 -P "$NIX_BUILD_CORES" -n1 "$preloader"
chmod -R go+rX "$out"
'';
caCerts = config.environment.etc."ssl/certs/ca-certificates.crt".source;
commonPhpConfig = [
"curl.cainfo=${caCerts}"
"expose_php=false"
"extension=${phpPackages.apcu}/lib/php/extensions/apcu.so"
"extension=${phpPackages.imagick}/lib/php/extensions/imagick.so"
"memory_limit=${toString cfg.maxUploadSize}M"
"opcache.enable=1"
"opcache.enable_cli=1"
"opcache.interned_strings_buffer=8"
"opcache.max_accelerated_files=10000"
"opcache.memory_consumption=128"
"opcache.revalidate_freq=1"
"opcache.save_comments=1"
"opcache.validate_timestamps=0"
"pgsql.allow_persistent=1"
"pgsql.auto_reset_persistent=0"
"pgsql.ignore_notice=0"
"pgsql.log_notice=0"
"pgsql.max_links=-1"
"pgsql.max_persistent=-1"
"post_max_size=${toString cfg.maxUploadSize}M"
"upload_max_filesize=${toString cfg.maxUploadSize}M"
"user_ini.filename="
"zend_extension=opcache.so"
] ++ lib.optionals cfg.preloadOpcache [
"opcache.file_cache=${opcache}"
"opcache.file_cache_consistency_checks=0"
"opcache.validate_permission=0"
];
# Results in a systemd unit for nextcloud.service which only contains
# BindReadOnlyPaths options. The rest of the service is defined later in
# systemd.services.nextcloud and the contents here are merged accordingly.
nextcloudSandboxPaths = pkgs.runCommand "nextcloud-sandbox-paths" {
closureInfo = pkgs.closureInfo {
rootPaths = [ uwsgiNextcloud pkgs.glibcLocales php pkgs.dash ];
};
} ''
mkdir -p "$out/lib/systemd/system"
for service in nextcloud nextcloud-cron; do
serviceFile="$out/lib/systemd/system/$service.service"
echo '[Service]' > "$serviceFile"
while read storePath; do
if [ ! -L "$storePath" ]; then
echo "BindReadOnlyPaths=$storePath:$storePath:rbind"
fi
done < "$closureInfo/store-paths" >> "$serviceFile"
done
'';
phpCli = let
mkArgs = lib.concatMapStringsSep " " (opt: "-d ${lib.escapeShellArg opt}");
escPhp = lib.escapeShellArg "${php}/bin/php";
in escPhp + " " + mkArgs commonPhpConfig;
# NixOS options that are merged with the existing appids.
extraAppOptions = {};
package = pkgs.stdenv.mkDerivation rec {
name = "nextcloud-${version}";
inherit (upstreamInfo.nextcloud) version;
src = pkgs.fetchzip {
inherit (upstreamInfo.nextcloud) url sha256;
};
prePatch = let
inherit (upstreamInfo) applications;
notShipped = lib.const (appdata: !appdata.meta.isShipped);
extApps = lib.filterAttrs notShipped applications;
isEnabled = name: cfg.apps.${name}.enable;
enabledApps = lib.filter isEnabled (lib.attrNames extApps);
appPaths = lib.genAttrs enabledApps (name: pkgs.fetchzip {
inherit (extApps.${name}) url sha256;
});
in lib.concatStrings (lib.mapAttrsToList (appid: path: ''
cp -TR ${lib.escapeShellArg path} apps/${lib.escapeShellArg appid}
chmod -R +w apps/${lib.escapeShellArg appid}
'') appPaths); # FIXME: Avoid the chmod above!
buildPhase = lib.optionalString (cfg.theme == "breeze-dark") ''
cp -TR ${lib.escapeShellArg themeBreezeDark} themes/nextcloud-breeze-dark
'';
patches = [
patches/no-config-uid-check.patch
patches/executable-lookup.patch
patches/readonly-config-upgrade.patch
];
# Nextcloud checks whether the user matches the webserver user by comparing
# the current userid with the owner of config.php. In our case however, the
# config.php is inside the Nix store so it most certainly isn't owned by
# the nextcloud user.
postPatch = ''
sed -i -e 's/${
"\\($configUser *= *\\).*fileowner(.*config.php.*)"
}/\1$user/g' cron.php console.php
'' + cfg.extraPostPatch;
installPhase = "mkdir -p \"\$out/\"\ncp -R . \"$out/\"";
meta = {
description = "Sharing solution for files, calendars, contacts and more";
homepage = https://nextcloud.com;
license = lib.licenses.agpl3Plus;
};
};
mkPhpString = value: "'${lib.escape ["\\" "'"] value}'";
mkPhpAssocArray = attrs: let
mkKeyVal = key: val: "${mkPhpString key} => ${mkPhp val}";
pairs = lib.mapAttrsToList mkKeyVal attrs;
in "[${lib.concatStringsSep ", " pairs}]";
mkPhpArray = vals: "[${lib.concatMapStringsSep ", " mkPhp vals}]";
mkPhp = value:
if lib.isInt value then toString value
else if value == true then "true"
else if value == false then "false"
else if value == null then "null"
else if value ? __fromEnv then "$_ENV[${mkPhpString value.__fromEnv}]"
else if lib.isAttrs value then mkPhpAssocArray value
else if lib.isList value then mkPhpArray value
else mkPhpString value;
mkPhpConfig = value: "<?php\n$CONFIG = ${mkPhp value};\n";
# All of the static files we can serve as-is without going through PHP.
staticFiles = pkgs.runCommand "nextcloud-static" {
nextcloud = package;
} ''
cd "$nextcloud"
install -D -m 644 robots.txt "$out/robots.txt"
find . -type f \( ${let
mkArg = ext: "-name ${lib.escapeShellArg "*.${ext}"}";
in lib.concatMapStringsSep " -o " mkArg [
"css" "gif" "html" "ico" "jpg" "js" "png" "svg" "ttf" "woff" "woff2"
]} \) -exec ${pkgs.writeScript "install-static" ''
#!${pkgs.stdenv.shell}
for path in "$@"; do
install -D -m 644 "$path" "$out/$path"
done
''} {} +
'';
# All of the PHP files that may be run via HTTP request relative to the
# docroot and without extension.
entryPoints = [
"index" "remote" "public" "status" "ocs/v1" "ocs/v2" "ocs-provider/index"
"ocm-provider/index"
];
nextcloudConfigDir = let
nextcloudConfig = mkPhpConfig ({
instanceid.__fromEnv = "__NEXTCLOUD_SECRETS_INSTANCEID";
passwordsalt.__fromEnv = "__NEXTCLOUD_SECRETS_PASSWORDSALT";
secret.__fromEnv = "__NEXTCLOUD_SECRETS_SECRET";
trusted_domains = [];
datadirectory = "/var/lib/nextcloud/data";
version.__fromEnv = "__NEXTCLOUD_VERSION";
dbtype = "pgsql";
dbhost = "/run/postgresql";
dbname = "nextcloud";
dbuser = "nextcloud";
installed = true;
knowledgebaseenabled = true;
allow_user_to_change_display_name = true;
skeletondirectory = "";
lost_password_link = "disabled";
mail_domain = cfg.domain;
overwritehost = "${cfg.domain}${maybePort}";
overwriteprotocol = urlScheme;
overwritewebroot = "/";
"overwrite.cli.url" = "/";
"htaccess.RewriteBase" = "/";
"htaccess.IgnoreFrontController" = true;
updatechecker = false;
check_for_working_wellknown_setup = false;
check_for_working_htaccess = false;
config_is_read_only = true;
# We do check integrity on our end via the updater and tampering on the
# server can be verified via the store paths checksum, eg. comparing it
# against one from a different host.
"integrity.check.disabled" = true;
lastupdateat = 0;
log_type = "errorlog";
logdateformat = ""; # Already taken care by journald.
appstoreenabled = false;
apps_paths = [
{ path = "${package}/apps";
url = "/apps";
writable = false;
}
];
nix_executable_map = {
smbclient = "${pkgs.samba}/bin/smbclient";
sendmail = "${config.security.wrapperDir}/sendmail";
ffmpeg = "${pkgs.ffmpeg.bin}/bin/ffmpeg";
};
enabledPreviewProviders =
map (ft: "OC\\Preview\\${ft}") cfg.previewFileTypes;
preview_libreoffice_path = let
isNeeded = !lib.mutuallyExclusive cfg.previewFileTypes [
"MSOffice2003" "MSOffice2007" "MSOfficeDoc" "OpenDocument"
"StarOffice"
];
# TODO: Put into a separate sandbox.
libreoffice = "${pkgs.libreoffice-unwrapped}/lib/libreoffice/program/"
+ "soffice.bin";
in lib.optionalString isNeeded libreoffice;
"memcache.local" = "\\OC\\Memcache\\APCu";
supportedDatabases = [ "pgsql" ];
tempdirectory = "/tmp"; # TODO: NOT /tmp, because large files!
# By default this contains '.htaccess', but our web server doesn't parse
# these files, so we can safely allow them.
blacklisted_files = [];
cipher = "AES-256-CFB";
"upgrade.disable-web" = true;
} // (lib.optionalAttrs (cfg.theme != "default") {
theme = "nextcloud-${cfg.theme}";
}) // cfg.extraConfig);
in pkgs.writeTextFile {
name = "nextcloud-config";
text = nextcloudConfig;
destination = "/config.php";
checkPhase = "${php}/bin/php -l \"$out/config.php\"";
};
mkEnableDisableApps = occCmd: disableOnly: let
appPart = lib.partition (a: cfg.apps.${a}.enable) (lib.attrNames cfg.apps);
newState = pkgs.writeText "nextcloud-appstate.json" (builtins.toJSON ({
disable = appPart.wrong;
} // lib.optionalAttrs (!disableOnly) {
enable = lib.genAttrs appPart.right (app: cfg.apps.${app}.onlyGroups);
appconf = lib.genAttrs appPart.right (app: cfg.apps.${app}.config);
}));
enableDisableApps = pkgs.writeScript "nextcloud-enable-disable-apps.py" ''
#!${pkgs.python3Packages.python.interpreter}
import json
import subprocess
import sys
occ_cmd = sys.argv[2:]
cmd = occ_cmd + ['app:list', '--output=json']
applist = subprocess.check_output(cmd)
oldstate = json.loads(applist)
newstate = json.load(open(sys.argv[1], 'r'))
if 'enable' in newstate:
newenabled = set(newstate['enable'].keys()) \
- set(oldstate['enabled'].keys())
group_deferred = {}
for appid in newenabled:
groups = newstate['enable'][appid]
if groups is not None:
group_deferred[appid] = groups
continue
subprocess.check_call(occ_cmd + ['app:enable', appid])
for appid, groups in group_deferred.items():
groupargs = [arg for group in groups for arg in ['-g', group]]
subprocess.check_call(occ_cmd + ['app:enable'] + groupargs + [appid])
for appid in newenabled:
for key, value in newstate.get('appconf', {}).get(appid, {}).items():
args = ['config:app:set', appid, key, '--value=' + value]
subprocess.check_call(occ_cmd + args)
newdisabled = set(newstate['disable']) \
- set(oldstate['disabled'].keys())
for appid in newdisabled:
if appid not in oldstate['enabled'] and \
appid not in oldstate['disabled']:
continue
subprocess.check_call(occ_cmd + ['app:disable', appid])
'';
in "${lib.escapeShellArg enableDisableApps} ${newState} ${occCmd}";
nextcloudInit = pkgs.runCommand "nextcloud-init" {
nativeBuildInputs = [
postgresql php pkgs.glibcLocales
];
outputs = [ "out" "sql" "data" ];
nextcloud = package;
adminUser = "admin"; # XXX
adminPass = "foobar"; # XXX
} ''
initdb -D "$TMPDIR/tempdb" -E UTF8 -N -U "$tempDbUser"
pg_ctl start -w -D "$TMPDIR/tempdb" -o \
"-F --listen_addresses= --unix_socket_directories=$TMPDIR"
createuser -h "$TMPDIR" nextcloud
createdb -h "$TMPDIR" nextcloud -O nextcloud
mkdir tmpconfig
cat > tmpconfig/override.config.php <<EOF
<?php
\$CONFIG = [
'apps_paths' => [
['path' => '$nextcloud/apps', 'url' => '/apps', 'writable' => false],
['path' => '$PWD', 'url' => '/dummy', 'writable' => true]
],
'skeletondirectory' => "",
];
EOF
export NEXTCLOUD_CONFIG_DIR="$PWD/tmpconfig"
${phpCli} "$nextcloud/occ" maintenance:install \
--database pgsql \
--database-name nextcloud \
--database-host $TMPDIR \
--database-user nextcloud \
--admin-user "$adminUser" \
--admin-pass "$adminPass" \
--data-dir "$PWD/data"
${phpCli} "$nextcloud/occ" background:cron
${phpCli} "$nextcloud/occ" db:convert-filecache-bigint
${mkEnableDisableApps "${phpCli} \"$nextcloud/occ\"" true}
rm "$PWD/data/index.html" "$PWD/data/.htaccess"
pg_dump -h "$TMPDIR" nextcloud > "$sql"
tar cf "$data" -C data .
touch "$out"
'';
php = pkgs.php-embed;
phpPackages = let
needsGhostscript = lib.elem cfg.previewFileTypes [ "PDF" "Postscript" ];
in pkgs.phpPackages.override ({
inherit php;
} // lib.optionalAttrs needsGhostscript {
pkgs = pkgs // { imagemagick = pkgs.imagemagickBig; };
});
uwsgiNextcloud = pkgs.runCommand "uwsgi-nextcloud" {
uwsgi = pkgs.uwsgi.override {
plugins = [ "php" ];
withPAM = false;
withSystemd = true;
};
config = pkgs.writeText "wsgi-nextcloud.json" (builtins.toJSON {
uwsgi = {
auto-procname = true;
chdir = package;
die-on-term = true;
disable-logging = true;
env = [
"NEXTCLOUD_CONFIG_DIR=${nextcloudConfigDir}"
"PWD=${package}"
];
master = true;
php-allowed-script = map (name: "${package}/${name}.php") entryPoints;
php-index = "index.php";
php-docroot = package;
php-sapi-name = "apache";
php-set = commonPhpConfig ++ [ "display_errors=stderr" ];
plugins = [ "0:php" ];
processes = cfg.processes;
procname-prefix-spaced = "[nextcloud]";
single-interpreter = true;
socket = config.systemd.sockets.nextcloud.socketConfig.ListenStream;
strict = true;
};
});
nativeBuildInputs = [ pkgs.makeWrapper ];
buildInputs = [];
} "makeWrapper \"$uwsgi/bin/uwsgi\" \"$out\" --add-flags \"--json $config\"";
in {
options.nextcloud = {
domain = mkOption {
type = types.str;
default = "localhost";
example = "cloud.example.org";
description = "The main Nextcloud domain to use for serving the site.";
};
useSSL = lib.mkOption {
type = types.bool;
default = builtins.match ".+\\..+" cfg.domain != null;
defaultText =
"builtins.match \".+\\\\..+\" config.nextcloud.domain != null";
description = ''
Whether to allow HTTPS connections only. If <option>domain</option>
contains any dots the default is <literal>true</literal>, otherwise
it's <literal>false</literal>.
'';
};
useACME = lib.mkOption {
type = types.bool;
default = cfg.useSSL;
description = ''
Whether to use ACME to get a certificate for the domain specified in
<option>domain</option>. Defaults to <literal>true</literal> if
<option>useSSL</option> is enabled.
'';
};
port = lib.mkOption {
type = types.ints.u16;
default = 443;
example = 8000;
description = ''
If the port number set here is not <literal>80</literal> or
<literal>443</literal>, generated URLs will explicitly contain the port
number as part of the URL scheme.
This is only useful for development/debugging.
'';
};
baseUrl = mkOption {
type = types.str;
internal = true;
readOnly = true;
description = ''
This is a concatenation of the scheme, the host and an optional port
and it's used for internal references from other modules.
'';
};
processes = mkOption {
type = types.ints.unsigned;
default = if lib.isInt config.nix.maxJobs
then config.nix.maxJobs * 2
else 1;
defaultText = "if lib.isInt config.nix.maxJobs then"
+ " config.nix.maxJobs * 2 else 1";
description = "The amount of processes to spawn for uWSGI.";
};
previewFileTypes = mkOption {
type = types.listOf (types.enum [
"BMP" "Font" "GIF" "HEIC" "Illustrator" "JPEG" "MP3" "MSOffice2003"
"MSOffice2007" "MSOfficeDoc" "MarkDown" "Movie" "OpenDocument" "PDF"
"PNG" "Photoshop" "Postscript" "SVG" "StarOffice" "TIFF" "TXT"
"XBitmap"
]);
default = [
"BMP" "GIF" "HEIC" "JPEG" "MP3" "MarkDown" "PNG" "TXT" "XBitmap"
];
description = ''
File types for which to generate previews (eg. thumbnails).
The ones not enabled by default are disabled due to performance or
privacy concerns. For example some file types could cause segfaults.
'';
};
preloadOpcache = mkOption {
type = types.bool;
default = false;
description = ''
Whether to preload PHP's OPcache at build-time.
<warning><para>This is experimental and might result in errors, for
example if the shared memory based storage has no more space
available.</para></warning>
'';
};
theme = mkOption {
type = types.enum [ "default" "breeze-dark" ];
default = "default";
example = "breeze-dark";
description = ''
The UI theme to use for this Nextcloud instance.
'';
};
maxUploadSize = mkOption {
type = types.ints.unsigned;
default = 512;
example = 1024;
description = ''
The maximum file size allowed in uploads in megabytes.
<warning><para>Note that this setting also raises the maximum amount of
memory a single worker process might consume to the value specified
here.</para></warning>
'';
};
apps = lib.mapAttrs (appId: appinfo: {
enable = mkOption {
type = types.bool;
default = appinfo.meta.defaultEnable or false;
description = ''
Whether to enable the ${appinfo.meta.name} (${appinfo.meta.summary})
application.
'' + lib.optionalString (appinfo.meta ? homepage) ''
More information can be found at <link
xlink:href='${appinfo.meta.homepage}'/>.
'';
};
onlyGroups = mkOption {
type = types.nullOr (types.listOf types.str);
default = null;
example = [ "admin" "special" ];
description = ''
If the value is not <literal>null</literal>, enable the app only for
the groups specified as a list. The groups are created if they do not
exist.
'';
};
config = mkOption {
type = types.attrsOf types.str;
default = {};
internal = true;
description = ''
A set of configuration options to set for this app after it has been
enabled.
'';
};
} // (extraAppOptions.${appId} or {})) upstreamInfo.applications;
extraConfig = lib.mkOption {
type = types.attrsOf types.unspecified;
default = {};
example = {
hashingCost = 50;
lost_password_link = "disabled";
};
description = ''
Extra options to add to the Nextcloud config file, which will be
serialised into a PHP array.
'';
};
extraPostPatch = lib.mkOption {
type = types.lines;
default = "";
example = ''
rm -r apps/comments
'';
internal = true;
description = ''
Extra shell script lines to append to the <literal>postPatch</literal>
phase of the Nextcloud main derivation.
'';
};
};
imports = [ ./libreoffice-online ./gpx ./xmpp ];
config = {
assertions = lib.singleton {
assertion = cfg.apps.bookmarks.enable
-> !cfg.apps.bookmarks_fulltextsearch.enable;
message = toString [
"The 'bookmarks' and 'bookmarks_fulltextsearch' apps are incompatible,"
"see https://github.com/nextcloud/bookmarks#install"
];
};
nextcloud.baseUrl = "${urlScheme}://${cfg.domain}${maybePort}";
services.nginx.virtualHosts.${cfg.domain} = {
forceSSL = cfg.useSSL;
enableACME = cfg.useACME;
extraConfig = ''
error_page 403 ${cfg.baseUrl}/;
error_page 404 ${cfg.baseUrl}/;
'';
locations = let
mkRewritesRedirs = cmd: lib.mapAttrsToList (from: to: [
(lib.nameValuePair "= /${from}" { extraConfig = cmd + to + ";"; })
(lib.nameValuePair "= /${from}/" { extraConfig = cmd + to + ";"; })
]);
rewrites = mkRewritesRedirs "rewrite ^ /" {
".well-known/host-meta" = "public.php?service=host-meta";
".well-known/host-meta.json" = "public.php?service=host-meta-json";
".well-known/webfinger" = "public.php?service=webfinger";
"ocm-provider" = "ocm-provider/index.php";
"osm-provider" = "osm-provider/index.php";
};
redirects = mkRewritesRedirs "return 301 ${cfg.baseUrl}/" {
".well-known/carddav" = "remote.php/dav";
".well-known/caldav" = "remote.php/dav";
};
in lib.listToAttrs (lib.concatLists (rewrites ++ redirects)) // {
"/" = {
root = staticFiles;
tryFiles = "$uri $uri$is_args$args /index.php$uri$is_args$args";
extraConfig = "access_log off;";
};
"~ ^/(?:${lib.concatStringsSep "|" entryPoints})\\.php(?:$|/)" = {
extraConfig = ''
client_max_body_size ${toString cfg.maxUploadSize}M;
uwsgi_intercept_errors on;
uwsgi_pass unix:///run/nextcloud.socket;
'';
};
};
};
users.users.nextcloud = {
description = "Nextcloud Server User";
group = "nextcloud";
};
users.groups.nextcloud = {};
systemd.sockets.nextcloud = {
description = "Nextcloud uWSGI Socket";
wantedBy = [ "sockets.target" ];
socketConfig = {
ListenStream = "/run/nextcloud.socket";
SocketUser = "root";
SocketGroup = "nginx";
SocketMode = "0660";
};
};
systemd.timers.nextcloud-cron = {
description = "Timer For Nextcloud Cron";
wantedBy = [ "timers.target" ];
timerConfig.OnBootSec = "5m";
timerConfig.OnUnitActiveSec = "15m";
};
systemd.services.nextcloud-init-db = {
description = "Nextcloud Database Initialisation";
requiredBy = [ "nextcloud.service" ];
requires = [ "postgresql.service" ];
before = [ "nextcloud.service" ];
after = [ "postgresql.service" ];
unitConfig.ConditionPathExists = "!/var/lib/nextcloud/.init-done";
environment.PGHOST = "/run/postgresql";
serviceConfig = {
Type = "oneshot";
User = "postgres";
Group = "postgres";
RemainAfterExit = true;
ExecStart = [
"${postgresql}/bin/createuser nextcloud"
"${postgresql}/bin/createdb -O nextcloud nextcloud"
"${postgresql}/bin/psql -1 -f ${nextcloudInit.sql} nextcloud"
];
};
};
systemd.services.nextcloud-secrets-init = {
description = "Nextcloud Secret Values Initialisation";
requiredBy = [ "nextcloud-init.service" ];
before = [ "nextcloud-init.service" "nextcloud.service" ];
unitConfig.ConditionPathExists = "!/var/lib/nextcloud/secrets.env";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
UMask = "0077";
StateDirectory = "nextcloud";
StateDirectoryMode = "0710";
Group = "nextcloud";
ExecStart = pkgs.writeScript "nextcloud-secrets-init.py" ''
#!${pkgs.python3Packages.python.interpreter}
import secrets, string
LOWER_DIGITS = string.ascii_lowercase + string.digits
result = {
'INSTANCEID': "".join(secrets.choice(LOWER_DIGITS)
for i in range(10)),
# This is deprecated, but let's generate it anyway in case
# some app still uses this value.
'PASSWORDSALT': secrets.token_urlsafe(30),
'SECRET': secrets.token_urlsafe(48),
}
lines = ['__NEXTCLOUD_SECRETS_' + key + '="' + val + '"\n'
for key, val in result.items()]
open('/var/lib/nextcloud/secrets.env', 'w').write("".join(lines))
'';
};
};
systemd.services.nextcloud-init = {
description = "Nextcloud Data Initialisation";
requiredBy = [ "nextcloud.service" ];
requires = [ "nextcloud-init-db.service" ];
after = [ "nextcloud-init-db.service" ];
before = [ "nextcloud.service" ];
unitConfig.ConditionPathExists = "!/var/lib/nextcloud/.init-done";
environment.NEXTCLOUD_CONFIG_DIR = nextcloudConfigDir;
serviceConfig = {
Type = "oneshot";
User = "nextcloud";
Group = "nextcloud";
RemainAfterExit = true;
PermissionsStartOnly = true;
StateDirectory = "nextcloud/data";
EnvironmentFile = "/var/lib/nextcloud/secrets.env";
ExecStart = let
tar = "${pkgs.gnutar}/bin/tar";
wantEncryption = cfg.apps.encryption.enable;
in [
"${tar} xf ${nextcloudInit.data} -C /var/lib/nextcloud/data"
] ++ lib.optional wantEncryption "${phpCli} ${occ} encryption:enable";
ExecStartPost =
"${pkgs.coreutils}/bin/touch /var/lib/nextcloud/.init-done";
};
};
systemd.packages = [ nextcloudSandboxPaths ];
systemd.services.nextcloud-upgrade = {
description = "Nextcloud Update Actions";
requiredBy = [ "nextcloud.service" ];
requires = [ "nextcloud-init-db.service" "nextcloud-init.service" ];
after = [ "nextcloud-init-db.service" "nextcloud-init.service" ];
before = [ "nextcloud.service" "nextcloud-cron.service" ];
environment.NEXTCLOUD_CONFIG_DIR = nextcloudConfigDir;
environment.__NEXTCLOUD_VERSION = package.version;
script = ''
if [ -e /var/lib/nextcloud/.version ]; then
__NEXTCLOUD_VERSION="$(< /var/lib/nextcloud/.version)" \
${phpCli} ${occ} upgrade
fi
${mkEnableDisableApps "${phpCli} ${occ}" false}
'';
postStart = ''
echo -n ${lib.escapeShellArg package.version} \
> /var/lib/nextcloud/.version
'';
serviceConfig = {
Type = "oneshot";
User = "nextcloud";
Group = "nextcloud";
RemainAfterExit = true;
PermissionsStartOnly = true;
StateDirectory = "nextcloud/data";
EnvironmentFile = "/var/lib/nextcloud/secrets.env";
};
};
systemd.services.nextcloud = {
description = "Nextcloud Server";
requires = [ "postgresql.service" ];
after = [ "network.target" "sockets.target" "postgresql.service" ];
environment.__NEXTCLOUD_VERSION = package.version;
serviceConfig = {
Type = "notify";
User = "nextcloud";
Group = "nextcloud";
StateDirectory = "nextcloud/data";
EnvironmentFile = "/var/lib/nextcloud/secrets.env";
ExecStart = "@${uwsgiNextcloud} nextcloud";
KillMode = "process";
ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
BindReadOnlyPaths = [
"/run/postgresql" "/run/systemd/notify" "/etc/resolv.conf"
# Nextcloud uses shell_exec() for things like generating office
# document previews, so we need to have /bin/sh.
"${pkgs.dash}/bin/dash:/bin/sh"
];
MountAPIVFS = true;
MountFlags = "private";
PrivateDevices = true;
PrivateTmp = true;
PrivateUsers = true;
ProtectControlGroups = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
RootDirectory = nextcloudSandboxPaths;
TemporaryFileSystem = "/";
};
};
systemd.services.nextcloud-cron = {
description = "Nextcloud Cron";
requires = [ "nextcloud.service" ];
after = [ "nextcloud.service" ];
environment.NEXTCLOUD_CONFIG_DIR = nextcloudConfigDir;
environment.__NEXTCLOUD_VERSION = package.version;
serviceConfig = {
Type = "oneshot";
User = "nextcloud";
Group = "nextcloud";
StateDirectory = "nextcloud/data";
ExecStart = "${php}/bin/php -f ${package}/cron.php";
EnvironmentFile = "/var/lib/nextcloud/secrets.env";
BindReadOnlyPaths = [
"/run/postgresql" "/etc/resolv.conf"
# Nextcloud uses shell_exec() for things like generating office
# document previews, so we need to have /bin/sh.
"${pkgs.dash}/bin/dash:/bin/sh"
];
MountAPIVFS = true;
MountFlags = "private";
PrivateDevices = true;
PrivateTmp = true;
PrivateUsers = true;
ProtectControlGroups = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
RootDirectory = nextcloudSandboxPaths;
TemporaryFileSystem = "/";
};
};
environment.systemPackages = [ occUser dbShell ];
};
}