summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/admin/komodo-periphery.nix
blob: 848409746720b54544a5abe147fbd6c85592bf88 (plain)
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
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.services.komodo-periphery;
  settingsFormat = pkgs.formats.toml { };

  actualRepoDir = if cfg.repoDir != null then cfg.repoDir else "${cfg.rootDirectory}/repos";
  actualStackDir = if cfg.stackDir != null then cfg.stackDir else "${cfg.rootDirectory}/stacks";
  actualBuildDir = if cfg.buildDir != null then cfg.buildDir else "${cfg.rootDirectory}/builds";

  genFinalSettings =
    let
      actualServerEnabled =
        if cfg.inbound.serverEnabled != null then
          cfg.inbound.serverEnabled
        else
          (cfg.outbound.coreAddress == "");

      hasAnyPrivateKey = cfg.auth.privateKey != "";

      baseSettings = {
        default_terminal_command = cfg.defaultTerminalCommand;
        disable_terminals = cfg.disableTerminals;
        disable_container_terminals = cfg.disableContainerTerminals;

        stats_polling_rate = cfg.statsPollingRate;
        container_stats_polling_rate = cfg.containerStatsPollingRate;
        legacy_compose_cli = cfg.legacyComposeCli;

        include_disk_mounts = cfg.includeDiskMounts;
        exclude_disk_mounts = cfg.excludeDiskMounts;

        # When a private key is explicitly configured, it's passed via env var.
        # Otherwise, use the default file path so Periphery auto-generates a key.
        private_key = if !hasAnyPrivateKey then "file:${cfg.rootDirectory}/keys/periphery.key" else "";
        core_public_keys = [ ];
        passkeys = [ ];

        server_enabled = actualServerEnabled;
        port = cfg.inbound.port;
        bind_ip = cfg.inbound.bindIp;
        allowed_ips = cfg.inbound.allowedIps;
        ssl_enabled = cfg.inbound.ssl.enable;
      }
      // {
        core_address = cfg.outbound.coreAddress;
        connect_as = cfg.outbound.connectAs;
        onboarding_key = "";
      }
      // {
        logging = {
          level = cfg.logging.level;
          stdio = cfg.logging.stdio;
          opentelemetry_service_name = cfg.logging.opentelemetryServiceName;
          opentelemetry_scope_name = cfg.logging.opentelemetryScopeName;
          pretty = cfg.logging.pretty;
        }
        // lib.optionalAttrs (cfg.logging.otlpEndpoint != "") {
          otlp_endpoint = cfg.logging.otlpEndpoint;
        };
        pretty_startup_config = cfg.prettyStartupConfig;
      }
      // cfg.extraSettings;
    in
    lib.filterAttrsRecursive (_: v: v != null && v != { } && v != [ ] && v != "") baseSettings;

  configFile =
    if cfg.configFile == null then
      settingsFormat.generate "komodo-periphery.toml" genFinalSettings
    else
      cfg.configFile;
