Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 70 additions & 21 deletions sdk/src/main/java/io/opentdf/platform/sdk/Planner.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
Expand All @@ -20,6 +21,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

Expand All @@ -29,8 +31,6 @@
private final Config.TDFConfig tdfConfig;
private final SDK.Services services;
private final BiFunction<SDK.Services, Config.TDFConfig, Autoconfigure.Granter> granterFactory;


private static final Logger logger = LoggerFactory.getLogger(Planner.class);

Planner(Config.TDFConfig config, SDK.Services services, BiFunction<SDK.Services, Config.TDFConfig, Autoconfigure.Granter> granterFactory) {
Expand All @@ -45,11 +45,14 @@

Map<String, List<Config.KASInfo>> getSplits() {
List<Autoconfigure.KeySplitTemplate> splitPlan;
SimpleKasKey baseKey = null;
if (tdfConfig.autoconfigure) {
if (tdfConfig.splitPlan != null && !tdfConfig.splitPlan.isEmpty()) {
throw new IllegalArgumentException("cannot use autoconfigure with a split plan provided in the TDFConfig");
}
splitPlan = getAutoconfigurePlan(services, tdfConfig);
Plan plan = getAutoconfigurePlan(services, tdfConfig);
splitPlan = plan.splits;
baseKey = plan.baseKey;
} else if (tdfConfig.splitPlan == null || tdfConfig.splitPlan.isEmpty()) {
splitPlan = generatePlanFromProvidedKases(tdfConfig.kasInfoList);
} else {
Expand All @@ -61,14 +64,23 @@
if (splitPlan.isEmpty()) {
throw new SDK.KasInfoMissing("no plan was constructed via autoconfigure, explicit split plan or provided kases");
}
return resolveKeys(splitPlan);
return resolveKeys(splitPlan, baseKey);
}

private List<Autoconfigure.KeySplitTemplate> getAutoconfigurePlan(SDK.Services services, Config.TDFConfig tdfConfig) {
private Plan getAutoconfigurePlan(SDK.Services services, Config.TDFConfig tdfConfig) {
Autoconfigure.Granter granter = granterFactory.apply(services, tdfConfig);
return granter.getSplits(defaultKases(tdfConfig), Planner::getUUID, () -> Planner.fetchBaseKey(services.wellknown()));
}

// The granter calls the supplier only if it needs the base key, so this stays null otherwise.
var fetchedBaseKey = new AtomicReference<SimpleKasKey>();

var splits = granter.getSplits(defaultKases(tdfConfig), Planner::getUUID, () -> {
Optional<SimpleKasKey> fetched = fetchBaseKey(services.wellknown());
fetchedBaseKey.set(fetched.orElse(null));
return fetched;
});

return new Plan(splits, fetchedBaseKey.get());
}

List<Autoconfigure.KeySplitTemplate> generatePlanFromProvidedKases(List<Config.KASInfo> kases) {
if (kases.size() == 1) {
Expand Down Expand Up @@ -140,10 +152,10 @@
.setKasUri(kasUri)
.setPublicKey(
SimpleKasPublicKey.newBuilder()
.setKid(kid)
.setAlgorithm(algorithm)
.setPem(pem)
.build())
.setKid(kid)
.setAlgorithm(algorithm)
.setPem(pem)
.build())
.build());
}

Expand All @@ -159,7 +171,7 @@
return value == null || value.isBlank();
}

