File: test_ssl_cert.py

package info (click to toggle)
pg-auto-failover 2.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,368 kB
  • sloc: ansic: 58,369; python: 5,515; sql: 3,177; makefile: 629; sh: 35
file content (292 lines) | stat: -rw-r--r-- 8,530 bytes parent folder | download | duplicates (3)
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
import tests.pgautofailover_utils as pgautofailover
import tests.ssl_cert_utils as cert
from nose.tools import *

import subprocess
import os, os.path, time, shutil

cluster = None
node1 = None
node2 = None


def setup_module():
    global cluster
    cluster = pgautofailover.Cluster()

    client_top_directory = os.path.join(os.getenv("HOME"), ".postgresql")

    cluster.create_root_cert(
        client_top_directory, basename="root", CN="/CN=root.pgautofailover.ca"
    )


def teardown_module():
    cluster.destroy()

    # remove client side setup for certificates too
    client_top_directory = os.path.join(os.getenv("HOME"), ".postgresql")

    p = subprocess.Popen(
        [
            "sudo",
            "-E",
            "-u",
            os.getenv("USER"),
            "env",
            "PATH=" + os.getenv("PATH"),
            "rm",
            "-rf",
            client_top_directory,
        ]
    )
    assert p.wait() == 0

    # also remove certificates we created for the servers
    p = subprocess.run(
        [
            "sudo",
            "-E",
            "-u",
            os.getenv("USER"),
            "env",
            "PATH=" + os.getenv("PATH"),
            "rm",
            "-rf",
            "/tmp/certs",
        ]
    )
    assert p.returncode == 0


def test_000_create_monitor():
    # create SSL certs and keys for this server
    #
    # https://www.postgresql.org/docs/11/ssl-tcp.html
    #
    # server.crt and server.key should be stored on the server, and root.crt
    # should be stored on the client so the client can verify that the
    # server's leaf certificate was signed by its trusted root certificate.
    # root.key should be stored offline for use in creating future
    # certificates.
    #
    # https://www.postgresql.org/docs/current/libpq-ssl.html
    #
    # If the server attempts to verify the identity of the client by
    # requesting the client's leaf certificate, libpq will send the
    # certificates stored in file ~/.postgresql/postgresql.crt in the user's
    # home directory
    # Now, create a server certificate signed by the new root certificate
    # authority
    client_top_directory = os.path.join(os.getenv("HOME"), ".postgresql")

    # now create and sign the CLIENT certificate
    clientCert = cert.SSLCert(
        client_top_directory, basename="postgresql", CN="/CN=autoctl_node"
    )
    clientCert.create_signed_certificate(cluster.cert)

    # now create and sign the SERVER certificate for the monitor
    serverCert = cert.SSLCert(
        "/tmp/certs/monitor", "server", "/CN=monitor.pgautofailover.ca"
    )
    serverCert.create_signed_certificate(cluster.cert)

    # the root user also needs the certificates, tests are connecting with it
    root_top_directory = "/root/.postgresql"
    p = subprocess.run(
        ["sudo", "install", "-d", "-m", "740", root_top_directory]
    )
    assert p.returncode == 0

    p = subprocess.run(
        [
            "sudo",
            "cp",
            clientCert.crt,
            clientCert.csr,
            clientCert.key,
            root_top_directory,
        ]
    )
    assert p.returncode == 0

    p = subprocess.run(
        [
            "ls",
            "-ld",
            client_top_directory,
            root_top_directory,
            os.path.join(root_top_directory, "postgresql.crt"),
            os.path.join(root_top_directory, "postgresql.csr"),
            os.path.join(root_top_directory, "postgresql.key"),
            cluster.cert.crt,
            cluster.cert.csr,
            cluster.cert.key,
            clientCert.crt,
            clientCert.csr,
            clientCert.key,
            serverCert.crt,
            serverCert.csr,
            serverCert.key,
        ],
        text=True,
        capture_output=True,
    )
    print("%s" % p.stdout)

    #
    # Now create the monitor Postgres instance with the certificates
    #
    monitor = cluster.create_monitor(
        "/tmp/cert/monitor",
        authMethod="skip",
        sslMode="verify-ca",
        sslCAFile=cluster.cert.crt,
        sslServerKey=serverCert.key,
        sslServerCert=serverCert.crt,
    )
    monitor.run()
    monitor.wait_until_pg_is_running()

    with open(os.path.join("/tmp/cert/monitor", "pg_hba.conf"), "a") as hba:
        hba.write("hostssl all all %s cert\n" % cluster.networkSubnet)

    monitor.reload_postgres()

    # check the SSL settings
    cmd = [
        "openssl",
        "s_client",
        "-starttls",
        "postgres",
        "-connect",
        "172.27.1.2:5432",
        "-showcerts",
        "-CAfile",
        cluster.cert.crt,
    ]
    print(" ".join(cmd))
    p = subprocess.run(
        [
            "sudo",
            "-E",
            "-u",
            os.getenv("USER"),
            "env",
            "PATH=" + os.getenv("PATH"),
        ]
        + cmd,
        input="",
        text=True,
        capture_output=True,
    )
    if p.returncode != 0:
        print("" % p.stdout)
        print("" % p.stderr)
    assert p.returncode == 0

    # print connection string
    print("monitor: %s" % monitor.connection_string())
    monitor.check_ssl("on", "verify-ca")


