-
Notifications
You must be signed in to change notification settings - Fork 6
New keys for created/updated sites are handled via new pattern as well #406
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
aulme
merged 6 commits into
main
from
aul-UID2-5227-unify-existing-cloud-encryption-key-code
Mar 28, 2025
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c94689b
Replace existing key backfill code with the new framework
aulme e001055
Monitoring
aulme c5b7eae
feedback
aulme 07ebfca
Order of keys listed doesn't matter
aulme e3d18ef
Merge remote-tracking branch 'origin/main' into aul-UID2-5227-unify-e…
aulme 7a03582
[CI Pipeline] Released Snapshot version: 5.18.8-alpha-127-SNAPSHOT
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
src/main/java/com/uid2/admin/cloudencryption/CloudEncryptionKeyDiff.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package com.uid2.admin.cloudencryption; | ||
|
|
||
| import com.uid2.shared.model.CloudEncryptionKey; | ||
|
|
||
| import java.text.MessageFormat; | ||
| import java.util.HashSet; | ||
| import java.util.Set; | ||
|
|
||
| public record CloudEncryptionKeyDiff( | ||
| int before, | ||
| int after, | ||
| int created, | ||
| int removed, | ||
| int unchanged | ||
| ) { | ||
| public static CloudEncryptionKeyDiff calculateDiff(Set<CloudEncryptionKey> keysBefore, Set<CloudEncryptionKey> keysAfter) { | ||
| var before = keysBefore.size(); | ||
| var after = keysAfter.size(); | ||
|
|
||
| var intersection = new HashSet<>(keysBefore); | ||
| intersection.retainAll(keysAfter); | ||
| int unchanged = intersection.size(); | ||
|
|
||
| var onlyInLeft = new HashSet<>(keysBefore); | ||
| onlyInLeft.removeAll(keysAfter); | ||
| int removed = onlyInLeft.size(); | ||
|
|
||
| var onlyInRight = new HashSet<>(keysAfter); | ||
| onlyInRight.removeAll(keysBefore); | ||
| int created = onlyInRight.size(); | ||
|
|
||
| return new CloudEncryptionKeyDiff(before, after, created, removed, unchanged); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return MessageFormat.format( | ||
| "before={0}, after={1}, created={2}, removed={3}, unchanged={4}", | ||
| before, | ||
| after, | ||
| created, | ||
| removed, | ||
| unchanged | ||
| ); | ||
| } | ||
| } |
147 changes: 67 additions & 80 deletions
147
src/main/java/com/uid2/admin/cloudencryption/CloudEncryptionKeyManager.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,109 +1,96 @@ | ||
| package com.uid2.admin.cloudencryption; | ||
|
|
||
| import com.uid2.admin.model.CloudEncryptionKeySummary; | ||
| import com.uid2.admin.store.writer.CloudEncryptionKeyStoreWriter; | ||
| import com.uid2.shared.auth.OperatorKey; | ||
| import com.uid2.shared.auth.RotatingOperatorKeyProvider; | ||
| import com.uid2.shared.model.CloudEncryptionKey; | ||
| import com.uid2.shared.store.reader.RotatingCloudEncryptionKeyProvider; | ||
| import io.micrometer.core.instrument.Counter; | ||
| import io.micrometer.core.instrument.Gauge; | ||
| import io.micrometer.core.instrument.Metrics; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.time.Instant; | ||
| import java.util.*; | ||
| import java.util.function.Function; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class CloudEncryptionKeyManager { | ||
| private final RotatingCloudEncryptionKeyProvider keyProvider; | ||
| private final RotatingOperatorKeyProvider operatorKeyProvider; | ||
| private final CloudEncryptionKeyStoreWriter keyWriter; | ||
| private final CloudKeyStatePlanner planner; | ||
| private Set<OperatorKey> operatorKeys; | ||
| private Set<CloudEncryptionKey> existingKeys; | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(CloudEncryptionKeyManager.class); | ||
|
|
||
| private final RotatingCloudEncryptionKeyProvider RotatingCloudEncryptionKeyProvider; | ||
| private final CloudEncryptionKeyStoreWriter cloudEncryptionKeyStoreWriter; | ||
| private final CloudSecretGenerator secretGenerator; | ||
| private static final Logger logger = LoggerFactory.getLogger(CloudEncryptionKeyManager.class); | ||
|
|
||
| public CloudEncryptionKeyManager( | ||
| RotatingCloudEncryptionKeyProvider RotatingCloudEncryptionKeyProvider, | ||
| CloudEncryptionKeyStoreWriter cloudEncryptionKeyStoreWriter, | ||
| CloudSecretGenerator keyGenerator | ||
| ) { | ||
| this.RotatingCloudEncryptionKeyProvider = RotatingCloudEncryptionKeyProvider; | ||
| this.cloudEncryptionKeyStoreWriter = cloudEncryptionKeyStoreWriter; | ||
| this.secretGenerator = keyGenerator; | ||
| } | ||
|
|
||
| // Ensures there are `keyCountPerSite` sites for each site corresponding of operatorKeys. If there are less - create new ones. | ||
| // Give all new keys for each site `activationInterval` seconds between activations, starting now | ||
| public void generateKeysForOperators( | ||
| Collection<OperatorKey> operatorKeys, | ||
| long activationInterval, | ||
| int keyCountPerSite | ||
| ) throws Exception { | ||
| this.RotatingCloudEncryptionKeyProvider.loadContent(); | ||
|
|
||
| if (operatorKeys == null || operatorKeys.isEmpty()) { | ||
| throw new IllegalArgumentException("Operator keys collection must not be null or empty"); | ||
| } | ||
| if (activationInterval <= 0) { | ||
| throw new IllegalArgumentException("Key activate interval must be greater than zero"); | ||
| } | ||
| if (keyCountPerSite <= 0) { | ||
| throw new IllegalArgumentException("Key count per site must be greater than zero"); | ||
| } | ||
|
|
||
| for (Integer siteId : uniqueSiteIdsForOperators(operatorKeys)) { | ||
| ensureEnoughKeysForSite(activationInterval, keyCountPerSite, siteId); | ||
| } | ||
| RotatingCloudEncryptionKeyProvider keyProvider, | ||
| CloudEncryptionKeyStoreWriter keyWriter, | ||
| RotatingOperatorKeyProvider operatorKeyProvider, | ||
| CloudKeyStatePlanner planner) { | ||
| this.keyProvider = keyProvider; | ||
| this.operatorKeyProvider = operatorKeyProvider; | ||
| this.keyWriter = keyWriter; | ||
| this.planner = planner; | ||
| } | ||
|
|
||
| private void ensureEnoughKeysForSite(long activationInterval, int keyCountPerSite, Integer siteId) throws Exception { | ||
| // Check if the site ID already exists in the S3 key provider and has fewer than the required number of keys | ||
| int currentKeyCount = countKeysForSite(siteId); | ||
| if (currentKeyCount >= keyCountPerSite) { | ||
| LOGGER.info("Site ID {} already has the required number of keys. Skipping key generation.", siteId); | ||
| return; | ||
| } | ||
|
|
||
| int keysToGenerate = keyCountPerSite - currentKeyCount; | ||
| for (int i = 0; i < keysToGenerate; i++) { | ||
| addKey(activationInterval, siteId, i); | ||
| // For any site that has an operator create a new key activating now | ||
| // Keep up to 5 most recent old keys per site, delete the rest | ||
| public void rotateKeys() throws Exception { | ||
| boolean success = false; | ||
| try { | ||
| refreshCloudData(); | ||
| var desiredKeys = planner.planRotation(existingKeys, operatorKeys); | ||
| writeKeys(desiredKeys); | ||
| success = true; | ||
| var diff = CloudEncryptionKeyDiff.calculateDiff(existingKeys, desiredKeys); | ||
| logger.info("Key rotation complete. Diff: {}", diff); | ||
| } catch (Exception e) { | ||
| success = false; | ||
| logger.error("Key rotation failed", e); | ||
| throw e; | ||
| } finally { | ||
| Counter.builder("uid2.cloud_encryption_key_manager.rotations") | ||
| .tag("success", Boolean.toString(success)) | ||
| .description("The number of times rotations have happened") | ||
| .register(Metrics.globalRegistry); | ||
| } | ||
| LOGGER.info("Generated {} keys for site ID {}", keysToGenerate, siteId); | ||
| } | ||
|
|
||
| private void addKey(long keyActivateInterval, Integer siteId, int keyIndex) throws Exception { | ||
| long created = Instant.now().getEpochSecond(); | ||
| long activated = created + (keyIndex * keyActivateInterval); | ||
| CloudEncryptionKey cloudEncryptionKey = generateCloudEncryptionKey(siteId, activated, created); | ||
| addCloudEncryptionKey(cloudEncryptionKey); | ||
| } | ||
|
|
||
| private static Set<Integer> uniqueSiteIdsForOperators(Collection<OperatorKey> operatorKeys) { | ||
| Set<Integer> uniqueSiteIds = new HashSet<>(); | ||
| for (OperatorKey operatorKey : operatorKeys) { | ||
| uniqueSiteIds.add(operatorKey.getSiteId()); | ||
| // For any site that has an operator, if there are no keys, create a key activating now | ||
| public void backfillKeys() throws Exception { | ||
| try { | ||
| refreshCloudData(); | ||
| var desiredKeys = planner.planBackfill(existingKeys, operatorKeys); | ||
| writeKeys(desiredKeys); | ||
| var diff = CloudEncryptionKeyDiff.calculateDiff(existingKeys, desiredKeys); | ||
| logger.info("Key backfill complete. Diff: {}", diff); | ||
| } catch (Exception e) { | ||
| logger.error("Key backfill failed", e); | ||
| throw e; | ||
| } | ||
| return uniqueSiteIds; | ||
| } | ||
|
|
||
| CloudEncryptionKey generateCloudEncryptionKey(int siteId, long activates, long created) throws Exception { | ||
| int newKeyId = getNextKeyId(); | ||
| String secret = secretGenerator.generate(); | ||
| return new CloudEncryptionKey(newKeyId, siteId, activates, created, secret); | ||
| } | ||
|
|
||
| void addCloudEncryptionKey(CloudEncryptionKey cloudEncryptionKey) throws Exception { | ||
| Map<Integer, CloudEncryptionKey> cloudEncryptionKeys = new HashMap<>(RotatingCloudEncryptionKeyProvider.getAll()); | ||
| cloudEncryptionKeys.put(cloudEncryptionKey.getId(), cloudEncryptionKey); | ||
| cloudEncryptionKeyStoreWriter.upload(cloudEncryptionKeys, null); | ||
| public List<CloudEncryptionKeySummary> getKeySummaries() throws Exception { | ||
| refreshCloudData(); | ||
| return existingKeys.stream().map(CloudEncryptionKeySummary::fromFullKey).toList(); | ||
| } | ||
|
|
||
| int getNextKeyId() { | ||
| Map<Integer, CloudEncryptionKey> cloudEncryptionKeys = RotatingCloudEncryptionKeyProvider.getAll(); | ||
| if (cloudEncryptionKeys == null || cloudEncryptionKeys.isEmpty()) { | ||
| return 1; | ||
| } | ||
| return cloudEncryptionKeys.keySet().stream().max(Integer::compareTo).orElse(0) + 1; | ||
| private void writeKeys(Set<CloudEncryptionKey> desiredKeys) throws Exception { | ||
| var keysForWriting = desiredKeys.stream().collect(Collectors.toMap( | ||
| CloudEncryptionKey::getId, | ||
| Function.identity()) | ||
| ); | ||
| keyWriter.upload(keysForWriting, null); | ||
| } | ||
|
|
||
| int countKeysForSite(int siteId) { | ||
| Map<Integer, CloudEncryptionKey> allKeys = RotatingCloudEncryptionKeyProvider.getAll(); | ||
| return (int) allKeys.values().stream().filter(key -> key.getSiteId() == siteId).count(); | ||
| private void refreshCloudData() throws Exception { | ||
| keyProvider.loadContent(); | ||
| operatorKeyProvider.loadContent(operatorKeyProvider.getMetadata()); | ||
| operatorKeys = new HashSet<>(operatorKeyProvider.getAll()); | ||
| existingKeys = new HashSet<>(keyProvider.getAll().values()); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.