about summary refs log tree commit diff
path: root/flake.nix
blob: b8ba086a4420dda4040f8baf275e5fbb32dbadee (plain) (blame)
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
{
  inputs = {
    flake-utils = {
      type = "github";
      owner = "numtide";
      repo = "flake-utils";
      ref = "master";
    };
    rust = {
      type = "github";
      owner = "oxalica";
      repo = "rust-overlay";
      ref = "master";
      inputs.nixpkgs.follows = "nixpkgs";
    };
    naersk = {
      type = "github";
      owner = "nmattia";
      repo = "naersk";
      ref = "master";
      inputs.nixpkgs.follows = "nixpkgs";
    };
  };
  outputs = { self, nixpkgs, rust, flake-utils, naersk }: let
    supportedSystems = ["aarch64-linux" "x86_64-linux"];
    forAllSystems = f: flake-utils.lib.eachSystem supportedSystems f;
  in {
    nixosModule = { config, pkgs, lib, ... }: with lib; let
      cfg = config.services.kittybox;
    in {
      options = {
        services.kittybox = {
          enable = mkOption {
            type = types.bool;
            default = false;
            description = ''
              Whether to enable Kittybox, the IndieWeb blogging solution.
            '';
          };
          package = mkOption {
            type = types.package;
            default = self.packages.${config.nixpkgs.localSystem.system}.kittybox;
            defaultText = "<kittybox package from the official flake>";
            description = "Which Kittybox derivation to use.";
          };

          bind = mkOption {
            type = types.nullOr types.str;
            default = "127.0.0.1";
            description = "The host for Kittybox to bind to.";
            example = "192.168.1.100";
          };
          port = mkOption {
            type = types.int;
            default = 8080;
            description = "The port for Kittybox to listen at.";
            example = 16420;
          };
          logLevel = mkOption {
            type = types.str;
            default = "warn";
            example = "info";
            description = "Specify the server verbosity level. Uses RUST_LOG environment variable internally.";
          };
          redisUri = mkOption {
            type = types.nullOr types.str;
            default = null;
            example = "redis://192.168.1.200:6379/";
            description = "Set the Redis instance used as backing storage. If null, Redis will be configured on localhost. Use services.redis to change parameters.";
          };
          tokenEndpoint = mkOption {
            type = types.str;
            example = "https://tokens.indieauth.com/token";
            description = "Token endpoint to use for authenticating Micropub requests. Use the example if you are unsure.";
          };
          authorizationEndpoint = mkOption {
            type = types.str;
            example = "https://indieauth.com/auth";
            description = "Authorization endpoint to use to authenticate the user. You can use the default if you are unsure.";
          };
          mediaEndpoint = mkOption {
            type = types.nullOr types.str;
            description = "The URL of a media endpoint to announce when asked by a Micropub client. Strongly recommended if you plan to upload images.";
          };
          microsubServer = mkOption {
            type = types.nullOr types.str;
            example = "https://aperture.p3k.io/microsub/69420";
            description = ''
              The URL of your Microsub server, which saves feeds for you
              and allows you to browse Web content from one place. Try
              https://aperture.p3k.io/ if you don't have one yet!
            '';
          };
          webmentionEndpoint = mkOption {
            type = types.nullOr types.str;
            example = "https://webmention.io/example.com/webmention";
            description = ''
              The URL of your webmention endpoint, which allows you to
              receive notifications about your site's content being featured
              or interacted with elsewhere on the IndieWeb.

              By default Kittybox expects the Webmention endpoint to post
              updates using an internal token. kittybox-webmention is an
              endpoint capable of that.
            '';
          };
          internalTokenFile = mkOption {
            type = types.nullOr types.str;
            default = null;
            example = "/run/secrets/kittybox-shared-secret";
            description = "A shared secret that will, when passed, allow unlimited editing access to database. Keep it safe.";
          };
        };
      };
      config = lib.mkIf cfg.enable {
        systemd.services.kittybox = {
          description = "An IndieWeb-enabled blog engine";

          wantedBy = [ "multi-user.target" ];
          after = [ "network.target" ];

          restartTriggers = [
            cfg.package
            cfg.redisUri cfg.tokenEndpoint
            cfg.authorizationEndpoint
            cfg.internalTokenFile
            cfg.bind cfg.port
          ];

          environment = {
            SERVE_AT = "${cfg.bind}:${builtins.toString cfg.port}";
            AUTHORIZATION_ENDPOINT = cfg.authorizationEndpoint;
            TOKEN_ENDPOINT = cfg.tokenEndpoint;
            MEDIA_ENDPOINT = cfg.mediaEndpoint;
            MICROSUB_ENDPOINT = cfg.microsubServer;
            WEBMENTION_ENDPOINT = cfg.webmentionEndpoint;
            REDIS_URI = if (cfg.redisUri == null) then "redis://127.0.0.1:6379/" else cfg.redisUri;
          };

          script = ''
            if [[ -f ${cfg.internalTokenFile} ]]; then
              export KITTYBOX_INTERNAL_TOKEN=$(${pkgs.coreutils}/bin/cat ${cfg.internalTokenFile})
            fi
            exec ${cfg.package}/bin/kittybox
          '';

          serviceConfig = {
            DynamicUser = true;
          };
        };
        services.redis = lib.mkIf (cfg.redisUri == null) {
          enable = true;
        };
      };
    };
  } // forAllSystems (system: let
    pkgs = import nixpkgs {
      localSystem.system = system;
      overlays = [ rust.overlay ];
    };
    rust-bin = pkgs.rust-bin.stable.latest;
    packages = {
      kittybox = { stdenv, lib, redis, naersk-lib }:
      naersk-lib.buildPackage {
        pname = "kittybox";
        version = "0.1.0";

        src = ./.;

        checkInputs = [ redis ];
        doCheck = stdenv.hostPlatform == stdenv.targetPlatform;

        meta = with lib.meta; {
          maintainers = with maintainers; [ vika_nezrimaya ];
          platforms = supportedSystems;
          mainProgram = "kittybox";
        };
      };
    };
  in {
    packages = let
      naersk-lib = naersk.lib.${system}.override {
        rustc = pkgs.rust-bin.nightly.latest.minimal;
        cargo = pkgs.rust-bin.nightly.latest.minimal;
      };
    in {
      kittybox = pkgs.callPackage packages.kittybox { inherit naersk-lib; };
    };
    defaultPackage = self.packages.${system}.kittybox;

    checks = {
      nixos-test = pkgs.nixosTest ({ lib }: {
        name = "nixos-kittybox";

        nodes = {
          kittybox = { config, pkgs, lib, ... }: {
            imports = [ self.nixosModule ];

            services.kittybox = {
              enable = true;
              # It never actually contacts those endpoints anyway unless we use Micropub so it's fine!
              # TODO: Once we have self-hosted software for those endpoints,
              #       make an e2e test for common workflows (e.g. making a post)
              tokenEndpoint = "https://example.com";
              authorizationEndpoint = "https://example.com";
            };

            environment.systemPackages = with pkgs; [
              curl
            ];
          };
        };

        testScript = ''
          import json

          kittybox.start()
          kittybox.wait_for_unit("default.target")
          with subtest("Verify that Kittybox started correctly..."):
              kittybox.succeed("curl --silent http://localhost:8080/micropub")

          with subtest("Onboarding should correctly work..."):
              onboarding_json = {
                  "user": {
                      "type": ["h-card"],
                      "properties": {
                          "name": ["Vika"],
                          "pronoun": ["she/her"],
                          "url": ["https://twitter.com/VikaNezrimaya"],
                          "note": ["Just a simple girl. Do I even exist or am I a vestige of the past long gone?"]
                      }
                    },
                    "first_post": {
                        "type": ["h-entry"],
                        "properties": {
                            "content": ["Hello!"]
                        }
                    },
                    "blog_name": "Test Hideout",
                    "feeds": []
              }
              kittybox.succeed("echo '{}' | curl --silent http://localhost:8080/ -d@- -H 'Content-Type: application/json'".format(json.dumps(onboarding_json).replace("'", "'\''$")))
              # Testing for a known string is the easiest way to determine that the onboarding worked
              kittybox.succeed("curl --silent http://localhost:8080/ | grep 'vestige of the past long gone'")
        '';
      });
    };

    devShell = pkgs.mkShell {
      name = "rust-dev-shell";
      nativeBuildInputs = with pkgs; [
        pkg-config lld
        rust-bin.default
        rust-bin.rls
        rust-bin.rust-src
        redis
      ];
    };
  });
}