diff --git a/src/main/java/io/github/jopenlibs/vault/api/database/Database.java b/src/main/java/io/github/jopenlibs/vault/api/database/Database.java index 4f51a72d..02a2257d 100644 --- a/src/main/java/io/github/jopenlibs/vault/api/database/Database.java +++ b/src/main/java/io/github/jopenlibs/vault/api/database/Database.java @@ -7,6 +7,7 @@ import io.github.jopenlibs.vault.json.Json; import io.github.jopenlibs.vault.json.JsonObject; import io.github.jopenlibs.vault.response.DatabaseResponse; +import io.github.jopenlibs.vault.response.DatabaseStaticResponse; import io.github.jopenlibs.vault.rest.RestResponse; import java.nio.charset.StandardCharsets; import java.util.List; @@ -125,6 +126,31 @@ public DatabaseResponse createOrUpdateRole(final String roleName, }); } + public DatabaseStaticResponse createOrUpdateStaticRole(final String roleName, + final DatabaseStaticRoleOptions options) throws VaultException { + return retry(attempt -> { + final String requestJson = staticRoleOptionsToJson(options); + + final RestResponse restResponse = getRest()//NOPMD + .url(String.format("%s/v1/%s/static-roles/%s", config.getAddress(), this.mountPath, + roleName)) + .token(config.getToken()) + .header("X-Vault-Namespace", this.nameSpace) + .header("X-Vault-Request", "true") + .body(requestJson.getBytes(StandardCharsets.UTF_8)) + .readTimeoutSeconds(config.getReadTimeout()) + .post(); + + // Validate restResponse + if (restResponse.getStatus() != 204) { + throw new VaultException( + "Vault responded with HTTP status code: " + restResponse.getStatus(), + restResponse.getStatus()); + } + return new DatabaseStaticResponse(restResponse, attempt); + }); + } + /** *

Operation to retrieve an role using the Database backend. Relies on an authentication * token being present in the VaultConfig instance.

@@ -167,8 +193,29 @@ public DatabaseResponse getRole(final String roleName) throws VaultException { }); } + public DatabaseStaticResponse getStaticRole(final String roleName) throws VaultException { + return retry(attempt -> { + final RestResponse restResponse = getRest()//NOPMD + .url(String.format("%s/v1/%s/static-roles/%s", config.getAddress(), this.mountPath, + roleName)) + .token(config.getToken()) + .header("X-Vault-Namespace", this.nameSpace) + .header("X-Vault-Request", "true") + .readTimeoutSeconds(config.getReadTimeout()) + .get(); + + // Validate response + if (restResponse.getStatus() != 200 && restResponse.getStatus() != 404) { + throw new VaultException( + "Vault responded with HTTP status code: " + restResponse.getStatus(), + restResponse.getStatus()); + } + return new DatabaseStaticResponse(restResponse, attempt); + }); + } + /** - *

Operation to revike a certificate in the vault using the Database backend. + *

Operation to revoke a certificate in the vault using the Database backend. * Relies on an authentication token being present in the VaultConfig * instance.

* @@ -259,6 +306,27 @@ public DatabaseResponse deleteRole(final String roleName) throws VaultException }); } + public DatabaseStaticResponse deleteStaticRole(final String roleName) throws VaultException { + return retry(attempt -> { + final RestResponse restResponse = getRest()//NOPMD + .url(String.format("%s/v1/%s/static-roles/%s", config.getAddress(), this.mountPath, + roleName)) + .token(config.getToken()) + .header("X-Vault-Namespace", this.nameSpace) + .header("X-Vault-Request", "true") + .readTimeoutSeconds(config.getReadTimeout()) + .delete(); + + // Validate response + if (restResponse.getStatus() != 204) { + throw new VaultException( + "Vault responded with HTTP status code: " + restResponse.getStatus(), + restResponse.getStatus()); + } + return new DatabaseStaticResponse(restResponse, attempt); + }); + } + /** *

Operation to generate a new set of credentials using the Database backend. * @@ -308,6 +376,32 @@ public DatabaseResponse creds(final String roleName) throws VaultException { }); } + public DatabaseStaticResponse staticCreds(final String roleName) throws VaultException { + return retry(attempt -> { + final RestResponse restResponse = getRest()//NOPMD + .url(String.format("%s/v1/%s/static-creds/%s", config.getAddress(), this.mountPath, + roleName)) + .token(config.getToken()) + .header("X-Vault-Namespace", this.nameSpace) + .header("X-Vault-Request", "true") + .readTimeoutSeconds(config.getReadTimeout()) + .get(); + + // Validate response + if (restResponse.getStatus() != 200 && restResponse.getStatus() != 404) { + String body = + restResponse.getBody() != null ? new String(restResponse.getBody(), + StandardCharsets.UTF_8) + : "(no body)"; + throw new VaultException( + "Vault responded with HTTP status code: " + restResponse.getStatus() + + " " + body, restResponse.getStatus()); + } + + return new DatabaseStaticResponse(restResponse, attempt); + }); + } + private String roleOptionsToJson(final DatabaseRoleOptions options) { final JsonObject jsonObject = Json.object(); @@ -328,6 +422,22 @@ private String roleOptionsToJson(final DatabaseRoleOptions options) { return jsonObject.toString(); } + private String staticRoleOptionsToJson(final DatabaseStaticRoleOptions options) { + final JsonObject jsonObject = Json.object(); + + if (options != null) { + addJsonFieldIfNotNull(jsonObject, "db_name", options.getDbName()); + addJsonFieldIfNotNull(jsonObject, "username", options.getUsername()); + addJsonFieldIfNotNull(jsonObject, "credential_type", options.getCredentialType()); + addJsonFieldIfNotNull(jsonObject, "rotation_period", options.getRotationPeriod()); + addJsonFieldIfNotNull(jsonObject, "skip_import_rotation", options.getSkipImportRotation()); + addJsonFieldIfNotNull(jsonObject, "rotation_statements", + joinList(options.getRotationStatements())); + } + + return jsonObject.toString(); + } + private String joinList(List data) { String result = ""; diff --git a/src/main/java/io/github/jopenlibs/vault/api/database/DatabaseStaticCredential.java b/src/main/java/io/github/jopenlibs/vault/api/database/DatabaseStaticCredential.java new file mode 100644 index 00000000..f3f15f32 --- /dev/null +++ b/src/main/java/io/github/jopenlibs/vault/api/database/DatabaseStaticCredential.java @@ -0,0 +1,53 @@ +package io.github.jopenlibs.vault.api.database; + +public class DatabaseStaticCredential extends DatabaseCredential { + private String lastVaultRotation; + private String ttl; + private String rotationPeriod; + + /** + * @return Returns the last vault rotation time associated with the retrieved Credential + */ + public String getLastVaultRotation() { + return lastVaultRotation; + } + + /** + * @return Returns the TTL associated with the retrieved Credential + */ + public String getTtl() { + return ttl; + } + + /** + * @return Returns the rotation period associated with the retrieved Credential + */ + public String getRotationPeriod() { + return rotationPeriod; + } + + public DatabaseStaticCredential username(String username) { + super.username(username); + return this; + } + + public DatabaseStaticCredential password(String password) { + super.password(password); + return this; + } + + public DatabaseStaticCredential rotationPeriod(String period) { + this.rotationPeriod = period; + return this; + } + + public DatabaseStaticCredential ttl(String ttl) { + this.ttl = ttl; + return this; + } + + public DatabaseStaticCredential lastVaultRotation(String rotation) { + this.lastVaultRotation = rotation; + return this; + } +} diff --git a/src/main/java/io/github/jopenlibs/vault/api/database/DatabaseStaticRoleOptions.java b/src/main/java/io/github/jopenlibs/vault/api/database/DatabaseStaticRoleOptions.java new file mode 100644 index 00000000..87bba862 --- /dev/null +++ b/src/main/java/io/github/jopenlibs/vault/api/database/DatabaseStaticRoleOptions.java @@ -0,0 +1,129 @@ +package io.github.jopenlibs.vault.api.database; + +import java.util.ArrayList; +import java.util.List; + +public class DatabaseStaticRoleOptions { + + private String name; + private String dbName; + private List rotationStatements = new ArrayList<>(); + private String username; + private String credentialType; + private String lastVaultRotation; + private String rotationPeriod; + private Boolean skipImportRotation; + + public String getName() { + return name; + } + + public String getDbName() { + return dbName; + } + + public String getCredentialType() { + return credentialType; + } + + public String getLastVaultRotation() { + return lastVaultRotation; + } + + public String getRotationPeriod() { + return rotationPeriod; + } + + public Boolean getSkipImportRotation() { + return skipImportRotation; + } + + public String getUsername() { + return username; + } + + public List getRotationStatements() { + return rotationStatements; + } + + /** + * @param name {@code String} – Specifies the name of the role to create. This is specified as + * part of the URL. + * @return This object, with name populated, ready for other builder methods or immediate use. + */ + public DatabaseStaticRoleOptions name(final String name) { + this.name = name; + return this; + } + + /** + * @param dbName {@code String} - The name of the database connection to use for this role. + * @return This object, with dbName populated, ready for other builder methods or immediate use. + */ + public DatabaseStaticRoleOptions dbName(final String dbName) { + this.dbName = dbName; + return this; + } + + /** + * @param + * @return This object, with username populated, ready for other builder methods or immediate + * use. + */ + public DatabaseStaticRoleOptions username(final String username) { + this.username = username; + return this; + } + + /** + * @param + * @return This object, with skipImportRotation populated, ready for other builder methods or immediate + * use. + */ + public DatabaseStaticRoleOptions skipImportRotation(final Boolean skipImportRotation) { + this.skipImportRotation = skipImportRotation; + return this; + } + + /** + * @param + * @return This object, with rotationPeriod populated, ready for other builder methods or immediate + * use. + */ + public DatabaseStaticRoleOptions rotationPeriod(final String rotationPeriod) { + this.rotationPeriod = rotationPeriod; + return this; + } + + /** + * @param + * @return This object, with lastVaultRotation populated, ready for other builder methods or immediate + * use. + */ + public DatabaseStaticRoleOptions lastVaultRotation(final String lastVaultRotation) { + this.lastVaultRotation = lastVaultRotation; + return this; + } + + /** + * @param + * @return This object, with credentialType populated, ready for other builder methods or immediate + * use. + */ + public DatabaseStaticRoleOptions credentialType(final String credentialType) { + this.credentialType = credentialType; + return this; + } + + /** + * @param creationStatements {@code List} – Specifies the database statements executed + * to rotate the password for a user. See the plugin's API page for more information on support and + * formatting for this parameter. + * @return This object, with rotationStatements populated, ready for other builder methods or + * immediate use. + */ + public DatabaseStaticRoleOptions rotationStatements(final List rotationStatements) { + this.rotationStatements = rotationStatements; + return this; + } +} diff --git a/src/main/java/io/github/jopenlibs/vault/response/DatabaseResponse.java b/src/main/java/io/github/jopenlibs/vault/response/DatabaseResponse.java index 73977f9a..4de34fdc 100644 --- a/src/main/java/io/github/jopenlibs/vault/response/DatabaseResponse.java +++ b/src/main/java/io/github/jopenlibs/vault/response/DatabaseResponse.java @@ -52,7 +52,7 @@ private DatabaseRoleOptions buildRoleOptionsFromData(final Map d final String dbName = data.get("db_name"); final String defaultTtl = data.get("default_ttl"); - final String maxTtl = data.get("default_ttl"); + final String maxTtl = data.get("max_ttl"); if (dbName == null && defaultTtl == null && maxTtl == null) { return null; @@ -85,8 +85,7 @@ private DatabaseCredential buildCredentialFromData(final Map dat } private JsonArray safeGetJsonArray(JsonObject source, String key) { - if (source == null || source.get(key) == null || source.get(key) == null || !source.get(key) - .isArray()) { + if (source == null || source.get(key) == null || !source.get(key).isArray()) { return new JsonArray(); } diff --git a/src/main/java/io/github/jopenlibs/vault/response/DatabaseStaticResponse.java b/src/main/java/io/github/jopenlibs/vault/response/DatabaseStaticResponse.java new file mode 100644 index 00000000..c56cde19 --- /dev/null +++ b/src/main/java/io/github/jopenlibs/vault/response/DatabaseStaticResponse.java @@ -0,0 +1,104 @@ +package io.github.jopenlibs.vault.response; + +import io.github.jopenlibs.vault.api.Logical; +import io.github.jopenlibs.vault.api.database.DatabaseStaticCredential; +import io.github.jopenlibs.vault.api.database.DatabaseStaticRoleOptions; +import io.github.jopenlibs.vault.json.JsonArray; +import io.github.jopenlibs.vault.json.JsonObject; +import io.github.jopenlibs.vault.json.JsonValue; +import io.github.jopenlibs.vault.rest.RestResponse; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class DatabaseStaticResponse extends LogicalResponse { + + private DatabaseStaticCredential credential; + + private DatabaseStaticRoleOptions roleOptions; + + public DatabaseStaticCredential getCredential() { + return credential; + } + + public DatabaseStaticRoleOptions getStaticRoleOptions() { + return roleOptions; + } + + /** + * @param restResponse The raw HTTP response from Vault. + * @param retries The number of retry attempts that occurred during the API call (can be zero). + */ + public DatabaseStaticResponse(RestResponse restResponse, int retries) { + super(restResponse, retries, Logical.logicalOperations.authentication); + credential = buildCredentialFromData(this.getData()); + roleOptions = buildStaticRoleOptionsFromData(this.getData(), this.getDataObject()); + } + + private DatabaseStaticRoleOptions buildStaticRoleOptionsFromData(final Map data, + final JsonObject jsonObject) { + if (data == null || data.isEmpty()) { + return null; + } + + final List rotationStatements = extractFromJsonArray( + safeGetJsonArray(jsonObject, "rotation_statements")); + + final String credentialType = data.get("credential_type"); + final String dbName = data.get("db_name"); + final String lastVaultRotation = data.get("last_vault_rotation"); + final String rotationPeriod = data.get("rotation_period"); + final String skipImportRotationStr = data.get("skip_import_rotation"); + final Boolean skipImportRotation = + skipImportRotationStr == null ? null : Boolean.parseBoolean(skipImportRotationStr); + final String username = data.get("username"); + + if (dbName == null && username == null) { + return null; + } + + return new DatabaseStaticRoleOptions() + .rotationStatements(rotationStatements) + .dbName(dbName) + .lastVaultRotation(lastVaultRotation) + .rotationPeriod(rotationPeriod) + .skipImportRotation(skipImportRotation) + .username(username); + } + + private DatabaseStaticCredential buildCredentialFromData(final Map data) { + if (data == null) { + return null; + } + final String username = data.get("username"); + final String password = data.get("password"); + final String lastRotation = data.get("last_vault_rotation"); + final String rotationPeriod = data.get("rotation_period"); + final String ttl = data.get("ttl"); + + if (username == null && password == null) { + return null; + } + + return new DatabaseStaticCredential() + .username(username) + .password(password) + .lastVaultRotation(lastRotation) + .rotationPeriod(rotationPeriod) + .ttl(ttl); + } + + private JsonArray safeGetJsonArray(JsonObject source, String key) { + if (source == null || source.get(key) == null || !source.get(key).isArray()) { + return new JsonArray(); + } + + return source.get(key).asArray(); + } + + private List extractFromJsonArray(JsonArray array) { + return array.values().stream() + .map(JsonValue::asString) + .collect(Collectors.toUnmodifiableList()); + } +} diff --git a/src/test/java/io/github/jopenlibs/vault/api/AuthBackendDatabaseIT.java b/src/test/java/io/github/jopenlibs/vault/api/AuthBackendDatabaseIT.java index 84df360d..dddd3d3e 100644 --- a/src/test/java/io/github/jopenlibs/vault/api/AuthBackendDatabaseIT.java +++ b/src/test/java/io/github/jopenlibs/vault/api/AuthBackendDatabaseIT.java @@ -3,17 +3,23 @@ import io.github.jopenlibs.vault.Vault; import io.github.jopenlibs.vault.VaultException; import io.github.jopenlibs.vault.api.database.DatabaseRoleOptions; +import io.github.jopenlibs.vault.api.database.DatabaseStaticRoleOptions; import io.github.jopenlibs.vault.response.DatabaseResponse; +import io.github.jopenlibs.vault.response.DatabaseStaticResponse; import io.github.jopenlibs.vault.util.DbContainer; +import io.github.jopenlibs.vault.util.TestConstants; import io.github.jopenlibs.vault.util.VaultContainer; import java.io.IOException; import java.util.List; +import java.util.Map; import junit.framework.TestCase; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; +import org.testcontainers.containers.ExecConfig; import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNotNull; import static junit.framework.TestCase.assertTrue; public class AuthBackendDatabaseIT { @@ -39,7 +45,8 @@ public void testRoleCreation() throws VaultException { "CREATE USER \"{{name}}\" WITH PASSWORD '{{password}}'; GRANT ALL PRIVILEGES ON DATABASE \"postgres\" to \"{{name}}\";"); final var roleToCreate = new DatabaseRoleOptions().dbName("postgres") - .creationStatements(creationStatements); + .creationStatements(creationStatements) + .defaultTtl("100").maxTtl("300"); DatabaseResponse response = vault.database().createOrUpdateRole("test-role", roleToCreate); TestCase.assertEquals(204, response.getRestResponse().getStatus()); @@ -48,6 +55,8 @@ public void testRoleCreation() throws VaultException { TestCase.assertEquals(200, role.getRestResponse().getStatus()); assertTrue(compareRoleOptions(role.getRoleOptions(), roleToCreate)); + TestCase.assertEquals("100", role.getRoleOptions().getDefaultTtl()); + TestCase.assertEquals("300", role.getRoleOptions().getMaxTtl()); } @Test @@ -103,6 +112,98 @@ public void testGetCredentials() throws VaultException { TestCase.assertTrue(credsResponse.getCredential().getUsername().contains("new-role")); } + @Test + public void testStaticRoleCreation() throws VaultException { + final Vault vault = container.getRootVault(); + + final var creationStatements = List.of( + "CREATE USER \"{{name}}\" WITH PASSWORD '{{password}}'; GRANT ALL PRIVILEGES ON DATABASE \"postgres\" to \"{{name}}\";"); + + DatabaseResponse response = vault.database().createOrUpdateRole("base-role", + new DatabaseRoleOptions().dbName("postgres") + .creationStatements(creationStatements)); + TestCase.assertEquals(204, response.getRestResponse().getStatus()); + + DatabaseResponse credsResponse = vault.database().creds("base-role"); + + final var rotationStatements = List.of( + "ALTER USER \"{{name}}\" WITH PASSWORD '{{password}}';"); + + final var roleToCreate = + new DatabaseStaticRoleOptions().dbName("postgres") + .username(credsResponse.getCredential().getUsername()) + .skipImportRotation(false) + .rotationStatements(rotationStatements) + .rotationPeriod("300").credentialType("password"); + + DatabaseStaticResponse staticResponse = + vault.database().createOrUpdateStaticRole("test-static-role", roleToCreate); + TestCase.assertEquals(204, staticResponse.getRestResponse().getStatus()); + + DatabaseStaticResponse role = + vault.database().getStaticRole("test-static-role"); + assertEquals("300", role.getStaticRoleOptions().getRotationPeriod()); + assertEquals(Boolean.FALSE, role.getStaticRoleOptions().getSkipImportRotation()); + assertEquals(credsResponse.getCredential().getUsername(), + role.getStaticRoleOptions().getUsername()); + + DatabaseStaticResponse rotCredsResponse = + vault.database().staticCreds("test-static-role"); + assertEquals(credsResponse.getCredential().getUsername(), + rotCredsResponse.getCredential().getUsername()); + assertNotNull(rotCredsResponse.getCredential().getPassword()); + assertTrue(!credsResponse.getCredential().getPassword() + .equals(rotCredsResponse.getCredential().getPassword())); + assertEquals(roleToCreate.getRotationPeriod(), + rotCredsResponse.getCredential().getRotationPeriod()); + assertNotNull(rotCredsResponse.getCredential().getLastVaultRotation()); + } + + @Test + public void testDeleteStaticRole() throws Exception { + final Vault vault = container.getRootVault(); + + String[] psql = new String[] { + "psql", "-U", TestConstants.POSTGRES_USER, "-w", "-c", + "create user \"del-static-role\" with password 'password'" }; + DbContainer.ExecResult result = + dbContainer.execInContainer(ExecConfig.builder() + .command(psql) + .envVars(Map.of("PGPASSWORD", TestConstants.POSTGRES_PASSWORD)) + .build()); + assertEquals(0, result.getExitCode()); + assertEquals("CREATE ROLE", result.getStdout().trim()); + + final var rotationStatements = List.of( + "ALTER USER \"{{name}}\" WITH PASSWORD '{{password}}';"); + + final var roleToCreate = + new DatabaseStaticRoleOptions().dbName("postgres") + .username("del-static-role") + .skipImportRotation(true) + .rotationPeriod("300") + .rotationStatements(rotationStatements); + + DatabaseStaticResponse staticResponse = + vault.database().createOrUpdateStaticRole("del-static-role", roleToCreate); + TestCase.assertEquals(204, staticResponse.getRestResponse().getStatus()); + DatabaseStaticResponse checkRole = + vault.database().getStaticRole("del-static-role"); + // Vault doesn't know the password yet, so this is null + // This verifies skipImportRotation=true is working + assertTrue(checkRole.getCredential().getPassword() == null); + + DatabaseStaticResponse deletedRole = + vault.database().deleteStaticRole("del-static-role"); + TestCase.assertEquals(204, deletedRole.getRestResponse().getStatus()); + + try { + DatabaseStaticResponse role = vault.database().getStaticRole("delete-role"); + } catch (VaultException e) { + assertEquals("This should have failed", 404, e.getHttpStatusCode()); + } + } + private boolean compareRoleOptions(DatabaseRoleOptions expected, DatabaseRoleOptions actual) { return expected.getCreationStatements().size() == actual.getCreationStatements().size() && expected.getRenewStatements().size() == actual.getRenewStatements().size() &&