in
{
  imports = with lib; [
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "port" ]
      [ "services" "komodo-periphery" "inbound" "port" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "bindIp" ]
      [ "services" "komodo-periphery" "inbound" "bindIp" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "allowedIps" ]
      [ "services" "komodo-periphery" "inbound" "allowedIps" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "ssl" "enable" ]
      [ "services" "komodo-periphery" "inbound" "ssl" "enable" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "ssl" "keyFile" ]
      [ "services" "komodo-periphery" "inbound" "ssl" "keyFile" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "ssl" "certFile" ]
      [ "services" "komodo-periphery" "inbound" "ssl" "certFile" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "serverEnabled" ]
      [ "services" "komodo-periphery" "inbound" "serverEnabled" ]
    )
    (mkRenamedOptionModule
      [ "services" "komodo-periphery" "disableContainerExec" ]
      [ "services" "komodo-periphery" "disableContainerTerminals" ]
    )
    (mkRemovedOptionModule [ "services" "komodo-periphery" "passkeys" ]
      "services.komodo-periphery.passkeys has been removed. Use passkeyFiles for v1.X compatibility, or migrate to auth.privateKey and auth.corePublicKeys (v2.0+)."
    )
    (mkRemovedOptionModule [ "services" "komodo-periphery" "outbound" "onboardingKey" ]
      "services.komodo-periphery.outbound.onboardingKey has been removed. Use outbound.onboardingKeyFile instead for better security."
    )
  ];

  options.services.komodo-periphery = {
    enable = lib.mkEnableOption "Periphery, a multi-server Docker and Git deployment agent by Komodo";

    package = lib.mkPackageOption pkgs "komodo" { };

    dockerHost = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        Docker host socket URI to use for container operations.
        If null, uses the default Docker socket and automatically enables Docker.
        Set this to use alternative container runtimes like Podman or remote Docker hosts.
      '';
      example = lib.literalExpression ''
        # Podman rootless
        "unix:///run/user/1000/podman/podman.sock"

        # Podman rootful
        "unix:///run/podman/podman.sock"

        # Remote Docker
        "tcp://192.168.1.100:2375"
      '';
    };

    configFile = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      description = ''
        Path to the Periphery configuration file.

        - If `null` (default), a configuration file will be automatically generated
          from the module options (recommended for most users).
        - If set to a path, that file will be used directly as the configuration file.
        - You can also use `pkgs.writeText` to write configuration inline in your NixOS configuration.

        When using a custom config file, all other module options (except `package`, `user`, `group`,
        `environment`, and `environmentFile`) will be ignored.
      '';
      example = lib.literalExpression ''
        # Option 1: Use an existing config file
        "/etc/komodo/periphery.toml"

        # Option 2: Write config inline using pkgs.writeText
        pkgs.writeText "periphery.toml" '''
          root_directory = "/var/lib/komodo-periphery"

          logging.level = "info"
          logging.stdio = "standard"
        '''
      '';
    };

    rootDirectory = lib.mkOption {
      type = lib.types.path;
      default = "/var/lib/komodo-periphery";
      description = "Root directory for Komodo Periphery data.";
    };

    repoDir = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      defaultText = lib.literalExpression ''"''${config.services.komodo-periphery.rootDirectory}/repos"'';
      description = "Directory for Komodo Periphery to manage repos. If null, defaults to `\${rootDirectory}/repos`.";
    };

    stackDir = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      defaultText = lib.literalExpression ''"''${config.services.komodo-periphery.rootDirectory}/stacks"'';
      description = "Directory for Komodo Periphery to manage stacks. If null, defaults to `\${rootDirectory}/stacks`.";
    };

    buildDir = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      defaultText = lib.literalExpression ''"''${config.services.komodo-periphery.rootDirectory}/builds"'';
      description = "Directory for Komodo Periphery to manage builds. If null, defaults to `\${rootDirectory}/builds`.";
    };

    logging = {
      level = lib.mkOption {
        type = lib.types.enum [
          "off"
          "error"
          "warn"
          "info"
          "debug"
          "trace"
        ];
        default = "info";
        description = "Logging verbosity level.";
      };

      stdio = lib.mkOption {
        type = lib.types.enum [
          "standard"
          "json"
          "none"
        ];
        default = "standard";
        description = "Logging format for stdout/stderr.";
      };

      otlpEndpoint = lib.mkOption {
        type = lib.types.str;
        default = "";
        description = "OpenTelemetry OTLP endpoint for traces.";
        example = "http://localhost:4317";
      };

      opentelemetryServiceName = lib.mkOption {
        type = lib.types.str;
        default = "Periphery";
        description = "(v2.0+) OpenTelemetry service name attached to telemetry.";
      };

      opentelemetryScopeName = lib.mkOption {
        type = lib.types.str;
        default = "Komodo";
        description = "(v2.0+) OpenTelemetry scope name attached to telemetry.";
      };

      pretty = lib.mkOption {
        type = lib.types.bool;
        default = false;
        description = "(v2.0+) Enable human-readable logging (multi-line).";
      };
    };

    prettyStartupConfig = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "(v2.0+) Enable human-readable startup config log (multi-line).";
    };

    passkeyFiles = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      description = ''
        Path to file containing passkeys (v1.X compatibility).
        This will be passed via `PERIPHERY_PASSKEYS_FILE` environment variable.
        Consider migrating to the new v2.0+ authentication mechanism.
      '';
      example = "/run/secrets/komodo-passkey";
    };

    extraSettings = lib.mkOption {
      type = settingsFormat.type;
      default = { };
      description = "Extra settings to add to the generated TOML config.";
      example = {
        secrets.GITHUB_TOKEN = "ghp_xxxx";
      };
    };

    defaultTerminalCommand = lib.mkOption {
      type = lib.types.str;
      default = "bash";
      description = "(v2.0+) Default terminal command used to initialize the shell.";
      example = "zsh";
    };

    disableTerminals = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "Disable remote shell access through Periphery.";
    };

    disableContainerTerminals = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "(v2.0+) Disable remote container shell access through Periphery.";
    };

    statsPollingRate = lib.mkOption {
      type = lib.types.str;
      default = "5-sec";
      description = "System stats polling interval.";
      example = "10-sec";
    };

    containerStatsPollingRate = lib.mkOption {
      type = lib.types.str;
      default = "30-sec";
      description = "Container stats polling interval.";
      example = "1-min";
    };

    legacyComposeCli = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "Use `docker-compose` instead of `docker compose`.";
    };

    includeDiskMounts = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [ ];
      description = "Only include these mount paths in disk reporting.";
      example = [
        "/mnt/data"
        "/mnt/backup"
      ];
    };

    excludeDiskMounts = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [ ];
      description = "Exclude these mount paths from disk reporting.";
      example = [
        "/tmp"
        "/boot"
      ];
    };

    auth = {
      privateKey = lib.mkOption {
        type = lib.types.str;
        default = "";
        description = ''
          (v2.0+) Private key used with the Noise handshake.

          Use `file:/path/to/file` prefix to load from a file. If the file doesn't exist,
          Periphery will generate and write a new key to the path.

          If empty, defaults to `file:''${rootDirectory}/keys/periphery.key`.
        '';
        example = lib.literalExpression ''
          # Reference a secret file
          "file:''${config.age.secrets.komodo-private-key.path}"

          # Or direct path
          "file:/run/secrets/komodo-private-key"
        '';
      };

      corePublicKeys = lib.mkOption {
        type = lib.types.listOf lib.types.str;
        default = [ ];
        description = ''
          (v2.0+) Accepted public keys to allow Core(s) to connect.
          Accepts Spki base64 DER directly or can reference files using `file:/path/to/core.pub` prefix.
          You can mix direct keys and file references.

          For better security, use the `file:` prefix to reference secret files.
        '';
        example = lib.literalExpression ''
          [
            # Direct key value
            "MCowBQYDK2VuAyEATZgrjGHeF0KJUe0+n77+qAWOg3YzEzXOmQWaRgO3OGQ="
            # Reference secret files
            "file:''${config.age.secrets.komodo-core1-pub.path}"
            "file:''${config.age.secrets.komodo-core2-pub.path}"
          ]
        '';
      };
    };

    inbound = {
      serverEnabled = lib.mkOption {
        type = lib.types.nullOr lib.types.bool;
        default = null;
        description = ''
          Enable the inbound connection server for Core -> Periphery connections.
          If null, defaults to false when `outbound.coreAddress` is defined, otherwise true.
        '';
      };

      port = lib.mkOption {
        type = lib.types.port;
        default = 8120;
        description = "Port for the inbound Periphery server to listen on.";
      };

      bindIp = lib.mkOption {
        type = lib.types.str;
        default = "[::]";
        description = ''
          IP address the periphery server will bind to.
          The default allows external IPv4 and IPv6 connections.
        '';
      };

      allowedIps = lib.mkOption {
        type = lib.types.listOf lib.types.str;
        default = [ ];
        description = ''
          Limit the IP addresses which can connect to Periphery.
          Supports IPv4/IPv6 addresses and subnets.
          Empty list allows all connections.
        '';
        example = [
          "::ffff:12.34.56.78"
          "10.0.10.0/24"
        ];
      };

      ssl = {
        enable = lib.mkEnableOption "(v2.0+) SSL/TLS support for inbound connections" // {
          default = true;
        };

        keyFile = lib.mkOption {
          type = lib.types.path;
          default = "${cfg.rootDirectory}/ssl/key.pem";
          defaultText = lib.literalExpression ''"''${config.services.komodo-periphery.rootDirectory}/ssl/key.pem"'';
          description = ''
            Path to SSL key file.
            If the file doesn't exist and SSL is enabled, self-signed keys will be generated using openssl.
          '';
        };

        certFile = lib.mkOption {
          type = lib.types.path;
          default = "${cfg.rootDirectory}/ssl/cert.pem";
          defaultText = lib.literalExpression ''"''${config.services.komodo-periphery.rootDirectory}/ssl/cert.pem"'';
          description = ''
            Path to SSL certificate file.
            If the file doesn't exist and SSL is enabled, self-signed certificate will be generated using openssl.
          '';
        };
      };
    };

    outbound = {
      coreAddress = lib.mkOption {
        type = lib.types.str;
        default = "";
        description = ''
          (v2.0+) The address of Komodo Core. Must be reachable from this host.
          If provided, Periphery will operate in outbound mode.
        '';
        example = "demo.komo.do";
      };

      connectAs = lib.mkOption {
        type = lib.types.str;
        default = "";
        description = ''
          (v2.0+) The Server this Periphery agent should connect as.
          Must match an existing Server name or id.
        '';
        example = "server-name";
      };

      onboardingKeyFile = lib.mkOption {
        type = lib.types.nullOr lib.types.path;
        default = null;
        description = ''
          (v2.0+) Path to file containing the onboarding key.
          This will be passed via `PERIPHERY_ONBOARDING_KEY_FILE` environment variable.
        '';
        example = lib.literalExpression ''"''${config.age.secrets.komodo-onboarding.path}"'';
      };
    };

    user = lib.mkOption {
      type = lib.types.str;
      default = "komodo-periphery";
      description = "User under which the Periphery agent runs.";
    };

    group = lib.mkOption {
      type = lib.types.str;
      default = "komodo-periphery";
      description = "Group under which the Periphery agent runs.";
    };

    environmentFile = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      description = "Environment file for additional configuration via environment variables.";
      example = "/run/secrets/komodo-periphery.env";
    };

    environment = lib.mkOption {
      type = lib.types.attrsOf lib.types.str;
      default = { };
      description = "Environment variables to set for the service.";
      example = {
        RUST_LOG = "komodo=debug";
        DOCKER_HOST = "unix:///var/run/docker.sock";
      };
    };
  };

  config = lib.mkIf cfg.enable {
    virtualisation.docker.enable = lib.mkDefault (cfg.dockerHost == null);

    users.users.${cfg.user} = lib.mkIf (cfg.user == "komodo-periphery") {
      isSystemUser = true;
      group = cfg.group;
      description = "Komodo Periphery service user";
      home = cfg.rootDirectory;
      extraGroups = lib.optional (cfg.dockerHost == null) "docker";
    };

    users.groups.${cfg.group} = lib.mkIf (cfg.group == "komodo-periphery") { };

    systemd.tmpfiles.settings."10-komodo-periphery" = {
      "${cfg.rootDirectory}".d = {
        mode = "0755";
        user = cfg.user;
        group = cfg.group;
      };
      "${actualRepoDir}".d = {
        mode = "0755";
        user = cfg.user;
        group = cfg.group;
      };
      "${actualStackDir}".d = {
        mode = "0755";
        user = cfg.user;
        group = cfg.group;
      };
      "${actualBuildDir}".d = {
        mode = "0755";
        user = cfg.user;
        group = cfg.group;
      };
      "${cfg.rootDirectory}/keys".d = {
        mode = "0700";
        user = cfg.user;
        group = cfg.group;
      };
      "${cfg.rootDirectory}/ssl".d = {
        mode = "0700";
        user = cfg.user;
        group = cfg.group;
      };
    };

    systemd.services.komodo-periphery = {
      description = "Komodo Periphery - Multi-server Docker and Git deployment agent";
      after = [
        "network-online.target"
      ]
      ++ lib.optional (cfg.dockerHost == null) "docker.service";
      wants = [
        "network-online.target"
      ]
      ++ lib.optional (cfg.dockerHost == null) "docker.service";
      wantedBy = [ "multi-user.target" ];

      # Periphery shells out to `docker`, `docker compose` and `git` through `sh -c`.
      path = [
        pkgs.git
        config.virtualisation.docker.package
      ]
      ++ lib.optionals (!cfg.disableTerminals) [
        "/run/current-system/sw"
        "/run/wrappers"
      ];

      serviceConfig = {
        Type = "simple";
        User = cfg.user;
        Group = cfg.group;
        SupplementaryGroups = lib.mkIf (cfg.dockerHost == null) [ "docker" ];
        Restart = "on-failure";
        RestartSec = "10s";
        WorkingDirectory = cfg.rootDirectory;

        ExecStart = lib.escapeShellArgs [
          (lib.getExe' cfg.package "periphery")
          "--config-path"
          configFile
        ];

        Environment = lib.mapAttrsToList (name: value: "${name}=${value}") (
          lib.optionalAttrs (cfg.configFile == null) {
            PERIPHERY_ROOT_DIRECTORY = cfg.rootDirectory;
            PERIPHERY_REPO_DIR = actualRepoDir;
            PERIPHERY_STACK_DIR = actualStackDir;
            PERIPHERY_BUILD_DIR = actualBuildDir;
          }
          // lib.optionalAttrs (cfg.configFile == null && cfg.inbound.ssl.enable) {
            PERIPHERY_SSL_KEY_FILE = cfg.inbound.ssl.keyFile;
            PERIPHERY_SSL_CERT_FILE = cfg.inbound.ssl.certFile;
          }
          // lib.optionalAttrs (cfg.dockerHost != null) {
            DOCKER_HOST = cfg.dockerHost;
          }
          // lib.optionalAttrs (cfg.passkeyFiles != null) {
            PERIPHERY_PASSKEYS_FILE = cfg.passkeyFiles;
          }
          // lib.optionalAttrs (cfg.auth.privateKey != "") {
            PERIPHERY_PRIVATE_KEY = cfg.auth.privateKey;
          }
          // lib.optionalAttrs (cfg.auth.corePublicKeys != [ ]) {
            PERIPHERY_CORE_PUBLIC_KEYS = lib.concatStringsSep "," cfg.auth.corePublicKeys;
          }
          // lib.optionalAttrs (cfg.outbound.onboardingKeyFile != null) {
            PERIPHERY_ONBOARDING_KEY_FILE = cfg.outbound.onboardingKeyFile;
          }
          // cfg.environment
        );

        EnvironmentFile = lib.mkIf (cfg.environmentFile != null) cfg.environmentFile;

        StateDirectory = "komodo-periphery";
        StateDirectoryMode = "0755";

        NoNewPrivileges = true;
        PrivateTmp = true;
        ProtectSystem = "full";
        ProtectHome = "read-only";
      };
    };
  };

  meta.maintainers = with lib.maintainers; [ channinghe ];
}