/*
* This file is part of cert-signer
* Copyright (c) 2024 Paolo Lulli.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package net.lulli.certsigner.network;
import org.json.JSONObject;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
public class VaultLocal {
private final String endpoint;
private final String token;
public VaultLocal(String endpoint, String token) {
Objects.requireNonNull(token);
Objects.requireNonNull(endpoint);
this.endpoint = endpoint;
this.token = token;
}
public boolean storeSecret(String secretName, Map secretMap) {
var url = String.format("%s/%s", endpoint, secretName);
var containerJson = new JSONObject();
containerJson.put("options", new ArrayList());
containerJson.put("version", 0);
containerJson.put("data", secretMap);
try {
postToVault(url, containerJson.toString(), token);
} catch (Exception ignored) {
return false;
}
return true;
}
private static JSONObject getWithHeader(String url, String headerName, String headerValue) {
try {
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create(url)).header("accept", "application/json")
.header(headerName, headerValue).build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
return new JSONObject(response.body());
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public Optional retrieveSecret(String secretName) {
var url = String.format("%s/%s", endpoint, secretName);
var json = getWithHeader(url, "X-Vault-Token", token);
if (null != json) {
return Optional.of(json.toString());
}
return Optional.empty();
}
public static String postToVault(String url, String payload, String token)
throws Exception {
var client = HttpClient.newBuilder().build();
var request = HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(payload))
.header("X-Vault-Token", token)
.uri(URI.create(url)).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
return response.body().toString();
}
}