Map<String, List<Config.KASInfo>> resolveKeys(List<Autoconfigure.KeySplitTemplate> splitPlan) {
Map<String, List<Config.KASInfo>> resolveKeys(List<Autoconfigure.KeySplitTemplate> splitPlan, @Nullable SimpleKasKey baseKey) {

Check failure on line 174 in sdk/src/main/java/io/opentdf/platform/sdk/Planner.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 23 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=opentdf_java-sdk&issues=AaI4xfpPDzT2-vmpiDLr&open=AaI4xfpPDzT2-vmpiDLr&pullRequest=444
Map<String, List<Config.KASInfo>> conjunction = new HashMap<>();
var latestKASInfo = new HashMap<String, Config.KASInfo>();
// Seed anything passed in manually
Expand All @@ -174,14 +186,27 @@
// TODO First look up in attribute information / add to split plan?
Config.KASInfo ki = latestKASInfo.get(splitInfo.kas);
if (ki == null || ki.PublicKey == null || ki.PublicKey.isBlank() || (splitInfo.kid != null && !splitInfo.kid.equals(ki.KID))) {
logger.info("no public key provided for KAS at {}, retrieving", splitInfo.kas);
var getKI = new Config.KASInfo();
getKI.URL = splitInfo.kas;
getKI.KID = splitInfo.kid;
getKI.Algorithm = splitInfo.keyType == null
? (tdfConfig.wrappingKeyType == null ? null : tdfConfig.wrappingKeyType.toString())
: splitInfo.keyType.toString();
ki = services.kas().getPublicKey(getKI);
if (baseKey != null && isBaseKeySplit(splitInfo, baseKey)) {
// get PEM from the base key directly
// asking KAS by algorithm would not be correct
// since KAS would only return its default key
// which may be different from the base key
ki = Config.KASInfo.fromSimpleKasKey(baseKey);
} else {
// get public key from KAS server or key cache
// based on (URL+Algorithm+KID) combination
// this is the case for attributes
// for grants, the public key would be fetched from KAS server by algorithm only
// see KASClient.getPublicKey method
logger.info("no public key provided for KAS at {}, retrieving", splitInfo.kas);
var getKI = new Config.KASInfo();
getKI.URL = splitInfo.kas;
getKI.KID = splitInfo.kid;
getKI.Algorithm = splitInfo.keyType == null
? (tdfConfig.wrappingKeyType == null ? null : tdfConfig.wrappingKeyType.toString())
: splitInfo.keyType.toString();
ki = services.kas().getPublicKey(getKI);
}
latestKASInfo.put(splitInfo.kas, ki);
}
conjunction.computeIfAbsent(splitInfo.splitID, s -> new ArrayList<>()).add(ki);
Expand All @@ -202,4 +227,28 @@
}
return defk.isEmpty() ? allk : defk;
}
}

/**
* Returns whether a split targets the discovered base key: same KAS URL and the base key's KID.
* Guards against wrapping unrelated splits with the base key.
* @param split the split to check
* @param baseKey the base key from the well-known configuration
* @return true if the split should be wrapped with the base key
*/
private static boolean isBaseKeySplit(Autoconfigure.KeySplitTemplate split, SimpleKasKey baseKey) {
return split.kas.equals(baseKey.getKasUri())
&& baseKey.getPublicKey().getKid().equals(split.kid);
}

private static final class Plan {
final List<Autoconfigure.KeySplitTemplate> splits;

@Nullable
final SimpleKasKey baseKey;

Plan(List<Autoconfigure.KeySplitTemplate> splits, @Nullable SimpleKasKey baseKey) {
this.splits = splits;
this.baseKey = baseKey;
}
}
}
147 changes: 124 additions & 23 deletions sdk/src/test/java/io/opentdf/platform/sdk/PlannerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import io.opentdf.platform.policy.Algorithm;
import io.opentdf.platform.policy.Attribute;
import io.opentdf.platform.policy.AttributeRuleTypeEnum;
import io.opentdf.platform.policy.SimpleKasKey;
import io.opentdf.platform.policy.SimpleKasPublicKey;
import io.opentdf.platform.wellknownconfiguration.GetWellKnownConfigurationResponse;
import io.opentdf.platform.wellknownconfiguration.WellKnownServiceClientInterface;
import org.assertj.core.api.Assertions;
Expand Down Expand Up @@ -115,15 +117,32 @@
}

