Skip to content

Commit

Permalink
Reduce technical debt
Browse files Browse the repository at this point in the history
  • Loading branch information
sophokles73 committed Oct 20, 2023
1 parent 6ffdace commit 34f67be
Show file tree
Hide file tree
Showing 38 changed files with 518 additions and 494 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import org.eclipse.hono.client.ClientErrorException;
import org.eclipse.hono.util.CredentialsConstants;
import org.eclipse.hono.util.RequestResponseApiConstants;

import io.jsonwebtoken.Claims;
import io.vertx.core.json.JsonObject;
Expand All @@ -43,7 +44,7 @@ default JsonObject parseCredentialsFromClaims(final JsonObject claims) {

final var credentials = new JsonObject();
credentials.put(
CredentialsConstants.FIELD_PAYLOAD_TENANT_ID,
RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID,
Optional.ofNullable(claims.getString(CredentialsConstants.CLAIM_TENANT_ID))
.orElseThrow(() -> new ClientErrorException(
HttpURLConnection.HTTP_UNAUTHORIZED,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.eclipse.hono.service.auth.DeviceUser;
import org.eclipse.hono.util.CredentialsConstants;
import org.eclipse.hono.util.CredentialsObject;
import org.eclipse.hono.util.RequestResponseApiConstants;

import io.opentracing.Tracer;
import io.vertx.core.Future;
Expand Down Expand Up @@ -71,7 +72,7 @@ public JwtCredentials getCredentials(final JsonObject authInfo) {

Objects.requireNonNull(authInfo);
try {
final String tenantId = authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID);
final String tenantId = authInfo.getString(RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID);
final String authId = authInfo.getString(CredentialsConstants.FIELD_AUTH_ID);
final String jws = authInfo.getString(CredentialsConstants.FIELD_PASSWORD);
if (tenantId == null || authId == null || jws == null) {
Expand All @@ -80,7 +81,7 @@ public JwtCredentials getCredentials(final JsonObject authInfo) {
final JsonObject clientContext = authInfo.copy();
// credentials object already contains tenant ID, client ID and the JWT from the password field, so
// remove them from the client context
clientContext.remove(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID);
clientContext.remove(RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID);
clientContext.remove(CredentialsConstants.FIELD_AUTH_ID);
clientContext.remove(CredentialsConstants.FIELD_PASSWORD);
return JwtCredentials.create(tenantId, authId, jws, clientContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,41 +121,47 @@ void testExpandValidJwtWithMultipleDifferentPublicKeysWithinTheirValidityPeriod(
final SignatureAlgorithm alg = SignatureAlgorithm.ES256;
jwtHeader.put(JwsHeader.ALGORITHM, alg.getValue());
final KeyPair keyPair1 = generateKeyPair(alg, 256);
final byte[] publicKey1 = keyPair1.getPublic().getEncoded();

final KeyPair keyPair2 = generateKeyPair(alg, 256);
final byte[] publicKey2 = keyPair2.getPublic().getEncoded();

final JsonObject secondSecret = CredentialsObject.emptySecret(
instantNow.minusSeconds(1500),
instantNow.plusSeconds(5000))
.put(RegistryManagementConstants.FIELD_SECRETS_ALGORITHM, CredentialsConstants.EC_ALG)
.put(CredentialsConstants.FIELD_SECRETS_KEY, keyPair2.getPublic().getEncoded());

final var creds = CredentialsObject.fromRawPublicKey(
deviceId,
authId,
CredentialsConstants.EC_ALG,
publicKey1,
keyPair1.getPublic().getEncoded(),
instantNow.minusSeconds(3600),
instantNow.plusSeconds(3600));
final JsonObject secret = CredentialsObject.emptySecret(
instantNow.minusSeconds(1500),
instantNow.plusSeconds(5000));
secret.put(RegistryManagementConstants.FIELD_SECRETS_ALGORITHM, CredentialsConstants.EC_ALG);
secret.put(CredentialsConstants.FIELD_SECRETS_KEY, publicKey2);
creds.addSecret(secret);
creds.addSecret(secondSecret);

final String jwt1 = generateJws(
jwtHeader,
generateJwtClaims(null, null, instantNow, instantPlus24Hours),
alg,
keyPair1.getPrivate());
final String jwt2 = generateJws(
jwtHeader,
generateJwtClaims(null, null, instantNow, instantPlus24Hours),
alg,
keyPair2.getPrivate());

authTokenValidator.expand(jwt1, creds.getCandidateSecrets(), ALLOWED_CLOCK_SKEW)
.compose(jws1 -> {
final String jwt2 = generateJws(
jwtHeader,
generateJwtClaims(null, null, instantNow, instantPlus24Hours),
alg,
keyPair2.getPrivate());
ctx.verify(() -> {
assertThat(jws1.getBody().getExpiration().toInstant()).isAtMost(instantPlus24Hours);
});
return authTokenValidator.expand(jwt2, creds.getCandidateSecrets(), ALLOWED_CLOCK_SKEW);
})
.onComplete(ctx.succeedingThenComplete());
.onComplete(ctx.succeeding(jws2 -> {
ctx.verify(() -> {
assertThat(jws2.getBody().getExpiration().toInstant()).isAtMost(instantPlus24Hours);
});
ctx.completeNow();
}));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.eclipse.hono.client.ClientErrorException;
import org.eclipse.hono.client.ServiceInvocationException;
import org.eclipse.hono.util.CredentialsConstants;
import org.eclipse.hono.util.RequestResponseApiConstants;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
Expand Down Expand Up @@ -159,7 +160,7 @@ public JsonObject parseCredentialsFromString(final String uri) {
final var tenant = uriSplit[2];
final var authId = uriSplit[3];
return new JsonObject()
.put(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID, tenant)
.put(RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID, tenant)
.put(CredentialsConstants.FIELD_AUTH_ID, authId)
.put(Claims.ISSUER, authId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.eclipse.hono.client.ClientErrorException;
import org.eclipse.hono.client.ServiceInvocationException;
import org.eclipse.hono.util.CredentialsConstants;
import org.eclipse.hono.util.RequestResponseApiConstants;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
Expand Down Expand Up @@ -154,7 +155,7 @@ public JsonObject parseCredentialsFromString(final String clientId) {
final var tenant = clientIdSplit[splitLength - 3];
final var authId = clientIdSplit[splitLength - 1];
return new JsonObject()
.put(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID, tenant)
.put(RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID, tenant)
.put(CredentialsConstants.FIELD_AUTH_ID, authId)
.put(Claims.ISSUER, authId);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
* Copyright (c) 2020, 2023 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
Expand Down Expand Up @@ -46,6 +46,9 @@ public abstract class BasicCache<K, V> implements Cache<K, V>, Lifecycle {

private static final Logger LOG = LoggerFactory.getLogger(BasicCache.class);

/**
* The vert.x instance that this cache runs on.
*/
protected final Vertx vertx;
private final BasicCacheContainer cacheManager;
private final AtomicBoolean stopCalled = new AtomicBoolean();
Expand Down Expand Up @@ -158,7 +161,7 @@ public Future<Void> put(final K key, final V value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);

return withCache(aCache -> aCache.putAsync(key, value).thenApply(v -> (Void) null));
return withCache(aCache -> aCache.putAsync(key, value).thenApply(v -> null));
}

@Override
Expand All @@ -167,7 +170,7 @@ public Future<Void> put(final K key, final V value, final long lifespan, final T
Objects.requireNonNull(value);
Objects.requireNonNull(lifespanUnit);

return withCache(aCache -> aCache.putAsync(key, value, lifespan, lifespanUnit).thenApply(v -> (Void) null));
return withCache(aCache -> aCache.putAsync(key, value, lifespan, lifespanUnit).thenApply(v -> null));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -610,30 +610,24 @@ private Future<String> checkAdapterInstanceId(
adapterInstanceId, tenantId, deviceId);
}
})
.onFailure(thr -> {
LOG.debug(
"error calling listener for obsolete adapter instance id '{}' [tenant: {}, device-id: {}]",
adapterInstanceId, tenantId, deviceId, thr);
})
.compose(s -> {
return cache.remove(getAdapterInstanceEntryKey(tenantId, deviceId), adapterInstanceId)
.onSuccess(removed -> {
if (removed) {
LOG.debug(
"removed entry with obsolete adapter instance id '{}' [tenant: {}, device-id: {}]",
adapterInstanceId, tenantId, deviceId);
}
})
.onFailure(thr -> {
.onFailure(thr -> LOG.debug(
"error calling listener for obsolete adapter instance id '{}' [tenant: {}, device-id: {}]",
adapterInstanceId, tenantId, deviceId, thr)
)
.compose(s -> cache.remove(getAdapterInstanceEntryKey(tenantId, deviceId), adapterInstanceId)
.onSuccess(removed -> {
if (removed) {
LOG.debug(
"error removing entry with obsolete adapter instance id '{}' [tenant: {}, device-id: {}]",
adapterInstanceId, tenantId, deviceId, thr);
});
})
.recover(thr -> {
"removed entry with obsolete adapter instance id '{}' [tenant: {}, device-id: {}]",
adapterInstanceId, tenantId, deviceId);
}
})
.onFailure(thr -> LOG.debug(
"error removing entry with obsolete adapter instance id '{}' [tenant: {}, device-id: {}]",
adapterInstanceId, tenantId, deviceId, thr)))
.recover(thr ->
// errors treated as not found adapter instance
return Future.succeededFuture();
})
Future.succeededFuture())
.mapEmpty();
} else if (status == AdapterInstanceStatus.SUSPECTED_DEAD) {
LOG.debug(
Expand Down Expand Up @@ -666,24 +660,19 @@ private void checkForCacheAvailability(final Promise<Status> status) {
.onComplete(ar -> status.tryComplete(ar.result()));
}

@Override
public void registerLivenessChecks(final HealthCheckHandler livenessHandler) {
// nothing to register
}

@Override
public Future<Void> start() {
if (cache instanceof Lifecycle) {
return ((Lifecycle) cache).start();
if (cache instanceof Lifecycle lifecycle) {
return lifecycle.start();
} else {
return Future.succeededFuture();
}
}

@Override
public Future<Void> stop() {
if (cache instanceof Lifecycle) {
return ((Lifecycle) cache).stop();
if (cache instanceof Lifecycle lifecycle) {
return lifecycle.stop();
} else {
return Future.succeededFuture();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ protected Future<Void> connectToCache() {
} else {
r.fail(new IllegalStateException("cache [" + cacheName + "] is not configured"));
}
} catch (final Throwable t) {
r.fail(t);
} catch (final Exception e) {
r.fail(e);
}
}, attempt -> {
if (attempt.succeeded()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,16 +253,9 @@ public void registerReadinessChecks(final HealthCheckHandler readinessHandler) {
// verify that client is connected
readinessHandler.register(
String.format("connection-to-%s-%s", connection.getConfig().getServerRole(), UUID.randomUUID()),
status -> {
connection.isConnected()
.onSuccess(ok -> status.tryComplete(Status.OK()))
.onFailure(t -> status.tryComplete(Status.KO()));
});
}

@Override
public void registerLivenessChecks(final HealthCheckHandler livenessHandler) {
// no liveness checks to be added
status -> connection.isConnected()
.onSuccess(ok -> status.tryComplete(Status.OK()))
.onFailure(t -> status.tryComplete(Status.KO())));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,12 @@ class Noop {

@Override
public void completed(final String outcome) {
// nothing to do
}

@Override
public void timeout() {
// nothing to do
}

};
Expand All @@ -80,18 +82,12 @@ public Sample start(final String tenantId) {

@Override
public void noCredit(final String tenantId) {
// nothing to do
}

};

private static final Factory FACTORY = new Factory() {

@Override
public SendMessageSampler create(final String messageType) {
return SAMPLER;
}

};
private static final Factory FACTORY = (String messageType) -> SAMPLER;

private Noop() {
}
Expand Down
Loading

0 comments on commit 34f67be

Please sign in to comment.