Browse Source

Store the granted license key in tb_cluster

The enrollment now collects its license key from the portal when the grant is
done, and keeps it in tb_cluster.license_secret. A claim that has nothing to
hand over yet leaves the flow for the next poll; a refused claim ends the flow
registered without a key; a transport failure is left to the existing backoff.
pull/16221/head
Viacheslav Klimov 2 months ago
parent
commit
fde6809287
Failed to extract signature
  1. 8
      application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql
  2. 16
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java
  3. 4
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java
  4. 8
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java
  5. 44
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java
  6. 25
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java
  7. 56
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java
  8. 48
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java
  9. 13
      dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java
  10. 1
      dao/src/main/resources/sql/schema-entities.sql
  11. 27
      dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java

8
application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql

@ -11,6 +11,7 @@
CREATE TABLE IF NOT EXISTS tb_cluster (
cluster_id uuid NOT NULL,
license_claim_token varchar,
license_secret varchar,
CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id)
);
@ -19,3 +20,10 @@ CREATE TABLE IF NOT EXISTS tb_cluster (
CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true));
-- TB_CLUSTER END
-- TB_CLUSTER LICENSE SECRET START
-- The CREATE above is a no-op on a database that already carries tb_cluster.
ALTER TABLE tb_cluster ADD COLUMN IF NOT EXISTS license_secret varchar;
-- TB_CLUSTER LICENSE SECRET END

16
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java

@ -0,0 +1,16 @@
package org.thingsboard.server.service.community_grant;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestClientException;
/**
* Thrown by {@link CommunityGrantPortalClient#claimLicense} when the portal will not hand the license key
* over. Terminal, unlike a transport failure: retrying the claim cannot change the answer.
*/
public class CommunityGrantLicenseClaimRefusedException extends RestClientException {
public CommunityGrantLicenseClaimRefusedException(HttpStatusCodeException cause) {
super(cause.getMessage(), cause);
}
}

4
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java

@ -0,0 +1,4 @@
package org.thingsboard.server.service.community_grant;
public record CommunityGrantLicenseClaimRequest(String claimToken) {
}

8
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java

