]> git.basschouten.com Git - openhab-addons.git/blob
19ee819bc51e7b65379786e68832b67a6f269b3e
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.io.mqttembeddedbroker.internal;
14
15 import static org.hamcrest.CoreMatchers.is;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.junit.jupiter.api.Assertions.*;
18 import static org.mockito.ArgumentMatchers.*;
19 import static org.mockito.Mockito.verify;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.nio.file.Path;
24 import java.nio.file.Paths;
25 import java.security.GeneralSecurityException;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.Semaphore;
30 import java.util.concurrent.TimeUnit;
31
32 import javax.naming.ConfigurationException;
33
34 import org.apache.commons.io.FileUtils;
35 import org.h2.mvstore.MVMap;
36 import org.h2.mvstore.MVStore;
37 import org.junit.jupiter.api.AfterEach;
38 import org.junit.jupiter.api.BeforeEach;
39 import org.junit.jupiter.api.Test;
40 import org.junit.jupiter.api.extension.ExtendWith;
41 import org.mockito.Mock;
42 import org.mockito.junit.jupiter.MockitoExtension;
43 import org.openhab.core.OpenHAB;
44 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
45 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection.MqttVersion;
46 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection.Protocol;
47 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
48 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
49 import org.openhab.core.io.transport.mqtt.MqttException;
50 import org.openhab.core.io.transport.mqtt.MqttService;
51 import org.openhab.core.test.java.JavaTest;
52
53 import io.moquette.broker.RetainedMessage;
54 import io.moquette.broker.subscriptions.Topic;
55
56 /**
57  * Tests connections with the embedded broker. Checks for credential based login,
58  * check for SSL connections.
59  *
60  * @author David Graeff - Initial contribution
61  */
62 @ExtendWith(MockitoExtension.class)
63 public class MqttEmbeddedBrokerServiceTest extends JavaTest {
64
65     private EmbeddedBrokerService subject;
66     private Map<String, Object> config = new HashMap<>();
67     private @Mock MqttService service;
68
69     @BeforeEach
70     public void setUp() throws ConfigurationException, MqttException, GeneralSecurityException, IOException {
71         config.put("username", "username");
72         config.put("password", "password");
73         config.put("port", 12345);
74         config.put("secure", false);
75         config.put("persistenceFile", "");
76
77         subject = new EmbeddedBrokerService(service, config);
78     }
79
80     @AfterEach
81     public void cleanUp() {
82         subject.deactivate();
83     }
84
85     public void waitForConnectionChange(MqttBrokerConnection c, MqttConnectionState expectedState)
86             throws InterruptedException {
87         Semaphore semaphore = new Semaphore(1);
88         semaphore.acquire();
89
90         MqttConnectionObserver mqttConnectionObserver = (state, error) -> {
91             if (state == expectedState) {
92                 semaphore.release();
93             }
94         };
95         c.addConnectionObserver(mqttConnectionObserver);
96         if (c.connectionState() == expectedState) {
97             semaphore.release();
98         }
99
100         // Start the connection and wait until timeout or connected callback returns.
101         semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS);
102
103         c.removeConnectionObserver(mqttConnectionObserver);
104     }
105
106     @Test
107     public void connectUnsecureAndTestCredentials() throws InterruptedException, IOException, ExecutionException {
108         MqttBrokerConnection c = subject.getConnection();
109         assertNotNull(c);
110         waitForConnectionChange(c, MqttConnectionState.CONNECTED);
111
112         assertThat(c.getUser(), is("username"));
113         assertThat(c.getPassword(), is("password"));
114
115         assertThat(c.connectionState(), is(MqttConnectionState.CONNECTED));
116         verify(service).addBrokerConnection(anyString(), eq(c));
117
118         // Connect with a second connection but wrong credentials
119         MqttBrokerConnection wrongCredentials = new MqttBrokerConnection(Protocol.TCP, MqttVersion.V3, c.getHost(),
120                 c.getPort(), false, "wrongCred");
121         wrongCredentials.setCredentials("someUser", "somePassword");
122
123         if (wrongCredentials.start().get()) {
124             fail("Wrong credentials accepted!");
125         }
126
127         wrongCredentials.stop().get();
128
129         // Connect with a second connection but correct credentials
130         MqttBrokerConnection correctCredentials = new MqttBrokerConnection(Protocol.TCP, MqttVersion.V3, c.getHost(),
131                 c.getPort(), false, "correctCred");
132         correctCredentials.setCredentials(c.getUser(), c.getPassword());
133
134         if (!correctCredentials.start().get()) {
135             fail("Couldn't connect although correct credentials");
136         }
137
138         correctCredentials.stop().get();
139     }
140
141     @Test
142     public void connectSecure() throws InterruptedException, IOException {
143         config.put("secure", true);
144         subject.modified(config);
145
146         MqttBrokerConnection c = subject.getConnection();
147         assertNotNull(c);
148
149         waitForConnectionChange(c, MqttConnectionState.CONNECTED);
150
151         assertThat(c.getUser(), is("username"));
152         assertThat(c.getPassword(), is("password"));
153
154         assertThat(c.connectionState(), is(MqttConnectionState.CONNECTED));
155         verify(service).addBrokerConnection(anyString(), eq(c));
156     }
157
158     @Test
159     public void testPersistence() throws InterruptedException, IOException, ExecutionException {
160         config.put("persistenceFile", "persist.mqtt");
161         Path path = Paths.get(OpenHAB.getUserDataFolder()).toAbsolutePath();
162         File jksFile = path.resolve("persist.mqtt").toFile();
163
164         if (jksFile.exists()) {
165             jksFile.delete();
166         }
167
168         subject.modified(config);
169
170         MqttBrokerConnection c = subject.getConnection();
171         assertNotNull(c);
172
173         waitForConnectionChange(c, MqttConnectionState.CONNECTED);
174
175         c.publish("demotopic", "testtest".getBytes(), 2, true).get();
176
177         // Stop server -> close persistence storage and sync it to disk
178         subject.deactivate();
179         assertTrue(jksFile.exists());
180         // this is needed to ensure the file is correctly written
181         waitForAssert(() -> assertEquals(12288, jksFile.length()));
182
183         // The original file is still open, create a temp file for examination
184         File temp = File.createTempFile("abc", ".tmp");
185         temp.deleteOnExit();
186         FileUtils.copyFile(jksFile, temp);
187
188         MVStore mvStore = new MVStore.Builder().fileName(temp.getAbsolutePath()).autoCommitDisabled().open();
189         MVMap<Topic, RetainedMessage> openMap = mvStore.openMap("retained_store");
190
191         assertThat(openMap.size(), is(1));
192         for (Map.Entry<Topic, RetainedMessage> entry : openMap.entrySet()) {
193             assertThat(entry.getKey().toString(), is("demotopic"));
194             assertThat(new String(entry.getValue().getPayload()), is("testtest"));
195         }
196     }
197 }