This is an automated email from the ASF dual-hosted git repository.
zhaojinchao 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 8d578015977 Remove PostgreSQLAuthenticationHandler (#24185)
8d578015977 is described below
commit 8d5780159776c252f4ff287fdd73dbedec940895
Author: Liang Zhang <[email protected]>
AuthorDate: Thu Feb 16 07:56:09 2023 +0800
Remove PostgreSQLAuthenticationHandler (#24185)
* Remove PostgreSQLAuthenticationHandler
* Remove PostgreSQLAuthenticationHandler
---
.../handshake/PostgreSQLComStartupPacket.java | 6 +-
.../PostgreSQLPasswordAuthenticationPacket.java | 3 -
.../generic/PostgreSQLComStartupPacketTest.java | 2 +-
.../OpenGaussAuthenticationEngine.java | 50 +++----
.../PostgreSQLAuthenticationEngine.java | 61 +++++----
.../PostgreSQLAuthenticationHandler.java | 62 ---------
.../PostgreSQLAuthenticationEngineTest.java | 14 +-
.../PostgreSQLAuthenticationHandlerTest.java | 148 ---------------------
8 files changed, 73 insertions(+), 273 deletions(-)
diff --git
a/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/PostgreSQLComStartupPacket.java
b/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/PostgreSQLComStartupPacket.java
index bd9986c583c..6f575c20148 100644
---
a/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/PostgreSQLComStartupPacket.java
+++
b/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/PostgreSQLComStartupPacket.java
@@ -58,11 +58,11 @@ public final class PostgreSQLComStartupPacket implements
PostgreSQLPacket {
}
/**
- * Get user.
+ * Get user name.
*
- * @return user
+ * @return username
*/
- public String getUser() {
+ public String getUsername() {
return parametersMap.get(USER_NAME_KEY);
}
diff --git
a/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/authentication/PostgreSQLPasswordAuthenticationPacket.java
b/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/authentication/PostgreSQLPasswordAuthenticationPacket.java
index 46b1d20ef28..db52c61ca53 100644
---
a/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/authentication/PostgreSQLPasswordAuthenticationPacket.java
+++
b/db-protocol/postgresql/src/main/java/org/apache/shardingsphere/db/protocol/postgresql/packet/handshake/authentication/PostgreSQLPasswordAuthenticationPacket.java
@@ -17,7 +17,6 @@
package
org.apache.shardingsphere.db.protocol.postgresql.packet.handshake.authentication;
-import lombok.RequiredArgsConstructor;
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;
@@ -25,9 +24,7 @@ import
org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacket
/**
* Password authentication (backend) packet for PostgreSQL.
- *
*/
-@RequiredArgsConstructor
public final class PostgreSQLPasswordAuthenticationPacket implements
PostgreSQLIdentifierPacket {
private static final int AUTH_REQ_PASSWORD = 3;
diff --git
a/db-protocol/postgresql/src/test/java/org/apache/shardingsphere/db/protocol/postgresql/packet/generic/PostgreSQLComStartupPacketTest.java
b/db-protocol/postgresql/src/test/java/org/apache/shardingsphere/db/protocol/postgresql/packet/generic/PostgreSQLComStartupPacketTest.java
index 3a69f99a759..0558cbf6fc5 100644
---
a/db-protocol/postgresql/src/test/java/org/apache/shardingsphere/db/protocol/postgresql/packet/generic/PostgreSQLComStartupPacketTest.java
+++
b/db-protocol/postgresql/src/test/java/org/apache/shardingsphere/db/protocol/postgresql/packet/generic/PostgreSQLComStartupPacketTest.java
@@ -42,7 +42,7 @@ public final class PostgreSQLComStartupPacketTest {
PostgreSQLPacketPayload payload = createPayload(parametersMap,
packetMessageLength, byteBuf);
PostgreSQLComStartupPacket actual = new
PostgreSQLComStartupPacket(payload);
assertThat(actual.getDatabase(), is("test_db"));
- assertThat(actual.getUser(), is("postgres"));
+ assertThat(actual.getUsername(), is("postgres"));
assertThat(actual.getClientEncoding(), is("UTF8"));
assertThat(byteBuf.writerIndex(), is(packetMessageLength));
}
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 510f9b5d555..39335bcb6ee 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
@@ -100,20 +100,37 @@ public final class OpenGaussAuthenticationEngine
implements AuthenticationEngine
return startupMessageReceived ? processPasswordMessage(context,
(PostgreSQLPacketPayload) payload) : processStartupMessage(context,
(PostgreSQLPacketPayload) payload);
}
+ private AuthenticationResult processPasswordMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload) {
+ char messageType = (char) payload.readInt1();
+ if (PostgreSQLMessagePacketType.PASSWORD_MESSAGE.getValue() !=
messageType) {
+ throw new ProtocolViolationException("password",
Character.toString(messageType));
+ }
+ PostgreSQLPasswordMessagePacket passwordMessagePacket = new
PostgreSQLPasswordMessagePacket(payload);
+
OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(currentAuthResult.getUsername(),
currentAuthResult.getDatabase(),
+ saltHexString, nonceHexString, serverIteration,
passwordMessagePacket);
+ context.write(new PostgreSQLAuthenticationOKPacket());
+ context.write(new PostgreSQLParameterStatusPacket("server_version",
PostgreSQLServerInfo.getServerVersion()));
+ context.write(new PostgreSQLParameterStatusPacket("client_encoding",
clientEncoding));
+ context.write(new PostgreSQLParameterStatusPacket("server_encoding",
"UTF8"));
+ context.write(new PostgreSQLParameterStatusPacket("integer_datetimes",
"on"));
+
context.writeAndFlush(PostgreSQLReadyForQueryPacket.NOT_IN_TRANSACTION);
+ return
AuthenticationResultBuilder.finished(currentAuthResult.getUsername(), "",
currentAuthResult.getDatabase());
+ }
+
private AuthenticationResult processStartupMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload) {
startupMessageReceived = true;
- PostgreSQLComStartupPacket comStartupPacket = new
PostgreSQLComStartupPacket(payload);
- clientEncoding = comStartupPacket.getClientEncoding();
+ PostgreSQLComStartupPacket startupPacket = new
PostgreSQLComStartupPacket(payload);
+ clientEncoding = startupPacket.getClientEncoding();
context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).set(PostgreSQLCharacterSets.findCharacterSet(clientEncoding));
- String user = comStartupPacket.getUser();
- if (Strings.isNullOrEmpty(user)) {
+ String username = startupPacket.getUsername();
+ if (Strings.isNullOrEmpty(username)) {
throw new EmptyUsernameException();
}
- serverIteration = comStartupPacket.getVersion() ==
OpenGaussProtocolVersion.PROTOCOL_351.getVersion() ?
PROTOCOL_351_SERVER_ITERATOR : PROTOCOL_350_SERVER_ITERATOR;
- String serverSignature =
calculateServerSignature(comStartupPacket.getVersion(), user);
+ 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(
- comStartupPacket.getVersion(), saltHexString.getBytes(),
nonceHexString.getBytes(), serverSignature.getBytes(), serverIteration));
- currentAuthResult = AuthenticationResultBuilder.continued(user, "",
comStartupPacket.getDatabase());
+ startupPacket.getVersion(), saltHexString.getBytes(),
nonceHexString.getBytes(), serverSignature.getBytes(), serverIteration));
+ currentAuthResult = AuthenticationResultBuilder.continued(username,
"", startupPacket.getDatabase());
return currentAuthResult;
}
@@ -125,21 +142,4 @@ public final class OpenGaussAuthenticationEngine
implements AuthenticationEngine
String password = authorityRule.findUser(new Grantee(username,
"%")).map(ShardingSphereUser::getPassword).orElse("");
return
OpenGaussAuthenticationHandler.calculateServerSignature(password,
saltHexString, nonceHexString, serverIteration);
}
-
- private AuthenticationResult processPasswordMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload) {
- char messageType = (char) payload.readInt1();
- if (PostgreSQLMessagePacketType.PASSWORD_MESSAGE.getValue() !=
messageType) {
- throw new ProtocolViolationException("password",
Character.toString(messageType));
- }
- PostgreSQLPasswordMessagePacket passwordMessagePacket = new
PostgreSQLPasswordMessagePacket(payload);
-
OpenGaussAuthenticationHandler.loginWithSCRAMSha256Password(currentAuthResult.getUsername(),
currentAuthResult.getDatabase(),
- saltHexString, nonceHexString, serverIteration,
passwordMessagePacket);
- context.write(new PostgreSQLAuthenticationOKPacket());
- context.write(new PostgreSQLParameterStatusPacket("server_version",
PostgreSQLServerInfo.getServerVersion()));
- context.write(new PostgreSQLParameterStatusPacket("client_encoding",
clientEncoding));
- context.write(new PostgreSQLParameterStatusPacket("server_encoding",
"UTF8"));
- context.write(new PostgreSQLParameterStatusPacket("integer_datetimes",
"on"));
-
context.writeAndFlush(PostgreSQLReadyForQueryPacket.NOT_IN_TRANSACTION);
- return
AuthenticationResultBuilder.finished(currentAuthResult.getUsername(), "",
currentAuthResult.getDatabase());
- }
}
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 4cb66714fe5..b6fac60c925 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
@@ -19,6 +19,7 @@ package
org.apache.shardingsphere.proxy.frontend.postgresql.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.payload.PacketPayload;
@@ -36,10 +37,15 @@ import
org.apache.shardingsphere.db.protocol.postgresql.packet.handshake.authent
import
org.apache.shardingsphere.db.protocol.postgresql.packet.identifier.PostgreSQLIdentifierPacket;
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;
@@ -69,8 +75,6 @@ public final class PostgreSQLAuthenticationEngine implements
AuthenticationEngin
private AuthenticationResult currentAuthResult;
- private final PostgreSQLAuthenticationHandler authenticationHandler = new
PostgreSQLAuthenticationHandler();
-
@Override
public int handshake(final ChannelHandlerContext context) {
return ConnectionIdGenerator.getInstance().nextId();
@@ -83,30 +87,16 @@ public final class PostgreSQLAuthenticationEngine
implements AuthenticationEngin
return AuthenticationResultBuilder.continued();
}
payload.getByteBuf().resetReaderIndex();
- return startupMessageReceived ? processPasswordMessage(context,
(PostgreSQLPacketPayload) payload) : processStartupMessage(context,
(PostgreSQLPacketPayload) payload);
- }
-
- private AuthenticationResult processStartupMessage(final
ChannelHandlerContext context, final PostgreSQLPacketPayload payload) {
- startupMessageReceived = true;
- PostgreSQLComStartupPacket comStartupPacket = new
PostgreSQLComStartupPacket(payload);
- clientEncoding = comStartupPacket.getClientEncoding();
-
context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).set(PostgreSQLCharacterSets.findCharacterSet(clientEncoding));
- String user = comStartupPacket.getUser();
- if (Strings.isNullOrEmpty(user)) {
- throw new EmptyUsernameException();
- }
- context.writeAndFlush(getIdentifierPacket(user));
- currentAuthResult = AuthenticationResultBuilder.continued(user, "",
comStartupPacket.getDatabase());
- return currentAuthResult;
+ 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);
- authenticationHandler.login(currentAuthResult.getUsername(),
currentAuthResult.getDatabase(), md5Salt, passwordMessagePacket);
+ login(currentAuthResult.getDatabase(),
currentAuthResult.getUsername(), md5Salt, passwordMessagePacket.getDigest(),
rule);
// TODO implement PostgreSQLServerInfo like MySQLServerInfo
context.write(new PostgreSQLAuthenticationOKPacket());
context.write(new PostgreSQLParameterStatusPacket("server_version",
PostgreSQLServerInfo.getServerVersion()));
@@ -118,8 +108,31 @@ public final class PostgreSQLAuthenticationEngine
implements AuthenticationEngin
return
AuthenticationResultBuilder.finished(currentAuthResult.getUsername(), "",
currentAuthResult.getDatabase());
}
- private PostgreSQLIdentifierPacket getIdentifierPacket(final String
username) {
- AuthorityRule rule =
ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class);
+ private void login(final String databaseName, final String username, final
byte[] md5Salt, final String digest, final AuthorityRule rule) {
+
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<>(PostgreSQLAuthenticatorType.class,
rule).newInstance(user.get()).authenticate(user.get(), new Object[]{digest,
md5Salt}),
+ () -> 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();
+ }
+ 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));
if (authenticator.isPresent() &&
PostgreSQLAuthenticationMethod.PASSWORD.getMethodName().equals(authenticator.get().getAuthenticationMethodName()))
{
diff --git
a/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationHandler.java
b/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationHandler.java
deleted file mode 100644
index 45093f56b9c..00000000000
---
a/proxy/frontend/postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationHandler.java
+++ /dev/null
@@ -1,62 +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.postgresql.authentication;
-
-import com.google.common.base.Strings;
-import org.apache.shardingsphere.authority.checker.AuthorityChecker;
-import org.apache.shardingsphere.authority.rule.AuthorityRule;
-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.postgresql.authentication.authenticator.PostgreSQLAuthenticatorType;
-
-import java.util.Optional;
-
-/**
- * Authentication handler for PostgreSQL.
- */
-public final class PostgreSQLAuthenticationHandler {
-
- /**
- * Login.
- *
- * @param username username
- * @param databaseName database name
- * @param md5Salt MD5 salt
- * @param passwordMessagePacket password message packet
- */
- public void login(final String username, final String databaseName, final
byte[] md5Salt, 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<>(PostgreSQLAuthenticatorType.class,
rule).newInstance(user.get())
- .authenticate(user.get(), new
Object[]{passwordMessagePacket.getDigest(), md5Salt}),
- () -> new InvalidPasswordException(username));
- ShardingSpherePreconditions.checkState(null == databaseName || new
AuthorityChecker(rule, grantee).isAuthorized(databaseName),
- () -> new PrivilegeNotGrantedException(username,
databaseName));
- }
-}
diff --git
a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
index e326f01511e..ecfef45693f 100644
---
a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
+++
b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
@@ -81,6 +81,13 @@ public final class PostgreSQLAuthenticationEngineTest
extends ProxyContextRestor
@Before
public void setup() {
when(channelHandlerContext.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY)).thenReturn(mock(Attribute.class));
+ mockInitProxyContext();
+ }
+
+ private void mockInitProxyContext() {
+ ContextManager contextManager = mock(ContextManager.class,
RETURNS_DEEP_STUBS);
+
when(contextManager.getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(new
ShardingSphereRuleMetaData(Collections.singleton(mock(AuthorityRule.class))));
+ ProxyContext.init(contextManager);
}
@Test
@@ -130,7 +137,6 @@ public final class PostgreSQLAuthenticationEngineTest
extends ProxyContextRestor
@SneakyThrows(ReflectiveOperationException.class)
private void assertLogin(final String inputPassword) {
- mockInitProxyContext();
PostgreSQLPacketPayload payload = new
PostgreSQLPacketPayload(createByteBuf(16, 128), StandardCharsets.UTF_8);
payload.writeInt4(64);
payload.writeInt4(196608);
@@ -160,12 +166,6 @@ public final class PostgreSQLAuthenticationEngineTest
extends ProxyContextRestor
assertThat(actual.isFinished(), is(password.equals(inputPassword)));
}
- private void mockInitProxyContext() {
- ContextManager contextManager = mock(ContextManager.class,
RETURNS_DEEP_STUBS);
-
when(contextManager.getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(new
ShardingSphereRuleMetaData(Collections.singleton(mock(AuthorityRule.class))));
- ProxyContext.init(contextManager);
- }
-
private ByteBuf createByteBuf(final int initialCapacity, final int
maxCapacity) {
return new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT,
initialCapacity, maxCapacity);
}
diff --git
a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationHandlerTest.java
b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationHandlerTest.java
deleted file mode 100644
index b310bac821a..00000000000
---
a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationHandlerTest.java
+++ /dev/null
@@ -1,148 +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.postgresql.authentication;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.UnpooledByteBufAllocator;
-import io.netty.buffer.UnpooledHeapByteBuf;
-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.postgresql.packet.handshake.PostgreSQLPasswordMessagePacket;
-import
org.apache.shardingsphere.db.protocol.postgresql.payload.PostgreSQLPacketPayload;
-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.postgresql.ProxyContextRestorer;
-import
org.apache.shardingsphere.proxy.frontend.postgresql.authentication.authenticator.impl.PostgreSQLMD5PasswordAuthenticator;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.internal.configuration.plugins.Plugins;
-
-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 PostgreSQLAuthenticationHandlerTest extends
ProxyContextRestorer {
-
- private static final String SCHEMA_PATTERN = "schema_%s";
-
- private final String username = "postgres";
-
- private final String password = "sharding";
-
- private final String database = "schema_0";
-
- private final String md5Salt = "md5test";
-
- private PostgreSQLPasswordMessagePacket passwordMessagePacket;
-
- @Before
- public void init() {
- PostgreSQLPacketPayload payload = new
PostgreSQLPacketPayload(createByteBuf(16, 128), StandardCharsets.UTF_8);
- String md5Digest = md5Encode(md5Salt.getBytes(StandardCharsets.UTF_8));
- payload.writeInt4(4 + md5Digest.length() + 1);
- payload.writeStringNul(md5Digest);
- passwordMessagePacket = new PostgreSQLPasswordMessagePacket(payload);
- }
-
- @Test
- public void assertLoginSuccess() {
- initProxyContext(new ShardingSphereUser(username, password, "%"));
- new PostgreSQLAuthenticationHandler().login(username, database,
md5Salt.getBytes(StandardCharsets.UTF_8), passwordMessagePacket);
- }
-
- @Test(expected = UnknownUsernameException.class)
- public void assertLoginWithAbsentUser() {
- initProxyContext(new ShardingSphereUser("username", password, "%"));
- new PostgreSQLAuthenticationHandler().login(username, database,
md5Salt.getBytes(StandardCharsets.UTF_8), passwordMessagePacket);
- }
-
- @Test(expected = InvalidPasswordException.class)
- public void assertLoginWithIncorrectPassword() {
- initProxyContext(new ShardingSphereUser(username, "password", "%"));
- new PostgreSQLAuthenticationHandler().login(username, database,
md5Salt.getBytes(StandardCharsets.UTF_8), passwordMessagePacket);
- }
-
- @Test(expected = InvalidPasswordException.class)
- public void assertLoginWithoutPassword() {
- initProxyContext(new ShardingSphereUser(username, null, "%"));
- new PostgreSQLAuthenticationHandler().login(username, database,
md5Salt.getBytes(StandardCharsets.UTF_8), 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));
- }
-
- @SneakyThrows(ReflectiveOperationException.class)
- private String md5Encode(final byte[] md5Salt) {
- return (String)
Plugins.getMemberAccessor().invoke(PostgreSQLMD5PasswordAuthenticator.class.getDeclaredMethod("md5Encode",
String.class, String.class, byte[].class),
- new PostgreSQLMD5PasswordAuthenticator(), username, password,
md5Salt);
- }
-}