@ -0,0 +1,8 @@
package org.thingsboard.server.service.community_grant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/** {@code secret} is set only once {@code activated} is true. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record CommunityGrantLicenseClaimResponse(boolean activated, String secret) {
}

44
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java

@ -358,9 +358,7 @@ public class CommunityGrantPoller extends TbApplicationEventListener<PartitionCh
log.debug("Ignoring a portal status response with no status value");
return;
}
CommunityGrantState terminalState = terminalStateFor(statusValue);
if (terminalState != null) {
retire(token, terminalState, now, null);
if (applyIfTerminal(token, statusValue, now)) {
return;
}
switch (statusValue) {
@ -372,6 +370,38 @@ public class CommunityGrantPoller extends TbApplicationEventListener<PartitionCh
}
}
/** @return whether the status was a terminal one, even when the flow could not be ended on this poll. */
private boolean applyIfTerminal(String token, String status, long now) {
CommunityGrantState terminalState = terminalStateFor(status);
if (terminalState == null) {
return false;
}
if (terminalState == CommunityGrantState.REGISTERED) {
onDone(token, now);
} else {
retire(token, terminalState, now, null);
}
return true;
}
/** The key is stored before the token is cleared, so a failure above it leaves the next poll to retry. */
private void onDone(String token, long now) {
String licenseSecret;
try {
licenseSecret = portalClient.claimLicense(token);
} catch (CommunityGrantLicenseClaimRefusedException e) {
log.warn("The license portal did not hand over the license key for this registration ({}). "
+ "The registration stands and the key can be entered by hand later", e.getMessage());
retire(token, CommunityGrantState.REGISTERED, now, null);
return;
}
if (StringUtils.isEmpty(licenseSecret)) {
return;
}
tbClusterStore.saveLicenseSecret(licenseSecret);
retire(token, CommunityGrantState.REGISTERED, now, null);
}
/** @return the state the flow ends in, or {@code null} if the status is not a terminal one. */
private static CommunityGrantState terminalStateFor(String status) {
return switch (status) {
@ -450,10 +480,10 @@ public class CommunityGrantPoller extends TbApplicationEventListener<PartitionCh
if (uploadedStatus == null) {
return;
}
CommunityGrantState terminalState = terminalStateFor(uploadedStatus);
if (terminalState != null) {
retire(token, terminalState, now, null);
} else if ("UNDER_REVIEW".equals(uploadedStatus)) {
if (applyIfTerminal(token, uploadedStatus, now)) {
return;
}
if ("UNDER_REVIEW".equals(uploadedStatus)) {
onUnderReview(token, now);
} else {
log.debug("Ignoring an unrecognized portal status after the upload");

25
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java

@ -9,6 +9,7 @@ import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
@ -40,6 +41,7 @@ public class CommunityGrantPortalClient {
private static final String BASE_PATH = "/api/noauth/communityGrant";
private static final String CLUSTER_STATUS_PATH = BASE_PATH + "/clusterStatus?clusterId={clusterId}";
private static final String LICENSE_CLAIM_PATH = "/api/noauth/freeLicense/claim";
/** A header rather than a query parameter, which would be written to access and proxy logs. */
private static final String CLAIM_TOKEN_HEADER = "X-TB-Claim-Token";
@ -209,6 +211,29 @@ public class CommunityGrantPortalClient {
return response == null ? null : response.status();
}
/**
* This route reads the claim token from the body, not from the header the grant routes use.
*
* @return the granted license key, or {@code null} while the portal has none to hand over yet
* @throws CommunityGrantLicenseClaimRefusedException if the portal refuses the claim
*/
public String claimLicense(String token) {
String url = baseUrl + LICENSE_CLAIM_PATH;
CommunityGrantLicenseClaimResponse response;
try {
response = restTemplate.postForObject(url, new CommunityGrantLicenseClaimRequest(token),
CommunityGrantLicenseClaimResponse.class);
} catch (HttpStatusCodeException e) {
// A rate-limited claim is the one client error that is worth trying again.
if (e.getStatusCode().is4xxClientError()
&& e.getStatusCode().value() != HttpStatus.TOO_MANY_REQUESTS.value()) {
throw new CommunityGrantLicenseClaimRefusedException(e);
}
throw e;
}
return response != null && response.activated() ? response.secret() : null;
}
/**
* @throws CommunityGrantCheckerTooLargeException if the checker exceeds {@code maxCheckerSizeBytes}
* @throws ResourceAccessException if reading the stream fails

56
application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java

@ -9,10 +9,14 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState;
import org.thingsboard.server.common.data.community_grant.CommunityGrantMode;
@ -42,6 +46,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@ -53,6 +58,7 @@ import static org.mockito.Mockito.when;
class CommunityGrantPollerTest {
private static final String TOKEN = "token-one";
private static final String LICENSE_SECRET = "granted-license-key";
private static final String SIGN_UP_URL =
"https://portal.example/communityGrant?clusterId=c1&claimToken=t1";
private static final UUID CLUSTER_ID = UUID.fromString("2f0a5b1e-1111-4a2b-9c3d-4e5f60718293");
@ -105,6 +111,7 @@ class CommunityGrantPollerTest {
return stored;
});
lenient().when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of(TOKEN));
lenient().when(portalClient.claimLicense(TOKEN)).thenReturn(LICENSE_SECRET);
lenient().when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID));
lenient().doReturn(scheduledPoll).when(scheduler).schedule(any(Runnable.class), anyLong(), any());
// Non-null, so the supervisor's already-running guard can trip.
@ -318,6 +325,55 @@ class CommunityGrantPollerTest {
verify(tbClusterStore).clearLicenseClaimToken(TOKEN);
}
@Test
void testDoneStoresTheGrantedLicenseKeyBeforeClearingTheToken() {
poller.apply(TOKEN, status("DONE", null));
InOrder inOrder = inOrder(tbClusterStore);
inOrder.verify(tbClusterStore).saveLicenseSecret(LICENSE_SECRET);
inOrder.verify(tbClusterStore).clearLicenseClaimToken(TOKEN);
assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED);
}
@Test
void testDoneWithNoKeyToHandOverYetLeavesTheFlowForTheNextPoll() {
when(portalClient.claimLicense(TOKEN)).thenReturn(null);
poller.apply(TOKEN, status("DONE", null));
assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP);
assertThat(poller.isArmed()).isTrue();
verify(tbClusterStore, never()).saveLicenseSecret(anyString());
verify(tbClusterStore, never()).clearLicenseClaimToken(anyString());
}
@Test
void testDoneWithARefusedClaimRegistersWithoutAKey() {
when(portalClient.claimLicense(TOKEN)).thenThrow(new CommunityGrantLicenseClaimRefusedException(
new HttpClientErrorException(HttpStatus.BAD_REQUEST)));
poller.apply(TOKEN, status("DONE", null));
assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED);
assertThat(poller.isArmed()).isFalse();
verify(tbClusterStore, never()).saveLicenseSecret(anyString());
verify(tbClusterStore).clearLicenseClaimToken(TOKEN);
}
@Test
void testDoneWithAnUnreachablePortalIsLeftToTheFailureBackoff() {
when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenReturn(status("DONE", null));
when(portalClient.claimLicense(TOKEN)).thenThrow(new ResourceAccessException("connection refused"));
clearInvocations(scheduler);
poller.pollAndReschedule();
assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP);
assertThat(poller.isArmed()).isTrue();
verify(tbClusterStore, never()).clearLicenseClaimToken(anyString());
verify(scheduler).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS));
}
@Test
void testDoneKeepsTheRegistrationLinkWhileRetiringEverythingElseAboutTheClaim() {
stored.setSignUpUrl(SIGN_UP_URL);

48
application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java

@ -39,6 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.headerDoesNotExist;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
@ -226,6 +227,53 @@ class CommunityGrantPortalClientTest {
mockServer.verify();
}
@Test
void testClaimLicenseSendsTheTokenInTheBodyAndReturnsTheKey() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().json("{\"claimToken\":\"" + TOKEN + "\"}"))
.andExpect(headerDoesNotExist(CLAIM_TOKEN_HEADER))
.andRespond(withSuccess("{\"activated\":true,\"secret\":\"granted-key\"}", MediaType.APPLICATION_JSON));
assertThat(client.claimLicense(TOKEN)).isEqualTo("granted-key");
mockServer.verify();
}
@Test
void testClaimLicenseReturnsNothingWhileThePortalHasNoKeyYet() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andRespond(withSuccess("{\"activated\":false}", MediaType.APPLICATION_JSON));
assertThat(client.claimLicense(TOKEN)).isNull();
mockServer.verify();
}
@Test
void testClaimLicenseTurnsAClientErrorIntoARefusal() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andRespond(withStatus(HttpStatus.BAD_REQUEST));
assertThatThrownBy(() -> client.claimLicense(TOKEN))
.isInstanceOf(CommunityGrantLicenseClaimRefusedException.class);
mockServer.verify();
}
@Test
void testClaimLicenseLeavesARetryableAnswerToTheCaller() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andRespond(withStatus(HttpStatus.TOO_MANY_REQUESTS));
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andRespond(withServerError());
assertThatThrownBy(() -> client.claimLicense(TOKEN))
.isInstanceOf(HttpStatusCodeException.class)
.isNotInstanceOf(CommunityGrantLicenseClaimRefusedException.class);
assertThatThrownBy(() -> client.claimLicense(TOKEN))
.isInstanceOf(HttpStatusCodeException.class)
.isNotInstanceOf(CommunityGrantLicenseClaimRefusedException.class);
mockServer.verify();
}
@Test
void testDownloadChecker() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64"))

13
dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java

@ -11,7 +11,10 @@ import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.UUID;
/** Accessor for the single {@code tb_cluster} row: the cluster id and the license portal claim token. */
/**
* Accessor for the single {@code tb_cluster} row: the cluster id, the license portal claim token and the
* license key the portal granted.
*/
@Component
@Profile("!install")
@RequiredArgsConstructor
@ -25,6 +28,14 @@ public class TbClusterStore {
rs -> rs.next() ? Optional.ofNullable(rs.getObject("cluster_id", UUID.class)) : Optional.empty());
}
public Optional<String> getLicenseSecret() {
return getColumn("license_secret");
}
public void saveLicenseSecret(String secret) {
updateColumn("license_secret", secret, "license secret");
}
public Optional<String> getLicenseClaimToken() {
return getColumn("license_claim_token");
}

1
dao/src/main/resources/sql/schema-entities.sql

@ -7,6 +7,7 @@
CREATE TABLE IF NOT EXISTS tb_cluster (
cluster_id uuid NOT NULL,
license_claim_token varchar,
license_secret varchar,
CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id)
);

27
dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java

@ -71,6 +71,33 @@ public class TbClusterStoreTest extends AbstractServiceTest {
assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-two");
}
@Test
public void testSaveAndReadLicenseSecret() {
assertThat(tbClusterStore.getLicenseSecret()).isEmpty();
tbClusterStore.saveLicenseSecret("secret-one");
assertThat(tbClusterStore.getLicenseSecret()).contains("secret-one");
tbClusterStore.saveLicenseSecret("secret-two");
assertThat(tbClusterStore.getLicenseSecret()).contains("secret-two");
}
@Test
public void testLicenseSecretAndClaimTokenAreStoredApart() {
tbClusterStore.saveLicenseSecret("secret-one");
tbClusterStore.saveLicenseClaimToken("token-one");
tbClusterStore.clearLicenseClaimToken("token-one");
assertThat(tbClusterStore.getLicenseSecret()).contains("secret-one");
assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty();
}
@Test
public void testSaveLicenseSecretFailsWhenClusterRowIsMissing() {
jdbcTemplate.update("DELETE FROM tb_cluster");
assertThatThrownBy(() -> tbClusterStore.saveLicenseSecret("secret-one"))
.isInstanceOf(IllegalStateException.class);
assertThat(tbClusterStore.getLicenseSecret()).isEqualTo(Optional.empty());
}
@Test
public void testClearLicenseClaimToken() {
tbClusterStore.saveLicenseClaimToken("token-one");

Loading…
Cancel
Save