Skip to content

Commit

Permalink
Action for adding Cloud Assets sensitive data to Vault
Browse files Browse the repository at this point in the history
  • Loading branch information
petrovic-d committed Oct 4, 2024
1 parent 3013ef5 commit 67d76ce
Show file tree
Hide file tree
Showing 16 changed files with 597 additions and 818 deletions.

Large diffs are not rendered by default.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.cloud.oracle.actions;

import com.oracle.bmc.vault.model.SecretSummary;
import com.oracle.bmc.vault.requests.ListSecretsRequest;
import com.oracle.bmc.vault.responses.ListSecretsResponse;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.netbeans.api.progress.ProgressHandle;
import static org.netbeans.modules.cloud.oracle.NotificationUtils.showMessage;
import static org.netbeans.modules.cloud.oracle.NotificationUtils.showWarningMessage;
import org.netbeans.modules.cloud.oracle.assets.CloudAssets;
import org.netbeans.modules.cloud.oracle.assets.Steps;
import org.netbeans.modules.cloud.oracle.items.OCIItem;
import org.netbeans.modules.cloud.oracle.steps.KeyStep;
import org.netbeans.modules.cloud.oracle.vault.KeyItem;
import org.netbeans.modules.cloud.oracle.vault.SensitiveData;
import org.netbeans.modules.cloud.oracle.vault.VaultItem;
import org.netbeans.modules.cloud.oracle.vault.VaultItemClient;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
*
* @author Dusan Petrovic
*/
@ActionID(
category = "Tools",
id = "org.netbeans.modules.cloud.oracle.actions.AddSecretsToVault"
)
@ActionRegistration(
displayName = "#AddSecretsToVault",
asynchronous = true
)
@ActionReferences(value = {
@ActionReference(path = "Cloud/Oracle/Vault/Actions", position = 250)
})
@NbBundle.Messages({
"AddSecretsToVault=Add Cloud Assets Secrets to OCI Vault",
"ReadingSecrets=Reading existing Secrets",
"CreatingSecret=Creating secret {0}",
"UpdatingSecret=Updating secret {0}",
"SecretsCreated=Secrets were created or updated",
"UpdatingVault=Updating {0} Vault"
})
public class AddSecretsToVault implements ActionListener {
private static final Logger LOG = Logger.getLogger(AddSecretsToVault.class.getName());

private final VaultItem context;

public AddSecretsToVault(VaultItem context) {
this.context = context;
}

@Override
public void actionPerformed(ActionEvent e) {
Steps.getDefault().executeMultistep(new KeyStep(context), Lookup.EMPTY).thenAccept(vals -> {
KeyItem key = vals.getValueForStep(KeyStep.class);

ProgressHandle h = ProgressHandle.createHandle(Bundle.UpdatingVault(context.getName()));
h.start();
h.progress(Bundle.ReadingSecrets());

try {
VaultItemClient vclient = new VaultItemClient(context);
Map<String, String> existingSecrets = getExistingSecrets(vclient).stream()
.collect(Collectors.toMap(s -> s.getSecretName(), s -> s.getId()));

Map<String, String> cloudAssetsSecrets = getCloudAssetsSecrets();
for (Map.Entry<String, String> entry : cloudAssetsSecrets.entrySet()) {
String secretName = entry.getKey();
if (existingSecrets.containsKey(secretName)) {
h.progress(Bundle.UpdatingSecret(secretName));
vclient.updateExistingSecret(entry, existingSecrets.get(secretName));
} else {
h.progress(Bundle.CreatingSecret(secretName));
vclient.createNewSecret(entry, key);
}
}
showMessage(Bundle.SecretsCreated());
} catch (Throwable ex) {
h.finish();
showWarningMessage(ex.getMessage());
} finally {
h.finish();
}
});
}

private List<SecretSummary> getExistingSecrets(VaultItemClient client) {
ListSecretsRequest listSecretsRequest = ListSecretsRequest.builder()
.compartmentId(context.getCompartmentId())
.vaultId(context.getKey().getValue())
.limit(88)
.build();

ListSecretsResponse secrets = client.listSecrets(listSecretsRequest);
return secrets.getItems();
}

private Map<String, String> getCloudAssetsSecrets() {
Map<String, String> secrets = new HashMap<>();
Collection<OCIItem> items = CloudAssets.getDefault().getItems();
for (OCIItem item : items) {
if (item instanceof SensitiveData) {
secrets.putAll(((SensitiveData) item).getSecrets());
}
}
return secrets;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@
@NbBundle.Messages({
"SuggestVault=For better security when using Autonomous Database, be sure to also add OCI Vault.",
"UpdatingConfigMap=Updating Config Map",
"CMUpdated=ConfigMap in \"{0}\" project was updated"
"CMUpdated=ConfigMap in \"{0}\" project was updated",
"NoConfigMap=No ConfigMap found in the Devops project {0}",
})
public class ConfigMapUploader {

Expand All @@ -111,15 +112,7 @@ public static void uploadConfigMap(CompletableFuture<Object> future) {
nsProviderBuilder.stepForClass(PasswordStep.class, (s) -> new KeyStep(vaultRef.get()));
} else if (item instanceof DatabaseItem) {
dbRef.set((DatabaseItem) item);
DatabaseConnection conn = null;
DatabaseConnection[] connections = ConnectionManager.getDefault().getConnections();
for (int i = 0; i < connections.length; i++) {
if (item.getKey().getValue().equals(
connections[i].getConnectionProperties().get("OCID"))) { //NOI18N
conn = connections[i];
break;
}
}
DatabaseConnection conn = ((DatabaseItem) item).getCorrespondingConnection();
String user, password;
if (conn != null) {
user = conn.getUser();
Expand Down Expand Up @@ -155,7 +148,7 @@ public static void uploadConfigMap(CompletableFuture<Object> future) {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(Bundle.CMUpdated(devopsProject.getName()), NotifyDescriptor.INFORMATION_MESSAGE);
DialogDisplayer.getDefault().notifyLater(msg);
} else {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(org.netbeans.modules.cloud.oracle.actions.Bundle.NoConfigMap(devopsProject.getName()), NotifyDescriptor.WARNING_MESSAGE);
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(Bundle.NoConfigMap(devopsProject.getName()), NotifyDescriptor.WARNING_MESSAGE);
DialogDisplayer.getDefault().notifyLater(msg);
}
future.complete(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ public class AddNewAssetCommand implements CommandProvider {
put("MetricsNamespace", new String[]{"io.micronaut.micrometer", "micronaut-micrometer-annotation"}); //NOI18N
}
};


@Override
public Set<String> getCommands() {
Expand All @@ -79,6 +78,7 @@ public Set<String> getCommands() {
@Override
public CompletableFuture<Object> runCommand(String command, List<Object> arguments) {
CompletableFuture future = new CompletableFuture();
boolean showSetRefNameStep = CloudAssets.getDefault().itemExistWithoutReferanceName(DatabaseItem.class);
Steps.NextStepProvider nsProvider = Steps.NextStepProvider.builder()
.stepForClass(ItemTypeStep.class, (s) -> {
if ("Databases".equals(s.getValue())) {
Expand All @@ -100,7 +100,18 @@ public CompletableFuture<Object> runCommand(String command, List<Object> argumen
if (i == null) {
item = new AddADBAction().addADB();
} else {
item = CompletableFuture.completedFuture(i);
if (showSetRefNameStep) {
SetReferenceNameAction action = new SetReferenceNameAction(i);
item = action.setReferenceName().thenAccept(referenceName -> {
if (referenceName == null) {
future.completeExceptionally(new IllegalArgumentException("Reference name not set"));
return;
}
CloudAssets.getDefault().setReferenceName(i, referenceName);
}).thenCompose(val -> CompletableFuture.completedFuture(i));
} else {
item = CompletableFuture.completedFuture(i);
}
}
} else {
OCIItem i = values.getValueForStep(SuggestedStep.class);
Expand Down Expand Up @@ -134,6 +145,9 @@ public CompletableFuture<Object> runCommand(String command, List<Object> argumen
DependencyUtils.addAnnotationProcessor(project, processor[0], processor[1]);
}
} catch (IllegalStateException e) {
if ("Databases".equals(itemType)) {
CloudAssets.getDefault().removeReferenceNameFor(i);
}
future.completeExceptionally(e);
}
future.complete(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,33 @@ public <T extends OCIItem> T getItem(Class<T> clazz) {
}
}
return null;
}

public boolean setReferenceName(OCIItem item, String refName) {
Parameters.notNull("refName", refName); //NOI18N
Parameters.notNull("OCIItem", item); //NOI18N
}

public boolean itemExistWithoutReferanceName(Class<? extends OCIItem> cls) {
return getReferenceNamesByClass(cls).isEmpty() &&
CloudAssets.getDefault().getItems().stream().anyMatch(item -> cls.isInstance(item));
}

public boolean referenceNameExist(String itemPath, String refName) {
for (Entry<OCIItem, String> refEntry : refNames.entrySet()) {
if (refEntry.getKey().getKey().getPath().equals(item.getKey().getPath())
if (refEntry.getKey().getKey().getPath().equals(itemPath)
&& refName.equals(refEntry.getValue())) {
return false;
return true;
}
}
return false;
}

public void removeReferenceNameFor(OCIItem item) {
refNames.remove(item);
}

public boolean setReferenceName(OCIItem item, String refName) {
Parameters.notNull("refName", refName); //NOI18N
Parameters.notNull("OCIItem", item); //NOI18N
if (referenceNameExist(item.getKey().getPath(), refName)) {
return false;
}
String oldRefName = refNames.get(item);
refNames.put(item, refName);
storeAssets();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.netbeans.api.db.explorer.ConnectionManager;
import org.netbeans.api.db.explorer.DatabaseConnection;
import org.netbeans.modules.cloud.oracle.bucket.BucketItem;
import org.netbeans.modules.cloud.oracle.database.DatabaseItem;
import org.netbeans.modules.cloud.oracle.developer.MetricsNamespaceItem;
import org.netbeans.modules.cloud.oracle.items.OCIItem;
import org.netbeans.modules.cloud.oracle.vault.VaultItem;
Expand Down Expand Up @@ -71,7 +71,6 @@ public final class PropertiesGenerator {
public PropertiesGenerator(boolean local) {
Collection<OCIItem> items = CloudAssets.getDefault().getItems();
VaultItem vault = null;
DatabaseConnection conn = null;
for (OCIItem item : items) {
if ("Vault".equals(item.getKey().getPath())) {
vault = (VaultItem) item;
Expand All @@ -90,14 +89,8 @@ public PropertiesGenerator(boolean local) {
application.put("micronaut.object-storage.oracle-cloud." + nameLowercase + ".namespace", ((BucketItem) item).getNamespace()); //NOI18N
break;
case "Databases": //NOI18N
DatabaseConnection[] connections = ConnectionManager.getDefault().getConnections();
for (int i = 0; i < connections.length; i++) {
if (item.getKey().getValue().equals(
connections[i].getConnectionProperties().get("OCID"))) { //NOI18N
conn = connections[i];
break;
}
}
DatabaseConnection conn = ((DatabaseItem) item).getCorrespondingConnection();

if (conn != null) {

if (vault != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.CompletableFuture;
import org.netbeans.modules.cloud.oracle.items.OCIItem;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.netbeans.modules.cloud.oracle.steps.ReferenceNameStep;
import org.openide.awt.ActionID;
import org.openide.awt.ActionRegistration;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
Expand Down Expand Up @@ -56,25 +56,17 @@ public SetReferenceNameAction(OCIItem context) {

@Override
public void actionPerformed(ActionEvent e) {
String oldRefName = CloudAssets.getDefault().getReferenceName(context);
if (oldRefName == null) {
oldRefName = "";
}
NotifyDescriptor.InputLine inp = new NotifyDescriptor.InputLine(oldRefName, Bundle.ReferenceName());
Object selected = DialogDisplayer.getDefault().notify(inp);
if (DialogDescriptor.OK_OPTION != selected) {
return;
}
String refName = inp.getInputText();
if (refName.matches("[a-zA-Z0-9]+")) { //NOI18N
if (!CloudAssets.getDefault().setReferenceName(context, refName)) {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(Bundle.ReferenceNameSame());
DialogDisplayer.getDefault().notify(msg);
}
} else {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(Bundle.ReferenceNameValidationError());
DialogDisplayer.getDefault().notify(msg);
}
setReferenceName();
}

public CompletableFuture<String> setReferenceName() {
CompletableFuture future = new CompletableFuture();
Steps.getDefault().executeMultistep(new ReferenceNameStep(context), Lookup.EMPTY)
.thenAccept(vals -> {
String refName = vals.getValueForStep(ReferenceNameStep.class);
CloudAssets.getDefault().setReferenceName(context, refName);
future.complete(refName);
});
return future;
}
}
Loading

0 comments on commit 67d76ce

Please sign in to comment.