Skip to content

Commit

Permalink
Add GCP Secret Manager Connection String Provider for Oracle JDBC (#119)
Browse files Browse the repository at this point in the history
* Add GCP Secret Manager Connection String Provider

* Add configuration properties files

* Refactor Common Utilities and Parameters

* fix keyVaultConnectionStringProvider Tests in Azure && refactor TCPS and SEPS wallets providers

* update Readme.md file

* Add example for Connection String Provider in GCP

* Rename 'tns-alias' parameter to 'tnsAlias' for consistency
  • Loading branch information
MouhsinElmajdouby authored Nov 15, 2024
1 parent aa76cc1 commit a2946e7
Show file tree
Hide file tree
Showing 14 changed files with 527 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ public void testGetParameters() {
.filter(parameter -> "tns-alias".equals(parameter.name()))
.findFirst()
.orElseThrow(AssertionError::new);
assertFalse(aliasParameter.isSensitive());
assertFalse(aliasParameter.isRequired());
assertTrue(aliasParameter.isSensitive());
assertTrue(aliasParameter.isRequired());
assertNull(aliasParameter.defaultValue());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ private CommonParameters() {}
* <p><b>Note:</b> The alias should exactly match one of the aliases defined
* in your tnsnames.ora file.</p>
*/
public static final Parameter<String> TNS_ALIAS = Parameter.create();
public static final Parameter<String> TNS_ALIAS = Parameter.create(
REQUIRED, SENSITIVE
);


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
** Copyright (c) 2024 Oracle and/or its affiliates.
**
** The Universal Permissive License (UPL), Version 1.0
**
** Subject to the condition set forth below, permission is hereby granted to any
** person obtaining a copy of this software, associated documentation and/or data
** (collectively the "Software"), free of charge and under any and all copyright
** rights in the Software, and any and all patent rights owned or freely
** licensable by each licensor hereunder covering either (i) the unmodified
** Software as contributed to or provided by such licensor, or (ii) the Larger
** Works (as defined below), to deal in both
**
** (a) the Software, and
** (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
** one is included with the Software (each a "Larger Work" to which the Software
** is contributed by such licensors),
**
** without restriction, including without limitation the rights to copy, create
** derivative works of, display, perform, and distribute the Software and make,
** use, sell, offer for sale, import, export, have made, and have sold the
** Software and the Larger Work(s), and to sublicense the foregoing rights on
** either these or other terms.
**
** This license is subject to the following condition:
** The above copyright notice and either this complete permission notice or at
** a minimum a reference to the UPL must be included in all copies or
** substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
*/

package oracle.jdbc.provider.util;

import java.util.Base64;

/**
* Utility class for common file handling operations.
*/
public final class FileUtils {

/**
* Checks if the given byte array is Base64-encoded.
*/
public static boolean isBase64Encoded(byte[] secretBytes) {
try {
Base64.getDecoder().decode(secretBytes);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import oracle.security.pki.OracleWallet;

import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Enumeration;

/**
Expand Down Expand Up @@ -250,18 +248,6 @@ public static Credentials getCredentials(
}
}

/**
* Checks if the given byte array is Base64-encoded.
*/
public static boolean isBase64Encoded(byte[] secretBytes) {
try {
Base64.getDecoder().decode(secretBytes);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}

/**
* A username and password.
*/
Expand Down
40 changes: 40 additions & 0 deletions ojdbc-provider-gcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ Provider</a></dt>
<dd>Provides TCPS/TLS wallet for secure connections to an Autonomous Database from the Secret Manager service</dd>
<dt><a href="#secret-manager-seps-wallet-provider">Secret Manager SEPS Wallet Provider</a></dt>
<dd>Provides SEPS (Secure External Password Store) wallets for secure username and password retrieval from the Secret Manager service</dd>
<dt><a href="#secret-manager-connection-string-provider">Secret Manager Connection String Provider</a></dt>
<dd>Provides connection strings for secure database connectivity based on aliases, retrieved from the `tnsnames.ora`
file stored in GCP Secret Manager.</dd>
</dl>

Visit any of the links above to find information and usage examples for a
Expand Down Expand Up @@ -329,3 +332,40 @@ An example of a [connection properties file](https://docs.oracle.com/en/database

This provider supports wallets stored in GCP Secret Manager as both base64-encoded strings and imported files. It automatically detects the storage format and processes the wallet accordingly, ensuring flexibility in managing your SEPS credentials.

## Secret Manager Connection String Provider

The Connection String Provider provides Oracle JDBC with a connection string managed by the GCP Secret Manager service.
This is a Resource Provider identified by the name `ojdbc-provider-gcp-secretmanager-tnsnames`.

This provider retrieves a `tnsnames.ora` file stored in GCP Secret Manager, allowing selection of connection strings
based on specified aliases. The `tnsnames.ora` file can be stored as a base64-encoded string or as a raw file,
and the provider automatically detects the format.

This enables flexible configuration for secure database connections using the alias names defined in your `tnsnames.ora` file.

<table>
<thead>
<tr>
<th>Parameter Name</th>
<th>Description</th>
<th>Accepted Values</th>
<th>Default Value</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>secretVersionName</code></td>
<td>The version name of the secret in GCP Secret Manager that contains the <code>tnsnames.ora</code> file.</td>
<td>The <a href="https://cloud.google.com/secret-manager/docs/creating-and-accessing-secrets">GCP Secret Manager Secret Version</a>, typically in the form:<br><pre>projects/{project-id}/secrets/{secret-id}/versions/{version-id}</pre></td>
<td><i>No default value. A value must be configured for this parameter.</i></td>
</tr>
<tr>
<td><code>tnsAlias</code></td>
<td>Specifies the alias to retrieve the appropriate connection string from the <code>tnsnames.ora</code> file.</td>
<td>Any valid alias present in your <code>tnsnames.ora</code> file.</td>
<td><i>No default value. A value must be configured for this parameter.</i></td>
</tr>
</tbody>
</table>

An example of a [connection properties file](https://docs.oracle.com/en/database/oracle/oracle-database/23/jajdb/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_CONFIG_FILE) that configures this provider can be found in [example-vault.properties](example-vault.properties).
6 changes: 6 additions & 0 deletions ojdbc-provider-gcp/example-test.properties
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,9 @@ GCP_SSO_SEPS_SECRET_VERSION_NAME=projects/project-id/secrets/sso-seps-secret/ver

# Corrupted SEPS Wallet Secret stored in GCP Secret Manager for negative test cases
GCP_CORRUPTED_SEPS_WALLET_SECRET_VERSION_NAME=projects/project-id/secrets/corrupted-seps-secret/versions/1

# Secret version name for tnsnames.ora file in GCP Secret Manager
GCP_SECRET_MANAGER_TNS_NAMES_SECRET_VERSION=projects/project-id/secrets/tnsnames-ora-secret/versions/1

# Alias to retrieve specific connection string from tnsnames.ora in GCP Secret Manager
GCP_SECRET_MANAGER_TNS_ALIAS_SECRET_NAME=your_tns_alias
9 changes: 9 additions & 0 deletions ojdbc-provider-gcp/example-vault.properties
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,12 @@ oracle.jdbc.provider.username.secretVersionName=${USERNAME_SECRET_VERSION_NAME}
# property named "PASSWORD_SECRET_VERSION_NAME":
oracle.jdbc.provider.password=ojdbc-provider-gcp-secretmanager-password
oracle.jdbc.provider.password.secretVersionName=${PASSWORD_SECRET_VERSION_NAME}

# Configures the GCP Secret Manager Connection String Provider. The secret version name and
# tns alias are configured as environment variables or JVM system properties
# named "GCP_SECRET_VERSION_NAME" and "TNS_ALIAS".
oracle.jdbc.provider.connectionString=ojdbc-provider-gcp-secretmanager-tnsnames
oracle.jdbc.provider.connectionString.secretVersionName=${GCP_SECRET_VERSION_NAME}
oracle.jdbc.provider.connectionString.tnsAlias=${TNS_ALIAS}


Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
** Copyright (c) 2024 Oracle and/or its affiliates.
**
** The Universal Permissive License (UPL), Version 1.0
**
** Subject to the condition set forth below, permission is hereby granted to any
** person obtaining a copy of this software, associated documentation and/or data
** (collectively the "Software"), free of charge and under any and all copyright
** rights in the Software, and any and all patent rights owned or freely
** licensable by each licensor hereunder covering either (i) the unmodified
** Software as contributed to or provided by such licensor, or (ii) the Larger
** Works (as defined below), to deal in both
**
** (a) the Software, and
** (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
** one is included with the Software (each a "Larger Work" to which the Software
** is contributed by such licensors),
**
** without restriction, including without limitation the rights to copy, create
** derivative works of, display, perform, and distribute the Software and make,
** use, sell, offer for sale, import, export, have made, and have sold the
** Software and the Larger Work(s), and to sublicense the foregoing rights on
** either these or other terms.
**
** This license is subject to the following condition:
** The above copyright notice and either this complete permission notice or at
** a minimum a reference to the UPL must be included in all copies or
** substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
*/

package oracle.jdbc.provider.gcp.resource;

import oracle.jdbc.provider.resource.ResourceParameter;
import oracle.jdbc.provider.util.FileUtils;
import oracle.jdbc.provider.util.TNSNames;
import oracle.jdbc.spi.ConnectionStringProvider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Map;

import static oracle.jdbc.provider.util.CommonParameters.TNS_ALIAS;


/**
* <p>
* A provider for securely retrieving the connection string from a tnsnames.ora
* file stored in GCP Secret Manager for use with an Oracle Autonomous Database.
* The tnsnames.ora file can be stored either as a base64-encoded secret or in
* raw binary format in GCP Secret Manager. This provider automatically
* detects and decodes base64-encoded content as needed before parsing the
* file to retrieve connection strings based on specified aliases.
* </p>
* <p>
* This class implements the {@link ConnectionStringProvider} SPI defined by
* Oracle JDBC. It is designed to be instantiated via {@link java.util.ServiceLoader}.
* </p>
*/
public class GcpSecretManagerConnectionStringProvider
extends GcpSecretManagerProvider
implements ConnectionStringProvider {

private static final ResourceParameter[] TNS_NAMES_PARAMETERS = {
new ResourceParameter("tnsAlias", TNS_ALIAS)
};

/**
* A public no-arg constructor used by {@link java.util.ServiceLoader} to
* construct an instance of this provider.
*/
public GcpSecretManagerConnectionStringProvider() {
super("secretmanager-tnsnames", TNS_NAMES_PARAMETERS);
}

/**
* Retrieves a database connection string from the tnsnames.ora file stored
* in GCP Secret Manager.
* <p>
* This method accesses the file in GCP Secret Manager, detects if the content
* is base64-encoded, and decodes it if necessary. The tnsnames.ora content is
* then parsed to locate the connection string associated with the specified
* alias.
* </p>
*
* @param parameterValues The parameters required to access the tnsnames.ora
* file in GCP Secret Manager, including the secret name and the tns-alias.
* @return The connection string associated with the specified alias
* in the tnsnames.ora file.
* @throws IllegalStateException If there is an error reading the tnsnames.ora
* file or accessing the GCP Secret Manager.
* @throws IllegalArgumentException If the specified alias is invalid or
* does not exist in the tnsnames.ora file.
*/
@Override
public String getConnectionString(Map<Parameter, CharSequence> parameterValues) {

byte[] fileBytes = getSecret(parameterValues).toByteArray();

if (FileUtils.isBase64Encoded(fileBytes)) {
fileBytes = Base64.getDecoder().decode(fileBytes);
}

TNSNames tnsNames;
try (InputStream inputStream = new ByteArrayInputStream(fileBytes)) {
tnsNames = TNSNames.read(inputStream);
} catch (IOException e) {
throw new IllegalStateException("Failed to read tnsnames.ora content", e);
}

String alias;
try {
alias = parseParameterValues(parameterValues).getRequired(TNS_ALIAS);
} catch (IllegalStateException e) {
throw new IllegalArgumentException(
"Required parameter 'tnsAlias' is missing", e
);
}

String connectionString = tnsNames.getConnectionStringByAlias(alias);
if (connectionString == null) {
throw new IllegalArgumentException(
"Alias specified does not exist in tnsnames.ora: " + alias
);
}
return connectionString;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

import oracle.jdbc.provider.parameter.ParameterSet;
import oracle.jdbc.provider.resource.ResourceParameter;
import oracle.jdbc.provider.util.FileUtils;
import oracle.jdbc.provider.util.WalletUtils;
import oracle.jdbc.spi.PasswordProvider;
import oracle.jdbc.spi.UsernameProvider;
Expand Down Expand Up @@ -114,7 +115,7 @@ private WalletUtils.Credentials getWalletCredentials(

byte[] walletBytes = getSecret(parameterValues).toByteArray();

if (WalletUtils.isBase64Encoded(walletBytes)) {
if (FileUtils.isBase64Encoded(walletBytes)) {
walletBytes = Base64.getDecoder().decode(walletBytes);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@

import oracle.jdbc.provider.parameter.ParameterSet;
import oracle.jdbc.provider.resource.ResourceParameter;
import oracle.jdbc.provider.util.FileUtils;
import oracle.jdbc.provider.util.TlsUtils;
import oracle.jdbc.provider.util.WalletUtils;
import oracle.jdbc.spi.TlsConfigurationProvider;

import javax.net.ssl.SSLContext;
Expand Down Expand Up @@ -113,7 +113,7 @@ public SSLContext getSSLContext(Map<Parameter, CharSequence> parameterValues) {

byte[] fileBytes = getSecret(parameterValues).toByteArray();

if (WalletUtils.isBase64Encoded(fileBytes)) {
if (FileUtils.isBase64Encoded(fileBytes)) {
fileBytes = Base64.getDecoder().decode(fileBytes);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
oracle.jdbc.provider.gcp.resource.GcpSecretManagerConnectionStringProvider
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,11 @@ public enum GcpTestProperty {

GCP_SSO_SEPS_SECRET_VERSION_NAME,

GCP_CORRUPTED_SEPS_WALLET_SECRET_VERSION_NAME;
GCP_CORRUPTED_SEPS_WALLET_SECRET_VERSION_NAME,

GCP_SECRET_MANAGER_TNS_NAMES_SECRET_VERSION,

GCP_SECRET_MANAGER_TNS_ALIAS_SECRET_NAME,

GCP_NON_BASE64_TNS_NAMES_SECRET_VERSION;
}
Loading

0 comments on commit a2946e7

Please sign in to comment.