This is an automated email from the ASF dual-hosted git repository.
duanzhengqiang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git
The following commit(s) were added to refs/heads/master by this push:
new f57d4122e67 Remove OpenGaussAuthenticationHandler (#24199)
f57d4122e67 is described below
commit f57d4122e67ef955f925a44bbbe4695cb7366332
Author: Liang Zhang <[email protected]>
AuthorDate: Thu Feb 16 22:45:35 2023 +0800
Remove OpenGaussAuthenticationHandler (#24199)
* Remove OpenGaussAuthenticationHandler
* Remove OpenGaussAuthenticationHandler
---
.../plugin/PluginLifecycleServiceManagerTest.java | 3 +-
.../OpenGaussAuthenticationSCRAMSha256Packet.java | 76 ++++++++++-
...enGaussAuthenticationSCRAMSha256PacketTest.java | 24 ++--
.../OpenGaussAuthenticationEngine.java | 59 ++++----
.../OpenGaussAuthenticationHandler.java | 149 ---------------------
.../OpenGaussAuthenticationEngineTest.java | 27 ++--
.../OpenGaussAuthenticationHandlerTest.java | 149 ---------------------
.../fixture/OpenGaussAuthenticationAlgorithm.java | 14 +-
.../PostgreSQLAuthenticationEngine.java | 7 +-
9 files changed, 138 insertions(+), 370 deletions(-)
diff --git
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/plugin/PluginLifecycleServiceManagerTest.java
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/plugin/PluginLifecycleServiceManagerTest.java
index d662e7984d6..7df5a5cf430 100644
---
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/plugin/PluginLifecycleServiceManagerTest.java
+++
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/plugin/PluginLifecycleServiceManagerTest.java
@@ -52,7 +52,8 @@ public final class PluginLifecycleServiceManagerTest {
URLStreamHandlerFactory urlStreamHandlerFactory =
mock(URLStreamHandlerFactory.class);
PluginLifecycleServiceManager.init(Collections.emptyMap(),
Collections.emptyList(),
new PrivateMLet(new
URL[]{Paths.get(System.getProperty("java.io.tmpdir"),
"test.txt").toUri().toURL()},
- new
MultipleParentClassLoader(Collections.emptyList()), urlStreamHandlerFactory,
true), true);
+ new
MultipleParentClassLoader(Collections.emptyList()), urlStreamHandlerFactory,
true),
+ true);
verify(urlStreamHandlerFactory).createURLStreamHandler(anyString());
}
}
diff --git
a/db-protocol/opengauss/src/main/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256Packet.java
b/db-protocol/opengauss/src/main/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256Packet.java
index e7f8344e9a7..3dc1c6b8385 100644
---
a/db-protocol/opengauss/src/main/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256Packet.java
+++
b/db-protocol/opengauss/src/main/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256Packet.java
@@ -17,17 +17,34 @@
package org.apache.shardingsphere.db.protocol.opengauss.packet.authentication;
+import lombok.SneakyThrows;
import
org.apache.shardingsphere.db.protocol.opengauss.constant.OpenGaussProtocolVersion;
import
org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLIdentifierPacket;
import
org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLIdentifierTag;
import
org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLMessagePacketType;
import
org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;
+import javax.crypto.Mac;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.util.Locale;
+
/**
* Authentication request SCRAM SHA-256 for openGauss.
*/
public final class OpenGaussAuthenticationSCRAMSha256Packet implements
PostgreSQLIdentifierPacket {
+ private static final String PBKDF2_WITH_HMAC_SHA1_ALGORITHM =
"PBKDF2WithHmacSHA1";
+
+ private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
+
+ private static final String SERVER_KEY = "Server Key";
+
private static final int AUTH_REQ_SHA256 = 10;
private static final int PASSWORD_STORED_METHOD_SHA256 = 2;
@@ -42,14 +59,69 @@ public final class OpenGaussAuthenticationSCRAMSha256Packet
implements PostgreSQ
private final int serverIteration;
- public OpenGaussAuthenticationSCRAMSha256Packet(final
OpenGaussAuthenticationHexData authHexData, final int version, final byte[]
serverSignature, final int serverIteration) {
+ public OpenGaussAuthenticationSCRAMSha256Packet(final String password,
final OpenGaussAuthenticationHexData authHexData, final int version, final int
serverIteration) {
random64Code = authHexData.getSalt().getBytes();
token = authHexData.getNonce().getBytes();
this.version = version;
- this.serverSignature = serverSignature;
+ serverSignature = (version >=
OpenGaussProtocolVersion.PROTOCOL_350.getVersion() ? "" :
calculateServerSignature(password, authHexData, serverIteration)).getBytes();
this.serverIteration = serverIteration;
}
+ private static String calculateServerSignature(final String password,
final OpenGaussAuthenticationHexData authHexData, final int serverIteration) {
+ byte[] k = generateKFromPBKDF2(password, authHexData.getSalt(),
serverIteration);
+ byte[] serverKey = getKeyFromHmac(k,
SERVER_KEY.getBytes(StandardCharsets.UTF_8));
+ byte[] result = getKeyFromHmac(serverKey,
hexStringToBytes(authHexData.getNonce()));
+ return bytesToHexString(result);
+ }
+
+ @SneakyThrows({NoSuchAlgorithmException.class,
InvalidKeySpecException.class})
+ private static byte[] generateKFromPBKDF2(final String password, final
String saltString, final int serverIteration) {
+ char[] chars = password.toCharArray();
+ byte[] salt = hexStringToBytes(saltString);
+ PBEKeySpec spec = new PBEKeySpec(chars, salt, serverIteration, 32 * 8);
+ SecretKeyFactory skf =
SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1_ALGORITHM);
+ return skf.generateSecret(spec).getEncoded();
+ }
+
+ private static byte[] hexStringToBytes(final String rawHexString) {
+ if (null == rawHexString || rawHexString.isEmpty()) {
+ return new byte[0];
+ }
+ String hexString = rawHexString.toUpperCase(Locale.ENGLISH);
+ int length = hexString.length() / 2;
+ char[] hexChars = hexString.toCharArray();
+ byte[] result = new byte[length];
+ for (int i = 0; i < length; i++) {
+ int pos = i * 2;
+ result[i] = (byte) (charToByte(hexChars[pos]) << 4 |
charToByte(hexChars[pos + 1]));
+ }
+ return result;
+ }
+
+ private static byte charToByte(final char c) {
+ return (byte) "0123456789ABCDEF".indexOf(c);
+ }
+
+ @SneakyThrows({NoSuchAlgorithmException.class, InvalidKeyException.class})
+ private static byte[] getKeyFromHmac(final byte[] key, final byte[] data) {
+ SecretKeySpec signingKey = new SecretKeySpec(key,
HMAC_SHA256_ALGORITHM);
+ Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
+ mac.init(signingKey);
+ return mac.doFinal(data);
+ }
+
+ private static String bytesToHexString(final byte[] src) {
+ StringBuilder result = new StringBuilder();
+ for (byte each : src) {
+ String hex = Integer.toHexString(each & 255);
+ if (hex.length() < 2) {
+ result.append(0);
+ }
+ result.append(hex);
+ }
+ return result.toString();
+ }
+
@Override
public void write(final PostgreSQLPacketPayload payload) {
payload.writeInt4(AUTH_REQ_SHA256);
diff --git
a/db-protocol/opengauss/src/test/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256PacketTest.java
b/db-protocol/opengauss/src/test/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256PacketTest.java
index 18ac55084c0..043b9d23580 100644
---
a/db-protocol/opengauss/src/test/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256PacketTest.java
+++
b/db-protocol/opengauss/src/test/java/org/apache/shardingsphere/db/protocol/opengauss/packet/authentication/OpenGaussAuthenticationSCRAMSha256PacketTest.java
@@ -18,60 +18,52 @@
package org.apache.shardingsphere.db.protocol.opengauss.packet.authentication;
import
org.apache.shardingsphere.db.protocol.opengauss.constant.OpenGaussProtocolVersion;
-import
org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLMessagePacketType;
import
org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;
import org.junit.Test;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public final class OpenGaussAuthenticationSCRAMSha256PacketTest {
private final OpenGaussAuthenticationHexData authHexData = new
OpenGaussAuthenticationHexData();
- private final byte[] serverSignature = new byte[64];
-
@Test
public void assertWriteProtocol300Packet() {
PostgreSQLPacketPayload payload = mock(PostgreSQLPacketPayload.class);
- OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet(authHexData,
OpenGaussProtocolVersion.PROTOCOL_350.getVersion() - 1, serverSignature, 2048);
+ OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet("", authHexData,
OpenGaussProtocolVersion.PROTOCOL_350.getVersion() - 1, 2048);
packet.write(payload);
verify(payload).writeInt4(10);
verify(payload).writeInt4(2);
verify(payload).writeBytes(authHexData.getSalt().getBytes());
verify(payload).writeBytes(authHexData.getNonce().getBytes());
- verify(payload).writeBytes(serverSignature);
+ verify(payload, times(3)).writeBytes(any());
}
@Test
public void assertWriteProtocol350Packet() {
PostgreSQLPacketPayload payload = mock(PostgreSQLPacketPayload.class);
- OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet(authHexData,
OpenGaussProtocolVersion.PROTOCOL_350.getVersion(), serverSignature, 2048);
+ OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet("", authHexData,
OpenGaussProtocolVersion.PROTOCOL_350.getVersion(), 2048);
packet.write(payload);
verify(payload).writeInt4(10);
verify(payload).writeInt4(2);
verify(payload).writeBytes(authHexData.getSalt().getBytes());
verify(payload).writeBytes(authHexData.getNonce().getBytes());
+ verify(payload, times(2)).writeBytes(any());
}
@Test
public void assertWriteProtocol351Packet() {
PostgreSQLPacketPayload payload = mock(PostgreSQLPacketPayload.class);
- OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet(authHexData,
OpenGaussProtocolVersion.PROTOCOL_351.getVersion(), serverSignature, 10000);
+ OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet("", authHexData,
OpenGaussProtocolVersion.PROTOCOL_351.getVersion(), 10000);
packet.write(payload);
verify(payload).writeInt4(10);
verify(payload).writeInt4(2);
verify(payload).writeBytes(authHexData.getSalt().getBytes());
verify(payload).writeBytes(authHexData.getNonce().getBytes());
verify(payload).writeInt4(10000);
- }
-
- @Test
- public void assertIdentifierTag() {
- OpenGaussAuthenticationSCRAMSha256Packet packet = new
OpenGaussAuthenticationSCRAMSha256Packet(
- new OpenGaussAuthenticationHexData(),
OpenGaussProtocolVersion.PROTOCOL_351.getVersion(), serverSignature, 10000);
- assertThat(packet.getIdentifier(),
is(PostgreSQLMessagePacketType.AUTHENTICATION_REQUEST));
+ verify(payload, times(2)).writeBytes(any());
}
}
diff --git
a/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngine.java
b/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngine.java
index 0481467d2c5..5906847d93e 100644
---
a/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngine.java
+++
b/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngine.java
@@ -19,6 +19,7 @@ package
org.apache.shardingsphere.proxy.frontend.opengauss.authentication;
import com.google.common.base.Strings;
import io.netty.channel.ChannelHandlerContext;
+import org.apache.shardingsphere.authority.checker.AuthorityChecker;
import org.apache.shardingsphere.authority.rule.AuthorityRule;
import org.apache.shardingsphere.db.protocol.constant.CommonConstants;
import
org.apache.shardingsphere.db.protocol.opengauss.constant.OpenGaussProtocolVersion;
@@ -34,16 +35,25 @@ import
org.apache.shardingsphere.db.protocol.postgresql.packet.handshake.Postgre
import
org.apache.shardingsphere.db.protocol.postgresql.packet.handshake.PostgreSQLSSLNegativePacket;
import
org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLMessagePacketType;
import
org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;
+import
org.apache.shardingsphere.dialect.exception.syntax.database.UnknownDatabaseException;
import
org.apache.shardingsphere.dialect.postgresql.exception.authority.EmptyUsernameException;
+import
org.apache.shardingsphere.dialect.postgresql.exception.authority.InvalidPasswordException;
+import
org.apache.shardingsphere.dialect.postgresql.exception.authority.PrivilegeNotGrantedException;
+import
org.apache.shardingsphere.dialect.postgresql.exception.authority.UnknownUsernameException;
import
org.apache.shardingsphere.dialect.postgresql.exception.protocol.ProtocolViolationException;
import org.apache.shardingsphere.infra.metadata.user.Grantee;
import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser;
+import
org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import
org.apache.shardingsphere.proxy.backend.handler.admin.postgresql.PostgreSQLCharacterSets;
import
org.apache.shardingsphere.proxy.frontend.authentication.AuthenticationEngine;
import
org.apache.shardingsphere.proxy.frontend.authentication.AuthenticationResult;
import
org.apache.shardingsphere.proxy.frontend.authentication.AuthenticationResultBuilder;
+import
org.apache.shardingsphere.proxy.frontend.authentication.AuthenticatorFactory;
import
org.apache.shardingsphere.proxy.frontend.connection.ConnectionIdGenerator;
+import
org.apache.shardingsphere.proxy.frontend.opengauss.authentication.authenticator.OpenGaussAuthenticatorType;
+
+import java.util.Optional;
/**
* Authentication engine for openGauss.
@@ -56,10 +66,10 @@ public final class OpenGaussAuthenticationEngine implements
AuthenticationEngine
private static final int SSL_REQUEST_CODE = 80877103;
- private static final int PROTOCOL_351_SERVER_ITERATOR = 10000;
-
private static final int PROTOCOL_350_SERVER_ITERATOR = 2048;
+ private static final int PROTOCOL_351_SERVER_ITERATOR = 10000;
+
private final OpenGaussAuthenticationHexData authHexData = new
OpenGaussAuthenticationHexData();
private boolean startupMessageReceived;
@@ -82,16 +92,16 @@ public final class OpenGaussAuthenticationEngine implements
AuthenticationEngine
return AuthenticationResultBuilder.continued();
}
payload.getByteBuf().resetReaderIndex();
- return startupMessageReceived ? processPasswordMessage(context,
(PostgreSQLPacketPayload) payload) : processStartupMessage(context,
(PostgreSQLPacketPayload) payload);
+ AuthorityRule rule =
ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class);
+ return startupMessageReceived ? processPasswordMessage(context,
(PostgreSQLPacketPayload) payload, rule) : processStartupMessage(context,
(PostgreSQLPacketPayload) payload, rule);
}
- private AuthenticationResult processPasswordMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload) {
+ private AuthenticationResult processPasswordMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload, final
AuthorityRule rule) {
char messageType = (char) payload.readInt1();
- if (PostgreSQLMessagePacketType.PASSWORD_MESSAGE.getValue() !=
messageType) {
- throw new ProtocolViolationException("password",
Character.toString(messageType));
- }
+
ShardingSpherePreconditions.checkState(PostgreSQLMessagePacketType.PASSWORD_MESSAGE.getValue()
== messageType,
+ () -> new ProtocolViolationException("password",
Character.toString(messageType)));
PostgreSQLPasswordMessagePacket passwordMessagePacket = new
PostgreSQLPasswordMessagePacket(payload);
-
OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(currentAuthResult.getUsername(),
currentAuthResult.getDatabase(), authHexData, serverIteration,
passwordMessagePacket);
+ login(rule, passwordMessagePacket.getDigest());
context.write(new PostgreSQLAuthenticationOKPacket());
context.write(new PostgreSQLParameterStatusPacket("server_version",
PostgreSQLServerInfo.getServerVersion()));
context.write(new PostgreSQLParameterStatusPacket("client_encoding",
clientEncoding));
@@ -101,28 +111,29 @@ public final class OpenGaussAuthenticationEngine
implements AuthenticationEngine
return
AuthenticationResultBuilder.finished(currentAuthResult.getUsername(), "",
currentAuthResult.getDatabase());
}
- private AuthenticationResult processStartupMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload) {
+ private void login(final AuthorityRule rule, final String digest) {
+ String username = currentAuthResult.getUsername();
+ String databaseName = currentAuthResult.getDatabase();
+
ShardingSpherePreconditions.checkState(Strings.isNullOrEmpty(databaseName) ||
ProxyContext.getInstance().databaseExists(databaseName), () -> new
UnknownDatabaseException(databaseName));
+ Grantee grantee = new Grantee(username, "%");
+ Optional<ShardingSphereUser> user = rule.findUser(grantee);
+ ShardingSpherePreconditions.checkState(user.isPresent(), () -> new
UnknownUsernameException(username));
+ ShardingSpherePreconditions.checkState(new
AuthenticatorFactory<>(OpenGaussAuthenticatorType.class,
rule).newInstance(user.get())
+ .authenticate(user.get(), new Object[]{digest,
authHexData.getSalt(), authHexData.getNonce(), serverIteration}), () -> new
InvalidPasswordException(username));
+ ShardingSpherePreconditions.checkState(null == databaseName || new
AuthorityChecker(rule, grantee).isAuthorized(databaseName), () -> new
PrivilegeNotGrantedException(username, databaseName));
+ }
+
+ private AuthenticationResult processStartupMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload, final
AuthorityRule rule) {
startupMessageReceived = true;
PostgreSQLComStartupPacket startupPacket = new
PostgreSQLComStartupPacket(payload);
clientEncoding = startupPacket.getClientEncoding();
context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).set(PostgreSQLCharacterSets.findCharacterSet(clientEncoding));
String username = startupPacket.getUsername();
- if (Strings.isNullOrEmpty(username)) {
- throw new EmptyUsernameException();
- }
- serverIteration = startupPacket.getVersion() ==
OpenGaussProtocolVersion.PROTOCOL_351.getVersion() ?
PROTOCOL_351_SERVER_ITERATOR : PROTOCOL_350_SERVER_ITERATOR;
- String serverSignature =
calculateServerSignature(startupPacket.getVersion(), username);
- context.writeAndFlush(new
OpenGaussAuthenticationSCRAMSha256Packet(authHexData,
startupPacket.getVersion(), serverSignature.getBytes(), serverIteration));
+
ShardingSpherePreconditions.checkState(!Strings.isNullOrEmpty(username),
EmptyUsernameException::new);
+ serverIteration = startupPacket.getVersion() ==
OpenGaussProtocolVersion.PROTOCOL_350.getVersion() ?
PROTOCOL_350_SERVER_ITERATOR : PROTOCOL_351_SERVER_ITERATOR;
+ String password = rule.findUser(new Grantee(username,
"%")).map(ShardingSphereUser::getPassword).orElse("");
+ context.writeAndFlush(new
OpenGaussAuthenticationSCRAMSha256Packet(password, authHexData,
startupPacket.getVersion(), serverIteration));
currentAuthResult = AuthenticationResultBuilder.continued(username,
"", startupPacket.getDatabase());
return currentAuthResult;
}
-
- private String calculateServerSignature(final int version, final String
username) {
- if (version >= OpenGaussProtocolVersion.PROTOCOL_350.getVersion()) {
- return "";
- }
- AuthorityRule authorityRule =
ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class);
- String password = authorityRule.findUser(new Grantee(username,
"%")).map(ShardingSphereUser::getPassword).orElse("");
- return
OpenGaussAuthenticationHandler.calculateServerSignature(password, authHexData,
serverIteration);
- }
}
diff --git
a/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationHandler.java
b/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationHandler.java
deleted file mode 100644
index 368eb80edb7..00000000000
---
a/proxy/frontend/opengauss/src/main/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationHandler.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * 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.apache.shardingsphere.proxy.frontend.opengauss.authentication;
-
-import com.google.common.base.Strings;
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-import lombok.SneakyThrows;
-import org.apache.shardingsphere.authority.checker.AuthorityChecker;
-import org.apache.shardingsphere.authority.rule.AuthorityRule;
-import
org.apache.shardingsphere.db.protocol.opengauss.packet.authentication.OpenGaussAuthenticationHexData;
-import
org.apache.shardingsphere.db.protocol.postgresql.packet.handshake.PostgreSQLPasswordMessagePacket;
-import
org.apache.shardingsphere.dialect.exception.syntax.database.UnknownDatabaseException;
-import
org.apache.shardingsphere.dialect.postgresql.exception.authority.InvalidPasswordException;
-import
org.apache.shardingsphere.dialect.postgresql.exception.authority.PrivilegeNotGrantedException;
-import
org.apache.shardingsphere.dialect.postgresql.exception.authority.UnknownUsernameException;
-import org.apache.shardingsphere.infra.metadata.user.Grantee;
-import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser;
-import
org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;
-import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
-import
org.apache.shardingsphere.proxy.frontend.authentication.AuthenticatorFactory;
-import
org.apache.shardingsphere.proxy.frontend.opengauss.authentication.authenticator.OpenGaussAuthenticatorType;
-
-import javax.crypto.Mac;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.PBEKeySpec;
-import javax.crypto.spec.SecretKeySpec;
-import java.nio.charset.StandardCharsets;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.spec.InvalidKeySpecException;
-import java.util.Locale;
-import java.util.Optional;
-
-/**
- * Authentication handler for openGauss.
- *
- * @see <a
href="https://opengauss.org/zh/blogs/blogs.html?post/douxin/sm3_for_opengauss/">SM3
for openGauss</a>
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class OpenGaussAuthenticationHandler {
-
- private static final String PBKDF2_WITH_HMAC_SHA1_ALGORITHM =
"PBKDF2WithHmacSHA1";
-
- private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
-
- private static final String SERVER_KEY = "Server Key";
-
- /**
- * Login with SCRAM SHA-256 password.
- *
- * @param username username
- * @param databaseName database name
- * @param authHexData authentication hex data
- * @param serverIteration server iteration
- * @param passwordMessagePacket password message packet
- */
- public static void loginWithSCRAMSha256Password(final String username,
final String databaseName, final OpenGaussAuthenticationHexData authHexData,
final int serverIteration,
- final
PostgreSQLPasswordMessagePacket passwordMessagePacket) {
-
ShardingSpherePreconditions.checkState(Strings.isNullOrEmpty(databaseName) ||
ProxyContext.getInstance().databaseExists(databaseName), () -> new
UnknownDatabaseException(databaseName));
- AuthorityRule rule =
ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class);
- Grantee grantee = new Grantee(username, "%");
- Optional<ShardingSphereUser> user = rule.findUser(grantee);
- ShardingSpherePreconditions.checkState(user.isPresent(), () -> new
UnknownUsernameException(username));
- ShardingSpherePreconditions.checkState(new
AuthenticatorFactory<>(OpenGaussAuthenticatorType.class,
rule).newInstance(user.get())
- .authenticate(user.get(), new
Object[]{passwordMessagePacket.getDigest(), authHexData.getSalt(),
authHexData.getNonce(), serverIteration}),
- () -> new InvalidPasswordException(username));
- ShardingSpherePreconditions.checkState(null == databaseName || new
AuthorityChecker(rule, grantee).isAuthorized(databaseName),
- () -> new PrivilegeNotGrantedException(username,
databaseName));
- }
-
- /**
- * Calculate server signature.
- *
- * @param password password
- * @param authHexData authentication hex data
- * @param serverIteration server iteration
- * @return server signature
- */
- public static String calculateServerSignature(final String password, final
OpenGaussAuthenticationHexData authHexData, final int serverIteration) {
- byte[] k = generateKFromPBKDF2(password, authHexData.getSalt(),
serverIteration);
- byte[] serverKey = getKeyFromHmac(k,
SERVER_KEY.getBytes(StandardCharsets.UTF_8));
- byte[] result = getKeyFromHmac(serverKey,
hexStringToBytes(authHexData.getNonce()));
- return bytesToHexString(result);
- }
-
- @SneakyThrows({NoSuchAlgorithmException.class,
InvalidKeySpecException.class})
- private static byte[] generateKFromPBKDF2(final String password, final
String saltString, final int serverIteration) {
- char[] chars = password.toCharArray();
- byte[] salt = hexStringToBytes(saltString);
- PBEKeySpec spec = new PBEKeySpec(chars, salt, serverIteration, 32 * 8);
- SecretKeyFactory skf =
SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1_ALGORITHM);
- return skf.generateSecret(spec).getEncoded();
- }
-
- private static byte[] hexStringToBytes(final String rawHexString) {
- if (null == rawHexString || rawHexString.isEmpty()) {
- return new byte[0];
- }
- String hexString = rawHexString.toUpperCase(Locale.ENGLISH);
- int length = hexString.length() / 2;
- char[] hexChars = hexString.toCharArray();
- byte[] result = new byte[length];
- for (int i = 0; i < length; i++) {
- int pos = i * 2;
- result[i] = (byte) (charToByte(hexChars[pos]) << 4 |
charToByte(hexChars[pos + 1]));
- }
- return result;
- }
-
- private static byte charToByte(final char c) {
- return (byte) "0123456789ABCDEF".indexOf(c);
- }
-
- @SneakyThrows({NoSuchAlgorithmException.class, InvalidKeyException.class})
- private static byte[] getKeyFromHmac(final byte[] key, final byte[] data) {
- SecretKeySpec signingKey = new SecretKeySpec(key,
HMAC_SHA256_ALGORITHM);
- Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
- mac.init(signingKey);
- return mac.doFinal(data);
- }
-
- private static String bytesToHexString(final byte[] src) {
- StringBuilder result = new StringBuilder();
- for (byte each : src) {
- String hex = Integer.toHexString(each & 255);
- if (hex.length() < 2) {
- result.append(0);
- }
- result.append(hex);
- }
- return result.toString();
- }
-}
diff --git
a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngineTest.java
b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngineTest.java
index 496e5a303ee..c887f7ba991 100644
---
a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngineTest.java
+++
b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationEngineTest.java
@@ -24,7 +24,6 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import lombok.SneakyThrows;
import org.apache.shardingsphere.authority.config.AuthorityRuleConfiguration;
-import org.apache.shardingsphere.authority.rule.AuthorityRule;
import org.apache.shardingsphere.authority.rule.builder.AuthorityRuleBuilder;
import org.apache.shardingsphere.db.protocol.constant.CommonConstants;
import
org.apache.shardingsphere.db.protocol.opengauss.packet.authentication.OpenGaussAuthenticationSCRAMSha256Packet;
@@ -56,7 +55,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
-import java.util.LinkedHashMap;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
@@ -80,9 +78,19 @@ public final class OpenGaussAuthenticationEngineTest extends
ProxyContextRestore
@SuppressWarnings("unchecked")
@Before
public void setup() {
+ MetaDataContexts metaDataContexts = new
MetaDataContexts(mock(MetaDataPersistService.class),
+ new ShardingSphereMetaData(Collections.emptyMap(),
buildGlobalRuleMetaData(new ShardingSphereUser(username, password, "")),
mock(ConfigurationProperties.class)));
+ ContextManager contextManager = mock(ContextManager.class,
RETURNS_DEEP_STUBS);
+
when(contextManager.getMetaDataContexts()).thenReturn(metaDataContexts);
+ ProxyContext.init(contextManager);
when(channelHandlerContext.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY)).thenReturn(mock(Attribute.class));
}
+ private ShardingSphereRuleMetaData buildGlobalRuleMetaData(final
ShardingSphereUser user) {
+ AuthorityRuleConfiguration ruleConfig = new
AuthorityRuleConfiguration(Collections.singleton(user), new
AlgorithmConfiguration("ALL_PERMITTED", new Properties()), null);
+ return new ShardingSphereRuleMetaData(Collections.singleton(new
AuthorityRuleBuilder().build(ruleConfig, Collections.emptyMap(),
mock(ConfigurationProperties.class))));
+ }
+
@Test
public void assertSSLNegative() {
ByteBuf byteBuf = createByteBuf(8, 8);
@@ -129,10 +137,6 @@ public final class OpenGaussAuthenticationEngineTest
extends ProxyContextRestore
}
private void assertLogin(final String inputPassword) {
- MetaDataContexts metaDataContexts = getMetaDataContexts(new
ShardingSphereUser(username, password, ""));
- ContextManager contextManager = mock(ContextManager.class,
RETURNS_DEEP_STUBS);
-
when(contextManager.getMetaDataContexts()).thenReturn(metaDataContexts);
- ProxyContext.init(contextManager);
PostgreSQLPacketPayload payload = new
PostgreSQLPacketPayload(createByteBuf(16, 128), StandardCharsets.UTF_8);
payload.writeInt4(64);
payload.writeInt4(196608);
@@ -163,17 +167,6 @@ public final class OpenGaussAuthenticationEngineTest
extends ProxyContextRestore
return new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT,
initialCapacity, maxCapacity);
}
- private MetaDataContexts getMetaDataContexts(final ShardingSphereUser
user) {
- return new MetaDataContexts(mock(MetaDataPersistService.class),
- new ShardingSphereMetaData(new LinkedHashMap<>(),
buildGlobalRuleMetaData(user), new ConfigurationProperties(new Properties())));
- }
-
- private ShardingSphereRuleMetaData buildGlobalRuleMetaData(final
ShardingSphereUser user) {
- AuthorityRuleConfiguration ruleConfig = new
AuthorityRuleConfiguration(Collections.singletonList(user), new
AlgorithmConfiguration("ALL_PERMITTED", new Properties()), null);
- AuthorityRule rule = new AuthorityRuleBuilder().build(ruleConfig,
Collections.emptyMap(), mock(ConfigurationProperties.class));
- return new ShardingSphereRuleMetaData(Collections.singletonList(rule));
- }
-
@SneakyThrows(ReflectiveOperationException.class)
private byte[] getRandom64Code(final
OpenGaussAuthenticationSCRAMSha256Packet packet) {
return (byte[])
Plugins.getMemberAccessor().get(OpenGaussAuthenticationSCRAMSha256Packet.class.getDeclaredField("random64Code"),
packet);
diff --git
a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationHandlerTest.java
b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationHandlerTest.java
deleted file mode 100644
index 18b943ca28b..00000000000
---
a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/OpenGaussAuthenticationHandlerTest.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * 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.apache.shardingsphere.proxy.frontend.opengauss.authentication;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.UnpooledByteBufAllocator;
-import io.netty.buffer.UnpooledHeapByteBuf;
-import org.apache.shardingsphere.authority.config.AuthorityRuleConfiguration;
-import org.apache.shardingsphere.authority.rule.AuthorityRule;
-import org.apache.shardingsphere.authority.rule.builder.AuthorityRuleBuilder;
-import
org.apache.shardingsphere.db.protocol.opengauss.packet.authentication.OpenGaussAuthenticationHexData;
-import
org.apache.shardingsphere.db.protocol.postgresql.packet.handshake.PostgreSQLPasswordMessagePacket;
-import
org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;
-import
org.apache.shardingsphere.dialect.exception.syntax.database.UnknownDatabaseException;
-import
org.apache.shardingsphere.dialect.postgresql.exception.authority.InvalidPasswordException;
-import
org.apache.shardingsphere.dialect.postgresql.exception.authority.UnknownUsernameException;
-import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
-import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
-import org.apache.shardingsphere.infra.database.DefaultDatabase;
-import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
-import
org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
-import
org.apache.shardingsphere.infra.metadata.database.resource.ShardingSphereResourceMetaData;
-import
org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;
-import
org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
-import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser;
-import org.apache.shardingsphere.mode.manager.ContextManager;
-import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
-import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
-import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
-import org.apache.shardingsphere.proxy.frontend.opengauss.ProxyContextRestorer;
-import
org.apache.shardingsphere.proxy.frontend.opengauss.authentication.fixture.OpenGaussAuthenticationAlgorithm;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public final class OpenGaussAuthenticationHandlerTest extends
ProxyContextRestorer {
-
- private static final String SCHEMA_PATTERN = "schema_%s";
-
- private final String username = "gaussdb";
-
- private final String password = "P@ssw0rd";
-
- private final String database = "schema_0";
-
- private final OpenGaussAuthenticationHexData authHexData = new
OpenGaussAuthenticationHexData();
-
- private final int serverIteration = 2048;
-
- private PostgreSQLPasswordMessagePacket passwordMessagePacket;
-
- @Before
- public void init() {
- PostgreSQLPacketPayload payload = new
PostgreSQLPacketPayload(createByteBuf(16, 128), StandardCharsets.UTF_8);
- String digest = encodeDigest(password, serverIteration);
- payload.writeInt4(4 + digest.length() + 1);
- payload.writeStringNul(digest);
- passwordMessagePacket = new PostgreSQLPasswordMessagePacket(payload);
- }
-
- @Test
- public void assertLoginSuccess() {
- initProxyContext(new ShardingSphereUser(username, password, "%"));
- OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(username,
database, authHexData, serverIteration, passwordMessagePacket);
- }
-
- @Test(expected = UnknownUsernameException.class)
- public void assertLoginWithAbsentUser() {
- initProxyContext(new ShardingSphereUser("username", password, "%"));
- OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(username,
database, authHexData, serverIteration, passwordMessagePacket);
- }
-
- @Test(expected = InvalidPasswordException.class)
- public void assertLoginWithIncorrectPassword() {
- initProxyContext(new ShardingSphereUser(username, "password", "%"));
- OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(username,
database, authHexData, serverIteration, passwordMessagePacket);
- }
-
- @Test(expected = UnknownDatabaseException.class)
- public void assertLoginWithNonExistDatabase() {
- initProxyContext(new ShardingSphereUser(username, password, "%"));
- String database = "non_exist_database";
- OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(username,
database, authHexData, serverIteration, passwordMessagePacket);
- }
-
- private void initProxyContext(final ShardingSphereUser user) {
- ContextManager contextManager = mock(ContextManager.class,
RETURNS_DEEP_STUBS);
- MetaDataContexts metaDataContexts = getMetaDataContexts(user);
-
when(contextManager.getMetaDataContexts()).thenReturn(metaDataContexts);
- ProxyContext.init(contextManager);
- }
-
- private MetaDataContexts getMetaDataContexts(final ShardingSphereUser
user) {
- return new MetaDataContexts(mock(MetaDataPersistService.class),
- new ShardingSphereMetaData(getDatabases(),
buildGlobalRuleMetaData(user), new ConfigurationProperties(new Properties())));
- }
-
- private ByteBuf createByteBuf(final int initialCapacity, final int
maxCapacity) {
- return new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT,
initialCapacity, maxCapacity);
- }
-
- private Map<String, ShardingSphereDatabase> getDatabases() {
- Map<String, ShardingSphereDatabase> result = new HashMap<>(10, 1);
- for (int i = 0; i < 10; i++) {
- ShardingSphereDatabase database =
mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
- ShardingSphereSchema schema = mock(ShardingSphereSchema.class);
- when(database.getResourceMetaData()).thenReturn(new
ShardingSphereResourceMetaData("sharding_db", Collections.emptyMap()));
- when(database.getRuleMetaData()).thenReturn(new
ShardingSphereRuleMetaData(Collections.emptyList()));
-
when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(schema);
- when(schema.getTables()).thenReturn(Collections.emptyMap());
- result.put(String.format(SCHEMA_PATTERN, i), database);
- }
- return result;
- }
-
- private ShardingSphereRuleMetaData buildGlobalRuleMetaData(final
ShardingSphereUser user) {
- AuthorityRuleConfiguration ruleConfig = new
AuthorityRuleConfiguration(Collections.singletonList(user), new
AlgorithmConfiguration("ALL_PERMITTED", new Properties()), null);
- AuthorityRule rule = new AuthorityRuleBuilder().build(ruleConfig,
Collections.emptyMap(), mock(ConfigurationProperties.class));
- return new ShardingSphereRuleMetaData(Collections.singleton(rule));
- }
-
- private String encodeDigest(final String password, final int
serverIteration) {
- return new
String(OpenGaussAuthenticationAlgorithm.doRFC5802Algorithm(password,
authHexData.getSalt(), authHexData.getNonce(), serverIteration));
- }
-}
diff --git
a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/fixture/OpenGaussAuthenticationAlgorithm.java
b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/fixture/OpenGaussAuthenticationAlgorithm.java
index 85c81996bc6..fdec185ef1b 100644
---
a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/fixture/OpenGaussAuthenticationAlgorithm.java
+++
b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/authentication/fixture/OpenGaussAuthenticationAlgorithm.java
@@ -20,7 +20,7 @@ package
org.apache.shardingsphere.proxy.frontend.opengauss.authentication.fixtur
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
-import
org.apache.shardingsphere.proxy.frontend.opengauss.authentication.OpenGaussAuthenticationHandler;
+import
org.apache.shardingsphere.db.protocol.opengauss.packet.authentication.OpenGaussAuthenticationSCRAMSha256Packet;
import
org.apache.shardingsphere.proxy.frontend.opengauss.authentication.authenticator.impl.OpenGaussSCRAMSha256PasswordAuthenticator;
import org.mockito.internal.configuration.plugins.Plugins;
@@ -52,32 +52,32 @@ public final class OpenGaussAuthenticationAlgorithm {
@SneakyThrows(ReflectiveOperationException.class)
private static byte[] generateKFromPBKDF2(final String password, final
String saltString, final int serverIteration) {
- return (byte[])
Plugins.getMemberAccessor().invoke(OpenGaussAuthenticationHandler.class.getDeclaredMethod("generateKFromPBKDF2",
String.class, String.class, int.class),
- OpenGaussAuthenticationHandler.class, password, saltString,
serverIteration);
+ return (byte[])
Plugins.getMemberAccessor().invoke(OpenGaussAuthenticationSCRAMSha256Packet.class.getDeclaredMethod("generateKFromPBKDF2",
String.class, String.class, int.class),
+ OpenGaussAuthenticationSCRAMSha256Packet.class, password,
saltString, serverIteration);
}
@SneakyThrows(ReflectiveOperationException.class)
private static byte[] getKeyFromHmac(final byte[] key, final byte[] data) {
return (byte[]) Plugins.getMemberAccessor().invoke(
-
OpenGaussAuthenticationHandler.class.getDeclaredMethod("getKeyFromHmac",
byte[].class, byte[].class), OpenGaussAuthenticationHandler.class, key, data);
+
OpenGaussAuthenticationSCRAMSha256Packet.class.getDeclaredMethod("getKeyFromHmac",
byte[].class, byte[].class), OpenGaussAuthenticationSCRAMSha256Packet.class,
key, data);
}
@SneakyThrows(ReflectiveOperationException.class)
private static byte[] sha256(final byte[] str) {
return (byte[]) Plugins.getMemberAccessor().invoke(
-
OpenGaussSCRAMSha256PasswordAuthenticator.class.getDeclaredMethod("sha256",
byte[].class), OpenGaussAuthenticationHandler.class, new Object[]{str});
+
OpenGaussSCRAMSha256PasswordAuthenticator.class.getDeclaredMethod("sha256",
byte[].class), OpenGaussAuthenticationSCRAMSha256Packet.class, new
Object[]{str});
}
@SneakyThrows(ReflectiveOperationException.class)
private static byte[] hexStringToBytes(final String rawHexString) {
return (byte[]) Plugins.getMemberAccessor().invoke(
-
OpenGaussAuthenticationHandler.class.getDeclaredMethod("hexStringToBytes",
String.class), OpenGaussAuthenticationHandler.class, rawHexString);
+
OpenGaussAuthenticationSCRAMSha256Packet.class.getDeclaredMethod("hexStringToBytes",
String.class), OpenGaussAuthenticationSCRAMSha256Packet.class, rawHexString);
}
@SneakyThrows(ReflectiveOperationException.class)
private static byte[] xor(final byte[] value1, final byte[] value2) {
return (byte[]) Plugins.getMemberAccessor().invoke(
-
OpenGaussSCRAMSha256PasswordAuthenticator.class.getDeclaredMethod("xor",
byte[].class, byte[].class), OpenGaussAuthenticationHandler.class, value1,
value2);
+
OpenGaussSCRAMSha256PasswordAuthenticator.class.getDeclaredMethod("xor",
byte[].class, byte[].class), OpenGaussAuthenticationSCRAMSha256Packet.class,
value1, value2);
}
private static void bytesToHex(final byte[] bytes, final byte[] hex, final
int offset, final int length) {
diff --git
a/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngine.java
b/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngine.java
index b6fac60c925..35bfcc2a71d 100644
---
a/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngine.java
+++
b/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngine.java
@@ -124,17 +124,14 @@ public final class PostgreSQLAuthenticationEngine
implements AuthenticationEngin
clientEncoding = startupPacket.getClientEncoding();
context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).set(PostgreSQLCharacterSets.findCharacterSet(clientEncoding));
String username = startupPacket.getUsername();
- if (Strings.isNullOrEmpty(username)) {
- throw new EmptyUsernameException();
- }
+
ShardingSpherePreconditions.checkState(!Strings.isNullOrEmpty(username),
EmptyUsernameException::new);
context.writeAndFlush(getIdentifierPacket(username, rule));
currentAuthResult = AuthenticationResultBuilder.continued(username,
"", startupPacket.getDatabase());
return currentAuthResult;
}
private PostgreSQLIdentifierPacket getIdentifierPacket(final String
username, final AuthorityRule rule) {
- Optional<ShardingSphereUser> user = rule.findUser(new
Grantee(username, ""));
- Optional<Authenticator> authenticator = user.map(optional -> new
AuthenticatorFactory<>(PostgreSQLAuthenticatorType.class,
rule).newInstance(optional));
+ Optional<Authenticator> authenticator = rule.findUser(new
Grantee(username, "")).map(optional -> new
AuthenticatorFactory<>(PostgreSQLAuthenticatorType.class,
rule).newInstance(optional));
if (authenticator.isPresent() &&
PostgreSQLAuthenticationMethod.PASSWORD.getMethodName().equals(authenticator.get().getAuthenticationMethodName()))
{
return new PostgreSQLPasswordAuthenticationPacket();
}