@Test
void autoconfigureUsesFetchedBaseKeyForUnmappedAttribute() {
var wellknownService = wellknownService(baseKeyConfiguration(structuredBaseKey("ec:secp256r1")));
void autoconfigureFailsWithoutBaseKeyOrDefaultKasForUnmappedAttribute() {
var kas = Mockito.mock(SDK.KAS.class);
var resolvedKey = new Config.KASInfo();
resolvedKey.URL = "https://example.com/base_key";
resolvedKey.KID = "thekid";
resolvedKey.Algorithm = "ec:secp256r1";
resolvedKey.PublicKey = "thepem";
Mockito.when(kas.getPublicKey(Mockito.any())).thenReturn(resolvedKey);
var services = new FakeServicesBuilder()
.setWellknownService(wellknownService(Struct.getDefaultInstance()))
.setKas(kas)
.build();
var planner = new Planner(configWithUnmappedAttribute(), services, Autoconfigure::createGranter);

assertThatThrownBy(planner::getSplits)
.isInstanceOf(AutoConfigureException.class)
.hasMessage("no default KAS specified; required for grantless plans");
Mockito.verify(kas, Mockito.never()).getPublicKey(Mockito.any());
}

@ParameterizedTest
@ValueSource(strings = {"rsa:2048", "rsa:4096", "ec:secp256r1", "ec:secp384r1", "ec:secp521r1"})
void autoconfigureWrapsWithDiscoveredBaseKeyWithoutCallingKas(String wireAlgorithm) {
var wellknownService = wellknownService(baseKeyConfiguration(structuredBaseKey(wireAlgorithm)));
var kas = Mockito.mock(SDK.KAS.class);
// KAS's default key for the algorithm differs from the base key (GAT-2345: swe-rsa-2048 vs r2)
var kasDefaultKey = new Config.KASInfo();
kasDefaultKey.URL = "https://example.com/base_key";
kasDefaultKey.KID = "kas-default-kid";
kasDefaultKey.Algorithm = wireAlgorithm;
kasDefaultKey.PublicKey = "kas-default-pem";
Mockito.when(kas.getPublicKey(Mockito.any())).thenReturn(kasDefaultKey);
var services = new FakeServicesBuilder().setWellknownService(wellknownService).setKas(kas).build();
var config = configWithUnmappedAttribute();
// A different configured default makes loss of the base key's algorithm observable.
Expand All @@ -133,30 +152,112 @@
var splits = planner.getSplits();

Assertions.assertThat(splits).containsOnlyKeys("");
Assertions.assertThat(splits.get("")).containsExactly(resolvedKey);
Assertions.assertThat(splits.get("")).hasSize(1);
var key = splits.get("").get(0);
assertThat(key.URL).isEqualTo("https://example.com/base_key");
assertThat(key.KID).isEqualTo("thekid");
assertThat(key.PublicKey).isEqualTo("thepem");
// the round trip through Algorithm and back must give a string createKeyAccess can parse
assertThat(key.Algorithm).isEqualTo(wireAlgorithm);
assertThat(KeyType.fromString(key.Algorithm)).hasToString(wireAlgorithm);
Mockito.verify(kas, Mockito.never()).getPublicKey(Mockito.any());
Mockito.verify(wellknownService).getWellKnownConfigurationBlocking(Mockito.any(), Mockito.anyMap());
}

@Test
void resolveKeysUsesBaseKeyForMatchingSplit() {
var kas = Mockito.mock(SDK.KAS.class);
var config = new Config.TDFConfig();
config.wrappingKeyType = KeyType.RSA2048Key;
var planner = plannerWithKas(config, kas);
var plan = List.of(new Autoconfigure.KeySplitTemplate(
"https://example.com/base_key", "", "thekid", KeyType.EC256Key));

Map<String, List<Config.KASInfo>> resolved = planner.resolveKeys(plan, baseKey());

Assertions.assertThat(resolved).containsOnlyKeys("");
Assertions.assertThat(resolved.get("")).hasSize(1);
var kasInfo = resolved.get("").get(0);
Assertions.assertThat(kasInfo.URL).isEqualTo("https://example.com/base_key");
Assertions.assertThat(kasInfo.KID).isEqualTo("thekid");
Assertions.assertThat(kasInfo.PublicKey).isEqualTo("thepem");
Assertions.assertThat(kasInfo.Algorithm).isEqualTo("ec:secp256r1");
Mockito.verify(kas, Mockito.never()).getPublicKey(Mockito.any());
}

@ParameterizedTest
@CsvSource({
"https://example.com/base_key, mapped-kid",
"https://example.com/base_key, ",
"https://other.example.com, thekid"
})
void resolveKeysUsesKasForNonBaseKeySplit(String kasUrl, String kid) {
var kas = Mockito.mock(SDK.KAS.class);
Mockito.when(kas.getPublicKey(Mockito.any())).thenAnswer(invocation -> {
Config.KASInfo req = invocation.getArgument(0);
var ret = new Config.KASInfo();
ret.URL = req.URL;
ret.KID = req.KID == null ? "kas-default-kid" : req.KID;
ret.Algorithm = req.Algorithm;
ret.PublicKey = "kas-pem";
return ret;
});
var config = new Config.TDFConfig();
config.wrappingKeyType = KeyType.RSA2048Key;
var planner = plannerWithKas(config, kas);
var plan = List.of(new Autoconfigure.KeySplitTemplate(kasUrl, "split1", kid, null));

Map<String, List<Config.KASInfo>> resolved = planner.resolveKeys(plan, baseKey());

var request = ArgumentCaptor.forClass(Config.KASInfo.class);
Mockito.verify(kas).getPublicKey(request.capture());
assertThat(request.getValue().URL).isEqualTo("https://example.com/base_key");
assertThat(request.getValue().KID).isEqualTo("thekid");
assertThat(request.getValue().Algorithm).isEqualTo("ec:secp256r1");
Mockito.verify(wellknownService).getWellKnownConfigurationBlocking(Mockito.any(), Mockito.anyMap());
Assertions.assertThat(request.getValue().URL).isEqualTo(kasUrl);
Assertions.assertThat(request.getValue().KID).isEqualTo(kid);

Assertions.assertThat(resolved).containsOnlyKeys("split1");
var kasInfo = resolved.get("split1").get(0);
Assertions.assertThat(kasInfo.PublicKey).isEqualTo("kas-pem");

Check warning on line 219 in sdk/src/test/java/io/opentdf/platform/sdk/PlannerTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Join these multiple assertions subject to one assertion chain.

See more on https://sonarcloud.io/project/issues?id=opentdf_java-sdk&issues=AaI4xfocDzT2-vmpiDLq&open=AaI4xfocDzT2-vmpiDLq&pullRequest=444
Assertions.assertThat(kasInfo.PublicKey).isNotEqualTo("thepem");
}

@Test
void autoconfigureFailsWithoutBaseKeyOrDefaultKasForUnmappedAttribute() {
void resolveKeysUsesBaseKeyWhenSeededEntryHasDifferentKid() {
var kas = Mockito.mock(SDK.KAS.class);
var services = new FakeServicesBuilder()
.setWellknownService(wellknownService(Struct.getDefaultInstance()))
.setKas(kas)
.build();
var planner = new Planner(configWithUnmappedAttribute(), services, Autoconfigure::createGranter);
var stale = new Config.KASInfo();
stale.URL = "https://example.com/base_key";
stale.KID = "old-kid";
stale.Algorithm = "ec:secp256r1";
stale.PublicKey = "old-pem";
var config = new Config.TDFConfig();
config.kasInfoList.add(stale);
var planner = plannerWithKas(config, kas);
var plan = List.of(new Autoconfigure.KeySplitTemplate(
"https://example.com/base_key", "", "thekid", KeyType.EC256Key));

assertThatThrownBy(planner::getSplits)
.isInstanceOf(AutoConfigureException.class)
.hasMessage("no default KAS specified; required for grantless plans");
Map<String, List<Config.KASInfo>> resolved = planner.resolveKeys(plan, baseKey());

var kasInfo = resolved.get("").get(0);
Assertions.assertThat(kasInfo.KID).isEqualTo("thekid");
Assertions.assertThat(kasInfo.PublicKey).isEqualTo("thepem");
Mockito.verify(kas, Mockito.never()).getPublicKey(Mockito.any());
}

private static SimpleKasKey baseKey() {
return SimpleKasKey.newBuilder()
.setKasUri("https://example.com/base_key")
.setPublicKey(SimpleKasPublicKey.newBuilder()
.setKid("thekid")
.setAlgorithm(Algorithm.ALGORITHM_EC_P256)
.setPem("thepem")
.build())
.build();
}

private static Planner plannerWithKas(Config.TDFConfig config, SDK.KAS kas) {
return new Planner(config, new FakeServicesBuilder().setKas(kas).build(),
(ignore1, ignored2) -> { throw new IllegalArgumentException("no granter needed"); });
}

private static Config.TDFConfig configWithUnmappedAttribute() {
var attribute = Attribute.newBuilder()
.setFqn("https://example.com/attr/classification")
Expand Down Expand Up @@ -292,7 +393,7 @@
new Autoconfigure.KeySplitTemplate("https://kas2.example.com", "split2", "kid2", null),
new Autoconfigure.KeySplitTemplate("https://kas3.example.com", "split2", null, KeyType.EC384Key)
);
Map<String, List<Config.KASInfo>> filledInPlan = planner.resolveKeys(plan);
Map<String, List<Config.KASInfo>> filledInPlan = planner.resolveKeys(plan, null);
assertThat(filledInPlan.keySet().stream().collect(Collectors.toList())).asList().containsExactlyInAnyOrder("split1", "split2");
assertThat(filledInPlan.get("split1")).asList().hasSize(2);
var kasInfo1 = filledInPlan.get("split1").stream().filter(k -> "kid1".equals(k.KID)).findFirst().get();
Expand Down
Loading