def test_001_init_primary():
    global node1

    # Create a server certificate signed by the root Certificate Authority
    certs_dir = "/tmp/certs/node1"

    serverCert = cert.SSLCert(
        "/tmp/certs/node1", "server", "/CN=node1.pgautofailover.ca"
    )
    serverCert.create_signed_certificate(cluster.cert)

    # Now create the server with the certificates
    node1 = cluster.create_datanode(
        "/tmp/cert/node1",
        authMethod="skip",
        sslMode="verify-ca",
        sslCAFile=cluster.cert.crt,
        sslServerKey=serverCert.key,
        sslServerCert=serverCert.crt,
    )
    node1.create(level="-vv")

    with open(os.path.join("/tmp/cert/node1", "pg_hba.conf"), "a") as hba:
        # node1.run_sql_query will need
        # host "172.27.1.1", user "docker", database "postgres"
        hba.write("hostssl postgres docker %s cert\n" % cluster.networkSubnet)
        hba.write("hostssl all all %s cert\n" % cluster.networkSubnet)
        hba.write(
            "hostssl replication all %s cert map=pgautofailover\n"
            % cluster.networkSubnet
        )

    with open(os.path.join("/tmp/cert/node1", "pg_ident.conf"), "a") as ident:
        # use an ident map to allow using the same cert for replication
        ident.write("pgautofailover autoctl_node pgautofailover_replicator\n")

    node1.reload_postgres()

    node1.run()
    assert node1.wait_until_state(target_state="single")
    node1.wait_until_pg_is_running()
    node1.check_ssl("on", "verify-ca", primary=True)


def test_002_create_t1():
    print()
    print(node1.connection_string())
    node1.run_sql_query("CREATE TABLE t1(a int)")
    node1.run_sql_query("INSERT INTO t1 VALUES (1), (2)")


def test_003_init_secondary():
    global node2

    # Create a server certificate signed by the root Certificate Authority
    certs_dir = "/tmp/certs/node2"

    serverCert = cert.SSLCert(
        "/tmp/certs/node2", "server", "/CN=node2.pgautofailover.ca"
    )
    serverCert.create_signed_certificate(cluster.cert)

    # Now create the server with the certificates
    node2 = cluster.create_datanode(
        "/tmp/cert/node2",
        authMethod="skip",
        sslMode="verify-ca",
        sslCAFile=cluster.cert.crt,
        sslServerKey=serverCert.key,
        sslServerCert=serverCert.crt,
    )
    node2.create(level="-vv")

    with open(os.path.join("/tmp/cert/node2", "pg_hba.conf"), "a") as hba:
        hba.write("hostssl all all %s cert\n" % cluster.networkSubnet)
        hba.write(
            "hostssl replication all %s cert map=pgautofailover\n"
            % cluster.networkSubnet
        )

    with open(os.path.join("/tmp/cert/node1", "pg_ident.conf"), "a") as ident:
        # use an ident map to allow using the same cert for replication
        ident.write("pgautofailover autoctl_node pgautofailover_replicator\n")

    node2.reload_postgres()

    node2.run()
    assert node2.wait_until_state(target_state="secondary")
    assert node1.wait_until_state(target_state="primary")
    node2.wait_until_pg_is_running()
    node2.check_ssl("on", "verify-ca")


def test_004_failover():
    print()
    print("Calling pgautofailover.failover() on the monitor")
    cluster.monitor.failover()
    assert node2.wait_until_state(target_state="primary")
    assert node1.wait_until_state(target_state="secondary")