about summary refs log tree commit diff
path: root/nixpkgs/nixos/tests/matrix/mautrix-meta-postgres.nix
blob: c9a45788afaf6483f95a068c12d638ed0303f826 (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
import ../make-test-python.nix ({ pkgs, ... }:
  let
    homeserverDomain = "server";
    homeserverUrl = "http://server:8008";
    userName = "alice";
    botUserName = "instagrambot";

    asToken = "this-is-my-totally-randomly-generated-as-token";
    hsToken = "this-is-my-totally-randomly-generated-hs-token";
  in
  {
    name = "mautrix-meta-postgres";
    meta.maintainers = pkgs.mautrix-meta.meta.maintainers;

    nodes = {
      server = { config, pkgs, ... }: {
        services.postgresql = {
          enable = true;

          ensureUsers = [
            {
              name = "mautrix-meta-instagram";
              ensureDBOwnership = true;
            }
          ];

          ensureDatabases = [
            "mautrix-meta-instagram"
          ];
        };

        systemd.services.mautrix-meta-instagram = {
          wants = [ "postgres.service" ];
          after = [ "postgres.service" ];
        };

        services.matrix-synapse = {
          enable = true;
          settings = {
            database.name = "sqlite3";

            enable_registration = true;

            # don't use this in production, always use some form of verification
            enable_registration_without_verification = true;

            listeners = [ {
              # The default but tls=false
              bind_addresses = [
                "0.0.0.0"
              ];
              port = 8008;
              resources = [ {
                "compress" = true;
                "names" = [ "client" ];
              } {
                "compress" = false;
                "names" = [ "federation" ];
              } ];
              tls = false;
              type = "http";
            } ];
          };
        };

        services.mautrix-meta.instances.instagram = {
          enable = true;

          environmentFile = pkgs.writeText ''my-secrets'' ''
            AS_TOKEN=${asToken}
            HS_TOKEN=${hsToken}
          '';

          settings = {
            homeserver = {
              address = homeserverUrl;
              domain = homeserverDomain;
            };

            appservice = {
              port = 8009;

              as_token = "$AS_TOKEN";
              hs_token = "$HS_TOKEN";

              database = {
                type = "postgres";
                uri = "postgres:///mautrix-meta-instagram?host=/var/run/postgresql";
              };

              bot.username = botUserName;
            };

            bridge.permissions."@${userName}:server" = "user";
          };
        };

        networking.firewall.allowedTCPPorts = [ 8008 8009 ];
      };

      client = { pkgs, ... }: {
        environment.systemPackages = [
          (pkgs.writers.writePython3Bin "do_test"
          {
            libraries = [ pkgs.python3Packages.matrix-nio ];
            flakeIgnore = [
              # We don't live in the dark ages anymore.
              # Languages like Python that are whitespace heavy will overrun
              # 79 characters..
              "E501"
            ];
          } ''
              import sys
              import functools
              import asyncio

              from nio import AsyncClient, RoomMessageNotice, RoomCreateResponse, RoomInviteResponse


              async def message_callback(matrix: AsyncClient, msg: str, _r, e):
                  print("Received matrix text message: ", e)
                  assert msg in e.body
                  exit(0)  # Success!


              async def run(homeserver: str):
                  matrix = AsyncClient(homeserver)
                  response = await matrix.register("${userName}", "foobar")
                  print("Matrix register response: ", response)

                  # Open a DM with the bridge bot
                  response = await matrix.room_create()
                  print("Matrix create room response:", response)
                  assert isinstance(response, RoomCreateResponse)
                  room_id = response.room_id

                  response = await matrix.room_invite(room_id, "@${botUserName}:${homeserverDomain}")
                  assert isinstance(response, RoomInviteResponse)

                  callback = functools.partial(
                      message_callback, matrix, "Hello, I'm an Instagram bridge bot."
                  )
                  matrix.add_event_callback(callback, RoomMessageNotice)

                  print("Waiting for matrix message...")
                  await matrix.sync_forever(timeout=30000)


              if __name__ == "__main__":
                  asyncio.run(run(sys.argv[1]))
            ''
          )
        ];
      };
    };

    testScript = ''
      def extract_token(data):
          stdout = data[1]
          stdout = stdout.strip()
          line = stdout.split('\n')[-1]
          return line.split(':')[-1].strip("\" '\n")

      def get_token_from(token, file):
          data = server.execute(f"cat {file} | grep {token}")
          return extract_token(data)

      def get_as_token_from(file):
          return get_token_from("as_token", file)

      def get_hs_token_from(file):
          return get_token_from("hs_token", file)

      config_yaml = "/var/lib/mautrix-meta-instagram/config.yaml"
      registration_yaml = "/var/lib/mautrix-meta-instagram/meta-registration.yaml"

      expected_as_token = "${asToken}"
      expected_hs_token = "${hsToken}"

      start_all()

      with subtest("start the server"):
          # bridge
          server.wait_for_unit("mautrix-meta-instagram.service")

          # homeserver
          server.wait_for_unit("matrix-synapse.service")

          server.wait_for_open_port(8008)
          # Bridge only opens the port after it contacts the homeserver
          server.wait_for_open_port(8009)

      with subtest("ensure messages can be exchanged"):
          client.succeed("do_test ${homeserverUrl} >&2")

      with subtest("ensure as_token, hs_token match from environment file"):
          as_token = get_as_token_from(config_yaml)
          hs_token = get_hs_token_from(config_yaml)
          as_token_registration = get_as_token_from(registration_yaml)
          hs_token_registration = get_hs_token_from(registration_yaml)

          assert as_token == expected_as_token, f"as_token in config should match the one specified (is: {as_token}, expected: {expected_as_token})"
          assert hs_token == expected_hs_token, f"hs_token in config should match the one specified (is: {hs_token}, expected: {expected_hs_token})"
          assert as_token_registration == expected_as_token, f"as_token in registration should match the one specified (is: {as_token_registration}, expected: {expected_as_token})"
          assert hs_token_registration == expected_hs_token, f"hs_token in registration should match the one specified (is: {hs_token_registration}, expected: {expected_hs_token})"

      with subtest("ensure as_token and hs_token stays same after restart"):
          server.systemctl("restart mautrix-meta-instagram")
          server.wait_for_open_port(8009)

          as_token = get_as_token_from(config_yaml)
          hs_token = get_hs_token_from(config_yaml)
          as_token_registration = get_as_token_from(registration_yaml)
          hs_token_registration = get_hs_token_from(registration_yaml)

          assert as_token == expected_as_token, f"as_token in config should match the one specified (is: {as_token}, expected: {expected_as_token})"
          assert hs_token == expected_hs_token, f"hs_token in config should match the one specified (is: {hs_token}, expected: {expected_hs_token})"
          assert as_token_registration == expected_as_token, f"as_token in registration should match the one specified (is: {as_token_registration}, expected: {expected_as_token})"
          assert hs_token_registration == expected_hs_token, f"hs_token in registration should match the one specified (is: {hs_token_registration}, expected: {expected_hs_token})"
    '';
  })